text
string
size
int64
token_count
int64
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector <ll> vi; int n; vi a, b; int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); while(cin >> n){ a.resize(1 << n); b.resize(a.size()); for(int i=0; i<a.size(); i++) cin >> a[i]; for(int i=0; i<(1<<n); i++){ int sum = 0; for(int j=0; (i ^ (1<<j)) < a.size(); j++){ sum += a[(i ^ (1<<j))]; } b[i] = sum; } int max1 = -1; for(int i=0; i<a.size(); i++){ for(int j=0; (i ^ (1<<j)) < a.size(); j++){ max1 = max(max1, (int)b[i] + (int)b[i^(1<<j)]); } } cout << max1 << "\n"; } return 0; }
836
340
#include "Convertible.hpp" #include <functional> #include <stdexcept> namespace succotash::utilities { //------------------------------------------------------------------------------ // Local functions which are not for export //------------------------------------------------------------------------------ inline void ThrowErrorImpl(const char* value, const char* desc) { char buffer[1024]; snprintf(buffer, sizeof(buffer), "Value '%s' exception, %s", value, desc); throw std::runtime_error(buffer); } template <typename T, typename Func> inline T ConvertStdlib(const char* value, Func func, const char* error_desc) { char* error; long result = func(value, &error); if (*value == '\0' || *error != '\0') { ThrowErrorImpl(value, error_desc); } return result; } //------------------------------------------------------------------------------ // Private methods //------------------------------------------------------------------------------ void Convertible::ThrowError(const char* desc) const { ThrowErrorImpl(this->value_, desc); } //------------------------------------------------------------------------------ // Public methods //------------------------------------------------------------------------------ Convertible::Convertible(const char* value) : value_(value) { } // String std::string Convertible::ToString() const { return std::string(value_); } // Basic numbers int Convertible::ToInt() const { return ToLong(); } unsigned int Convertible::ToUInt() const { return ToULong(); } long Convertible::ToLong() const { auto parser = std::bind(&strtol, std::placeholders::_1, std::placeholders::_2, 0); return ConvertStdlib<long>(value_, parser,"couldn't convert to int/long"); } unsigned long Convertible::ToULong() const { auto parser = std::bind(&strtoul, std::placeholders::_1, std::placeholders::_2, 0); return ConvertStdlib<unsigned long>(value_, parser, "couldn't convert to uint/ulong"); } // Numbers with floating precision float Convertible::ToFloat() const { auto parser = &strtof; return ConvertStdlib<float>(value_, parser, "couldn't convert to float"); } double Convertible::ToDouble() const { auto parser = &strtod; return ConvertStdlib<double>(value_, parser, "couldn't convert to double"); } // Bool bool Convertible::ToBool() const { std::string_view value(value_); if (value == "true" || value == "True") { return true; } else if (value == "false" || value == "False") { return false; } else { ThrowError("couldn't convert to bool"); return false; } } // Operators bool Convertible::operator==(const std::string& rhs) const { return rhs == value_; } } // namespace succotash::utilities
2,805
793
/* * HoldQueue1.hpp * * Created on: 2018/5/13 * Author: Qun Cheng * Author: Jiaxuan(Percy) Pan */ #ifndef HOLDQUEUE1_HPP_ #define HOLDQUEUE1_HPP_ #include "HoldQueue2.hpp" class HoldQueue1{ std::list<Job> q; public: HoldQueue1(){} bool empty(){ return q.empty(); } Job front(){ return q.front(); } void pop(){ q.pop_front(); } void print(){ for(Job j : q){ j.print(); } } void push(Job in){ if(q.empty()){ q.push_back(in); return; } list<Job>::iterator it; it = q.begin(); while(it != q.end()){ if(in.getRuntime() < it->getRuntime()){ q.insert(it, in); return; } it++; } if(in.getRuntime() < it->getRuntime()){ q.insert(it, in); return; } q.push_back(in); return; } }; #endif /* HOLDQUEUE1_HPP_ */
872
449
#include <algorithm> #include "atomutil.h" #include "elements.h" #include "renderer.h" #include "strings.h" namespace htmlparser { namespace { inline void WriteToBuffer(const std::string& str, std::stringbuf* buf) { buf->sputn(str.c_str(), str.size()); } // Writes str surrounded by quotes to buf. Normally it will use double quotes, // but if str contains a double quote, it will use single quotes. // It is used for writing the identifiers in a doctype declaration. // In valid HTML, they can't contains both types of quotes. inline void WriteQuoted(const std::string& str, std::stringbuf* buf) { char quote = '"'; if (str.find('\"') != std::string::npos) { quote = '\''; } buf->sputc(quote); WriteToBuffer(str, buf); buf->sputc(quote); } } // namespace. RenderError Renderer::Render(Node* node, std::stringbuf* buf) { switch (node->Type()) { case NodeType::ERROR_NODE: return RenderError::ERROR_NODE_NO_RENDER; case NodeType::TEXT_NODE: Strings::Escape(node->Data().data(), buf); return RenderError::NO_ERROR; case NodeType::DOCUMENT_NODE: for (Node* c = node->FirstChild(); c; c = c->NextSibling()) { auto err = Render(c, buf); if (err != RenderError::NO_ERROR) { return err; } } return RenderError::NO_ERROR; case NodeType::ELEMENT_NODE: // No-op. break; case NodeType::COMMENT_NODE: WriteToBuffer("<!--", buf); WriteToBuffer(node->Data().data(), buf); WriteToBuffer("-->", buf); return RenderError::NO_ERROR; case NodeType::DOCTYPE_NODE: { WriteToBuffer("<!DOCTYPE ", buf); WriteToBuffer(node->Data().data(), buf); std::string p; std::string s; for (auto& attr : node->Attributes()) { std::string key = attr.key; std::string value = attr.value; if (key == "public") { p = value; } else if (key == "system") { s = value; } } if (!p.empty()) { WriteToBuffer(" PUBLIC ", buf); WriteQuoted(p, buf); if (!s.empty()) { buf->sputc(' '); WriteQuoted(s, buf); } } else if (!s.empty()) { WriteToBuffer(" SYSTEM ", buf); WriteQuoted(s, buf); } buf->sputc('>'); return RenderError::NO_ERROR; } default: return RenderError::UNKNOWN_NODE_TYPE; } // Render the <xxx> opening tag. buf->sputc('<'); WriteToBuffer(node->DataAtom() == Atom::UNKNOWN ? node->Data().data() : AtomUtil::ToString(node->DataAtom()), buf); for (auto& attr : node->Attributes()) { std::string ns = attr.name_space; std::string k = attr.key; std::string v = attr.value; buf->sputc(' '); if (!ns.empty()) { WriteToBuffer(ns, buf); buf->sputc(':'); } WriteToBuffer(k, buf); if (!v.empty()) { WriteToBuffer("=\"", buf); Strings::Escape(v, buf); buf->sputc('"'); } } if (auto ve = std::find(kVoidElements.begin(), kVoidElements.end(), node->DataAtom()); ve != kVoidElements.end()) { if (node->FirstChild()) { return RenderError::VOID_ELEMENT_CHILD_NODE; } WriteToBuffer(">", buf); return RenderError::NO_ERROR; } buf->sputc('>'); // Add initial newline where there is danger of a newline being ignored. if (Node* c = node->FirstChild(); c && c->Type() == NodeType::TEXT_NODE && Strings::StartsWith( c->Data(), "\n")) { if (node->DataAtom() == Atom::PRE || node->DataAtom() == Atom::LISTING || node->DataAtom() == Atom::TEXTAREA) { buf->sputc('\n'); } } // Render any child nodes. if (std::find(kRawTextNodes.begin(), kRawTextNodes.end(), node->DataAtom()) != kRawTextNodes.end()) { for (Node* c = node->FirstChild(); c; c = c->NextSibling()) { if (c->Type() == NodeType::TEXT_NODE) { WriteToBuffer(c->Data().data(), buf); } else { auto err = Render(c, buf); if (err != RenderError::NO_ERROR) { return err; } } } if (node->DataAtom() == Atom::PLAINTEXT) { // Don't render anything else. <plaintext> must be the last element // in the file, with no closing tag. return RenderError::PLAIN_TEXT_ABORT; } } else { for (Node* c = node->FirstChild(); c; c = c->NextSibling()) { auto err = Render(c, buf); if (err != RenderError::NO_ERROR) { return err; } } } // Render the </xxx> closing tag. WriteToBuffer("</", buf); WriteToBuffer(node->DataAtom() == Atom::UNKNOWN ? node->Data().data() : AtomUtil::ToString(node->DataAtom()), buf); buf->sputc('>'); return RenderError::NO_ERROR; } } // namespace htmlparser.
4,892
1,643
/* * This file is part of liblcf. Copyright (c) 2018 liblcf authors. * https://github.com/EasyRPG/liblcf - https://easyrpg.org * * liblcf is Free/Libre Open Source Software, released under the MIT License. * For the full copyright and license information, please view the COPYING * file that was distributed with this source code. */ #include "lcf_options.h" #include "rpg_actor.h" #include "rpg_event.h" #include "rpg_map.h" #include "rpg_mapinfo.h" #include "rpg_system.h" #include "rpg_save.h" #include "rpg_chipset.h" #include "rpg_parameters.h" #include "data.h" void RPG::SaveActor::Setup(int actor_id) { const RPG::Actor& actor = Data::actors[actor_id - 1]; ID = actor.ID; name = actor.name; title = actor.title; sprite_name = actor.character_name; sprite_id = actor.character_index; sprite_flags = actor.transparent ? 3 : 0; face_name = actor.face_name; face_id = actor.face_index; level = actor.initial_level; exp = 0; hp_mod = 0; sp_mod = 0; attack_mod = 0; defense_mod = 0; spirit_mod = 0; agility_mod = 0; skills_size = 0; skills.clear(); equipped.clear(); equipped.push_back(actor.initial_equipment.weapon_id); equipped.push_back(actor.initial_equipment.shield_id); equipped.push_back(actor.initial_equipment.armor_id); equipped.push_back(actor.initial_equipment.helmet_id); equipped.push_back(actor.initial_equipment.accessory_id); current_hp = 0; current_sp = 0; battle_commands.resize(7, -1); status.resize(Data::states.size()); changed_battle_commands = false; class_id = -1; two_weapon = actor.two_weapon; lock_equipment = actor.lock_equipment; auto_battle = actor.auto_battle; super_guard = actor.super_guard; } void RPG::SaveInventory::Setup() { party = Data::system.party; party_size = party.size(); } void RPG::SaveMapEvent::Setup(const RPG::Event& event) { ID = event.ID; position_x = event.x; position_y = event.y; } void RPG::SaveMapInfo::Setup() { position_x = 0; position_y = 0; lower_tiles.resize(144); upper_tiles.resize(144); for (int i = 0; i < 144; i++) { lower_tiles[i] = i; upper_tiles[i] = i; } } void RPG::SaveMapInfo::Setup(const RPG::Map& map) { chipset_id = map.chipset_id; parallax_name = map.parallax_name; parallax_horz = map.parallax_loop_x; parallax_vert = map.parallax_loop_y; parallax_horz_auto = map.parallax_auto_loop_x; parallax_vert_auto = map.parallax_auto_loop_y; parallax_horz_speed = map.parallax_sx; parallax_vert_speed = map.parallax_sy; } void RPG::SaveSystem::Setup() { const RPG::System& system = Data::system; frame_count = 0; graphics_name = system.system_name; face_name = ""; face_id = -1; face_right = false; face_flip = false; transparent = false; music_stopping = false; title_music = system.title_music; battle_music = system.battle_music; battle_end_music = system.battle_end_music; inn_music = system.inn_music; // current_music // unknown1_music FIXME // unknown2_music FIXME // stored_music boat_music = system.boat_music; ship_music = system.ship_music; airship_music = system.airship_music; gameover_music = system.gameover_music; cursor_se = system.cursor_se; decision_se = system.decision_se; cancel_se = system.cancel_se; buzzer_se = system.buzzer_se; battle_se = system.battle_se; escape_se = system.escape_se; enemy_attack_se = system.enemy_attack_se; enemy_damaged_se = system.enemy_damaged_se; actor_damaged_se = system.actor_damaged_se; dodge_se = system.dodge_se; enemy_death_se = system.enemy_death_se; item_se = system.item_se; transition_out = system.transition_out; transition_in = system.transition_in; battle_start_fadeout = system.battle_start_fadeout; battle_start_fadein = system.battle_start_fadein; battle_end_fadeout = system.battle_end_fadeout; battle_end_fadein = system.battle_end_fadein; message_stretch = system.message_stretch; font_id = system.font_id; teleport_allowed = true; escape_allowed = true; save_allowed = true; menu_allowed = true; background = ""; save_count = 0; save_slot = -1; } void RPG::Save::Setup() { system.Setup(); screen = RPG::SaveScreen(); pictures.clear(); pictures.resize(50); for (int i = 1; i <= (int)pictures.size(); i++) { pictures[i - 1].ID = i; } actors.clear(); actors.resize(Data::actors.size()); for (int i = 1; i <= (int) actors.size(); i++) actors[i - 1].Setup(i); map_info.Setup(); party_location.move_speed = 4; boat_location.vehicle = RPG::SaveVehicleLocation::VehicleType_skiff; ship_location.vehicle = RPG::SaveVehicleLocation::VehicleType_ship; airship_location.vehicle = RPG::SaveVehicleLocation::VehicleType_airship; if (targets.empty()) { targets.resize(1); } } void RPG::Actor::Setup() { int max_final_level = 0; if (Data::system.ldb_id == 2003) { max_final_level = 99; if (final_level == -1) { final_level = max_final_level; } exp_base = exp_base == -1 ? 300 : exp_base; exp_inflation = exp_inflation == -1 ? 300 : exp_inflation; } else { max_final_level = 50; if (final_level == -1) { final_level = max_final_level; } exp_base = exp_base == -1 ? 30 : exp_base; exp_inflation = exp_inflation == -1 ? 30 : exp_inflation; } parameters.Setup(max_final_level); } void RPG::Chipset::Init() { terrain_data.resize(162, 1); passable_data_lower.resize(162, 15); passable_data_upper.resize(144, 15); passable_data_upper.front() = 31; } void RPG::System::Init() { party.resize(1, 1); menu_commands.resize(1, 1); } void RPG::Parameters::Setup(int final_level) { if (maxhp.size() < final_level) maxhp.resize(final_level, 1); if (maxsp.size() < final_level) maxsp.resize(final_level, 0); if (attack.size() < final_level) attack.resize(final_level, 1); if (defense.size() < final_level) defense.resize(final_level, 1); if (spirit.size() < final_level) spirit.resize(final_level, 1); if (agility.size() < final_level) agility.resize(final_level, 1); }
5,878
2,484
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <cstring> #include <string> #include <iomanip> #include <climits> #include <vector> #include <set> #include <queue> #define SIZE 10 using namespace std; int arr[SIZE]; int main() { ios::sync_with_stdio(false); string origNum, maxNum; cin >> origNum >> maxNum; memset(arr, 0, sizeof(arr)); for (int i = 0; i < origNum.length(); i++) { arr[origNum[i] - '0']++; } /* if (origNum.length() > maxNum.length()) { int delta = origNum.length() - maxNum.length(); string tmp = ""; while (delta--) { tmp += '0'; } maxNum = tmp + maxNum; } */ if (maxNum.length() == origNum.length()) { for (int i = 0; i < origNum.length(); i++) { if (arr[maxNum[i] - '0'] > 0) { arr[maxNum[i] - '0']--; string tmp = ""; for (int j = 0; j <= 9; j++) { for (int k = 0; k < arr[j]; k++) { tmp += (char)(j + '0'); } } bool canSelect = true; for (int j = i + 1; j < origNum.length(); j++) { if (maxNum[j] > tmp[j - i - 1]) { canSelect = true; break; } else if (maxNum[j] < tmp[j - i - 1]) { canSelect = false; break; } } if (canSelect) { cout << maxNum[i]; continue; } else { arr[maxNum[i] - '0']++; } } bool quitFlag = false; for (int j = maxNum[i] - '0' - 1; j >= 0; j--) { if (arr[j] > 0) { cout << j; arr[j]--; quitFlag = true; break; } } if (quitFlag) break; } } for (int i = 9; i >= 0; i--) { while (arr[i]) { cout << i; arr[i]--; } } cout << endl; return 0; }
2,490
764
#include <memory> #include <algorithm> #include <cassert> #include <cstdint> #include "circuit-repo.hpp" #include "circuit-test-util.hpp" #include "context-helib.hpp" int main(void) { using namespace SHEEP; ContextHElib_Fp<int8_t> ctx; std::vector<ContextHElib_Fp<int8_t>::Plaintext> pt_input = {55, -42, 120}; ContextHElib_Fp<int8_t>::Ciphertext ct = ctx.encrypt(pt_input); long const_val = 2; // Perform operation ContextHElib_Fp<int8_t>::Ciphertext ct_out = ctx.MultByConstant(ct, const_val); // Decrypt std::vector<ContextHElib_Fp<int8_t>::Plaintext> pt_out = ctx.decrypt(ct_out); assert(pt_out[0] == 110); assert(pt_out[1] == -84); assert(pt_out[2] == -16); }
703
312
// Copyright 2019 The Beam Team // // 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 "swap_offers_board.h" #include "p2p/protocol_base.h" namespace beam::wallet { SwapOffersBoard::SwapOffersBoard(FlyClient::INetwork& network, IWalletMessageEndpoint& messageEndpoint) : m_network(network), m_messageEndpoint(messageEndpoint) { for (auto channel : m_channelsMap) { m_network.BbsSubscribe(channel.second, m_lastTimestamp, this); } } const std::map<AtomicSwapCoin, BbsChannel> SwapOffersBoard::m_channelsMap = { {AtomicSwapCoin::Bitcoin, proto::Bbs::s_MaxChannels}, {AtomicSwapCoin::Litecoin, proto::Bbs::s_MaxChannels + 1}, {AtomicSwapCoin::Qtum, proto::Bbs::s_MaxChannels + 2} }; void SwapOffersBoard::OnMsg(proto::BbsMsg &&msg) { if (msg.m_Message.empty() || msg.m_Message.size() < MsgHeader::SIZE) return; SwapOfferToken token; SwapOfferConfirmation confirmation; try { MsgHeader header(msg.m_Message.data()); if (header.V0 != 0 || header.V1 != 0 || header.V2 != m_protocolVersion || header.type != 0) { LOG_WARNING() << "offer board message version unsupported"; return; } // message body Deserializer d; d.reset(msg.m_Message.data() + header.SIZE, header.size); d & token; d & confirmation.m_Signature; } catch(...) { LOG_WARNING() << "offer board message deserialization exception"; return; } auto newOffer = token.Unpack(); confirmation.m_offerData = toByteBuffer(token); if (!confirmation.IsValid(newOffer.m_publisherId.m_Pk)) { LOG_WARNING() << "offer board message signature is invalid"; return; } if (newOffer.m_coin >= AtomicSwapCoin::Unknown || newOffer.m_status > SwapOfferStatus::Failed) { LOG_WARNING() << "offer board message is invalid"; return; } auto it = m_offersCache.find(newOffer.m_txId); // New offer if (it == m_offersCache.end()) { m_offersCache[newOffer.m_txId] = newOffer; if (newOffer.m_status == SwapOfferStatus::Pending) { notifySubscribers(ChangeAction::Added, std::vector<SwapOffer>{newOffer}); } else { // Don't push irrelevant offers to subscribers } } // Existing offer update else { SwapOfferStatus existingStatus = m_offersCache[newOffer.m_txId].m_status; // Normal case if (existingStatus == SwapOfferStatus::Pending) { if (newOffer.m_status != SwapOfferStatus::Pending) { m_offersCache[newOffer.m_txId].m_status = newOffer.m_status; notifySubscribers(ChangeAction::Removed, std::vector<SwapOffer>{newOffer}); } } // Transaction state has changed asynchronously while board was offline. // Incomplete offer with SwapOfferStatus!=Pending was created. // If offer with SwapOfferStatus::Pending is still exist in network, // it need to be updated to latest status. else { if (newOffer.m_status == SwapOfferStatus::Pending) { sendUpdateToNetwork(newOffer.m_txId, newOffer.m_publisherId, newOffer.m_coin, existingStatus); } } } } /** * Watches for system state to remove stuck expired offers from board. * Notify only subscribers. Doesn't push any updates to network. */ void SwapOffersBoard::onSystemStateChanged(const Block::SystemState::ID& stateID) { Height currentHeight = stateID.m_Height; for (auto& pair : m_offersCache) { if (pair.second.m_status != SwapOfferStatus::Pending) continue; // has to be already removed from board auto peerResponseTime = pair.second.GetParameter<Height>(TxParameterID::PeerResponseTime); auto minHeight = pair.second.GetParameter<Height>(TxParameterID::MinHeight); if (peerResponseTime && minHeight) { auto expiresHeight = *minHeight + *peerResponseTime; if (expiresHeight <= currentHeight) { pair.second.m_status = SwapOfferStatus::Expired; notifySubscribers(ChangeAction::Removed, std::vector<SwapOffer>{pair.second}); } } } } void SwapOffersBoard::onTransactionChanged(ChangeAction action, const std::vector<TxDescription>& items) { if (action != ChangeAction::Removed) { for (const auto& item : items) { if (item.m_txType != TxType::AtomicSwap) continue; switch (item.m_status) { case TxStatus::InProgress: updateOffer(item.m_txId, SwapOfferStatus::InProgress); break; case TxStatus::Failed: { auto reason = item.GetParameter<TxFailureReason>(TxParameterID::InternalFailureReason); SwapOfferStatus status = SwapOfferStatus::Failed; if (reason && *reason == TxFailureReason::TransactionExpired) { status = SwapOfferStatus::Expired; } updateOffer(item.m_txId, status); break; } case TxStatus::Canceled: updateOffer(item.m_txId, SwapOfferStatus::Canceled); break; default: // ignore break; } } } } void SwapOffersBoard::updateOffer(const TxID& offerTxID, SwapOfferStatus newStatus) { if (newStatus == SwapOfferStatus::Pending) return; auto offerIt = m_offersCache.find(offerTxID); if (offerIt != m_offersCache.end()) { AtomicSwapCoin coin = offerIt->second.m_coin; WalletID publisherId = offerIt->second.m_publisherId; SwapOfferStatus currentStatus = offerIt->second.m_status; if (currentStatus == SwapOfferStatus::Pending) { m_offersCache[offerTxID].m_status = newStatus; notifySubscribers(ChangeAction::Removed, std::vector<SwapOffer>{m_offersCache[offerTxID]}); sendUpdateToNetwork(offerTxID, publisherId, coin, newStatus); } } else { // Case: updateOffer() had been called before offer appeared on board. // Here we don't know if offer exists in network at all. So board doesn't send any update to network. // Board stores incomplete offer to notify network when original Pending offer will be received from network. SwapOffer incompleteOffer(offerTxID); incompleteOffer.m_status = newStatus; m_offersCache[offerTxID] = incompleteOffer; } } auto SwapOffersBoard::getOffersList() const -> std::vector<SwapOffer> { std::vector<SwapOffer> offers; for (auto offer : m_offersCache) { SwapOfferStatus status = offer.second.m_status; if (status == SwapOfferStatus::Pending) { offers.push_back(offer.second); } } return offers; } auto SwapOffersBoard::getChannel(AtomicSwapCoin coin) const -> BbsChannel { auto it = m_channelsMap.find(coin); assert(it != std::cend(m_channelsMap)); return it->second; } void SwapOffersBoard::publishOffer(const SwapOffer& offer) const { auto swapCoin = offer.GetParameter<AtomicSwapCoin>(TxParameterID::AtomicSwapCoin); auto isBeamSide = offer.GetParameter<bool>(TxParameterID::AtomicSwapIsBeamSide); auto amount = offer.GetParameter<Amount>(TxParameterID::Amount); auto swapAmount = offer.GetParameter<Amount>(TxParameterID::AtomicSwapAmount); auto responseTime = offer.GetParameter<Height>(TxParameterID::PeerResponseTime); auto minimalHeight = offer.GetParameter<Height>(TxParameterID::MinHeight); if (!swapCoin || !isBeamSide || !amount || !swapAmount || !responseTime || !minimalHeight) { LOG_WARNING() << offer.m_txId << " Can't publish invalid offer.\n\t"; return; } LOG_INFO() << offer.m_txId << " Publish offer.\n\t" << "isBeamSide: " << (*isBeamSide ? "false" : "true") << "\n\t" << "swapCoin: " << std::to_string(*swapCoin) << "\n\t" << "amount: " << *amount << "\n\t" << "swapAmount: " << *swapAmount << "\n\t" << "responseTime: " << *responseTime << "\n\t" << "minimalHeight: " << *minimalHeight; beam::wallet::SwapOfferToken token(offer); m_messageEndpoint.SendAndSign(toByteBuffer(token), getChannel(*swapCoin), offer.m_publisherId, m_protocolVersion); } void SwapOffersBoard::sendUpdateToNetwork(const TxID& offerID, const WalletID& publisherID, AtomicSwapCoin coin, SwapOfferStatus newStatus) const { LOG_INFO() << offerID << " Update offer status to " << std::to_string(newStatus); beam::wallet::SwapOfferToken token(SwapOffer(offerID, newStatus, publisherID, coin)); m_messageEndpoint.SendAndSign(toByteBuffer(token), getChannel(coin), publisherID, m_protocolVersion); } void SwapOffersBoard::Subscribe(ISwapOffersObserver* observer) { assert(std::find(m_subscribers.begin(), m_subscribers.end(), observer) == m_subscribers.end()); m_subscribers.push_back(observer); } void SwapOffersBoard::Unsubscribe(ISwapOffersObserver* observer) { auto it = std::find(m_subscribers.begin(), m_subscribers.end(), observer); assert(it != m_subscribers.end()); m_subscribers.erase(it); } void SwapOffersBoard::notifySubscribers(ChangeAction action, const std::vector<SwapOffer>& offers) const { for (auto sub : m_subscribers) { sub->onSwapOffersChanged(action, std::vector<SwapOffer>{offers}); } } } // namespace beam::wallet
11,408
3,339
#ifndef TIME_HPP #define TIME_HPP #include <chrono> using namespace std::chrono; using timeStamp = time_point<steady_clock,microseconds>; using timeStampSeconds = time_point<steady_clock,seconds>; extern timeStamp programStart; timeStamp getCurrentTimeMicro(); timeStamp getTimeInFuture(uint64_t usec); int64_t timeSince(timeStamp t0); int64_t timeTo(timeStamp t0); int64_t getTimeDifference(timeStamp t0, timeStamp t1); int64_t timeSinceStart(timeStamp t0); int64_t unixTime(timeStamp t0); #endif /* #ifndef TIME_HPP #define TIME_HPP #include <chrono> #include <time.h> using namespace std::chrono; static inline int fastfloor(float fp) { int i = static_cast<int>(fp); return (fp < i) ? (i - 1) : (i); } nanoseconds timespecToDuration(timespec ts); time_point<system_clock, nanoseconds>timespecToTimePoint(timespec ts); struct timeStamp{ timespec time; timeStamp operator-(timeStamp &t1){ if(t1.time.tv_nsec > time.tv_nsec){ time.tv_sec--; time.tv_nsec = 999999999 + time.tv_nsec - t1.time.tv_nsec; } else{ time.tv_nsec -= t1.time.tv_nsec; } time.tv_sec -= t1.time.tv_sec; return *this; } timeStamp operator+(timeStamp &t1){ if(t1.time.tv_nsec + time.tv_nsec > 999999999){ } else{ time.tv_sec += t1.time.tv_sec; time.tv_nsec += t1.time.tv_nsec; } return *this; } timeStamp operator-(uint64_t usec){ long nsec = usec * 1000; int secx = fastfloor(usec / 1000000); time.tv_sec -= secx; nsec -= secx * 1000000000; if(nsec > time.tv_nsec){ time.tv_sec--; time.tv_nsec = 999999999 + time.tv_nsec - nsec; } else{ time.tv_nsec -= nsec; } return *this; } timeStamp operator+(uint64_t usec){ long nsec = usec * 1000; int secx = fastfloor(usec / 1000000); time.tv_sec -= secx; nsec -= secx * 1000000000; if(nsec + time.tv_nsec > 999999999){ time.tv_sec++; time.tv_nsec = (nsec + time.tv_nsec) - 999999999; } else{ time.tv_nsec += nsec; } return *this; } friend bool operator> (const timeStamp t1, const timeStamp t2){ if(t1.time.tv_sec > t2.time.tv_sec) return true; else return false; if(t1.time.tv_nsec > t2.time.tv_nsec) return true; else return false; } int64_t micros(){ return time.tv_sec * 1000000 + time.tv_nsec / 1000; } }; extern timeStamp programStart; timeStamp getCurrentTimeMicro(); timeStamp getTimeInFuture(uint64_t usec); int64_t timeSince(timeStamp t0); int64_t timeTo(timeStamp t0); int64_t getTimeDifference(timeStamp t0, timeStamp t1); int64_t timeSinceStart(timeStamp t0); int64_t unixTime(timeStamp t0); #endif */
3,005
1,222
// 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 "chromeos/services/secure_channel/ble_advertiser_impl.h" #include "base/bind.h" #include "base/containers/contains.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/timer/timer.h" #include "chromeos/components/multidevice/logging/logging.h" #include "chromeos/services/secure_channel/bluetooth_helper.h" #include "chromeos/services/secure_channel/error_tolerant_ble_advertisement_impl.h" #include "chromeos/services/secure_channel/shared_resource_scheduler.h" #include "chromeos/services/secure_channel/timer_factory.h" namespace chromeos { namespace secure_channel { BleAdvertiserImpl::ActiveAdvertisementRequest::ActiveAdvertisementRequest( DeviceIdPair device_id_pair, ConnectionPriority connection_priority, std::unique_ptr<base::OneShotTimer> timer) : device_id_pair(device_id_pair), connection_priority(connection_priority), timer(std::move(timer)) {} BleAdvertiserImpl::ActiveAdvertisementRequest::~ActiveAdvertisementRequest() = default; // static BleAdvertiserImpl::Factory* BleAdvertiserImpl::Factory::test_factory_ = nullptr; // static std::unique_ptr<BleAdvertiser> BleAdvertiserImpl::Factory::Create( Delegate* delegate, BluetoothHelper* bluetooth_helper, BleSynchronizerBase* ble_synchronizer_base, TimerFactory* timer_factory, scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner) { if (test_factory_) { return test_factory_->CreateInstance(delegate, bluetooth_helper, ble_synchronizer_base, timer_factory, sequenced_task_runner); } return base::WrapUnique( new BleAdvertiserImpl(delegate, bluetooth_helper, ble_synchronizer_base, timer_factory, sequenced_task_runner)); } // static void BleAdvertiserImpl::Factory::SetFactoryForTesting(Factory* test_factory) { test_factory_ = test_factory; } BleAdvertiserImpl::Factory::~Factory() = default; // static const int64_t BleAdvertiserImpl::kNumSecondsPerAdvertisementTimeslot = 10; BleAdvertiserImpl::BleAdvertiserImpl( Delegate* delegate, BluetoothHelper* bluetooth_helper, BleSynchronizerBase* ble_synchronizer_base, TimerFactory* timer_factory, scoped_refptr<base::SequencedTaskRunner> sequenced_task_runner) : BleAdvertiser(delegate), bluetooth_helper_(bluetooth_helper), ble_synchronizer_base_(ble_synchronizer_base), timer_factory_(timer_factory), sequenced_task_runner_(sequenced_task_runner), shared_resource_scheduler_(std::make_unique<SharedResourceScheduler>()) {} BleAdvertiserImpl::~BleAdvertiserImpl() = default; void BleAdvertiserImpl::AddAdvertisementRequest( const DeviceIdPair& request, ConnectionPriority connection_priority) { requests_already_removed_due_to_failed_advertisement_.erase(request); if (base::Contains(all_requests_, request)) { PA_LOG(ERROR) << "BleAdvertiserImpl::AddAdvertisementRequest(): Tried to " << "add advertisement request which was already present. " << "Request: " << request << ", Priority: " << connection_priority; NOTREACHED(); } all_requests_.insert(request); shared_resource_scheduler_->ScheduleRequest(request, connection_priority); // If an existing request is active but has a lower priority than // |connection_priority|, that request should be replaced by |request|. bool was_replaced = ReplaceLowPriorityAdvertisementIfPossible(connection_priority); if (was_replaced) return; UpdateAdvertisementState(); } void BleAdvertiserImpl::UpdateAdvertisementRequestPriority( const DeviceIdPair& request, ConnectionPriority connection_priority) { if (base::Contains(requests_already_removed_due_to_failed_advertisement_, request)) return; if (!base::Contains(all_requests_, request)) { PA_LOG(ERROR) << "BleAdvertiserImpl::UpdateAdvertisementRequestPriority(): " << "Tried to update request priority for a request, but that " << "request was not present. Request: " << request << ", Priority: " << connection_priority; NOTREACHED(); } base::Optional<size_t> index_for_active_request = GetIndexForActiveRequest(request); if (!index_for_active_request) { // If the request is not currently active, update its priority in the // scheduler. shared_resource_scheduler_->UpdateRequestPriority(request, connection_priority); // If an existing request is active but has a lower priority than // |connection_priority|, that request should be replaced by |request|. ReplaceLowPriorityAdvertisementIfPossible(connection_priority); return; } std::unique_ptr<ActiveAdvertisementRequest>& active_request = active_advertisement_requests_[*index_for_active_request]; // If there is an active advertisement and no pending advertisements, update // the active advertisement priority and return. if (shared_resource_scheduler_->empty()) { active_request->connection_priority = connection_priority; return; } // If there is an active advertisement and the new priority of the request // is still at least as high as the highest priority of all pending // requests, update the active advertisement priority and return. if (connection_priority >= *shared_resource_scheduler_->GetHighestPriorityOfScheduledRequests()) { active_request->connection_priority = connection_priority; return; } // The active advertisement's priority has been reduced, and it is now lower // than the priority of at least one pending request. Thus, stop the existing // advertisement and reschedule the request for later. StopAdvertisementRequestAndUpdateActiveRequests( *index_for_active_request, true /* replaced_by_higher_priority_advertisement */, false /* was_removed */); } void BleAdvertiserImpl::RemoveAdvertisementRequest( const DeviceIdPair& request) { // If the request has already been deleted, then this was invoked by a failure // callback following a failure to generate an advertisement. auto it = requests_already_removed_due_to_failed_advertisement_.find(request); if (it != requests_already_removed_due_to_failed_advertisement_.end()) { requests_already_removed_due_to_failed_advertisement_.erase(it); return; } if (!base::Contains(all_requests_, request)) { PA_LOG(ERROR) << "BleAdvertiserImpl::RemoveAdvertisementRequest(): Tried " << "to remove an advertisement request, but that request was " << "not present. Request: " << request; NOTREACHED(); } all_requests_.erase(request); base::Optional<size_t> index_for_active_request = GetIndexForActiveRequest(request); // If the request is not currently active, remove it from the scheduler and // return. if (!index_for_active_request) { shared_resource_scheduler_->RemoveScheduledRequest(request); return; } // The active advertisement should be stopped and not rescheduled. StopAdvertisementRequestAndUpdateActiveRequests( *index_for_active_request, false /* replaced_by_higher_priority_advertisement */, true /* was_removed */); } bool BleAdvertiserImpl::ReplaceLowPriorityAdvertisementIfPossible( ConnectionPriority connection_priority) { base::Optional<size_t> index_with_lower_priority = GetIndexWithLowerPriority(connection_priority); if (!index_with_lower_priority) return false; StopAdvertisementRequestAndUpdateActiveRequests( *index_with_lower_priority, true /* replaced_by_higher_priority_advertisement */, false /* was_removed */); return true; } base::Optional<size_t> BleAdvertiserImpl::GetIndexWithLowerPriority( ConnectionPriority connection_priority) { ConnectionPriority lowest_priority = ConnectionPriority::kHigh; base::Optional<size_t> index_with_lowest_priority; // Loop through |active_advertisement_requests_|, searching for the entry with // the lowest priority. for (size_t i = 0; i < active_advertisement_requests_.size(); ++i) { if (!active_advertisement_requests_[i]) continue; if (active_advertisement_requests_[i]->connection_priority < lowest_priority) { lowest_priority = active_advertisement_requests_[i]->connection_priority; index_with_lowest_priority = i; } } // If |index_with_lowest_priority| was never set, all active advertisement // requests have high priority, so they should not be replaced with the new // connection attempt. if (!index_with_lowest_priority) return base::nullopt; // If the lowest priority in |active_advertisement_requests_| is at least as // high as |connection_priority|, this slot shouldn't be replaced with the // new connection attempt. if (lowest_priority >= connection_priority) return base::nullopt; return *index_with_lowest_priority; } void BleAdvertiserImpl::UpdateAdvertisementState() { for (size_t i = 0; i < active_advertisement_requests_.size(); ++i) { // If there are any empty slots in |active_advertisement_requests_| and // |shared_resource_scheduler_| contains pending requests, remove the // pending request and make it active. if (!active_advertisement_requests_[i] && !shared_resource_scheduler_->empty()) { AddActiveAdvertisementRequest(i); } // If there are any empty slots in |active_advertisements_| and // |active_advertisement_requests_| contains a request for an advertisement, // generate a new active advertisement. if (active_advertisement_requests_[i] && !active_advertisements_[i]) AttemptToAddActiveAdvertisement(i); } } void BleAdvertiserImpl::AddActiveAdvertisementRequest(size_t index_to_add) { // Retrieve the next request from the scheduler. std::pair<DeviceIdPair, ConnectionPriority> request_with_priority = *shared_resource_scheduler_->GetNextScheduledRequest(); // Create a timer, and have it go off in kNumSecondsPerAdvertisementTimeslot // seconds. std::unique_ptr<base::OneShotTimer> timer = timer_factory_->CreateOneShotTimer(); timer->Start( FROM_HERE, base::TimeDelta::FromSeconds(kNumSecondsPerAdvertisementTimeslot), base::BindOnce( &BleAdvertiserImpl::StopAdvertisementRequestAndUpdateActiveRequests, base::Unretained(this), index_to_add, false /* replaced_by_higher_priority_advertisement */, false /* was_removed */)); active_advertisement_requests_[index_to_add] = std::make_unique<ActiveAdvertisementRequest>(request_with_priority.first, request_with_priority.second, std::move(timer)); } void BleAdvertiserImpl::AttemptToAddActiveAdvertisement(size_t index_to_add) { const DeviceIdPair pair = active_advertisement_requests_[index_to_add]->device_id_pair; std::unique_ptr<DataWithTimestamp> service_data = bluetooth_helper_->GenerateForegroundAdvertisement(pair); // If an advertisement could not be created, the request is immediately // removed. It's also tracked to prevent future operations from referencing // the removed request. if (!service_data) { RemoveAdvertisementRequest(pair); requests_already_removed_due_to_failed_advertisement_.insert(pair); // Schedules AttemptToNotifyFailureToGenerateAdvertisement() to run // after the tasks in the current sequence. This is done to avoid invoking // an advertisement generation failure callback on the same call stack that // added the advertisement request in the first place. sequenced_task_runner_->PostTask( FROM_HERE, base::BindOnce( &BleAdvertiserImpl::AttemptToNotifyFailureToGenerateAdvertisement, weak_factory_.GetWeakPtr(), pair)); return; } active_advertisements_[index_to_add] = ErrorTolerantBleAdvertisementImpl::Factory::Create( pair, std::move(service_data), ble_synchronizer_base_); } base::Optional<size_t> BleAdvertiserImpl::GetIndexForActiveRequest( const DeviceIdPair& request) { for (size_t i = 0; i < active_advertisement_requests_.size(); ++i) { auto& active_request = active_advertisement_requests_[i]; if (active_request && active_request->device_id_pair == request) return i; } return base::nullopt; } void BleAdvertiserImpl::StopAdvertisementRequestAndUpdateActiveRequests( size_t index, bool replaced_by_higher_priority_advertisement, bool was_removed) { // Stop the actual advertisement at this index, if there is one. StopActiveAdvertisement(index); // Make a copy of the request to stop from |active_advertisement_requests_|, // then reset the original version which resided in the array. std::unique_ptr<ActiveAdvertisementRequest> request_to_stop = std::move(active_advertisement_requests_[index]); // If the request was not removed by a client, this request is being stopped // either due to a timeout or due to a higher-priority request taking its // spot. In these two cases, the request should be rescheduled, and the // delegate should be notified that the timeslot ended. if (!was_removed) { shared_resource_scheduler_->ScheduleRequest( request_to_stop->device_id_pair, request_to_stop->connection_priority); NotifyAdvertisingSlotEnded(request_to_stop->device_id_pair, replaced_by_higher_priority_advertisement); } UpdateAdvertisementState(); } void BleAdvertiserImpl::StopActiveAdvertisement(size_t index) { auto& active_advertisement = active_advertisements_[index]; if (!active_advertisement) return; // If |active_advertisement| is already in the process of stopping, there is // nothing to do. if (active_advertisement->HasBeenStopped()) return; active_advertisement->Stop( base::BindOnce(&BleAdvertiserImpl::OnActiveAdvertisementStopped, base::Unretained(this), index)); } void BleAdvertiserImpl::OnActiveAdvertisementStopped(size_t index) { active_advertisements_[index].reset(); UpdateAdvertisementState(); } void BleAdvertiserImpl::AttemptToNotifyFailureToGenerateAdvertisement( const DeviceIdPair& device_id_pair) { // If the request is not found, then that request has either been removed // again or re-scheduled after it failed to generate an advertisement, but // before this task could execute. if (!base::Contains(requests_already_removed_due_to_failed_advertisement_, device_id_pair)) { return; } NotifyFailureToGenerateAdvertisement(device_id_pair); } } // namespace secure_channel } // namespace chromeos
15,126
4,587
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ssm/model/LabelParameterVersionResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::SSM::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; LabelParameterVersionResult::LabelParameterVersionResult() : m_parameterVersion(0) { } LabelParameterVersionResult::LabelParameterVersionResult(const Aws::AmazonWebServiceResult<JsonValue>& result) : m_parameterVersion(0) { *this = result; } LabelParameterVersionResult& LabelParameterVersionResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("InvalidLabels")) { Array<JsonView> invalidLabelsJsonList = jsonValue.GetArray("InvalidLabels"); for(unsigned invalidLabelsIndex = 0; invalidLabelsIndex < invalidLabelsJsonList.GetLength(); ++invalidLabelsIndex) { m_invalidLabels.push_back(invalidLabelsJsonList[invalidLabelsIndex].AsString()); } } if(jsonValue.ValueExists("ParameterVersion")) { m_parameterVersion = jsonValue.GetInt64("ParameterVersion"); } return *this; }
1,420
457
// Copyright 2010-2018, Google Inc. // 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 "unix/ibus/key_event_handler.h" #include "base/logging.h" #include "base/port.h" #include "base/singleton.h" namespace mozc { namespace ibus { namespace { bool IsModifierToBeSentOnKeyUp(const commands::KeyEvent &key_event) { if (key_event.modifier_keys_size() == 0) { return false; } if (key_event.modifier_keys_size() == 1 && key_event.modifier_keys(0) == commands::KeyEvent::CAPS) { return false; } return true; } } // namespace KeyEventHandler::KeyEventHandler() : key_translator_(new KeyTranslator) { Clear(); } bool KeyEventHandler::GetKeyEvent( guint keyval, guint keycode, guint modifiers, config::Config::PreeditMethod preedit_method, bool layout_is_jp, commands::KeyEvent *key) { DCHECK(key); key->Clear(); if (!key_translator_->Translate( keyval, keycode, modifiers, preedit_method, layout_is_jp, key)) { LOG(ERROR) << "Translate failed"; return false; } const bool is_key_up = ((modifiers & IBUS_RELEASE_MASK) != 0); return ProcessModifiers(is_key_up, keyval, key); } void KeyEventHandler::Clear() { is_non_modifier_key_pressed_ = false; currently_pressed_modifiers_.clear(); modifiers_to_be_sent_.clear(); } bool KeyEventHandler::ProcessModifiers(bool is_key_up, guint keyval, commands::KeyEvent *key_event) { // Manage modifier key event. // Modifier key event is sent on key up if non-modifier key has not been // pressed since key down of modifier keys and no modifier keys are pressed // anymore. // Following examples are expected behaviors. // // E.g.) Shift key is special. If Shift + printable key is pressed, key event // does NOT have shift modifiers. It is handled by KeyTranslator class. // <Event from ibus> <Event to server> // Shift down | None // "a" down | A // "a" up | None // Shift up | None // // E.g.) Usual key is sent on key down. Modifier keys are not sent if usual // key is sent. // <Event from ibus> <Event to server> // Ctrl down | None // "a" down | Ctrl+a // "a" up | None // Ctrl up | None // // E.g.) Modifier key is sent on key up. // <Event from ibus> <Event to server> // Shift down | None // Shift up | Shift // // E.g.) Multiple modifier keys are sent on the last key up. // <Event from ibus> <Event to server> // Shift down | None // Control down | None // Shift up | None // Control up | Control+Shift // // Essentialy we cannot handle modifier key evnet perfectly because // - We cannot get current keyboard status with ibus. If some modifiers // are pressed or released without focusing the target window, we // cannot handle it. // E.g.) // <Event from ibus> <Event to server> // Ctrl down | None // (focuses out, Ctrl up, focuses in) // Shift down | None // Shift up | None (But we should send Shift key) // To avoid a inconsistent state as much as possible, we clear states // when key event without modifier keys is sent. const bool is_modifier_only = !(key_event->has_key_code() || key_event->has_special_key()); // We may get only up/down key event when a user moves a focus. // This code handles such situation as much as possible. // This code has a bug. If we send Shift + 'a', KeyTranslator removes a shift // modifier and converts 'a' to 'A'. This codes does NOT consider these // situation since we don't have enough data to handle it. // TODO(hsumita): Moves the logic about a handling of Shift or Caps keys from // KeyTranslator to MozcEngine. if (key_event->modifier_keys_size() == 0) { Clear(); } if (!currently_pressed_modifiers_.empty() && !is_modifier_only) { is_non_modifier_key_pressed_ = true; } if (is_non_modifier_key_pressed_) { modifiers_to_be_sent_.clear(); } if (is_key_up) { currently_pressed_modifiers_.erase(keyval); if (!is_modifier_only) { return false; } if (!currently_pressed_modifiers_.empty() || modifiers_to_be_sent_.empty()) { is_non_modifier_key_pressed_ = false; return false; } if (is_non_modifier_key_pressed_) { return false; } DCHECK(!is_non_modifier_key_pressed_); // Modifier key event fires key_event->mutable_modifier_keys()->Clear(); for (std::set<commands::KeyEvent::ModifierKey>::const_iterator it = modifiers_to_be_sent_.begin(); it != modifiers_to_be_sent_.end(); ++it) { key_event->add_modifier_keys(*it); } modifiers_to_be_sent_.clear(); } else if (is_modifier_only) { // TODO(hsumita): Supports a key sequence below. // - Ctrl down // - a down // - Alt down // We should add Alt key to |currently_pressed_modifiers|, but current // implementation does NOT do it. if (currently_pressed_modifiers_.empty() || !modifiers_to_be_sent_.empty()) { for (size_t i = 0; i < key_event->modifier_keys_size(); ++i) { modifiers_to_be_sent_.insert(key_event->modifier_keys(i)); } } currently_pressed_modifiers_.insert(keyval); return false; } // Clear modifier data just in case if |key| has no modifier keys. if (!IsModifierToBeSentOnKeyUp(*key_event)) { Clear(); } return true; } } // namespace ibus } // namespace mozc
7,082
2,344
// Copyright (c) 2018 DENSO CORPORATION. All rights reserved. /** * Sound content class */ #ifndef RBASOUNDCONTENT_HPP #define RBASOUNDCONTENT_HPP #ifdef _MSC_VER #ifdef _WINDLL #define DLL_EXPORT __declspec(dllexport) #else #define DLL_EXPORT __declspec(dllimport) #endif #else #define DLL_EXPORT #endif #include <list> #include <string> #include "RBAContentLoserType.hpp" namespace rba { class RBASoundContentState; class RBAZone; /** * @class RBASoundContent * Define the object of sound content.<br> * Sound content has plural status. * When sound contents connected to a zone, active status is output. * Object has zone definitions, that can output itself. * Each object can define plural zone which can output sound contents. */ class DLL_EXPORT RBASoundContent { protected: RBASoundContent()=default; RBASoundContent(const RBASoundContent&)=delete; RBASoundContent(RBASoundContent&&)=delete; RBASoundContent& operator=(const RBASoundContent&)=delete; RBASoundContent& operator=(RBASoundContent&&)=delete; ~RBASoundContent()=default; public: /** * @brief Returns the name of the sound content. * @return Sound content name */ virtual std::string getName() const=0; /** * @brief Returns the state of the sound content. * @return List of the sound content state */ virtual const std::list<const RBASoundContentState*>& getContentStates() const=0; /** * @brief Returns the zone of the sound content. * @return List of the zone */ virtual const std::list<const RBAZone*>& getZones() const=0; /** * @brief Returns the loser type. * @return Loser type */ virtual RBAContentLoserType getLoserType() const=0; public: /** * @brief Defines the default loser type. */ const static RBAContentLoserType LOSER_TYPE_EDEFAULT = RBAContentLoserType::NEVER_GIVEUP; }; } #endif
1,868
638
/* * This file is part of the Simutrans project under the Artistic License. * (see LICENSE.txt) */ #include <string.h> #include "../simworld.h" #include "../simobj.h" #include "../simmem.h" #include "../display/simimg.h" #include "../bauer/brueckenbauer.h" #include "../descriptor/bridge_desc.h" #include "../boden/grund.h" #include "../dataobj/loadsave.h" #include "../obj/pillar.h" #include "../obj/bruecke.h" #include "../dataobj/environment.h" pillar_t::pillar_t(loadsave_t *file) : obj_t() { desc = NULL; asymmetric = false; rdwr(file); } pillar_t::pillar_t(koord3d pos, player_t *player, const bridge_desc_t *desc, bridge_desc_t::img_t img, int hoehe) : obj_t(pos) { this->desc = desc; this->dir = (uint8)img; set_yoff(-hoehe); set_owner( player ); asymmetric = desc->has_pillar_asymmetric(); calc_image(); } void pillar_t::calc_image() { bool hide = false; int height = get_yoff(); if( grund_t *gr = welt->lookup(get_pos()) ) { slope_t::type slope = gr->get_grund_hang(); if( desc->has_pillar_asymmetric() ) { if( dir == bridge_desc_t::NS_Pillar ) { height += ( (corner_sw(slope) + corner_se(slope) ) * TILE_HEIGHT_STEP )/2; } else { height += ( ( corner_se(slope) + corner_ne(slope) ) * TILE_HEIGHT_STEP ) / 2; } if( height > 0 ) { hide = true; } } else { // on slope use mean height ... height += ( ( corner_se(slope) + corner_ne(slope) + corner_sw(slope) + corner_se(slope) ) * TILE_HEIGHT_STEP ) / 4; } } image = hide ? IMG_EMPTY : desc->get_background( (bridge_desc_t::img_t)dir, get_pos().z-height/TILE_HEIGHT_STEP >= welt->get_snowline() || welt->get_climate( get_pos().get_2d() ) == arctic_climate ); } /** * @return Einen Beschreibungsstring fuer das Objekt, der z.B. in einem * Beobachtungsfenster angezeigt wird. */ void pillar_t::show_info() { planquadrat_t *plan=welt->access(get_pos().get_2d()); for(unsigned i=0; i<plan->get_boden_count(); i++ ) { grund_t *bd=plan->get_boden_bei(i); if(bd->ist_bruecke()) { bruecke_t* br = bd->find<bruecke_t>(); if(br && br->get_desc()==desc) { br->show_info(); } } } } void pillar_t::rdwr(loadsave_t *file) { xml_tag_t p( file, "pillar_t" ); obj_t::rdwr(file); if(file->is_saving()) { const char *s = desc->get_name(); file->rdwr_str(s); file->rdwr_byte(dir); } else { char s[256]; file->rdwr_str(s, lengthof(s)); file->rdwr_byte(dir); desc = bridge_builder_t::get_desc(s); if(desc==0) { if(strstr(s,"ail")) { desc = bridge_builder_t::get_desc("ClassicRail"); dbg->warning("pillar_t::rdwr()","Unknown bridge %s replaced by ClassicRail",s); } else if(strstr(s,"oad")) { desc = bridge_builder_t::get_desc("ClassicRoad"); dbg->warning("pillar_t::rdwr()","Unknown bridge %s replaced by ClassicRoad",s); } } asymmetric = desc && desc->has_pillar_asymmetric(); if( file->is_version_less(112, 7) && env_t::pak_height_conversion_factor==2 ) { switch(dir) { case bridge_desc_t::OW_Pillar: dir = bridge_desc_t::OW_Pillar2; break; case bridge_desc_t::NS_Pillar: dir = bridge_desc_t::NS_Pillar2; break; } } } } void pillar_t::rotate90() { obj_t::rotate90(); // may need to hide/show asymmetric pillars // this is done now in calc_image, which is called after karte_t::rotate anyway // we cannot decide this here, since welt->lookup(get_pos())->get_grund_hang() cannot be called // since we are in the middle of the rotation process // the rotated image parameter is just one in front/back switch(dir) { case bridge_desc_t::NS_Pillar: dir=bridge_desc_t::OW_Pillar ; break; case bridge_desc_t::OW_Pillar: dir=bridge_desc_t::NS_Pillar ; break; case bridge_desc_t::NS_Pillar2: dir=bridge_desc_t::OW_Pillar2 ; break; case bridge_desc_t::OW_Pillar2: dir=bridge_desc_t::NS_Pillar2 ; break; } }
3,858
1,745
// Copyright (c) 2019-2020 Xenios SEZC // https://www.veriblock.org // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef __SIGNUTIL__HPP__ #define __SIGNUTIL__HPP__ #include <stdexcept> #include <vector> #include "slice.hpp" #include "blob.hpp" namespace altintegration { static const size_t PRIVATE_KEY_SIZE = 32; static const size_t PUBLIC_KEY_COMPRESSED_SIZE = 33; static const size_t PUBLIC_KEY_UNCOMPRESSED_SIZE = 65; using PrivateKey = Blob<PRIVATE_KEY_SIZE>; using PublicKey = Blob<PUBLIC_KEY_UNCOMPRESSED_SIZE>; using Signature = std::vector<uint8_t>; // VBK encoded keys are plain byte arrays using PrivateKeyVbk = std::vector<uint8_t>; using PublicKeyVbk = std::vector<uint8_t>; /** * Convert VBK encoded private key to the PrivateKey type. * @param key VBK encoded private key * @throws std::out_of_range if key is malformed * @return PrivateKey for inner use */ PrivateKey privateKeyFromVbk(PrivateKeyVbk key); /** * Convert VBK encoded public key to the PublicKey type. * @param key VBK encoded public key * @throws std::out_of_range if key is malformed * @return PublicKey for inner use */ PublicKey publicKeyFromVbk(PublicKeyVbk key); /** * Convert PublicKey type to VBK encoding. * @param key PublicKey format public key * @throws std::out_of_range if key is malformed * @return byte array with VBK encoded public key */ PublicKeyVbk publicKeyToVbk(PublicKey key); /** * Derive public key from the private key. * @param privateKey use this private key to generate public key * @throws std::out_of_range if privateKey is malformed * @return PublicKey type generated public key */ PublicKey derivePublicKey(PrivateKey privateKey); /** * Sign message for VBK usage. * This function calculates SHA256 of the message and applies * secp256k1 signature. Result is encoded in VBK format. * @param message message to sign * @param privateKey sign with this private key * @throws std::out_of_range if privateKey is malformed * @return byte array with VBK encoded signature */ Signature veriBlockSign(Slice<const uint8_t> message, PrivateKey privateKey); /** * Verify message previously signed with veriBlockSign. * This function calculates SHA256 of the message, decodes * signature from VBK format and verifies signature * using provided public key. Signature should be formed * with secp256k1 algorithm. Public key should be derived * from signer's private key. * @param message message to verify with * @param signature VBK encoded signature to verify * @param publicKey verify signature with this public key * @throws std::out_of_range if publicKey is malformed * @return 1 if signature is valid, 0 - otherwise */ int veriBlockVerify(Slice<const uint8_t> message, Signature signature, PublicKey publicKey); } // namespace altintegration #endif //__SIGNUTIL__HPP__
2,988
924
/* * $Id: mech.hitloc.c,v 1.1.1.1 2005/01/11 21:18:17 kstevens Exp $ * * Author: Markus Stenberg <fingon@iki.fi> * * Copyright (c) 1996 Markus Stenberg * Copyright (c) 1998-2002 Thomas Wouters * Copyright (c) 2000-2002 Cord Awtry * All rights reserved * * Created: Fri Sep 20 19:54:48 1996 fingon * Last modified: Tue Jun 16 18:23:58 1998 fingon * */ #include <stdio.h> #include <string.h> #include "copyright.h" #include "autoconf.h" #include "config.h" #include "db.h" #include "stringutil.h" #include "alloc.h" #include "mech.h" #include "mech.events.h" #include "p.mech.utils.h" #include "p.mech.combat.h" #include "p.mech.damage.h" #include "p.aero.bomb.h" #include "p.mech.update.h" #include "p.crit.h" #include "p.glue.h" #include "mech.notify.h" #include "p.mech.notify.h" extern void muxevent_remove_type_data(int, void *); #define CHECK_ZERO_LOC(mech,a,b) ( GetSectInt(mech, a) > 0 ? a : b ) int FindPunchLocation(int hitGroup) { int roll = Number(1, 6); switch (hitGroup) { case LEFTSIDE: switch (roll) { case 1: case 2: return LTORSO; case 3: return CTORSO; case 4: case 5: return LARM; case 6: return HEAD; } case BACK: case FRONT: switch (roll) { case 1: return LARM; case 2: return LTORSO; case 3: return CTORSO; case 4: return RTORSO; case 5: return RARM; case 6: return HEAD; } break; case RIGHTSIDE: switch (roll) { case 1: case 2: return RTORSO; case 3: return CTORSO; case 4: case 5: return RARM; case 6: return HEAD; } } return CTORSO; } int FindKickLocation(int hitGroup) { int roll = Number(1, 6); switch (hitGroup) { case LEFTSIDE: return LLEG; case BACK: case FRONT: switch (roll) { case 1: case 2: case 3: return RLEG; case 4: case 5: case 6: return LLEG; } case RIGHTSIDE: return RLEG; } return RLEG; } int get_bsuit_hitloc(MECH * mech) { int i; int table[NUM_BSUIT_MEMBERS]; int last = 0; for (i = 0; i < NUM_BSUIT_MEMBERS; i++) if (GetSectInt(mech, i)) table[last++] = i; if (!last) return -1; return table[Number(0, last - 1)]; } int TransferTarget(MECH * mech, int hitloc) { switch (MechType(mech)) { case CLASS_BSUIT: return get_bsuit_hitloc(mech); case CLASS_AERO: switch (hitloc) { case AERO_NOSE: case AERO_LWING: case AERO_RWING: case AERO_ENGINE: case AERO_COCKPIT: return AERO_FUSEL; } break; case CLASS_MECH: case CLASS_MW: switch (hitloc) { case RARM: case RLEG: return RTORSO; break; case LARM: case LLEG: return LTORSO; break; case RTORSO: case LTORSO: return CTORSO; break; } break; } return -1; } int FindSwarmHitLocation(int *iscritical, int *isrear) { *isrear = 0; *iscritical = 1; switch (Roll()) { case 12: case 2: return HEAD; case 3: case 11: *isrear = 1; return CTORSO; case 4: *isrear = 1; case 5: return RTORSO; case 10: *isrear = 1; case 9: return LTORSO; case 6: return RARM; case 8: return LARM; case 7: return CTORSO; } return HEAD; } int crittable(MECH * mech, int loc, int tres) { int d; if (MechMove(mech) == MOVE_NONE) return 0; if (!GetSectOArmor(mech, loc)) return 1; if (MechType(mech) != CLASS_MECH && btechconf.btech_vcrit <= 1) return 0; d = (100 * GetSectArmor(mech, loc)) / GetSectOArmor(mech, loc); if (d < tres) return 1; if (d == 100) { if (Number(1, 71) == 23) return 1; return 0; } if (d < (100 - ((100 - tres) / 2))) if (Number(1, 11) == 6) return 1; return 0; } int FindFasaHitLocation(MECH * mech, int hitGroup, int *iscritical, int *isrear) { int roll, hitloc = 0; int side; *iscritical = 0; roll = Roll(); if (MechStatus(mech) & COMBAT_SAFE) return 0; if (MechDugIn(mech) && GetSectOInt(mech, TURRET) && Number(1, 100) >= 42) return TURRET; rollstat.hitrolls[roll - 2]++; rollstat.tothrolls++; switch (MechType(mech)) { case CLASS_BSUIT: if ((hitloc = get_bsuit_hitloc(mech)) < 0) return Number(0, NUM_BSUIT_MEMBERS - 1); case CLASS_MW: case CLASS_MECH: switch (hitGroup) { case LEFTSIDE: switch (roll) { case 2: *iscritical = 1; return LTORSO; case 3: return LLEG; case 4: case 5: return LARM; case 6: return LLEG; case 7: return LTORSO; case 8: return CTORSO; case 9: return RTORSO; case 10: return RARM; case 11: return RLEG; case 12: return HEAD; } case RIGHTSIDE: switch (roll) { case 2: *iscritical = 1; return RTORSO; case 3: return RLEG; case 4: case 5: return RARM; case 6: return RLEG; case 7: return RTORSO; case 8: return CTORSO; case 9: return LTORSO; case 10: return LARM; case 11: return LLEG; case 12: return HEAD; } case FRONT: case BACK: switch (roll) { case 2: *iscritical = 1; return CTORSO; case 3: case 4: return RARM; case 5: return RLEG; case 6: return RTORSO; case 7: return CTORSO; case 8: return LTORSO; case 9: return LLEG; case 10: case 11: return LARM; case 12: return HEAD; } } break; case CLASS_VEH_GROUND: switch (hitGroup) { case LEFTSIDE: switch (roll) { case 2: /* A Roll on Determining Critical Hits Table */ *iscritical = 1; return LSIDE; case 3: if (btechconf.btech_tankfriendly) { if (!Fallen(mech)) { mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c"); switch (MechMove(mech)) { case MOVE_TRACK: mech_notify(mech, MECHALL, "One of your tracks is seriously damaged!!"); break; case MOVE_WHEEL: mech_notify(mech, MECHALL, "One of your wheels is seriously damaged!!"); break; case MOVE_HOVER: mech_notify(mech, MECHALL, "Your air skirt is seriously damaged!!"); break; case MOVE_HULL: case MOVE_SUB: case MOVE_FOIL: mech_notify(mech, MECHALL, "Your speed slows down a lot.."); break; } LowerMaxSpeed(mech, MP2); } return LSIDE; } /* Cripple tank */ if (!Fallen(mech)) { mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c"); switch (MechMove(mech)) { case MOVE_TRACK: mech_notify(mech, MECHALL, "One of your tracks is destroyed, imobilizing your vehicle!!"); break; case MOVE_WHEEL: mech_notify(mech, MECHALL, "One of your wheels is destroyed, imobilizing your vehicle!!"); break; case MOVE_HOVER: mech_notify(mech, MECHALL, "Your lift fan is destroyed, imobilizing your vehicle!!"); break; case MOVE_HULL: case MOVE_SUB: case MOVE_FOIL: mech_notify(mech, MECHALL, "You are halted in your tracks - literally."); } SetMaxSpeed(mech, 0.0); MakeMechFall(mech); } return LSIDE; case 4: case 5: /* MP -1 */ if (!Fallen(mech)) { mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c"); switch (MechMove(mech)) { case MOVE_TRACK: mech_notify(mech, MECHALL, "One of your tracks is damaged!!"); break; case MOVE_WHEEL: mech_notify(mech, MECHALL, "One of your wheels is damaged!!"); break; case MOVE_HOVER: mech_notify(mech, MECHALL, "Your air skirt is damaged!!"); break; case MOVE_HULL: case MOVE_SUB: case MOVE_FOIL: mech_notify(mech, MECHALL, "Your speed slows down.."); break; } LowerMaxSpeed(mech, MP1); } return LSIDE; break; case 6: case 7: case 8: case 9: /* MP -1 if hover */ return LSIDE; case 10: return (GetSectInt(mech, TURRET)) ? TURRET : LSIDE; case 11: if (GetSectInt(mech, TURRET)) { if (!(MechTankCritStatus(mech) & TURRET_LOCKED)) { mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c"); MechTankCritStatus(mech) |= TURRET_LOCKED; mech_notify(mech, MECHALL, "Your turret takes a direct hit and immobilizes!"); } return TURRET; } else return LSIDE; case 12: /* A Roll on Determining Critical Hits Table */ *iscritical = 1; return LSIDE; } break; case RIGHTSIDE: switch (roll) { case 2: *iscritical = 1; return RSIDE; case 3: if (btechconf.btech_tankfriendly) { if (!Fallen(mech)) { mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c"); switch (MechMove(mech)) { case MOVE_TRACK: mech_notify(mech, MECHALL, "One of your tracks is seriously damaged!!"); break; case MOVE_WHEEL: mech_notify(mech, MECHALL, "One of your wheels is seriously damaged!!"); break; case MOVE_HOVER: mech_notify(mech, MECHALL, "Your air skirt is seriously damaged!!"); break; case MOVE_HULL: case MOVE_SUB: case MOVE_FOIL: mech_notify(mech, MECHALL, "Your speed slows down a lot.."); break; } LowerMaxSpeed(mech, MP2); } return RSIDE; } /* Cripple Tank */ if (!Fallen(mech)) { mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c"); switch (MechMove(mech)) { case MOVE_TRACK: mech_notify(mech, MECHALL, "One of your tracks is destroyed, imobilizing your vehicle!!"); break; case MOVE_WHEEL: mech_notify(mech, MECHALL, "One of your wheels is destroyed, imobilizing your vehicle!!"); break; case MOVE_HOVER: mech_notify(mech, MECHALL, "Your lift fan is destroyed, imobilizing your vehicle!!"); break; case MOVE_HULL: case MOVE_SUB: case MOVE_FOIL: mech_notify(mech, MECHALL, "You are halted in your tracks - literally."); } SetMaxSpeed(mech, 0.0); MakeMechFall(mech); } return RSIDE; case 4: case 5: /* MP -1 */ if (!Fallen(mech)) { mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c"); switch (MechMove(mech)) { case MOVE_TRACK: mech_notify(mech, MECHALL, "One of your tracks is damaged!!"); break; case MOVE_WHEEL: mech_notify(mech, MECHALL, "One of your wheels is damaged!!"); break; case MOVE_HOVER: mech_notify(mech, MECHALL, "Your air skirt is damaged!!"); break; case MOVE_HULL: case MOVE_SUB: case MOVE_FOIL: mech_notify(mech, MECHALL, "Your speed slows down.."); break; } LowerMaxSpeed(mech, MP1); } return RSIDE; case 6: case 7: case 8: return RSIDE; case 9: /* MP -1 if hover */ if (!Fallen(mech)) { if (MechMove(mech) == MOVE_HOVER) { mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c"); mech_notify(mech, MECHALL, "Your air skirt is damaged!!"); LowerMaxSpeed(mech, MP1); } } return RSIDE; case 10: return (GetSectInt(mech, TURRET)) ? TURRET : RSIDE; case 11: if (GetSectInt(mech, TURRET)) { if (!(MechTankCritStatus(mech) & TURRET_LOCKED)) { mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c"); MechTankCritStatus(mech) |= TURRET_LOCKED; mech_notify(mech, MECHALL, "Your turret takes a direct hit and immobilizes!"); } return TURRET; } else return RSIDE; case 12: /* A Roll on Determining Critical Hits Table */ *iscritical = 1; return RSIDE; } break; case FRONT: case BACK: side = (hitGroup == FRONT ? FSIDE : BSIDE); switch (roll) { case 2: /* A Roll on Determining Critical Hits Table */ *iscritical = 1; return side; case 3: if (btechconf.btech_tankshield) { if (btechconf.btech_tankfriendly) { if (!Fallen(mech)) { mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c"); switch (MechMove(mech)) { case MOVE_TRACK: mech_notify(mech, MECHALL, "One of your tracks is seriously damaged!!"); break; case MOVE_WHEEL: mech_notify(mech, MECHALL, "One of your wheels is seriously damaged!!"); break; case MOVE_HOVER: mech_notify(mech, MECHALL, "Your air skirt is seriously damaged!!"); break; case MOVE_HULL: case MOVE_SUB: case MOVE_FOIL: mech_notify(mech, MECHALL, "Your speed slows down a lot.."); break; } LowerMaxSpeed(mech, MP2); } return side; } /* Cripple tank */ if (!Fallen(mech)) { mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c"); switch (MechMove(mech)) { case MOVE_TRACK: mech_notify(mech, MECHALL, "One of your tracks is destroyed, imobilizing your vehicle!!"); break; case MOVE_WHEEL: mech_notify(mech, MECHALL, "One of your wheels is destroyed, imobilizing your vehicle!!"); break; case MOVE_HOVER: mech_notify(mech, MECHALL, "Your lift fan is destroyed, imobilizing your vehicle!!"); break; case MOVE_HULL: case MOVE_SUB: case MOVE_FOIL: mech_notify(mech, MECHALL, "You are halted in your tracks - literally."); } SetMaxSpeed(mech, 0.0); MakeMechFall(mech); } } return side; case 4: /* MP -1 */ if (btechconf.btech_tankshield) { if (!Fallen(mech)) { mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c"); switch (MechMove(mech)) { case MOVE_TRACK: mech_notify(mech, MECHALL, "One of your tracks is damaged!!"); break; case MOVE_WHEEL: mech_notify(mech, MECHALL, "One of your wheels is damaged!!"); break; case MOVE_HOVER: mech_notify(mech, MECHALL, "Your air skirt is damaged!!"); break; case MOVE_HULL: case MOVE_SUB: case MOVE_FOIL: mech_notify(mech, MECHALL, "Your speed slows down.."); break; } LowerMaxSpeed(mech, MP1); } } return side; case 5: /* MP -1 if Hovercraft */ if (!Fallen(mech)) { if (MechMove(mech) == MOVE_HOVER) { mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c"); mech_notify(mech, MECHALL, "Your air skirt is damaged!!"); LowerMaxSpeed(mech, MP1); } } return side; case 6: case 7: case 8: case 9: return side; case 10: return (GetSectInt(mech, TURRET)) ? TURRET : side; case 11: *iscritical = 1; /* Lock turret into place */ if (GetSectInt(mech, TURRET)) { if (!(MechTankCritStatus(mech) & TURRET_LOCKED)) { mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c"); MechTankCritStatus(mech) |= TURRET_LOCKED; mech_notify(mech, MECHALL, "Your turret takes a direct hit and immobilizes!"); } return TURRET; } else return side; case 12: /* A Roll on Determining Critical Hits Table */ if (crittable(mech, (GetSectInt(mech, TURRET)) ? TURRET : side, btechconf.btech_critlevel)) *iscritical = 1; return (GetSectInt(mech, TURRET)) ? TURRET : side; } } break; case CLASS_AERO: switch (hitGroup) { case FRONT: switch (roll) { case 2: case 12: return AERO_COCKPIT; case 3: case 11: if (crittable(mech, AERO_NOSE, 90)) LoseWeapon(mech, AERO_NOSE); return AERO_NOSE; case 4: case 10: if (roll == 10) DestroyBomb(mech, AERO_FUSEL); return AERO_FUSEL; case 5: return AERO_RWING; case 9: return AERO_LWING; case 6: case 7: case 8: return AERO_NOSE; } break; case LEFTSIDE: case RIGHTSIDE: side = ((hitGroup == LEFTSIDE) ? AERO_LWING : AERO_RWING); switch (roll) { case 2: return AERO_COCKPIT; case 12: if (crittable(mech, AERO_ENGINE, 99)) *iscritical = 1; return AERO_ENGINE; case 3: case 11: if (crittable(mech, side, 99)) LoseWeapon(mech, side); return side; case 4: case 10: if (crittable(mech, AERO_ENGINE, 90)) DestroyHeatSink(mech, AERO_ENGINE); return AERO_ENGINE; case 5: DestroyBomb(mech, AERO_FUSEL); return AERO_FUSEL; case 9: return AERO_NOSE; case 6: case 8: return side; case 7: return AERO_FUSEL; } break; case BACK: switch (roll) { case 2: case 12: if (crittable(mech, AERO_ENGINE, 90)) *iscritical = 1; return AERO_ENGINE; case 3: case 11: aero_ControlEffect(mech); return AERO_FUSEL; case 4: case 7: case 10: if (crittable(mech, AERO_FUSEL, 90)) DestroyHeatSink(mech, AERO_FUSEL); return AERO_FUSEL; case 5: return AERO_RWING; case 9: return AERO_LWING; case 6: case 8: return AERO_ENGINE; } } break; case CLASS_DS: case CLASS_SPHEROID_DS: switch (hitGroup) { case FRONT: switch (roll) { case 2: case 12: if (crittable(mech, DS_NOSE, 30)) ds_BridgeHit(mech); return DS_NOSE; case 3: case 11: if (crittable(mech, DS_NOSE, 50)) LoseWeapon(mech, DS_NOSE); return DS_NOSE; case 5: return DS_RWING; case 6: case 7: case 8: return DS_NOSE; case 9: return DS_LWING; case 4: case 10: return (Number(1, 2)) == 1 ? DS_LWING : DS_RWING; } case LEFTSIDE: case RIGHTSIDE: side = (hitGroup == LEFTSIDE) ? DS_LWING : DS_RWING; if (Number(1, 2) == 2) SpheroidToRear(mech, side); switch (roll) { case 2: if (crittable(mech, DS_NOSE, 30)) ds_BridgeHit(mech); return DS_NOSE; case 3: case 11: if (crittable(mech, side, 60)) LoseWeapon(mech, side); return side; case 4: case 5: case 6: case 7: case 8: case 10: return side; case 9: return DS_NOSE; case 12: if (crittable(mech, side, 60)) *iscritical = 1; return side; } case BACK: switch (roll) { case 2: case 12: if (crittable(mech, DS_AFT, 60)) *iscritical = 1; return DS_AFT; case 3: case 11: return DS_AFT; case 4: case 7: case 10: if (crittable(mech, DS_AFT, 60)) DestroyHeatSink(mech, DS_AFT); return DS_AFT; case 5: hitloc = DS_RWING; SpheroidToRear(mech, hitloc); return hitloc; case 6: case 8: return DS_AFT; case 9: hitloc = DS_LWING; SpheroidToRear(mech, hitloc); return hitloc; } } break; case CLASS_VTOL: switch (hitGroup) { case LEFTSIDE: switch (roll) { case 2: hitloc = ROTOR; *iscritical = 1; DoVTOLRotorDestroyedCrit(mech, NULL, 1); break; case 3: *iscritical = 1; break; case 4: case 5: hitloc = ROTOR; DoVTOLRotorDamagedCrit(mech); break; case 6: case 7: case 8: hitloc = LSIDE; break; case 9: /* Destroy Main Weapon but do not destroy armor */ DestroyMainWeapon(mech); hitloc = 0; break; case 10: case 11: hitloc = ROTOR; DoVTOLRotorDamagedCrit(mech); break; case 12: hitloc = ROTOR; *iscritical = 1; DoVTOLRotorDamagedCrit(mech); break; } break; case RIGHTSIDE: switch (roll) { case 2: hitloc = ROTOR; *iscritical = 1; DoVTOLRotorDestroyedCrit(mech, NULL, 1); break; case 3: *iscritical = 1; break; case 4: case 5: hitloc = ROTOR; DoVTOLRotorDamagedCrit(mech); break; case 6: case 7: case 8: hitloc = RSIDE; break; case 9: /* Destroy Main Weapon but do not destroy armor */ DestroyMainWeapon(mech); break; case 10: case 11: hitloc = ROTOR; DoVTOLRotorDamagedCrit(mech); break; case 12: hitloc = ROTOR; *iscritical = 1; DoVTOLRotorDamagedCrit(mech); break; } break; case FRONT: case BACK: side = (hitGroup == FRONT ? FSIDE : BSIDE); switch (roll) { case 2: hitloc = ROTOR; *iscritical = 1; DoVTOLRotorDestroyedCrit(mech, NULL, 1); break; case 3: hitloc = ROTOR; DoVTOLRotorDestroyedCrit(mech, NULL, 1); break; case 4: case 5: hitloc = ROTOR; DoVTOLRotorDamagedCrit(mech); break; case 6: case 7: case 8: case 9: hitloc = side; break; case 10: case 11: hitloc = ROTOR; DoVTOLRotorDamagedCrit(mech); break; case 12: hitloc = ROTOR; *iscritical = 1; DoVTOLRotorDamagedCrit(mech); break; } break; } break; case CLASS_VEH_NAVAL: switch (hitGroup) { case LEFTSIDE: switch (roll) { case 2: hitloc = LSIDE; if (crittable(mech, hitloc, 40)) *iscritical = 1; break; case 3: case 4: case 5: hitloc = LSIDE; break; case 9: hitloc = LSIDE; break; case 10: if (GetSectInt(mech, TURRET)) hitloc = TURRET; else hitloc = LSIDE; break; case 11: if (GetSectInt(mech, TURRET)) { hitloc = TURRET; if (crittable(mech, hitloc, 40)) *iscritical = 1; } else hitloc = LSIDE; break; case 12: hitloc = LSIDE; *iscritical = 1; break; } break; case RIGHTSIDE: switch (roll) { case 2: case 12: hitloc = RSIDE; if (crittable(mech, hitloc, 40)) *iscritical = 1; break; case 3: case 4: case 5: case 6: case 7: case 8: hitloc = RSIDE; break; case 10: if (GetSectInt(mech, TURRET)) hitloc = TURRET; else hitloc = RSIDE; break; case 11: if (GetSectInt(mech, TURRET)) { hitloc = TURRET; if (crittable(mech, hitloc, 40)) *iscritical = 1; } else hitloc = RSIDE; break; } break; case FRONT: case BACK: side = (hitGroup == FRONT ? FSIDE : BSIDE); switch (roll) { case 2: case 12: hitloc = side; if (crittable(mech, hitloc, 40)) *iscritical = 1; break; case 3: hitloc = side; break; case 4: hitloc = side; break; case 5: hitloc = side; break; case 6: case 7: case 8: case 9: hitloc = side; break; case 10: if (GetSectInt(mech, TURRET)) hitloc = TURRET; else hitloc = side; break; case 11: if (GetSectInt(mech, TURRET)) { hitloc = TURRET; *iscritical = 1; } else hitloc = side; break; } break; } break; } return (hitloc); } /* Do L3 FASA motive system crits */ void DoMotiveSystemHit(MECH * mech, int wRollMod) { int wRoll; char strVhlTypeName[30]; wRoll = Roll() + wRollMod; switch (MechMove(mech)) { case MOVE_TRACK: strcpy(strVhlTypeName, "tank"); break; case MOVE_WHEEL: strcpy(strVhlTypeName, "vehicle"); wRoll += 2; break; case MOVE_HOVER: strcpy(strVhlTypeName, "hovercraft"); wRoll += 4; break; case MOVE_HULL: strcpy(strVhlTypeName, "ship"); break; case MOVE_FOIL: strcpy(strVhlTypeName, "hydrofoil"); wRoll += 4; break; case MOVE_SUB: strcpy(strVhlTypeName, "submarine"); break; default: strcpy(strVhlTypeName, "weird unidentifiable toy (warn a wizard!)"); break; } if (wRoll < 8) /* no effect */ return; mech_notify(mech, MECHALL, "%ch%cyCRITICAL HIT!!%c"); if (wRoll < 10) { /* minor effect */ MechPilotSkillBase(mech) += 1; if (Fallen(mech)) mech_notify(mech, MECHALL, "%cr%chYour destroyed motive system takes another hit!%cn"); else mech_notify(mech, MECHALL, tprintf ("%%cr%%chYour motive system takes a minor hit, making it harder to control your %s!%%cn", strVhlTypeName)); if (MechSpeed(mech) != 0.0) MechLOSBroadcast(mech, "wobbles slightly."); } else if (wRoll < 12) { /* moderate effect */ MechPilotSkillBase(mech) += 2; if (Fallen(mech)) mech_notify(mech, MECHALL, "%cr%chYour destroyed motive system takes another hit!%cn"); else mech_notify(mech, MECHALL, tprintf ("%%cr%%chYour motive system takes a moderate hit, slowing you down and making it harder to control your %s!%%cn", strVhlTypeName)); if (MechSpeed(mech) != 0.0) MechLOSBroadcast(mech, "wobbles violently."); LowerMaxSpeed(mech, MP1); correct_speed(mech); } else { if (Fallen(mech)) mech_notify(mech, MECHALL, "%cr%chYour destroyed motive system takes another hit!%cn"); else mech_notify(mech, MECHALL, tprintf ("%%cr%%chYour motive system is destroyed! Your %s can nolonger move!%%cn", strVhlTypeName)); if (MechSpeed(mech) > 0) MechLOSBroadcast(mech, "shakes violently then begins to slow down."); SetMaxSpeed(mech, 0.0); MakeMechFall(mech); correct_speed(mech); } } int FindAdvFasaVehicleHitLocation(MECH * mech, int hitGroup, int *iscritical, int *isrear) { int roll, hitloc = 0; int side; *iscritical = 0; roll = Roll(); if (MechStatus(mech) & COMBAT_SAFE) return 0; if (MechDugIn(mech) && GetSectInt(mech, TURRET) && Number(1, 100) >= 42) return TURRET; rollstat.hitrolls[roll - 2]++; rollstat.tothrolls++; switch (MechType(mech)) { case CLASS_VEH_GROUND: switch (hitGroup) { case LEFTSIDE: case RIGHTSIDE: side = (hitGroup == LEFTSIDE ? LSIDE : RSIDE); switch (roll) { case 2: hitloc = side; *iscritical = 1; break; case 3: hitloc = side; if (crittable(mech, hitloc, btechconf.btech_critlevel)) DoMotiveSystemHit(mech, 0); break; case 4: hitloc = side; break; case 5: hitloc = FSIDE; break; case 6: case 7: case 8: hitloc = side; break; case 9: hitloc = BSIDE; break; case 10: case 11: hitloc = CHECK_ZERO_LOC(mech, TURRET, side); break; case 12: hitloc = CHECK_ZERO_LOC(mech, TURRET, side); *iscritical = 1; break; } break; case FRONT: case BACK: side = (hitGroup == FRONT ? FSIDE : BSIDE); switch (roll) { case 2: hitloc = side; *iscritical = 1; break; case 3: hitloc = side; if (crittable(mech, hitloc, btechconf.btech_critlevel)) DoMotiveSystemHit(mech, 0); break; case 4: hitloc = side; break; case 5: hitloc = (hitGroup == FRONT ? RSIDE : LSIDE); break; case 6: case 7: case 8: hitloc = side; break; case 9: hitloc = (hitGroup == FRONT ? LSIDE : RSIDE); break; case 10: case 11: hitloc = CHECK_ZERO_LOC(mech, TURRET, (hitGroup == FRONT ? LSIDE : RSIDE)); break; case 12: hitloc = CHECK_ZERO_LOC(mech, TURRET, (hitGroup == FRONT ? LSIDE : RSIDE)); *iscritical = 1; break; } break; } break; case CLASS_VTOL: switch (hitGroup) { case LEFTSIDE: case RIGHTSIDE: side = (hitGroup == LEFTSIDE ? LSIDE : RSIDE); switch (roll) { case 2: hitloc = side; *iscritical = 1; break; case 3: case 4: hitloc = side; break; case 5: hitloc = FSIDE; break; case 6: case 7: case 8: hitloc = side; break; case 9: hitloc = BSIDE; break; case 10: case 11: hitloc = ROTOR; break; case 12: hitloc = ROTOR; *iscritical = 1; break; } break; case FRONT: case BACK: side = (hitGroup == FRONT ? FSIDE : BSIDE); switch (roll) { case 2: hitloc = side; *iscritical = 1; break; case 3: hitloc = side; break; case 4: hitloc = side; break; case 5: hitloc = (hitGroup == FRONT ? RSIDE : LSIDE); break; case 6: case 7: case 8: hitloc = side; break; case 9: hitloc = (hitGroup == FRONT ? LSIDE : RSIDE); break; case 10: case 11: hitloc = ROTOR; break; case 12: hitloc = ROTOR; *iscritical = 1; break; } break; } break; } if (!crittable(mech, hitloc, btechconf.btech_critlevel)) *iscritical = 0; return hitloc; } int FindHitLocation(MECH * mech, int hitGroup, int *iscritical, int *isrear) { int roll, hitloc = 0; int side; roll = Roll(); /* We have a varying set of crit charts we can use, so let's see what's been config'd */ switch (MechType(mech)) { case CLASS_VTOL: if (btechconf.btech_fasaadvvtolcrit) return FindAdvFasaVehicleHitLocation(mech, hitGroup, iscritical, isrear); else if (btechconf.btech_fasacrit) return FindFasaHitLocation(mech, hitGroup, iscritical, isrear); break; case CLASS_VEH_GROUND: if (btechconf.btech_fasaadvvhlcrit) return FindAdvFasaVehicleHitLocation(mech, hitGroup, iscritical, isrear); else if (btechconf.btech_fasacrit) return FindFasaHitLocation(mech, hitGroup, iscritical, isrear); break; default: if (btechconf.btech_fasacrit) return FindFasaHitLocation(mech, hitGroup, iscritical, isrear); break; } if (MechStatus(mech) & COMBAT_SAFE) return 0; if (MechDugIn(mech) && GetSectOInt(mech, TURRET) && Number(1, 100) >= 42) return TURRET; rollstat.hitrolls[roll - 2]++; rollstat.tothrolls++; switch (MechType(mech)) { case CLASS_BSUIT: if ((hitloc = get_bsuit_hitloc(mech)) < 0) return Number(0, NUM_BSUIT_MEMBERS - 1); case CLASS_MW: case CLASS_MECH: switch (hitGroup) { case LEFTSIDE: switch (roll) { case 2: if (crittable(mech, LTORSO, 60)) *iscritical = 1; return LTORSO; case 3: return LLEG; case 4: case 5: return LARM; case 6: return LLEG; case 7: return LTORSO; case 8: return CTORSO; case 9: return RTORSO; case 10: return RARM; case 11: return RLEG; case 12: return HEAD; } case RIGHTSIDE: switch (roll) { case 2: if (crittable(mech, RTORSO, 60)) *iscritical = 1; return RTORSO; case 3: return RLEG; case 4: case 5: return RARM; case 6: return RLEG; case 7: return RTORSO; case 8: return CTORSO; case 9: return LTORSO; case 10: return LARM; case 11: return LLEG; case 12: return HEAD; } case FRONT: case BACK: switch (roll) { case 2: if (crittable(mech, CTORSO, 60)) *iscritical = 1; return CTORSO; case 3: case 4: return RARM; case 5: return RLEG; case 6: return RTORSO; case 7: return CTORSO; case 8: return LTORSO; case 9: return LLEG; case 10: case 11: return LARM; case 12: return HEAD; } } break; case CLASS_VEH_GROUND: switch (hitGroup) { case LEFTSIDE: switch (roll) { case 2: case 12: if (crittable(mech, LSIDE, 40)) *iscritical = 1; return LSIDE; case 3: case 4: case 5: case 6: case 7: case 8: case 9: return LSIDE; case 10: return (GetSectInt(mech, TURRET)) ? TURRET : LSIDE; case 11: if (GetSectInt(mech, TURRET)) { if (crittable(mech, TURRET, 50)) *iscritical = 1; return TURRET; } else return LSIDE; } break; case RIGHTSIDE: switch (roll) { case 2: case 12: if (crittable(mech, RSIDE, 40)) *iscritical = 1; return RSIDE; case 3: case 4: case 5: case 6: case 7: case 8: case 9: return RSIDE; case 10: return (GetSectInt(mech, TURRET)) ? TURRET : RSIDE; case 11: if (GetSectInt(mech, TURRET)) { if (crittable(mech, TURRET, 50)) *iscritical = 1; return TURRET; } else return RSIDE; break; } break; case FRONT: case BACK: side = (hitGroup == FRONT ? FSIDE : BSIDE); switch (roll) { case 2: case 12: if (crittable(mech, FSIDE, 40)) *iscritical = 1; return side; case 3: case 4: case 5: case 6: case 7: case 8: case 9: return side; case 10: return (GetSectInt(mech, TURRET)) ? TURRET : side; case 11: if (GetSectInt(mech, TURRET)) { if (crittable(mech, TURRET, 50)) *iscritical = 1; return TURRET; } else return side; } } break; case CLASS_AERO: switch (hitGroup) { case FRONT: switch (roll) { case 2: case 12: return AERO_COCKPIT; case 3: case 11: if (crittable(mech, AERO_NOSE, 90)) LoseWeapon(mech, AERO_NOSE); return AERO_NOSE; case 4: case 10: if (roll == 10) DestroyBomb(mech, AERO_FUSEL); return AERO_FUSEL; case 5: return AERO_RWING; case 9: return AERO_LWING; case 6: case 7: case 8: return AERO_NOSE; } break; case LEFTSIDE: case RIGHTSIDE: side = ((hitGroup == LEFTSIDE) ? AERO_LWING : AERO_RWING); switch (roll) { case 2: return AERO_COCKPIT; case 12: if (crittable(mech, AERO_ENGINE, 99)) *iscritical = 1; return AERO_ENGINE; case 3: case 11: if (crittable(mech, side, 99)) LoseWeapon(mech, side); return side; case 4: case 10: if (crittable(mech, AERO_ENGINE, 90)) DestroyHeatSink(mech, AERO_ENGINE); return AERO_ENGINE; case 5: DestroyBomb(mech, AERO_FUSEL); return AERO_FUSEL; case 9: return AERO_NOSE; case 6: case 8: return side; case 7: return AERO_FUSEL; } break; case BACK: switch (roll) { case 2: case 12: if (crittable(mech, AERO_ENGINE, 90)) *iscritical = 1; return AERO_ENGINE; case 3: case 11: aero_ControlEffect(mech); return AERO_FUSEL; case 4: case 7: case 10: if (crittable(mech, AERO_FUSEL, 90)) DestroyHeatSink(mech, AERO_FUSEL); return AERO_FUSEL; case 5: return AERO_RWING; case 9: return AERO_LWING; case 6: case 8: return AERO_ENGINE; } } break; case CLASS_DS: case CLASS_SPHEROID_DS: switch (hitGroup) { case FRONT: switch (roll) { case 2: case 12: if (crittable(mech, DS_NOSE, 30)) ds_BridgeHit(mech); return DS_NOSE; case 3: case 11: if (crittable(mech, DS_NOSE, 50)) LoseWeapon(mech, DS_NOSE); return DS_NOSE; case 5: return DS_RWING; case 6: case 7: case 8: return DS_NOSE; case 9: return DS_LWING; case 4: case 10: return (Number(1, 2)) == 1 ? DS_LWING : DS_RWING; } case LEFTSIDE: case RIGHTSIDE: side = (hitGroup == LEFTSIDE) ? DS_LWING : DS_RWING; if (Number(1, 2) == 2) SpheroidToRear(mech, side); switch (roll) { case 2: if (crittable(mech, DS_NOSE, 30)) ds_BridgeHit(mech); return DS_NOSE; case 3: case 11: if (crittable(mech, side, 60)) LoseWeapon(mech, side); return side; case 4: case 5: case 6: case 7: case 8: case 10: return side; case 9: return DS_NOSE; case 12: if (crittable(mech, side, 60)) *iscritical = 1; return side; } case BACK: switch (roll) { case 2: case 12: if (crittable(mech, DS_AFT, 60)) *iscritical = 1; return DS_AFT; case 3: case 11: return DS_AFT; case 4: case 7: case 10: if (crittable(mech, DS_AFT, 60)) DestroyHeatSink(mech, DS_AFT); return DS_AFT; case 5: hitloc = DS_RWING; SpheroidToRear(mech, hitloc); return hitloc; case 6: case 8: return DS_AFT; case 9: hitloc = DS_LWING; SpheroidToRear(mech, hitloc); return hitloc; } } break; case CLASS_VTOL: switch (hitGroup) { case LEFTSIDE: switch (roll) { case 2: hitloc = ROTOR; *iscritical = 1; DoVTOLRotorDestroyedCrit(mech, NULL, 1); break; case 3: case 4: hitloc = ROTOR; DoVTOLRotorDamagedCrit(mech); break; case 5: case 6: case 7: case 8: case 9: hitloc = LSIDE; break; case 10: case 11: hitloc = ROTOR; DoVTOLRotorDamagedCrit(mech); break; case 12: hitloc = ROTOR; *iscritical = 1; DoVTOLRotorDamagedCrit(mech); break; } break; case RIGHTSIDE: switch (roll) { case 2: hitloc = ROTOR; *iscritical = 1; DoVTOLRotorDestroyedCrit(mech, NULL, 1); break; case 3: case 4: hitloc = ROTOR; DoVTOLRotorDamagedCrit(mech); break; case 5: case 6: case 7: case 8: case 9: hitloc = RSIDE; break; case 10: case 11: hitloc = ROTOR; DoVTOLRotorDamagedCrit(mech); break; case 12: hitloc = ROTOR; *iscritical = 1; DoVTOLRotorDamagedCrit(mech); break; } break; case FRONT: case BACK: switch (roll) { case 2: hitloc = ROTOR; *iscritical = 1; DoVTOLRotorDestroyedCrit(mech, NULL, 1); break; case 3: case 4: hitloc = ROTOR; DoVTOLRotorDamagedCrit(mech); break; case 5: case 6: case 7: case 8: case 9: hitloc = FSIDE; break; case 10: case 11: hitloc = ROTOR; DoVTOLRotorDamagedCrit(mech); break; case 12: hitloc = ROTOR; *iscritical = 1; DoVTOLRotorDamagedCrit(mech); break; } break; } break; case CLASS_VEH_NAVAL: switch (hitGroup) { case LEFTSIDE: switch (roll) { case 2: hitloc = LSIDE; if (crittable(mech, hitloc, 40)) *iscritical = 1; break; case 3: case 4: case 5: hitloc = LSIDE; break; case 9: hitloc = LSIDE; break; case 10: if (GetSectInt(mech, TURRET)) hitloc = TURRET; else hitloc = LSIDE; break; case 11: if (GetSectInt(mech, TURRET)) { hitloc = TURRET; if (crittable(mech, hitloc, 40)) *iscritical = 1; } else hitloc = LSIDE; break; case 12: hitloc = LSIDE; *iscritical = 1; break; } break; case RIGHTSIDE: switch (roll) { case 2: case 12: hitloc = RSIDE; if (crittable(mech, hitloc, 40)) *iscritical = 1; break; case 3: case 4: case 5: case 6: case 7: case 8: hitloc = RSIDE; break; case 10: if (GetSectInt(mech, TURRET)) hitloc = TURRET; else hitloc = RSIDE; break; case 11: if (GetSectInt(mech, TURRET)) { hitloc = TURRET; if (crittable(mech, hitloc, 40)) *iscritical = 1; } else hitloc = RSIDE; break; } break; case FRONT: case BACK: switch (roll) { case 2: case 12: hitloc = FSIDE; if (crittable(mech, hitloc, 40)) *iscritical = 1; break; case 3: hitloc = FSIDE; break; case 4: hitloc = FSIDE; break; case 5: hitloc = FSIDE; break; case 6: case 7: case 8: case 9: hitloc = FSIDE; break; case 10: if (GetSectInt(mech, TURRET)) hitloc = TURRET; else hitloc = FSIDE; break; case 11: if (GetSectInt(mech, TURRET)) { hitloc = TURRET; *iscritical = 1; } else hitloc = FSIDE; break; } break; } break; } return (hitloc); } int FindAreaHitGroup(MECH * mech, MECH * target) { int quadr; quadr = AcceptableDegree(FindBearing(MechFX(mech), MechFY(mech), MechFX(target), MechFY(target)) - MechFacing(target)); #if 1 if ((quadr >= 135) && (quadr <= 225)) return FRONT; if ((quadr < 45) || (quadr > 315)) return BACK; if ((quadr >= 45) && (quadr < 135)) return LEFTSIDE; return RIGHTSIDE; #else /* These are 'official' BT arcs */ if (quadr >= 120 && quadr <= 240) return FRONT; if (quadr < 30 || quadr > 330) return BACK; if (quadr >= 30 && quadr < 120) return LEFTSIDE; return RIGHTSIDE; #endif } int FindTargetHitLoc(MECH * mech, MECH * target, int *isrear, int *iscritical) { int hitGroup; /* *isrear = 0; */ *iscritical = 0; hitGroup = FindAreaHitGroup(mech, target); if (hitGroup == BACK) *isrear = 1; if (MechType(target) == CLASS_MECH && (MechStatus(target) & PARTIAL_COVER)) return FindPunchLocation(hitGroup); if (MechType(mech) == CLASS_MW && MechType(target) == CLASS_MECH && MechZ(mech) <= MechZ(target)) return FindKickLocation(hitGroup); if (MechType(target) == CLASS_MECH && ((MechType(mech) == CLASS_BSUIT && MechSwarmTarget(mech) == target->mynum))) return FindSwarmHitLocation(iscritical, isrear); return FindHitLocation(target, hitGroup, iscritical, isrear); } int findNARCHitLoc(MECH * mech, MECH * hitMech, int *tIsRearHit) { int tIsRear = 0; int tIsCritical = 0; int wHitLoc = FindTargetHitLoc(mech, hitMech, &tIsRear, &tIsCritical); while (GetSectInt(hitMech, wHitLoc) <= 0) { wHitLoc = TransferTarget(hitMech, wHitLoc); if (wHitLoc < 0) return -1; } *tIsRearHit = 0; if (tIsRear) { if (MechType(hitMech) == CLASS_MECH) *tIsRearHit = 1; else if (wHitLoc == FSIDE) wHitLoc = BSIDE; } return wHitLoc; } int FindTCHitLoc(MECH * mech, MECH * target, int *isrear, int *iscritical) { int hitGroup; *isrear = 0; *iscritical = 0; hitGroup = FindAreaHitGroup(mech, target); if (hitGroup == BACK) *isrear = 1; if (MechAimType(mech) == MechType(target) && Number(1, 6) >= 3) switch (MechType(target)) { case CLASS_MECH: case CLASS_MW: switch (MechAim(mech)) { case RARM: if (hitGroup != LEFTSIDE) return RARM; break; case LARM: if (hitGroup != RIGHTSIDE) return LARM; break; case RLEG: if (hitGroup != LEFTSIDE && !(MechStatus(target) & PARTIAL_COVER)) return RLEG; break; case LLEG: if (hitGroup != RIGHTSIDE && !(MechStatus(target) & PARTIAL_COVER)) return LLEG; break; case RTORSO: if (hitGroup != LEFTSIDE) return RTORSO; break; case LTORSO: if (hitGroup != RIGHTSIDE) return LTORSO; break; case CTORSO: /* if (hitGroup != LEFTSIDE && hitGroup != RIGHTSIDE) */ return CTORSO; case HEAD: if (Immobile(target)) return HEAD; } break; case CLASS_AERO: case CLASS_DS: switch (MechAim(mech)) { case AERO_NOSE: if (hitGroup != BACK) return AERO_NOSE; break; case AERO_LWING: if (hitGroup != RIGHTSIDE) return AERO_LWING; break; case AERO_RWING: if (hitGroup != LEFTSIDE) return AERO_RWING; break; case AERO_COCKPIT: if (hitGroup != BACK) return AERO_COCKPIT; break; case AERO_FUSEL: if (hitGroup != FRONT) return AERO_FUSEL; break; case AERO_ENGINE: if (hitGroup != FRONT) return AERO_ENGINE; break; } case CLASS_VEH_GROUND: case CLASS_VEH_NAVAL: case CLASS_VTOL: switch (MechAim(mech)) { case RSIDE: if (hitGroup != LEFTSIDE) return (RSIDE); break; case LSIDE: if (hitGroup != RIGHTSIDE) return (LSIDE); break; case FSIDE: if (hitGroup != BACK) return (FSIDE); break; case BSIDE: if (hitGroup != FRONT) return (BSIDE); break; case TURRET: return (TURRET); break; } break; } if (MechType(target) == CLASS_MECH && (MechStatus(target) & PARTIAL_COVER)) return FindPunchLocation(hitGroup); return FindHitLocation(target, hitGroup, iscritical, isrear); } int FindAimHitLoc(MECH * mech, MECH * target, int *isrear, int *iscritical) { int hitGroup; *isrear = 0; *iscritical = 0; hitGroup = FindAreaHitGroup(mech, target); if (hitGroup == BACK) *isrear = 1; if (MechType(target) == CLASS_MECH || MechType(target) == CLASS_MW) switch (MechAim(mech)) { case RARM: if (hitGroup != LEFTSIDE) return (RARM); break; case LARM: if (hitGroup != RIGHTSIDE) return (LARM); break; case RLEG: if (hitGroup != LEFTSIDE && !(MechStatus(target) & PARTIAL_COVER)) return (RLEG); break; case LLEG: if (hitGroup != RIGHTSIDE && !(MechStatus(target) & PARTIAL_COVER)) return (LLEG); break; case RTORSO: if (hitGroup != LEFTSIDE) return (RTORSO); break; case LTORSO: if (hitGroup != RIGHTSIDE) return (LTORSO); break; case CTORSO: return (CTORSO); case HEAD: return (HEAD); } else if (is_aero(target)) return MechAim(mech); else switch (MechAim(mech)) { case RSIDE: if (hitGroup != LEFTSIDE) return (RSIDE); break; case LSIDE: if (hitGroup != RIGHTSIDE) return (LSIDE); break; case FSIDE: if (hitGroup != BACK) return (FSIDE); break; case BSIDE: if (hitGroup != FRONT) return (BSIDE); break; case TURRET: return (TURRET); break; } if (MechType(target) == CLASS_MECH && (MechStatus(target) & PARTIAL_COVER)) return FindPunchLocation(hitGroup); return FindHitLocation(target, hitGroup, iscritical, isrear); }
53,641
19,756
#include <cstdio> #include <cstdlib> #define MAX_ELEMENT_COUNT 1000000 using namespace std; int d[MAX_ELEMENT_COUNT]; void qsort(int l, int r) { if (l < r) { int x = d[r]; int j = l - 1; for (int i = l; i <= r; i++) { if (d[i] <= x) { j++; int temp = d[i]; d[i] = d[j]; d[j] = temp; } } qsort(l, j - 1); qsort(j + 1, r); } } int main() { for (int i = 0; i < MAX_ELEMENT_COUNT; i++) { d[i] = rand(); } qsort(0, MAX_ELEMENT_COUNT - 1); for (int i = 0; i < MAX_ELEMENT_COUNT; i++) { printf("%d\n", d[i]); } return 0; }
587
347
/* * RandomSelector.actor.cpp * * This source file is part of the FoundationDB open source project * * Copyright 2013-2018 Apple Inc. and the FoundationDB project 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 "fdbclient/NativeAPI.actor.h" #include "fdbserver/TesterInterface.actor.h" #include "fdbclient/ReadYourWrites.h" #include "fdbserver/workloads/workloads.actor.h" #include "flow/actorcompiler.h" // This must be the last #include. struct RandomSelectorWorkload : TestWorkload { int minOperationsPerTransaction, maxOperationsPerTransaction, maxKeySpace, maxOffset, minInitialAmount, maxInitialAmount; double testDuration; bool fail; vector<Future<Void>> clients; PerfIntCounter transactions, retries; RandomSelectorWorkload(WorkloadContext const& wcx) : TestWorkload(wcx), transactions("Transactions"), retries("Retries") { minOperationsPerTransaction = getOption(options, LiteralStringRef("minOperationsPerTransaction"), 10); maxOperationsPerTransaction = getOption(options, LiteralStringRef("minOperationsPerTransaction"), 50); maxKeySpace = getOption(options, LiteralStringRef("maxKeySpace"), 20); maxOffset = getOption(options, LiteralStringRef("maxOffset"), 5); minInitialAmount = getOption(options, LiteralStringRef("minInitialAmount"), 5); maxInitialAmount = getOption(options, LiteralStringRef("maxInitialAmount"), 10); testDuration = getOption(options, LiteralStringRef("testDuration"), 10.0); fail = false; } std::string description() const override { return "RandomSelector"; } Future<Void> setup(Database const& cx) override { return randomSelectorSetup(cx->clone(), this); } Future<Void> start(Database const& cx) override { clients.push_back(timeout(randomSelectorClient(cx->clone(), this), testDuration, Void())); return delay(testDuration); } Future<bool> check(Database const& cx) override { clients.clear(); return !fail; } void getMetrics(vector<PerfMetric>& m) override { m.push_back(transactions.getMetric()); m.push_back(retries.getMetric()); } ACTOR Future<Void> randomSelectorSetup(Database cx, RandomSelectorWorkload* self) { state Value myValue = StringRef(format("%d", deterministicRandom()->randomInt(0, 10000000))); state Transaction tr(cx); state std::string clientID; clientID = format("%08d", self->clientId); loop { try { for (int i = 0; i < self->maxOffset; i++) { tr.set(StringRef(clientID + "a/" + format("%010d", i)), myValue); tr.set(StringRef(clientID + "c/" + format("%010d", i)), myValue); tr.set(StringRef(clientID + "e/" + format("%010d", i)), myValue); } wait(tr.commit()); break; } catch (Error& e) { wait(tr.onError(e)); tr.reset(); } } return Void(); } ACTOR Future<Void> randomSelectorClient(Database cx, RandomSelectorWorkload* self) { state int i; state int j; state std::string clientID; state std::string myKeyA; state std::string myKeyB; state std::string myValue; state std::string myRandomIDKey; state bool onEqualA; state bool onEqualB; state int offsetA; state int offsetB; state int randomLimit; state int randomByteLimit; state bool reverse; state Error error; clientID = format("%08d", self->clientId); loop { state Transaction tr(cx); loop { try { tr.clear(KeyRangeRef(StringRef(clientID + "b/"), StringRef(clientID + "c/"))); tr.clear(KeyRangeRef(StringRef(clientID + "d/"), StringRef(clientID + "e/"))); for (i = 0; i < deterministicRandom()->randomInt(self->minInitialAmount, self->maxInitialAmount + 1); i++) { myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1)); myValue = format("%d", deterministicRandom()->randomInt(0, 10000000)); tr.set(StringRef(clientID + "b/" + myKeyA), myValue); tr.set(StringRef(clientID + "d/" + myKeyA), myValue); //TraceEvent("RYOWInit").detail("Key",myKeyA).detail("Value",myValue); } wait(tr.commit()); break; } catch (Error& e) { wait(tr.onError(e)); } } state ReadYourWritesTransaction trRYOW(cx); try { for (i = 0; i < deterministicRandom()->randomInt(self->minOperationsPerTransaction, self->maxOperationsPerTransaction + 1); i++) { j = deterministicRandom()->randomInt(0, 16); if (j < 3) { myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1)); myValue = format("%d", deterministicRandom()->randomInt(0, 10000000)); //TraceEvent("RYOWset").detail("Key",myKeyA).detail("Value",myValue); trRYOW.set(StringRef(clientID + "b/" + myKeyA), myValue); loop { try { tr.set(StringRef(clientID + "d/" + myKeyA), myValue); wait(tr.commit()); break; } catch (Error& e) { wait(tr.onError(e)); } } } else if (j < 4) { myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1)); //TraceEvent("RYOWclear").detail("Key",myKeyA); trRYOW.clear(StringRef(clientID + "b/" + myKeyA)); loop { try { tr.clear(StringRef(clientID + "d/" + myKeyA)); wait(tr.commit()); break; } catch (Error& e) { wait(tr.onError(e)); } } } else if (j < 5) { int a = deterministicRandom()->randomInt(1, self->maxKeySpace + 1); int b = deterministicRandom()->randomInt(1, self->maxKeySpace + 1); myKeyA = format("%010d", std::min(a, b) - 1); myKeyB = format("%010d", std::max(a, b)); //TraceEvent("RYOWclearRange").detail("KeyA",myKeyA).detail("KeyB",myKeyB); trRYOW.clear( KeyRangeRef(StringRef(clientID + "b/" + myKeyA), StringRef(clientID + "b/" + myKeyB))); loop { try { tr.clear(KeyRangeRef(StringRef(clientID + "d/" + myKeyA), StringRef(clientID + "d/" + myKeyB))); wait(tr.commit()); break; } catch (Error& e) { wait(tr.onError(e)); } } } else if (j < 6) { myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1)); state Optional<Value> getTest1; Optional<Value> getTest = wait(trRYOW.get(StringRef(clientID + "b/" + myKeyA))); getTest1 = getTest; loop { try { Optional<Value> getTest2 = wait(tr.get(StringRef(clientID + "d/" + myKeyA))); if ((getTest1.present() && (!getTest2.present() || getTest1.get() != getTest2.get())) || (!getTest1.present() && getTest2.present())) { TraceEvent(SevError, "RanSelTestFailure") .detail("Reason", "The get results did not match") .detail("KeyA", myKeyA) .detail("RYOW", getTest1.present() ? printable(getTest1.get()) : "Not Present") .detail("Regular", getTest2.present() ? printable(getTest2.get()) : "Not Present"); self->fail = true; } tr.reset(); break; } catch (Error& e) { wait(tr.onError(e)); tr.reset(); } } } else if (j < 7) { myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1)); myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000)); myValue = format("%d", deterministicRandom()->randomInt(0, 10000000)); //TraceEvent("RYOWadd").detail("Key",myKeyA).detail("Value", "\\x01"); trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::AddValue); loop { try { tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef()); tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::AddValue); wait(tr.commit()); break; } catch (Error& e) { error = e; wait(tr.onError(e)); if (error.code() == error_code_commit_unknown_result) { Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey))); if (thing.present()) break; } } } } else if (j < 8) { myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1)); myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000)); myValue = format("%d", deterministicRandom()->randomInt(0, 10000000)); //TraceEvent("RYOWappendIfFits").detail("Key",myKeyA).detail("Value", myValue); trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::AppendIfFits); loop { try { tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef()); tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::AppendIfFits); wait(tr.commit()); break; } catch (Error& e) { error = e; wait(tr.onError(e)); if (error.code() == error_code_commit_unknown_result) { Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey))); if (thing.present()) break; } } } } else if (j < 9) { myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1)); myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000)); myValue = format("%d", deterministicRandom()->randomInt(0, 10000000)); //TraceEvent("RYOWand").detail("Key",myKeyA).detail("Value", myValue); trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::And); loop { try { tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef()); tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::And); wait(tr.commit()); break; } catch (Error& e) { error = e; wait(tr.onError(e)); if (error.code() == error_code_commit_unknown_result) { Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey))); if (thing.present()) break; } } } } else if (j < 10) { myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1)); myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000)); myValue = format("%d", deterministicRandom()->randomInt(0, 10000000)); //TraceEvent("RYOWor").detail("Key",myKeyA).detail("Value", myValue); trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::Or); loop { try { tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef()); tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::Or); wait(tr.commit()); break; } catch (Error& e) { error = e; wait(tr.onError(e)); if (error.code() == error_code_commit_unknown_result) { Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey))); if (thing.present()) break; } } } } else if (j < 11) { myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1)); myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000)); myValue = format("%d", deterministicRandom()->randomInt(0, 10000000)); //TraceEvent("RYOWxor").detail("Key",myKeyA).detail("Value", myValue); trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::Xor); loop { try { tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef()); tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::Xor); wait(tr.commit()); break; } catch (Error& e) { error = e; wait(tr.onError(e)); if (error.code() == error_code_commit_unknown_result) { Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey))); if (thing.present()) break; } } } } else if (j < 12) { myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1)); myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000)); myValue = format("%d", deterministicRandom()->randomInt(0, 10000000)); //TraceEvent("RYOWmax").detail("Key",myKeyA).detail("Value", myValue); trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::Max); loop { try { tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef()); tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::Max); wait(tr.commit()); break; } catch (Error& e) { error = e; wait(tr.onError(e)); if (error.code() == error_code_commit_unknown_result) { Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey))); if (thing.present()) break; } } } } else if (j < 13) { myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1)); myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000)); myValue = format("%d", deterministicRandom()->randomInt(0, 10000000)); //TraceEvent("RYOWmin").detail("Key",myKeyA).detail("Value", myValue); trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::Min); loop { try { tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef()); tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::Min); wait(tr.commit()); break; } catch (Error& e) { error = e; wait(tr.onError(e)); if (error.code() == error_code_commit_unknown_result) { Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey))); if (thing.present()) break; } } } } else if (j < 14) { myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1)); myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000)); myValue = format("%d", deterministicRandom()->randomInt(0, 10000000)); //TraceEvent("RYOWbytemin").detail("Key",myKeyA).detail("Value", myValue); trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::ByteMin); loop { try { tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef()); tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::ByteMin); wait(tr.commit()); break; } catch (Error& e) { error = e; wait(tr.onError(e)); if (error.code() == error_code_commit_unknown_result) { Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey))); if (thing.present()) break; } } } } else if (j < 15) { myKeyA = format("%010d", deterministicRandom()->randomInt(0, self->maxKeySpace + 1)); myRandomIDKey = format("%010d", deterministicRandom()->randomInt(0, 1000000000)); myValue = format("%d", deterministicRandom()->randomInt(0, 10000000)); //TraceEvent("RYOWbytemax").detail("Key",myKeyA).detail("Value", myValue); trRYOW.atomicOp(StringRef(clientID + "b/" + myKeyA), myValue, MutationRef::ByteMax); loop { try { tr.set(StringRef(clientID + "z/" + myRandomIDKey), StringRef()); tr.atomicOp(StringRef(clientID + "d/" + myKeyA), myValue, MutationRef::ByteMax); wait(tr.commit()); break; } catch (Error& e) { error = e; wait(tr.onError(e)); if (error.code() == error_code_commit_unknown_result) { Optional<Value> thing = wait(tr.get(StringRef(clientID + "z/" + myRandomIDKey))); if (thing.present()) break; } } } } else { int a = deterministicRandom()->randomInt(1, self->maxKeySpace + 1); int b = deterministicRandom()->randomInt(1, self->maxKeySpace + 1); myKeyA = format("%010d", std::min(a, b) - 1); myKeyB = format("%010d", std::max(a, b)); onEqualA = deterministicRandom()->randomInt(0, 2) != 0; onEqualB = deterministicRandom()->randomInt(0, 2) != 0; offsetA = deterministicRandom()->randomInt(-1 * self->maxOffset / 2, self->maxOffset / 2); offsetB = deterministicRandom()->randomInt(-1 * self->maxOffset / 2, self->maxOffset / 2); randomLimit = deterministicRandom()->randomInt(0, 2 * self->maxOffset + self->maxKeySpace); randomByteLimit = deterministicRandom()->randomInt(0, (self->maxOffset + self->maxKeySpace) * 512); reverse = deterministicRandom()->random01() > 0.5 ? false : true; //TraceEvent("RYOWgetRange").detail("KeyA", myKeyA).detail("KeyB", myKeyB).detail("OnEqualA",onEqualA).detail("OnEqualB",onEqualB).detail("OffsetA",offsetA).detail("OffsetB",offsetB).detail("RandomLimit",randomLimit).detail("RandomByteLimit", randomByteLimit).detail("Reverse", reverse); state Standalone<RangeResultRef> getRangeTest1; Standalone<RangeResultRef> getRangeTest = wait(trRYOW.getRange(KeySelectorRef(StringRef(clientID + "b/" + myKeyA), onEqualA, offsetA), KeySelectorRef(StringRef(clientID + "b/" + myKeyB), onEqualB, offsetB), randomLimit, false, reverse)); getRangeTest1 = getRangeTest; loop { try { Standalone<RangeResultRef> getRangeTest2 = wait( tr.getRange(KeySelectorRef(StringRef(clientID + "d/" + myKeyA), onEqualA, offsetA), KeySelectorRef(StringRef(clientID + "d/" + myKeyB), onEqualB, offsetB), randomLimit, false, reverse)); bool fail = false; if (getRangeTest1.size() != getRangeTest2.size()) { TraceEvent(SevError, "RanSelTestFailure") .detail("Reason", "The getRange results did not match sizes") .detail("Size1", getRangeTest1.size()) .detail("Size2", getRangeTest2.size()) .detail("Limit", randomLimit) .detail("ByteLimit", randomByteLimit) .detail("Bytes1", getRangeTest1.expectedSize()) .detail("Bytes2", getRangeTest2.expectedSize()) .detail("Reverse", reverse); fail = true; self->fail = true; } for (int k = 0; k < std::min(getRangeTest1.size(), getRangeTest2.size()); k++) { if (getRangeTest1[k].value != getRangeTest2[k].value) { std::string keyA = printable(getRangeTest1[k].key); std::string valueA = printable(getRangeTest1[k].value); std::string keyB = printable(getRangeTest2[k].key); std::string valueB = printable(getRangeTest2[k].value); TraceEvent(SevError, "RanSelTestFailure") .detail("Reason", "The getRange results did not match contents") .detail("KeyA", keyA) .detail("ValueA", valueA) .detail("KeyB", keyB) .detail("ValueB", valueB) .detail("Reverse", reverse); fail = true; self->fail = true; } } if (fail) { std::string outStr1 = ""; for (int k = 0; k < getRangeTest1.size(); k++) { outStr1 = outStr1 + printable(getRangeTest1[k].key) + " " + format("%d", getRangeTest1[k].value.size()) + " "; } std::string outStr2 = ""; for (int k = 0; k < getRangeTest2.size(); k++) { outStr2 = outStr2 + printable(getRangeTest2[k].key) + " " + format("%d", getRangeTest2[k].value.size()) + " "; } TraceEvent("RanSelTestLog").detail("RYOW", outStr1).detail("Normal", outStr2); } tr.reset(); break; } catch (Error& e) { wait(tr.onError(e)); } } } } wait(trRYOW.commit()); ++self->transactions; state Transaction finalTransaction(cx); loop { try { state Standalone<RangeResultRef> finalTest1 = wait(finalTransaction.getRange( KeyRangeRef(StringRef(clientID + "b/"), StringRef(clientID + "c/")), self->maxKeySpace)); Standalone<RangeResultRef> finalTest2 = wait(finalTransaction.getRange( KeyRangeRef(StringRef(clientID + "d/"), StringRef(clientID + "e/")), self->maxKeySpace)); if (finalTest1.size() != finalTest2.size()) { TraceEvent(SevError, "RanSelTestFailure") .detail("Reason", "The final results did not match sizes"); self->fail = true; } for (int k = 0; k < finalTest1.size(); k++) if (finalTest1[k].value != finalTest2[k].value) { TraceEvent(SevError, "RanSelTestFailure") .detail("Reason", "The final results did not match contents") .detail("KeyA", printable(finalTest1[k].key)) .detail("ValueA", printable(finalTest1[k].value)) .detail("KeyB", printable(finalTest2[k].key)) .detail("ValueB", printable(finalTest2[k].value)) .detail("Reverse", reverse); self->fail = true; } break; } catch (Error& e) { wait(finalTransaction.onError(e)); } } } catch (Error& e) { wait(trRYOW.onError(e)); ++self->retries; } } } }; WorkloadFactory<RandomSelectorWorkload> RandomSelectorWorkloadFactory("RandomSelector");
22,255
9,939
#include "gtest/gtest.h" #include "../vsearch/distance.h" #include "../vsearch/vsearch.pb.h" #include <iostream> #include <fstream> #include <string> class DistanceTest : public testing::Test { }; TEST(DistanceTest, DistanceTest_L2_Test_Far) { float pX[] = {1.3, 1.3}; float pY[] = {6.6, 6.2}; float r = vsearch::Distance::ComputeL2Distance(pX, pY, 2); EXPECT_FLOAT_EQ(r, 52.1); } TEST(DistanceTest, DistanceTest_L2_Test_Close) { float pX[] = {1.3, 1.3}; float pY[] = {1.29, 1.28}; float r = vsearch::Distance::ComputeL2Distance(pX, pY, 2); EXPECT_FLOAT_EQ(r, 0.00049999903); } TEST(DistanceTest, DistanceTest_Cosine_Test_Far) { float pX[] = {1.3, 1.3}; float pY[] = {6.6, 6.2}; float r = vsearch::Distance::ComputeCosineDistance(pX, pY, 2); EXPECT_FLOAT_EQ(r, -15.639999); } TEST(DistanceTest, DistanceTest_Cosine_Test_Close) { float pX[] = {1.3, 1.3}; float pY[] = {1.29, 1.28}; float r = vsearch::Distance::ComputeCosineDistance(pX, pY, 2); EXPECT_FLOAT_EQ(r, -2.3409998); } TEST(DistanceTest, DistanceTest_Cosine_Test_S2D_Far) { float pX[] = {1.3, 1.3}; float pY[] = {6.6, 6.2}; float r = vsearch::Distance::ComputeCosineDistance(pX, pY, 2); EXPECT_FLOAT_EQ(vsearch::Distance::ConvertCosineSimilarityToDistance(r), 16.639999); } TEST(DistanceTest, DistanceTest_Cosine_Test_S2D_Close) { float pX[] = {1.3, 1.3}; float pY[] = {1.29, 1.28}; float r = vsearch::Distance::ComputeCosineDistance(pX, pY, 2); EXPECT_FLOAT_EQ(vsearch::Distance::ConvertCosineSimilarityToDistance(r), 3.3409998); } TEST(DistanceTest, DistanceTest_L2_Test_Tensor) { vsearch::Index i; std::ifstream file; std::string s = std::string("/home/xjdr/src/xjdr/vectorsearch/tests/tensor.txt"); file.open(s.c_str(), std::fstream::in); if(!i.ParseFromIstream(&file)) { std::cerr << "Boooo" << std::endl; } float pX[i.index(0).size()]; float pY[i.index(1).size()]; std::memcpy(pX, i.index(0).data().c_str(), sizeof(float) * i.index(0).size()); std::memcpy(pY, i.index(1).data().c_str(), sizeof(float) * i.index(1).size()); float r = vsearch::Distance::ComputeL2Distance(pX, pY, i.index(0).size()); EXPECT_FLOAT_EQ(r, 369.71799); } TEST(DistanceTest, DistanceTest_Cosine_Test_Tensor) { vsearch::Index i; std::ifstream file; std::string s = std::string("/home/xjdr/src/xjdr/vectorsearch/tests/tensor.txt"); file.open(s.c_str(), std::fstream::in); if(!i.ParseFromIstream(&file)) { std::cerr << "Boooo" << std::endl; } float pX[i.index(0).size()]; float pY[i.index(1).size()]; std::memcpy(pX, i.index(0).data().c_str(), sizeof(float) * i.index(0).size()); std::memcpy(pY, i.index(1).data().c_str(), sizeof(float) * i.index(1).size()); float r = vsearch::Distance::ComputeCosineDistance(pX, pY, i.index(0).size()); EXPECT_FLOAT_EQ(r, -1435.8535); } TEST(DistanceTest, DistanceTest_CosineDistance_Test_Tensor) { vsearch::Index i; std::ifstream file; std::string s = std::string("/home/xjdr/src/xjdr/vectorsearch/tests/tensor.txt"); file.open(s.c_str(), std::fstream::in); if (!i.ParseFromIstream(&file)) { std::cerr << "Boooo" << std::endl; } float pX[i.index(0).size()]; float pY[i.index(1).size()]; std::memcpy(pX, i.index(0).data().c_str(), sizeof(float) * i.index(0).size()); std::memcpy(pY, i.index(1).data().c_str(), sizeof(float) * i.index(1).size()); float r = vsearch::Distance::ComputeCosineDistance(pX, pY, i.index(0).size()); EXPECT_FLOAT_EQ(vsearch::Distance::ConvertCosineSimilarityToDistance(r), 1436.8535); }
3,532
1,617
// XBrowseForFolder.cpp Version 1.2 // // Author: Hans Dietrich // hdietrich@gmail.com // // Description: // XBrowseForFolder.cpp implements XBrowseForFolder(), a function that // wraps SHBrowseForFolder(). // // History // Version 1.2 - 2008 February 29 // - Changed API to allow for initial CSIDL. // - Added option to set dialog caption, suggested by SimpleDivX. // - Added option to set root, suggested by Jean-Michel Reghem. // // Version 1.1 - 2003 September 29 (not released) // - Added support for edit box // // Version 1.0 - 2003 September 25 // - Initial public release // // License: // This software is released into the public domain. You are free to use // it in any way you like, except that you may not sell this source code. // // This software is provided "as is" with no expressed or implied warranty. // I accept no liability for any damage or loss of business that this // software may cause. // /////////////////////////////////////////////////////////////////////////////// /* Make sure we get the right version */ #define _WIN32_IE 0x0500 #ifndef __AFX_H__ #include <windows.h> #include <tchar.h> #endif #include <Shlobj.h> #include <io.h> #include "XBrowseForFolder.h" #ifndef __MINGW32__ #pragma warning(disable: 4127) // conditional expression is constant (_ASSERTE) #pragma warning(disable : 4996) // disable bogus deprecation warning #endif /* MingW does not have this */ #if !defined(BIF_NONEWFOLDERBUTTON) # define BIF_NONEWFOLDERBUTTON 0x200 #endif //============================================================================= // struct to pass to callback function //============================================================================= struct FOLDER_PROPS { LPCTSTR lpszTitle; LPCTSTR lpszInitialFolder; UINT ulFlags; }; #ifndef __AFX_H__ /////////////////////////////////////////////////////////////////////////////// // CRect - a minimal CRect class class CRect : public tagRECT { public: //CRect() { } CRect(int l = 0, int t = 0, int r = 0, int b = 0) { left = l; top = t; right = r; bottom = b; } int Width() const { return right - left; } int Height() const { return bottom - top; } void SwapLeftRight() { SwapLeftRight(LPRECT(this)); } static void SwapLeftRight(LPRECT lpRect) { LONG temp = lpRect->left; lpRect->left = lpRect->right; lpRect->right = temp; } operator LPRECT() { return this; } }; #endif /////////////////////////////////////////////////////////////////////////////// // ScreenToClientX - helper function in case non-MFC static void ScreenToClientX(HWND hWnd, LPRECT lpRect) { ::ScreenToClient(hWnd, (LPPOINT)lpRect); ::ScreenToClient(hWnd, ((LPPOINT)lpRect)+1); } /////////////////////////////////////////////////////////////////////////////// // MoveWindowX - helper function in case non-MFC static void MoveWindowX(HWND hWnd, CRect& rect, BOOL bRepaint) { ::MoveWindow(hWnd, rect.left, rect.top, rect.Width(), rect.Height(), bRepaint); } /////////////////////////////////////////////////////////////////////////////// // SizeBrowseDialog - resize dialog, move controls static void SizeBrowseDialog(HWND hWnd, FOLDER_PROPS *fp) { // find the folder tree and make dialog larger HWND hwndTree = FindWindowEx(hWnd, NULL, TEXT("SysTreeView32"), NULL); if (!hwndTree) { // ... this usually means that BIF_NEWDIALOGSTYLE is enabled. // Then the class name is as used in the code below. hwndTree = FindWindowEx(hWnd, NULL, TEXT("SHBrowseForFolder ShellNameSpace Control"), NULL); } CRect rectDlg; if (hwndTree) { // check if edit box int nEditHeight = 0; HWND hwndEdit = FindWindowEx(hWnd, NULL, TEXT("Edit"), NULL); CRect rectEdit; if (hwndEdit && (fp->ulFlags & BIF_EDITBOX)) { ::GetWindowRect(hwndEdit, &rectEdit); ScreenToClientX(hWnd, &rectEdit); nEditHeight = rectEdit.Height(); } else if (hwndEdit) { ::MoveWindow(hwndEdit, 20000, 20000, 10, 10, FALSE); ::ShowWindow(hwndEdit, SW_HIDE); hwndEdit = 0; } // make the dialog larger ::GetWindowRect(hWnd, &rectDlg); rectDlg.right += 40; rectDlg.bottom += 30; if (hwndEdit) rectDlg.bottom += nEditHeight + 5; MoveWindowX(hWnd, rectDlg, TRUE); ::GetClientRect(hWnd, &rectDlg); int hMargin = 10; int vMargin = 10; // check if new dialog style - this means that there will be a resizing // grabber in lower right corner if (fp->ulFlags & BIF_NEWDIALOGSTYLE) hMargin = ::GetSystemMetrics(SM_CXVSCROLL); // move the Cancel button CRect rectCancel; HWND hwndCancel = ::GetDlgItem(hWnd, IDCANCEL); if (hwndCancel) ::GetWindowRect(hwndCancel, &rectCancel); ScreenToClientX(hWnd, &rectCancel); int h = rectCancel.Height(); int w = rectCancel.Width(); rectCancel.bottom = rectDlg.bottom - vMargin;//nMargin; rectCancel.top = rectCancel.bottom - h; rectCancel.right = rectDlg.right - hMargin; //(scrollWidth + 2*borderWidth); rectCancel.left = rectCancel.right - w; if (hwndCancel) { MoveWindowX(hwndCancel, rectCancel, FALSE); } // move the OK button CRect rectOK(0, 0, 0, 0); HWND hwndOK = ::GetDlgItem(hWnd, IDOK); if (hwndOK) ::GetWindowRect(hwndOK, &rectOK); ScreenToClientX(hWnd, &rectOK); rectOK.bottom = rectCancel.bottom; rectOK.top = rectCancel.top; rectOK.right = rectCancel.left - 10; rectOK.left = rectOK.right - w; if (hwndOK) { MoveWindowX(hwndOK, rectOK, FALSE); } // expand the folder tree to fill the dialog CRect rectTree; ::GetWindowRect(hwndTree, &rectTree); ScreenToClientX(hWnd, &rectTree); if (hwndEdit) { rectEdit.left = hMargin; rectEdit.right = rectDlg.right - hMargin; rectEdit.top = vMargin; rectEdit.bottom = rectEdit.top + nEditHeight; MoveWindowX(hwndEdit, rectEdit, FALSE); rectTree.top = rectEdit.bottom + 5; } else { rectTree.top = vMargin; } rectTree.left = hMargin; rectTree.bottom = rectOK.top - 10;//nMargin; rectTree.right = rectDlg.right - hMargin; MoveWindowX(hwndTree, rectTree, FALSE); } } #ifdef AEROGLASS extern "C" { /* Include necessary variables and prototypes from dw.c */ extern int _DW_DARK_MODE_SUPPORTED; extern int _DW_DARK_MODE_ENABLED; extern BOOL (WINAPI * _DW_ShouldAppsUseDarkMode)(VOID); BOOL _DW_IsHighContrast(VOID); BOOL _DW_IsColorSchemeChangeMessage(LPARAM lParam); void _DW_RefreshTitleBarThemeColor(HWND window); BOOL CALLBACK _dw_set_child_window_theme(HWND window, LPARAM lParam); } #endif /////////////////////////////////////////////////////////////////////////////// // BrowseCallbackProc - SHBrowseForFolder callback function static int CALLBACK BrowseCallbackProc(HWND hWnd, // Window handle to the browse dialog box UINT uMsg, // Value identifying the event LPARAM lParam, // Value dependent upon the message LPARAM lpData) // Application-defined value that was // specified in the lParam member of the // BROWSEINFO structure { switch (uMsg) { #ifdef AEROGLASS case WM_SETTINGCHANGE: { if(_DW_DARK_MODE_SUPPORTED && _DW_IsColorSchemeChangeMessage(lpData)) { _DW_DARK_MODE_ENABLED = _DW_ShouldAppsUseDarkMode() && !_DW_IsHighContrast(); _DW_RefreshTitleBarThemeColor(hWnd); _dw_set_child_window_theme(hWnd, 0); EnumChildWindows(hWnd, _dw_set_child_window_theme, 0); } } break; #endif case BFFM_INITIALIZED: // sent when the browse dialog box has finished initializing. { // remove context help button from dialog caption LONG lStyle = ::GetWindowLong(hWnd, GWL_STYLE); lStyle &= ~DS_CONTEXTHELP; ::SetWindowLong(hWnd, GWL_STYLE, lStyle); lStyle = ::GetWindowLong(hWnd, GWL_EXSTYLE); lStyle &= ~WS_EX_CONTEXTHELP; ::SetWindowLong(hWnd, GWL_EXSTYLE, lStyle); FOLDER_PROPS *fp = (FOLDER_PROPS *) lpData; if (fp) { if (fp->lpszInitialFolder && fp->lpszInitialFolder[0]) { // set initial directory ::SendMessage(hWnd, BFFM_SETSELECTION, TRUE, (LPARAM)fp->lpszInitialFolder); } if (fp->lpszTitle && fp->lpszTitle[0]) { // set window caption ::SetWindowText(hWnd, fp->lpszTitle); } } #ifdef AEROGLASS if(_DW_DARK_MODE_SUPPORTED) { _dw_set_child_window_theme(hWnd, 0); EnumChildWindows(hWnd, _dw_set_child_window_theme, 0); _DW_RefreshTitleBarThemeColor(hWnd); } #endif SizeBrowseDialog(hWnd, fp); } break; case BFFM_SELCHANGED: // sent when the selection has changed { TCHAR szDir[MAX_PATH*2] = { 0 }; // fail if non-filesystem BOOL bRet = SHGetPathFromIDList((LPITEMIDLIST) lParam, szDir); if (bRet) { // fail if folder not accessible if (_taccess(szDir, 00) != 0) { bRet = FALSE; } else { SHFILEINFO sfi; ::SHGetFileInfo((LPCTSTR)lParam, 0, &sfi, sizeof(sfi), SHGFI_PIDL | SHGFI_ATTRIBUTES); // fail if pidl is a link if (sfi.dwAttributes & SFGAO_LINK) { bRet = FALSE; } } } // if invalid selection, disable the OK button if (!bRet) { ::EnableWindow(GetDlgItem(hWnd, IDOK), FALSE); } } break; } return 0; } /////////////////////////////////////////////////////////////////////////////// // // XBrowseForFolder() // // Purpose: Invoke the SHBrowseForFolder API. If lpszInitialFolder is // supplied, it will be the folder initially selected in the tree // folder list. Otherwise, the initial folder will be set to the // current directory. The selected folder will be returned in // lpszBuf. // // Parameters: hWnd - handle to the owner window for the dialog // lpszInitialFolder - initial folder in tree; if NULL, the initial // folder will be the current directory; if // if this is a CSIDL, must be a real folder. // nRootFolder - optional CSIDL of root folder for tree; // -1 = use default. // lpszCaption - optional caption for folder dialog // lpszBuf - buffer for the returned folder path // dwBufSize - size of lpszBuf in TCHARs // bEditBox - TRUE = include edit box in dialog // // Returns: BOOL - TRUE = success; FALSE = user hit Cancel // BOOL _cdecl XBrowseForFolder(HWND hWnd, LPCTSTR lpszInitialFolder, int nRootFolder, LPCTSTR lpszCaption, LPTSTR lpszBuf, DWORD dwBufSize, BOOL bEditBox /*= FALSE*/) { if (lpszBuf == NULL || dwBufSize < MAX_PATH) return FALSE; ZeroMemory(lpszBuf, dwBufSize*sizeof(TCHAR)); BROWSEINFO bi = { 0 }; // check if there is a special root folder LPITEMIDLIST pidlRoot = NULL; if (nRootFolder != -1) { if (SUCCEEDED(SHGetSpecialFolderLocation(hWnd, nRootFolder, &pidlRoot))) bi.pidlRoot = pidlRoot; } TCHAR szInitialPath[MAX_PATH*2] = { 0 }; if (lpszInitialFolder) { // is this a folder path string or a csidl? if (HIWORD(lpszInitialFolder) == 0) { // csidl int nFolder = LOWORD((UINT)(UINT_PTR)lpszInitialFolder); SHGetSpecialFolderPath(hWnd, szInitialPath, nFolder, FALSE); } else { // string _tcsncpy(szInitialPath, lpszInitialFolder, sizeof(szInitialPath)/sizeof(TCHAR)-2); } } if (!szInitialPath[0] && !bi.pidlRoot) { // no initial folder and no root, set to current directory ::GetCurrentDirectory(sizeof(szInitialPath)/sizeof(TCHAR)-2, szInitialPath); } FOLDER_PROPS fp; bi.hwndOwner = hWnd; bi.ulFlags = BIF_RETURNONLYFSDIRS; // do NOT use BIF_NEWDIALOGSTYLE, // or BIF_STATUSTEXT if (bEditBox) bi.ulFlags |= BIF_EDITBOX; bi.ulFlags |= BIF_NONEWFOLDERBUTTON; bi.lpfn = BrowseCallbackProc; bi.lParam = (LPARAM) &fp; fp.lpszInitialFolder = szInitialPath; fp.lpszTitle = lpszCaption; fp.ulFlags = bi.ulFlags; BOOL bRet = FALSE; LPITEMIDLIST pidlFolder = SHBrowseForFolder(&bi); if (pidlFolder) { TCHAR szBuffer[MAX_PATH*2] = { 0 }; if (SHGetPathFromIDList(pidlFolder, szBuffer)) { _tcsncpy(lpszBuf, szBuffer, dwBufSize-1); bRet = TRUE; } } // free up pidls IMalloc *pMalloc = NULL; if (SUCCEEDED(SHGetMalloc(&pMalloc)) && pMalloc) { if (pidlFolder) pMalloc->Free(pidlFolder); if (pidlRoot) pMalloc->Free(pidlRoot); pMalloc->Release(); } return bRet; }
12,887
5,210
// Copyright 2017 Fonero Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "lib/catch.hpp" #include "util/types.h" using namespace fonero; bool addBalance(int64_t balance, int64_t delta, int64_t resultBalance, int64_t maxBalance = std::numeric_limits<int64_t>::max()) { auto r = fonero::addBalance(balance, delta, maxBalance); REQUIRE(balance == resultBalance); return r; } TEST_CASE("balance", "[balance]") { auto const max = std::numeric_limits<int64_t>::max(); auto const min = std::numeric_limits<int64_t>::min(); REQUIRE(addBalance(0, 0, 0)); REQUIRE(addBalance(0, 10, 10)); REQUIRE(addBalance(10, 0, 10)); REQUIRE(addBalance(10, 10, 20)); REQUIRE(!addBalance(0, -5, 0)); REQUIRE(addBalance(10, -10, 0)); REQUIRE(addBalance(10, -9, 1)); REQUIRE(!addBalance(10, -11, 10)); REQUIRE(!addBalance(5, 5, 5, 9)); REQUIRE(!addBalance(0, 1, 0, 0)); REQUIRE(addBalance(0, 1, 1, max)); REQUIRE(!addBalance(0, max, 0, 0)); REQUIRE(addBalance(0, max, max, max)); REQUIRE(!addBalance(max, 1, max, 0)); REQUIRE(!addBalance(max, 1, max, max)); REQUIRE(!addBalance(max, max, max, 0)); REQUIRE(!addBalance(max, max, max, max)); REQUIRE(!addBalance(0, -1, 0, 0)); REQUIRE(!addBalance(0, -1, 0, max)); REQUIRE(!addBalance(0, min, 0, 0)); REQUIRE(!addBalance(0, -max, 0, 0)); REQUIRE(!addBalance(0, min, 0, max)); REQUIRE(!addBalance(0, -max, 0, max)); REQUIRE(!addBalance(max, -1, max, 0)); REQUIRE(addBalance(max, -1, max - 1, max)); REQUIRE(!addBalance(max, min, max, 0)); REQUIRE(addBalance(max, -max, 0, 0)); REQUIRE(!addBalance(max, min, max, max)); REQUIRE(addBalance(max, -max, 0, max)); }
1,892
859
/* for High Granularity Calorimeter * This geometry is essentially driven by topology, * which is thus encapsulated in this class. * This makes this geometry not suitable to be loaded * by regular CaloGeometryLoader<T> */ #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/Utilities/interface/Exception.h" #include "DataFormats/GeometrySurface/interface/Plane.h" #include "Geometry/HGCalGeometry/interface/HGCalGeometry.h" #include "Geometry/CaloGeometry/interface/CaloGenericDetId.h" #include "Geometry/CaloGeometry/interface/CaloCellGeometry.h" #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "TrackingTools/GeomPropagators/interface/AnalyticalPropagator.h" #include <cmath> #include <Math/Transform3D.h> #include <Math/EulerAngles.h> typedef CaloCellGeometry::Tr3D Tr3D; typedef std::vector<float> ParmVec; //#define EDM_ML_DEBUG HGCalGeometry::HGCalGeometry(const HGCalTopology& topology_) : m_topology(topology_), m_validGeomIds(topology_.totalGeomModules()), mode_(topology_.geomMode()), m_det(topology_.detector()), m_subdet(topology_.subDetector()), twoBysqrt3_(2.0 / std::sqrt(3.0)) { if (m_det == DetId::HGCalHSc) { m_cellVec2 = CellVec2(topology_.totalGeomModules()); } else { m_cellVec = CellVec(topology_.totalGeomModules()); } m_validIds.reserve(m_topology.totalModules()); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "Expected total # of Geometry Modules " << m_topology.totalGeomModules(); #endif } HGCalGeometry::~HGCalGeometry() {} void HGCalGeometry::fillNamedParams(DDFilteredView fv) {} void HGCalGeometry::initializeParms() {} void HGCalGeometry::localCorners(Pt3DVec& lc, const CCGFloat* pv, unsigned int i, Pt3D& ref) { if (m_det == DetId::HGCalHSc) { FlatTrd::localCorners(lc, pv, ref); } else { FlatHexagon::localCorners(lc, pv, ref); } } void HGCalGeometry::newCell( const GlobalPoint& f1, const GlobalPoint& f2, const GlobalPoint& f3, const CCGFloat* parm, const DetId& detId) { DetId geomId = getGeometryDetId(detId); int cells(0); HGCalTopology::DecodedDetId id = m_topology.decode(detId); if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) { cells = m_topology.dddConstants().numberCellsHexagon(id.iSec1); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "NewCell " << HGCalDetId(detId) << " GEOM " << HGCalDetId(geomId); #endif } else if (mode_ == HGCalGeometryMode::Trapezoid) { cells = 1; #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "NewCell " << HGCScintillatorDetId(detId) << " GEOM " << HGCScintillatorDetId(geomId); #endif } else { cells = m_topology.dddConstants().numberCellsHexagon(id.iLay, id.iSec1, id.iSec2, false); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "NewCell " << HGCSiliconDetId(detId) << " GEOM " << HGCSiliconDetId(geomId); #endif } const uint32_t cellIndex(m_topology.detId2denseGeomId(geomId)); if (m_det == DetId::HGCalHSc) { m_cellVec2.at(cellIndex) = FlatTrd(cornersMgr(), f1, f2, f3, parm); } else { m_cellVec.at(cellIndex) = FlatHexagon(cornersMgr(), f1, f2, f3, parm); } m_validGeomIds.at(cellIndex) = geomId; #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "Store for DetId " << std::hex << detId.rawId() << " GeomId " << geomId.rawId() << std::dec << " Index " << cellIndex << " cells " << cells; unsigned int nOld = m_validIds.size(); #endif if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) { for (int cell = 0; cell < cells; ++cell) { id.iCell1 = cell; DetId idc = m_topology.encode(id); if (m_topology.valid(idc)) { m_validIds.emplace_back(idc); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "Valid Id [" << cell << "] " << HGCalDetId(idc); #endif } } } else if (mode_ == HGCalGeometryMode::Trapezoid) { DetId idc = m_topology.encode(id); if (m_topology.valid(idc)) { m_validIds.emplace_back(idc); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "Valid Id [0] " << HGCScintillatorDetId(idc); #endif } else { edm::LogWarning("HGCalGeom") << "Check " << HGCScintillatorDetId(idc) << " from " << HGCScintillatorDetId(detId) << " ERROR ???"; } } else { #ifdef EDM_ML_DEBUG unsigned int cellAll(0), cellSelect(0); #endif for (int u = 0; u < 2 * cells; ++u) { for (int v = 0; v < 2 * cells; ++v) { if (((v - u) < cells) && (u - v) <= cells) { id.iCell1 = u; id.iCell2 = v; DetId idc = m_topology.encode(id); #ifdef EDM_ML_DEBUG ++cellAll; #endif if (m_topology.dddConstants().cellInLayer(id.iSec1, id.iSec2, u, v, id.iLay, true)) { m_validIds.emplace_back(idc); #ifdef EDM_ML_DEBUG ++cellSelect; edm::LogVerbatim("HGCalGeom") << "Valid Id [" << u << ", " << v << "] " << HGCSiliconDetId(idc); #endif } } } } #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "HGCalGeometry keeps " << cellSelect << " out of " << cellAll << " for wafer " << id.iSec1 << ":" << id.iSec2 << " in " << " layer " << id.iLay; #endif } #ifdef EDM_ML_DEBUG if (m_det == DetId::HGCalHSc) { edm::LogVerbatim("HGCalGeom") << "HGCalGeometry::newCell-> [" << cellIndex << "]" << " front:" << f1.x() << '/' << f1.y() << '/' << f1.z() << " back:" << f2.x() << '/' << f2.y() << '/' << f2.z() << " eta|phi " << m_cellVec2[cellIndex].etaPos() << ":" << m_cellVec2[cellIndex].phiPos(); } else { edm::LogVerbatim("HGCalGeom") << "HGCalGeometry::newCell-> [" << cellIndex << "]" << " front:" << f1.x() << '/' << f1.y() << '/' << f1.z() << " back:" << f2.x() << '/' << f2.y() << '/' << f2.z() << " eta|phi " << m_cellVec[cellIndex].etaPos() << ":" << m_cellVec[cellIndex].phiPos(); } unsigned int nNew = m_validIds.size(); if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) { edm::LogVerbatim("HGCalGeom") << "ID: " << HGCalDetId(detId) << " with valid DetId from " << nOld << " to " << nNew; } else if (mode_ == HGCalGeometryMode::Trapezoid) { edm::LogVerbatim("HGCalGeom") << "ID: " << HGCScintillatorDetId(detId) << " with valid DetId from " << nOld << " to " << nNew; } else if (m_topology.isHFNose()) { edm::LogVerbatim("HGCalGeom") << "ID: " << HFNoseDetId(detId) << " with valid DetId from " << nOld << " to " << nNew; } else { edm::LogVerbatim("HGCalGeom") << "ID: " << HGCSiliconDetId(detId) << " with valid DetId from " << nOld << " to " << nNew; } edm::LogVerbatim("HGCalGeom") << "Cell[" << cellIndex << "] " << std::hex << geomId.rawId() << ":" << m_validGeomIds[cellIndex].rawId() << std::dec; #endif } std::shared_ptr<const CaloCellGeometry> HGCalGeometry::getGeometry(const DetId& detId) const { if (detId == DetId()) return nullptr; // nothing to get DetId geomId = getGeometryDetId(detId); const uint32_t cellIndex(m_topology.detId2denseGeomId(geomId)); const GlobalPoint pos = (detId != geomId) ? getPosition(detId) : GlobalPoint(); return cellGeomPtr(cellIndex, pos); } bool HGCalGeometry::present(const DetId& detId) const { if (detId == DetId()) return false; DetId geomId = getGeometryDetId(detId); const uint32_t index(m_topology.detId2denseGeomId(geomId)); return (nullptr != getGeometryRawPtr(index)); } GlobalPoint HGCalGeometry::getPosition(const DetId& detid) const { unsigned int cellIndex = indexFor(detid); GlobalPoint glob; unsigned int maxSize = ((mode_ == HGCalGeometryMode::Trapezoid) ? m_cellVec2.size() : m_cellVec.size()); if (cellIndex < maxSize) { HGCalTopology::DecodedDetId id = m_topology.decode(detid); std::pair<float, float> xy; if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) { xy = m_topology.dddConstants().locateCellHex(id.iCell1, id.iSec1, true); const HepGeom::Point3D<float> lcoord(xy.first, xy.second, 0); glob = m_cellVec[cellIndex].getPosition(lcoord); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "getPosition:: index " << cellIndex << " Local " << lcoord.x() << ":" << lcoord.y() << " ID " << id.iCell1 << ":" << id.iSec1 << " Global " << glob; #endif } else if (mode_ == HGCalGeometryMode::Trapezoid) { const HepGeom::Point3D<float> lcoord(0, 0, 0); glob = m_cellVec2[cellIndex].getPosition(lcoord); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "getPositionTrap:: index " << cellIndex << " Local " << lcoord.x() << ":" << lcoord.y() << " ID " << id.iLay << ":" << id.iSec1 << ":" << id.iCell1 << " Global " << glob; #endif } else { xy = m_topology.dddConstants().locateCell(id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2, true, false, true); const HepGeom::Point3D<float> lcoord(xy.first, xy.second, 0); glob = m_cellVec[cellIndex].getPosition(lcoord); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "getPositionWafer:: index " << cellIndex << " Local " << lcoord.x() << ":" << lcoord.y() << " ID " << id.iLay << ":" << id.iSec1 << ":" << id.iSec2 << ":" << id.iCell1 << ":" << id.iCell2 << " Global " << glob; #endif } } return glob; } GlobalPoint HGCalGeometry::getWaferPosition(const DetId& detid) const { unsigned int cellIndex = indexFor(detid); GlobalPoint glob; unsigned int maxSize = ((mode_ == HGCalGeometryMode::Trapezoid) ? m_cellVec2.size() : m_cellVec.size()); if (cellIndex < maxSize) { const HepGeom::Point3D<float> lcoord(0, 0, 0); if (mode_ == HGCalGeometryMode::Trapezoid) { glob = m_cellVec2[cellIndex].getPosition(lcoord); } else { glob = m_cellVec[cellIndex].getPosition(lcoord); } #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "getPositionTrap:: ID " << std::hex << detid.rawId() << std::dec << " index " << cellIndex << " Global " << glob; #endif } return glob; } double HGCalGeometry::getArea(const DetId& detid) const { HGCalGeometry::CornersVec corners = getNewCorners(detid); double area(0); if (corners.size() > 1) { int n = corners.size() - 1; int j = n - 1; for (int i = 0; i < n; ++i) { area += ((corners[j].x() + corners[i].x()) * (corners[i].y() - corners[j].y())); j = i; } } return (0.5 * area); } HGCalGeometry::CornersVec HGCalGeometry::getCorners(const DetId& detid) const { unsigned int ncorner = ((m_det == DetId::HGCalHSc) ? FlatTrd::ncorner_ : FlatHexagon::ncorner_); HGCalGeometry::CornersVec co(ncorner, GlobalPoint(0, 0, 0)); unsigned int cellIndex = indexFor(detid); HGCalTopology::DecodedDetId id = m_topology.decode(detid); if (cellIndex < m_cellVec2.size() && m_det == DetId::HGCalHSc) { GlobalPoint v = getPosition(detid); std::pair<double, double> rr = m_topology.dddConstants().cellSizeTrap(id.iType, id.iSec1); float dr = k_half * (rr.second - rr.first); float dfi = m_cellVec2[cellIndex].param()[FlatTrd::k_Cell]; float dz = id.zSide * m_cellVec2[cellIndex].param()[FlatTrd::k_dZ]; float r = v.perp(); float fi = v.phi(); static const int signr[] = {1, 1, -1, -1, 1, 1, -1, -1}; static const int signf[] = {-1, 1, 1, -1, -1, 1, 1, -1}; static const int signz[] = {-1, -1, -1, -1, 1, 1, 1, 1}; for (unsigned int i = 0; i < ncorner; ++i) { co[i] = GlobalPoint((r + signr[i] * dr) * cos(fi + signf[i] * dfi), (r + signr[i] * dr) * sin(fi + signf[i] * dfi), (v.z() + signz[i] * dz)); } } else if (cellIndex < m_cellVec.size() && m_det != DetId::HGCalHSc) { std::pair<float, float> xy; if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) { xy = m_topology.dddConstants().locateCellHex(id.iCell1, id.iSec1, true); float dx = m_cellVec[cellIndex].param()[FlatHexagon::k_r]; float dy = k_half * m_cellVec[cellIndex].param()[FlatHexagon::k_R]; float dz = m_cellVec[cellIndex].param()[FlatHexagon::k_dZ]; static const int signx[] = {0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, 1}; static const int signy[] = {-2, -1, 1, 2, 1, -1, -2, -1, 1, 2, 1, -1}; static const int signz[] = {-1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1}; for (unsigned int i = 0; i < ncorner; ++i) { const HepGeom::Point3D<float> lcoord(xy.first + signx[i] * dx, xy.second + signy[i] * dy, signz[i] * dz); co[i] = m_cellVec[cellIndex].getPosition(lcoord); } } else { xy = m_topology.dddConstants().locateCell(id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2, true, false); float dx = k_fac2 * m_cellVec[cellIndex].param()[FlatHexagon::k_r]; float dy = k_fac1 * m_cellVec[cellIndex].param()[FlatHexagon::k_R]; float dz = -id.zSide * m_cellVec[cellIndex].param()[FlatHexagon::k_dZ]; static const int signx[] = {1, -1, -2, -1, 1, 2, 1, -1, -2, -1, 1, 2}; static const int signy[] = {1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0}; static const int signz[] = {-1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1}; for (unsigned int i = 0; i < ncorner; ++i) { const HepGeom::Point3D<float> lcoord(xy.first + signx[i] * dx, xy.second + signy[i] * dy, signz[i] * dz); co[i] = m_cellVec[cellIndex].getPosition(lcoord); } } } return co; } HGCalGeometry::CornersVec HGCalGeometry::get8Corners(const DetId& detid) const { unsigned int ncorner = FlatTrd::ncorner_; HGCalGeometry::CornersVec co(ncorner, GlobalPoint(0, 0, 0)); unsigned int cellIndex = indexFor(detid); HGCalTopology::DecodedDetId id = m_topology.decode(detid); if (cellIndex < m_cellVec2.size() && m_det == DetId::HGCalHSc) { GlobalPoint v = getPosition(detid); std::pair<double, double> rr = m_topology.dddConstants().cellSizeTrap(id.iType, id.iSec1); float dr = k_half * (rr.second - rr.first); float dfi = m_cellVec2[cellIndex].param()[FlatTrd::k_Cell]; float dz = id.zSide * m_cellVec2[cellIndex].param()[FlatTrd::k_dZ]; float r = v.perp(); float fi = v.phi(); static const int signr[] = {1, 1, -1, -1, 1, 1, -1, -1}; static const int signf[] = {-1, 1, 1, -1, -1, 1, 1, -1}; static const int signz[] = {-1, -1, -1, -1, 1, 1, 1, 1}; for (unsigned int i = 0; i < ncorner; ++i) { co[i] = GlobalPoint((r + signr[i] * dr) * cos(fi + signf[i] * dfi), (r + signr[i] * dr) * sin(fi + signf[i] * dfi), (v.z() + signz[i] * dz)); } } else if (cellIndex < m_cellVec.size() && m_det != DetId::HGCalHSc) { std::pair<float, float> xy; float dx(0); if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) { xy = m_topology.dddConstants().locateCellHex(id.iCell1, id.iSec1, true); dx = m_cellVec[cellIndex].param()[FlatHexagon::k_r]; } else { xy = m_topology.dddConstants().locateCell(id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2, true, false); dx = k_fac2 * m_cellVec[cellIndex].param()[FlatHexagon::k_r]; } static const int signx[] = {-1, -1, 1, 1, -1, -1, 1, 1}; static const int signy[] = {-1, 1, 1, -1, -1, 1, 1, -1}; static const int signz[] = {-1, -1, -1, -1, 1, 1, 1, 1}; float dz = m_cellVec[cellIndex].param()[FlatHexagon::k_dZ]; for (unsigned int i = 0; i < ncorner; ++i) { const HepGeom::Point3D<float> lcoord(xy.first + signx[i] * dx, xy.second + signy[i] * dx, signz[i] * dz); co[i] = m_cellVec[cellIndex].getPosition(lcoord); } } return co; } HGCalGeometry::CornersVec HGCalGeometry::getNewCorners(const DetId& detid) const { unsigned int ncorner = (m_det == DetId::HGCalHSc) ? 5 : 7; HGCalGeometry::CornersVec co(ncorner, GlobalPoint(0, 0, 0)); unsigned int cellIndex = indexFor(detid); HGCalTopology::DecodedDetId id = m_topology.decode(detid); if (cellIndex < m_cellVec2.size() && m_det == DetId::HGCalHSc) { GlobalPoint v = getPosition(detid); std::pair<double, double> rr = m_topology.dddConstants().cellSizeTrap(id.iType, id.iSec1); float dr = k_half * (rr.second - rr.first); float dfi = m_cellVec2[cellIndex].param()[FlatTrd::k_Cell]; float dz = -id.zSide * m_cellVec2[cellIndex].param()[FlatTrd::k_dZ]; float r = v.perp(); float fi = v.phi(); static const int signr[] = {1, 1, -1, -1}; static const int signf[] = {-1, 1, 1, -1}; for (unsigned int i = 0; i < ncorner - 1; ++i) { co[i] = GlobalPoint( (r + signr[i] * dr) * cos(fi + signf[i] * dfi), (r + signr[i] * dr) * sin(fi + signf[i] * dfi), (v.z() + dz)); } co[ncorner - 1] = GlobalPoint(0, 0, -2 * dz); } else if (cellIndex < m_cellVec.size() && m_det != DetId::HGCalHSc) { std::pair<float, float> xy; if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) { xy = m_topology.dddConstants().locateCellHex(id.iCell1, id.iSec1, true); } else { xy = m_topology.dddConstants().locateCell(id.iLay, id.iSec1, id.iSec2, id.iCell1, id.iCell2, true, false); } float dx = k_fac2 * m_cellVec[cellIndex].param()[FlatHexagon::k_r]; float dy = k_fac1 * m_cellVec[cellIndex].param()[FlatHexagon::k_R]; float dz = -id.zSide * m_cellVec[cellIndex].param()[FlatHexagon::k_dZ]; static const int signx[] = {1, -1, -2, -1, 1, 2}; static const int signy[] = {1, 1, 0, -1, -1, 0}; for (unsigned int i = 0; i < ncorner - 1; ++i) { const HepGeom::Point3D<float> lcoord(xy.first + signx[i] * dx, xy.second + signy[i] * dy, dz); co[i] = m_cellVec[cellIndex].getPosition(lcoord); } co[ncorner - 1] = GlobalPoint(0, 0, -2 * dz); } return co; } DetId HGCalGeometry::neighborZ(const DetId& idin, const GlobalVector& momentum) const { DetId idnew; HGCalTopology::DecodedDetId id = m_topology.decode(idin); int lay = ((momentum.z() * id.zSide > 0) ? (id.iLay + 1) : (id.iLay - 1)); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "neighborz1:: ID " << id.iLay << ":" << id.iSec1 << ":" << id.iSec2 << ":" << id.iCell1 << ":" << id.iCell2 << " New Layer " << lay << " Range " << m_topology.dddConstants().firstLayer() << ":" << m_topology.dddConstants().lastLayer(true) << " pz " << momentum.z(); #endif if ((lay >= m_topology.dddConstants().firstLayer()) && (lay <= m_topology.dddConstants().lastLayer(true)) && (momentum.z() != 0.0)) { GlobalPoint v = getPosition(idin); double z = id.zSide * m_topology.dddConstants().waferZ(lay, true); double grad = (z - v.z()) / momentum.z(); GlobalPoint p(v.x() + grad * momentum.x(), v.y() + grad * momentum.y(), z); double r = p.perp(); auto rlimit = topology().dddConstants().rangeR(z, true); if (r >= rlimit.first && r <= rlimit.second) idnew = getClosestCell(p); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "neighborz1:: Position " << v << " New Z " << z << ":" << grad << " new position " << p << " r-limit " << rlimit.first << ":" << rlimit.second; #endif } return idnew; } DetId HGCalGeometry::neighborZ(const DetId& idin, const MagneticField* bField, int charge, const GlobalVector& momentum) const { DetId idnew; HGCalTopology::DecodedDetId id = m_topology.decode(idin); int lay = ((momentum.z() * id.zSide > 0) ? (id.iLay + 1) : (id.iLay - 1)); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "neighborz2:: ID " << id.iLay << ":" << id.iSec1 << ":" << id.iSec2 << ":" << id.iCell1 << ":" << id.iCell2 << " New Layer " << lay << " Range " << m_topology.dddConstants().firstLayer() << ":" << m_topology.dddConstants().lastLayer(true) << " pz " << momentum.z(); #endif if ((lay >= m_topology.dddConstants().firstLayer()) && (lay <= m_topology.dddConstants().lastLayer(true)) && (momentum.z() != 0.0)) { GlobalPoint v = getPosition(idin); double z = id.zSide * m_topology.dddConstants().waferZ(lay, true); FreeTrajectoryState fts(v, momentum, charge, bField); Plane::PlanePointer nPlane = Plane::build(Plane::PositionType(0, 0, z), Plane::RotationType()); AnalyticalPropagator myAP(bField, alongMomentum, 2 * M_PI); TrajectoryStateOnSurface tsos = myAP.propagate(fts, *nPlane); GlobalPoint p; auto rlimit = topology().dddConstants().rangeR(z, true); if (tsos.isValid()) { p = tsos.globalPosition(); double r = p.perp(); if (r >= rlimit.first && r <= rlimit.second) idnew = getClosestCell(p); } #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "neighborz2:: Position " << v << " New Z " << z << ":" << charge << ":" << tsos.isValid() << " new position " << p << " r limits " << rlimit.first << ":" << rlimit.second; #endif } return idnew; } DetId HGCalGeometry::getClosestCell(const GlobalPoint& r) const { unsigned int cellIndex = getClosestCellIndex(r); if ((cellIndex < m_cellVec.size() && m_det != DetId::HGCalHSc) || (cellIndex < m_cellVec2.size() && m_det == DetId::HGCalHSc)) { HGCalTopology::DecodedDetId id = m_topology.decode(m_validGeomIds[cellIndex]); HepGeom::Point3D<float> local; if (r.z() > 0) { local = HepGeom::Point3D<float>(r.x(), r.y(), 0); id.zSide = 1; } else { local = HepGeom::Point3D<float>(-r.x(), r.y(), 0); id.zSide = -1; } if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) { const auto& kxy = m_topology.dddConstants().assignCell(local.x(), local.y(), id.iLay, id.iType, true); id.iCell1 = kxy.second; id.iSec1 = kxy.first; id.iType = m_topology.dddConstants().waferTypeT(kxy.first); if (id.iType != 1) id.iType = -1; } else if (mode_ == HGCalGeometryMode::Trapezoid) { id.iLay = m_topology.dddConstants().getLayer(r.z(), true); const auto& kxy = m_topology.dddConstants().assignCellTrap(r.x(), r.y(), r.z(), id.iLay, true); id.iSec1 = kxy[0]; id.iCell1 = kxy[1]; id.iType = kxy[2]; } else { id.iLay = m_topology.dddConstants().getLayer(r.z(), true); const auto& kxy = m_topology.dddConstants().assignCellHex(local.x(), local.y(), id.iLay, true); id.iSec1 = kxy[0]; id.iSec2 = kxy[1]; id.iType = kxy[2]; id.iCell1 = kxy[3]; id.iCell2 = kxy[4]; } #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "getClosestCell: local " << local << " Id " << id.zSide << ":" << id.iLay << ":" << id.iSec1 << ":" << id.iSec2 << ":" << id.iType << ":" << id.iCell1 << ":" << id.iCell2; #endif //check if returned cell is valid if (id.iCell1 >= 0) return m_topology.encode(id); } //if not valid or out of bounds return a null DetId return DetId(); } HGCalGeometry::DetIdSet HGCalGeometry::getCells(const GlobalPoint& r, double dR) const { HGCalGeometry::DetIdSet dss; return dss; } std::string HGCalGeometry::cellElement() const { if (m_subdet == HGCEE || m_det == DetId::HGCalEE) return "HGCalEE"; else if (m_subdet == HGCHEF || m_det == DetId::HGCalHSi) return "HGCalHEFront"; else if (m_subdet == HGCHEB || m_det == DetId::HGCalHSc) return "HGCalHEBack"; else return "Unknown"; } unsigned int HGCalGeometry::indexFor(const DetId& detId) const { unsigned int cellIndex = ((m_det == DetId::HGCalHSc) ? m_cellVec2.size() : m_cellVec.size()); if (detId != DetId()) { DetId geomId = getGeometryDetId(detId); cellIndex = m_topology.detId2denseGeomId(geomId); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "indexFor " << std::hex << detId.rawId() << ":" << geomId.rawId() << std::dec << " index " << cellIndex; #endif } return cellIndex; } unsigned int HGCalGeometry::sizeForDenseIndex() const { return m_topology.totalGeomModules(); } const CaloCellGeometry* HGCalGeometry::getGeometryRawPtr(uint32_t index) const { // Modify the RawPtr class if (m_det == DetId::HGCalHSc) { if (m_cellVec2.size() < index) return nullptr; const CaloCellGeometry* cell(&m_cellVec2[index]); return (nullptr == cell->param() ? nullptr : cell); } else { if (m_cellVec2.size() < index) return nullptr; const CaloCellGeometry* cell(&m_cellVec[index]); return (nullptr == cell->param() ? nullptr : cell); } } std::shared_ptr<const CaloCellGeometry> HGCalGeometry::cellGeomPtr(uint32_t index) const { if ((index >= m_cellVec.size() && m_det != DetId::HGCalHSc) || (index >= m_cellVec2.size() && m_det == DetId::HGCalHSc) || (m_validGeomIds[index].rawId() == 0)) return nullptr; static const auto do_not_delete = [](const void*) {}; if (m_det == DetId::HGCalHSc) { auto cell = std::shared_ptr<const CaloCellGeometry>(&m_cellVec2[index], do_not_delete); if (nullptr == cell->param()) return nullptr; return cell; } else { auto cell = std::shared_ptr<const CaloCellGeometry>(&m_cellVec[index], do_not_delete); if (nullptr == cell->param()) return nullptr; return cell; } } std::shared_ptr<const CaloCellGeometry> HGCalGeometry::cellGeomPtr(uint32_t index, const GlobalPoint& pos) const { if ((index >= m_cellVec.size() && m_det != DetId::HGCalHSc) || (index >= m_cellVec2.size() && m_det == DetId::HGCalHSc) || (m_validGeomIds[index].rawId() == 0)) return nullptr; if (pos == GlobalPoint()) return cellGeomPtr(index); if (m_det == DetId::HGCalHSc) { auto cell = std::make_shared<FlatTrd>(m_cellVec2[index]); cell->setPosition(pos); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "cellGeomPtr " << index << ":" << cell; #endif if (nullptr == cell->param()) return nullptr; return cell; } else { auto cell = std::make_shared<FlatHexagon>(m_cellVec[index]); cell->setPosition(pos); #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "cellGeomPtr " << index << ":" << cell; #endif if (nullptr == cell->param()) return nullptr; return cell; } } void HGCalGeometry::addValidID(const DetId& id) { edm::LogError("HGCalGeom") << "HGCalGeometry::addValidID is not implemented"; } unsigned int HGCalGeometry::getClosestCellIndex(const GlobalPoint& r) const { return ((m_det == DetId::HGCalHSc) ? getClosestCellIndex(r, m_cellVec2) : getClosestCellIndex(r, m_cellVec)); } template <class T> unsigned int HGCalGeometry::getClosestCellIndex(const GlobalPoint& r, const std::vector<T>& vec) const { float phip = r.phi(); float zp = r.z(); float dzmin(9999), dphimin(9999), dphi10(0.175); unsigned int cellIndex = vec.size(); for (unsigned int k = 0; k < vec.size(); ++k) { float dphi = phip - vec[k].phiPos(); while (dphi > M_PI) dphi -= 2 * M_PI; while (dphi <= -M_PI) dphi += 2 * M_PI; if (std::abs(dphi) < dphi10) { float dz = std::abs(zp - vec[k].getPosition().z()); if (dz < (dzmin + 0.001)) { dzmin = dz; if (std::abs(dphi) < (dphimin + 0.01)) { cellIndex = k; dphimin = std::abs(dphi); } else { if (cellIndex >= vec.size()) cellIndex = k; } } } } #ifdef EDM_ML_DEBUG edm::LogVerbatim("HGCalGeom") << "getClosestCellIndex::Input " << zp << ":" << phip << " Index " << cellIndex; if (cellIndex < vec.size()) edm::LogVerbatim("HGCalGeom") << " Cell z " << vec[cellIndex].getPosition().z() << ":" << dzmin << " phi " << vec[cellIndex].phiPos() << ":" << dphimin; #endif return cellIndex; } // FIXME: Change sorting algorithm if needed namespace { struct rawIdSort { bool operator()(const DetId& a, const DetId& b) { return (a.rawId() < b.rawId()); } }; } // namespace void HGCalGeometry::sortDetIds(void) { m_validIds.shrink_to_fit(); std::sort(m_validIds.begin(), m_validIds.end(), rawIdSort()); } void HGCalGeometry::getSummary(CaloSubdetectorGeometry::TrVec& trVector, CaloSubdetectorGeometry::IVec& iVector, CaloSubdetectorGeometry::DimVec& dimVector, CaloSubdetectorGeometry::IVec& dinsVector) const { unsigned int numberOfCells = m_topology.totalGeomModules(); // total Geom Modules both sides unsigned int numberOfShapes = k_NumberOfShapes; unsigned int numberOfParametersPerShape = ((m_det == DetId::HGCalHSc) ? (unsigned int)(k_NumberOfParametersPerTrd) : (unsigned int)(k_NumberOfParametersPerHex)); trVector.reserve(numberOfCells * numberOfTransformParms()); iVector.reserve(numberOfCells); dimVector.reserve(numberOfShapes * numberOfParametersPerShape); dinsVector.reserve(numberOfCells); for (unsigned itr = 0; itr < m_topology.dddConstants().getTrFormN(); ++itr) { HGCalParameters::hgtrform mytr = m_topology.dddConstants().getTrForm(itr); int layer = mytr.lay; if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) { for (int wafer = 0; wafer < m_topology.dddConstants().sectors(); ++wafer) { if (m_topology.dddConstants().waferInLayer(wafer, layer, true)) { HGCalParameters::hgtrap vol = m_topology.dddConstants().getModule(wafer, true, true); ParmVec params(numberOfParametersPerShape, 0); params[FlatHexagon::k_dZ] = vol.dz; params[FlatHexagon::k_r] = vol.cellSize; params[FlatHexagon::k_R] = twoBysqrt3_ * params[FlatHexagon::k_r]; dimVector.insert(dimVector.end(), params.begin(), params.end()); } } } else if (mode_ == HGCalGeometryMode::Trapezoid) { int indx = m_topology.dddConstants().layerIndex(layer, true); for (int md = m_topology.dddConstants().getParameter()->firstModule_[indx]; md <= m_topology.dddConstants().getParameter()->lastModule_[indx]; ++md) { HGCalParameters::hgtrap vol = m_topology.dddConstants().getModule(md, true, true); ParmVec params(numberOfParametersPerShape, 0); params[FlatTrd::k_dZ] = vol.dz; params[FlatTrd::k_Theta] = params[FlatTrd::k_Phi] = 0; params[FlatTrd::k_dY1] = params[FlatTrd::k_dY2] = vol.h; params[FlatTrd::k_dX1] = params[FlatTrd::k_dX3] = vol.bl; params[FlatTrd::k_dX2] = params[FlatTrd::k_dX4] = vol.tl; params[FlatTrd::k_Alp1] = params[FlatTrd::k_Alp2] = vol.alpha; params[FlatTrd::k_Cell] = vol.cellSize; dimVector.insert(dimVector.end(), params.begin(), params.end()); } } else { for (int wafer = 0; wafer < m_topology.dddConstants().sectors(); ++wafer) { if (m_topology.dddConstants().waferInLayer(wafer, layer, true)) { HGCalParameters::hgtrap vol = m_topology.dddConstants().getModule(wafer, true, true); ParmVec params(numberOfParametersPerShape, 0); params[FlatHexagon::k_dZ] = vol.dz; params[FlatHexagon::k_r] = vol.cellSize; params[FlatHexagon::k_R] = twoBysqrt3_ * params[FlatHexagon::k_r]; dimVector.insert(dimVector.end(), params.begin(), params.end()); } } } } for (unsigned int i(0); i < numberOfCells; ++i) { DetId detId = m_validGeomIds[i]; int layer(0); if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) { layer = HGCalDetId(detId).layer(); } else if (mode_ == HGCalGeometryMode::Trapezoid) { layer = HGCScintillatorDetId(detId).layer(); } else if (m_topology.isHFNose()) { layer = HFNoseDetId(detId).layer(); } else { layer = HGCSiliconDetId(detId).layer(); } dinsVector.emplace_back(m_topology.detId2denseGeomId(detId)); iVector.emplace_back(layer); Tr3D tr; auto ptr = cellGeomPtr(i); if (nullptr != ptr) { ptr->getTransform(tr, (Pt3DVec*)nullptr); if (Tr3D() == tr) { // there is no rotation const GlobalPoint& gp(ptr->getPosition()); tr = HepGeom::Translate3D(gp.x(), gp.y(), gp.z()); } const CLHEP::Hep3Vector tt(tr.getTranslation()); trVector.emplace_back(tt.x()); trVector.emplace_back(tt.y()); trVector.emplace_back(tt.z()); if (6 == numberOfTransformParms()) { const CLHEP::HepRotation rr(tr.getRotation()); const ROOT::Math::Transform3D rtr( rr.xx(), rr.xy(), rr.xz(), tt.x(), rr.yx(), rr.yy(), rr.yz(), tt.y(), rr.zx(), rr.zy(), rr.zz(), tt.z()); ROOT::Math::EulerAngles ea; rtr.GetRotation(ea); trVector.emplace_back(ea.Phi()); trVector.emplace_back(ea.Theta()); trVector.emplace_back(ea.Psi()); } } } } DetId HGCalGeometry::getGeometryDetId(DetId detId) const { DetId geomId; if ((mode_ == HGCalGeometryMode::Hexagon) || (mode_ == HGCalGeometryMode::HexagonFull)) { geomId = static_cast<DetId>(HGCalDetId(detId).geometryCell()); } else if (mode_ == HGCalGeometryMode::Trapezoid) { geomId = static_cast<DetId>(HGCScintillatorDetId(detId).geometryCell()); } else if (m_topology.isHFNose()) { geomId = static_cast<DetId>(HFNoseDetId(detId).geometryCell()); } else { geomId = static_cast<DetId>(HGCSiliconDetId(detId).geometryCell()); } return geomId; } #include "FWCore/Utilities/interface/typelookup.h" TYPELOOKUP_DATA_REG(HGCalGeometry);
34,406
13,461
/*============================================================================= Copyright (c) 2011-2019 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_RANGE_ADAPTOR_REVERSED_HPP #define SPROUT_RANGE_ADAPTOR_REVERSED_HPP #include <type_traits> #include <sprout/config.hpp> #include <sprout/container/traits.hpp> #include <sprout/container/functions.hpp> #include <sprout/iterator/reverse_iterator.hpp> #include <sprout/range/adaptor/detail/adapted_range_default.hpp> #include <sprout/type_traits/lvalue_reference.hpp> #include <sprout/utility/forward.hpp> #include <sprout/utility/lvalue_forward.hpp> namespace sprout { namespace adaptors { // // reversed_range // template<typename Range> class reversed_range : public sprout::adaptors::detail::adapted_range_default< Range, sprout::reverse_iterator<typename sprout::container_traits<Range>::iterator> > { public: typedef sprout::adaptors::detail::adapted_range_default< Range, sprout::reverse_iterator<typename sprout::container_traits<Range>::iterator> > base_type; typedef typename base_type::range_type range_type; typedef typename base_type::iterator iterator; public: SPROUT_CONSTEXPR reversed_range() SPROUT_DEFAULTED_DEFAULT_CONSTRUCTOR_DECL reversed_range(reversed_range const&) = default; explicit SPROUT_CONSTEXPR reversed_range(range_type& range) : base_type( iterator(sprout::end(range)), iterator(sprout::begin(range)) ) {} }; // // reversed_forwarder // class reversed_forwarder {}; // // reversed // namespace { SPROUT_STATIC_CONSTEXPR sprout::adaptors::reversed_forwarder reversed = {}; } // anonymous-namespace // // operator| // template<typename Range> inline SPROUT_CONSTEXPR sprout::adaptors::reversed_range< typename std::remove_reference<typename sprout::lvalue_reference<Range>::type>::type > operator|(Range&& lhs, sprout::adaptors::reversed_forwarder) { return sprout::adaptors::reversed_range< typename std::remove_reference<typename sprout::lvalue_reference<Range>::type>::type >( sprout::lvalue_forward<Range>(lhs) ); } } // namespace adaptors // // container_construct_traits // template<typename Range> struct container_construct_traits<sprout::adaptors::reversed_range<Range> > : public sprout::container_construct_traits<typename sprout::adaptors::reversed_range<Range>::base_type> {}; } // namespace sprout #endif // #ifndef SPROUT_RANGE_ADAPTOR_REVERSED_HPP
2,764
1,060
#include "vcepch.h" #include "RenderCommand.h" #include "Platform/OpenGL/OpenGLRendererAPI.h" namespace VCE { RendererAPI* RenderCommand::s_RendererAPI = new OpenGLRendererAPI; }
181
62
#include<bits/stdc++.h> using namespace std; class Solution { public: bool wordBreak(string s, vector<string>& wordDict) { unordered_set<string> dict(wordDict.begin(), wordDict.end()); vector<bool> dp(s.size() + 1, false);//dp表示字符之间的隔板,n个字符有n+1个隔板 dp[0] = true;//dp[0]是s[0]前面的隔板 for (int i = 1; i <= s.size(); i ++) { for (int j = i; j >= 0; j --) { if(dict.count(s.substr(j,i - j)) && dp[j]) { dp[i] = true; break; } } } return dp[s.size()]; } }; int main(){ string s = "leetcode"; vector<string> wordDict{"leet", "code"}; cout << Solution().wordBreak(s, wordDict) << endl; return 0; }
797
312
// // Benjamin Wagner 2018 // #include "generators/uniform_generator.h" #include <random> namespace generators { uniform_generator::uniform_generator(size_t min, uint64_t max, uint64_t count): built(false), min(min), max(max), count (count), data() { // Generate a pseudo random seed value std::random_device rd; seed = rd(); } uniform_generator::uniform_generator(size_t min, uint64_t max, uint64_t count, uint64_t seed): built(false), min(min), max(max), count (count), seed(seed), data() {} void uniform_generator::build() { std::mt19937 gen(seed); std::uniform_int_distribution<uint64_t> dis(min, max); data.reserve(count); built = true; for(uint64_t i = 0; i < count; ++i){ uint64_t val = dis(gen); data.emplace_back(val, i); } } std::vector<std::tuple<uint64_t, uint64_t>> uniform_generator::get_vec_copy() { if(!built){ throw std::logic_error("copying may not be called before distribution has been built."); } return data; } uint64_t uniform_generator::get_count() { return count; } } // namespace generators
1,236
411
// // guild.cpp // ********* // // Copyright (c) 2019 Sharon W (sharon at aegis dot gg) // // Distributed under the MIT License. (See accompanying file LICENSE) // #include "aegis/guild.hpp" #include <string> #include <memory> #include "aegis/core.hpp" #include "aegis/member.hpp" #include "aegis/channel.hpp" #include "aegis/error.hpp" #include "aegis/shards/shard.hpp" #include "aegis/ratelimit/ratelimit.hpp" namespace aegis { using json = nlohmann::json; AEGIS_DECL guild::guild(const int32_t _shard_id, const snowflake _id, core * _bot, asio::io_context & _io) : shard_id(_shard_id) , guild_id(_id) , _bot(_bot) , _io_context(_io) { } AEGIS_DECL guild::~guild() { #if !defined(AEGIS_DISABLE_ALL_CACHE) //TODO: remove guilds from members elsewhere when bot is removed from guild // if (get_bot().get_state() != Shutdown) // for (auto & v : members) // v.second->leave(guild_id); #endif } AEGIS_DECL core & guild::get_bot() const noexcept { return *_bot; } #if !defined(AEGIS_DISABLE_ALL_CACHE) AEGIS_DECL member * guild::self() const { return get_bot().self(); } AEGIS_DECL void guild::add_member(member * _member) noexcept { members.emplace(_member->_member_id, _member); } AEGIS_DECL void guild::remove_member(snowflake member_id) noexcept { auto _member = members.find(member_id); if (_member == members.end()) { AEGIS_DEBUG(get_bot().log, "Unable to remove member [{}] from guild [{}] (does not exist)", member_id, guild_id); return; } _member->second->leave(guild_id); members.erase(member_id); } AEGIS_DECL bool guild::member_has_role(snowflake member_id, snowflake role_id) const noexcept { std::shared_lock<shared_mutex> l(_m); auto _member = find_member(member_id); if (_member == nullptr) return false; auto & gi = _member->get_guild_info(guild_id); auto it = std::find_if(std::begin(gi.roles), std::end(gi.roles), [&](const snowflake & id) { if (id == role_id) return true; return false; }); if (it != std::end(gi.roles)) return true; return false; } AEGIS_DECL void guild::load_presence(const json & obj) noexcept { json user = obj["user"]; auto _member = _find_member(user["id"]); if (_member == nullptr) return; using user_status = aegis::gateway::objects::presence::user_status; const std::string & sts = obj["status"]; if (sts == "idle") _member->_status = user_status::Idle; else if (sts == "dnd") _member->_status = user_status::DoNotDisturb; else if (sts == "online") _member->_status = user_status::Online; else _member->_status = user_status::Offline; } AEGIS_DECL void guild::load_role(const json & obj) noexcept { snowflake role_id = obj["id"]; if (!roles.count(role_id)) roles.emplace(role_id, gateway::objects::role()); auto & _role = roles[role_id]; _role.role_id = role_id; _role.hoist = obj["hoist"]; _role.managed = obj["managed"]; _role.mentionable = obj["mentionable"]; _role._permission = permission(obj["permissions"].get<uint64_t>()); _role.position = obj["position"]; if (!obj["name"].is_null()) _role.name = obj["name"].get<std::string>(); _role.color = obj["color"]; } AEGIS_DECL const snowflake guild::get_owner() const noexcept { return owner_id; } AEGIS_DECL member * guild::find_member(snowflake member_id) const noexcept { std::shared_lock<shared_mutex> l(_m); auto m = members.find(member_id); if (m == members.end()) return nullptr; return m->second; } AEGIS_DECL member * guild::_find_member(snowflake member_id) const noexcept { auto m = members.find(member_id); if (m == members.end()) return nullptr; return m->second; } AEGIS_DECL channel * guild::find_channel(snowflake channel_id) const noexcept { std::shared_lock<shared_mutex> l(_m); auto m = channels.find(channel_id); if (m == channels.end()) return nullptr; return m->second; } AEGIS_DECL channel * guild::_find_channel(snowflake channel_id) const noexcept { auto m = channels.find(channel_id); if (m == channels.end()) return nullptr; return m->second; } AEGIS_DECL permission guild::get_permissions(snowflake member_id, snowflake channel_id) noexcept { if (!members.count(member_id) || !channels.count(channel_id)) return 0; return get_permissions(find_member(member_id), find_channel(channel_id)); } AEGIS_DECL permission guild::get_permissions(member * _member, channel * _channel) noexcept { if (_member == nullptr || _channel == nullptr) return 0; int64_t _base_permissions = base_permissions(_member); return compute_overwrites(_base_permissions, *_member, *_channel); } AEGIS_DECL int64_t guild::base_permissions(member & _member) const noexcept { try { if (owner_id == _member._member_id) return ~0; auto & role_everyone = get_role(guild_id); int64_t permissions = role_everyone._permission.get_allow_perms(); auto g = _member.get_guild_info(guild_id); for (auto & rl : g.roles) permissions |= get_role(rl)._permission.get_allow_perms(); if (permissions & 0x8)//admin return ~0; return permissions; } catch (std::out_of_range &) { return 0; } catch (std::exception & e) { _bot->log->error(fmt::format("guild::base_permissions() [{}]", e.what())); return 0; } catch (...) { _bot->log->error("guild::base_permissions uncaught"); return 0; } } AEGIS_DECL int64_t guild::compute_overwrites(int64_t _base_permissions, member & _member, channel & _channel) const noexcept { try { if (_base_permissions & 0x8)//admin return ~0; int64_t permissions = _base_permissions; if (_channel.overrides.count(guild_id)) { auto & overwrite_everyone = _channel.overrides[guild_id]; permissions &= ~overwrite_everyone.deny; permissions |= overwrite_everyone.allow; } auto & overwrites = _channel.overrides; int64_t allow = 0; int64_t deny = 0; auto g = _member.get_guild_info(guild_id); for (auto & rl : g.roles) { if (rl == guild_id) continue; if (overwrites.count(rl)) { auto & ow_role = overwrites[rl]; allow |= ow_role.allow; deny |= ow_role.deny; } } permissions &= ~deny; permissions |= allow; if (overwrites.count(_member._member_id)) { auto & ow_role = overwrites[_member._member_id]; permissions &= ~ow_role.deny; permissions |= ow_role.allow; } return permissions; } catch (std::exception &) { return 0; } } AEGIS_DECL const gateway::objects::role & guild::get_role(int64_t r) const { std::shared_lock<shared_mutex> l(_m); for (auto & kv : roles) if (kv.second.role_id == r) return kv.second; throw std::out_of_range(fmt::format("G: {} role:[{}] does not exist", guild_id, r)); } AEGIS_DECL void guild::remove_role(snowflake role_id) { std::unique_lock<shared_mutex> l(_m); try { for (auto & kv : members) { auto g = kv.second->get_guild_info(guild_id); for (auto & rl : g.roles) { if (rl == role_id) { auto it = std::find(g.roles.begin(), g.roles.end(), role_id); if (it != g.roles.end()) g.roles.erase(it); break; } } } roles.erase(role_id); } catch (std::out_of_range &) { } } AEGIS_DECL int32_t guild::get_member_count() const noexcept { return static_cast<int32_t>(members.size()); } AEGIS_DECL void guild::load(const json & obj, shards::shard * _shard) noexcept { //uint64_t application_id = obj->get("application_id").convert<uint64_t>(); snowflake g_id = obj["id"]; shard_id = _shard->get_id(); is_init = false; core & bot = get_bot(); try { json voice_states; if (!obj["name"].is_null()) name = obj["name"].get<std::string>(); if (!obj["icon"].is_null()) icon = obj["icon"].get<std::string>(); if (!obj["splash"].is_null()) splash = obj["splash"].get<std::string>(); owner_id = obj["owner_id"]; region = obj["region"].get<std::string>(); if (!obj["afk_channel_id"].is_null()) afk_channel_id = obj["afk_channel_id"]; afk_timeout = obj["afk_timeout"];//in seconds if (obj.count("embed_enabled") && !obj["embed_enabled"].is_null()) embed_enabled = obj["embed_enabled"]; //_guild.embed_channel_id = obj->get("embed_channel_id").convert<uint64_t>(); verification_level = obj["verification_level"]; default_message_notifications = obj["default_message_notifications"]; mfa_level = obj["mfa_level"]; if (obj.count("joined_at") && !obj["joined_at"].is_null()) joined_at = obj["joined_at"].get<std::string>(); if (obj.count("large") && !obj["large"].is_null()) large = obj["large"]; if (obj.count("unavailable") && !obj["unavailable"].is_null()) unavailable = obj["unavailable"]; else unavailable = false; if (obj.count("member_count") && !obj["member_count"].is_null()) member_count = obj["member_count"]; if (obj.count("voice_states") && !obj["voice_states"].is_null()) voice_states = obj["voice_states"]; if (obj.count("roles")) { const json & roles = obj["roles"]; for (auto & role : roles) { load_role(role); } } if (obj.count("members")) { const json & members = obj["members"]; for (auto & member : members) { snowflake member_id = member["user"]["id"]; auto _member = bot.member_create(member_id); std::unique_lock<shared_mutex> l(_member->mtx()); _member->load(this, member, _shard); this->members.emplace(member_id, _member); } } if (obj.count("channels")) { const json & channels = obj["channels"]; for (auto & channel_obj : channels) { snowflake channel_id = channel_obj["id"]; auto _channel = bot.channel_create(channel_id); _channel->load_with_guild(*this, channel_obj, _shard); _channel->guild_id = guild_id; _channel->_guild = this; this->channels.emplace(channel_id, _channel); } } if (obj.count("presences")) { const json & presences = obj["presences"]; for (auto & presence : presences) { load_presence(presence); } } if (obj.count("emojis")) { const json & emojis = obj["emojis"]; /*for (auto & emoji : emojis) { //loadEmoji(emoji, _guild); }*/ } if (obj.count("features")) { const json & features = obj["features"]; } /* for (auto & feature : features) { //?? } for (auto & voicestate : voice_states) { //no voice yet }*/ } catch (std::exception&e) { spdlog::get("aegis")->error("Shard#{} : Error processing guild[{}] {}", _shard->get_id(), g_id, (std::string)e.what()); } } #else AEGIS_DECL void guild::load(const json & obj, shards::shard * _shard) noexcept { //uint64_t application_id = obj->get("application_id").convert<uint64_t>(); snowflake g_id = obj["id"]; shard_id = _shard->get_id(); core & bot = get_bot(); try { if (obj.count("channels")) { const json & channels = obj["channels"]; for (auto & channel_obj : channels) { snowflake channel_id = channel_obj["id"]; auto _channel = bot.channel_create(channel_id); _channel->load_with_guild(*this, channel_obj, _shard); _channel->guild_id = guild_id; _channel->_guild = this; this->channels.emplace(channel_id, _channel); } } } catch (std::exception&e) { spdlog::get("aegis")->error("Shard#{} : Error processing guild[{}] {}", _shard->get_id(), g_id, (std::string)e.what()); } } #endif AEGIS_DECL void guild::remove_channel(snowflake channel_id) noexcept { auto it = channels.find(channel_id); if (it == channels.end()) { AEGIS_DEBUG(get_bot().log, "Unable to remove channel [{}] from guild [{}] (does not exist)", channel_id, guild_id); return; } channels.erase(it); } AEGIS_DECL channel * guild::get_channel(snowflake id) const noexcept { std::shared_lock<shared_mutex> l(_m); auto it = channels.find(id); if (it == channels.end()) return nullptr; return it->second; } /**\todo Incomplete. Signature may change. Location may change. */ AEGIS_DECL aegis::future<gateway::objects::guild> guild::get_guild() { return _bot->get_ratelimit().post_task<gateway::objects::guild>({ fmt::format("/guilds/{}", guild_id), rest::Get }); } AEGIS_DECL aegis::future<gateway::objects::guild> guild::modify_guild(lib::optional<std::string> name, lib::optional<std::string> voice_region, lib::optional<int> verification_level, lib::optional<int> default_message_notifications, lib::optional<int> explicit_content_filter, lib::optional<snowflake> afk_channel_id, lib::optional<int> afk_timeout, lib::optional<std::string> icon, lib::optional<snowflake> owner_id, lib::optional<std::string> splash) { #if !defined(AEGIS_DISABLE_ALL_CACHE) if ((!perms().can_manage_guild()) || (owner_id.has_value() && owner_id != self()->_member_id)) return aegis::make_exception_future<gateway::objects::guild>(error::no_permission); #endif json obj; if (name.has_value()) obj["name"] = name.value(); if (voice_region.has_value()) obj["region"] = voice_region.value(); if (verification_level.has_value()) obj["verification_level"] = verification_level.value(); if (default_message_notifications.has_value()) obj["default_message_notifications"] = default_message_notifications.value(); if (verification_level.has_value()) obj["explicit_content_filter"] = verification_level.value(); if (afk_channel_id.has_value()) obj["afk_channel_id"] = afk_channel_id.value(); if (afk_timeout.has_value()) obj["afk_timeout"] = afk_timeout.value(); if (icon.has_value()) obj["icon"] = icon.value(); if (owner_id.has_value())//requires OWNER obj["owner_id"] = owner_id.value(); if (splash.has_value())//VIP only obj["splash"] = splash.value(); return _bot->get_ratelimit().post_task<gateway::objects::guild>({ fmt::format("/guilds/{}", guild_id), rest::Patch, obj.dump() }); } AEGIS_DECL aegis::future<rest::rest_reply> guild::delete_guild() { #if !defined(AEGIS_DISABLE_ALL_CACHE) //requires OWNER if (owner_id != self()->_member_id) return aegis::make_exception_future(error::no_permission); #endif return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}", guild_id), rest::Delete }); } AEGIS_DECL aegis::future<gateway::objects::channel> guild::create_text_channel(const std::string & name, int64_t parent_id, bool nsfw, const std::vector<gateway::objects::permission_overwrite> & permission_overwrites) { #if !defined(AEGIS_DISABLE_ALL_CACHE) //requires MANAGE_CHANNELS if (!perms().can_manage_channels()) return aegis::make_exception_future<gateway::objects::channel>(error::no_permission); #endif json obj; obj["name"] = name; obj["type"] = 0; obj["parent_id"] = parent_id; obj["nsfw"] = nsfw; obj["permission_overwrites"] = json::array(); for (auto & p_ow : permission_overwrites) { obj["permission_overwrites"].push_back(p_ow); } return _bot->get_ratelimit().post_task<gateway::objects::channel>({ fmt::format("/guilds/{}/channels", guild_id), rest::Post, obj.dump() }); } AEGIS_DECL aegis::future<gateway::objects::channel> guild::create_voice_channel(const std::string & name, int32_t bitrate, int32_t user_limit, int64_t parent_id, const std::vector<gateway::objects::permission_overwrite> & permission_overwrites) { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_channels()) return aegis::make_exception_future<gateway::objects::channel>(error::no_permission); #endif json obj; obj["name"] = name; obj["type"] = 2; obj["bitrate"] = bitrate; obj["user_limit"] = user_limit; obj["parent_id"] = parent_id; obj["permission_overwrites"] = json::array(); for (auto & p_ow : permission_overwrites) { obj["permission_overwrites"].push_back(p_ow); } return _bot->get_ratelimit().post_task<gateway::objects::channel>({ fmt::format("/guilds/{}/channels", guild_id), rest::Post, obj.dump() }); } AEGIS_DECL aegis::future<gateway::objects::channel> guild::create_category_channel(const std::string & name, int64_t parent_id, const std::vector<gateway::objects::permission_overwrite> & permission_overwrites) { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_channels()) return aegis::make_exception_future<gateway::objects::channel>(error::no_permission); #endif json obj; obj["name"] = name; obj["type"] = 4; obj["permission_overwrites"] = json::array(); for (auto & p_ow : permission_overwrites) { obj["permission_overwrites"].push_back(p_ow); } return _bot->get_ratelimit().post_task<gateway::objects::channel>({ fmt::format("/guilds/{}/channels", guild_id), rest::Post, obj.dump() }); } /**\todo Incomplete. Signature may change */ AEGIS_DECL aegis::future<rest::rest_reply> guild::modify_channel_positions() { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_channels()) return aegis::make_exception_future(error::no_permission); #endif return aegis::make_exception_future(error::not_implemented); } AEGIS_DECL aegis::future<gateway::objects::member> guild::modify_guild_member(snowflake user_id, lib::optional<std::string> nick, lib::optional<bool> mute, lib::optional<bool> deaf, lib::optional<std::vector<snowflake>> roles, lib::optional<snowflake> channel_id) { json obj; #if !defined(AEGIS_DISABLE_ALL_CACHE) permission perm = perms(); if (nick.has_value()) { if (!perm.can_manage_names()) return aegis::make_exception_future<gateway::objects::member>(error::no_permission); obj["nick"] = nick.value();//requires MANAGE_NICKNAMES } if (mute.has_value()) { if (!perm.can_voice_mute()) return aegis::make_exception_future<gateway::objects::member>(error::no_permission); obj["mute"] = mute.value();//requires MUTE_MEMBERS } if (deaf.has_value()) { if (!perm.can_voice_deafen()) return aegis::make_exception_future<gateway::objects::member>(error::no_permission); obj["deaf"] = deaf.value();//requires DEAFEN_MEMBERS } if (roles.has_value()) { if (!perm.can_manage_roles()) return aegis::make_exception_future<gateway::objects::member>(error::no_permission); obj["roles"] = roles.value();//requires MANAGE_ROLES } if (channel_id.has_value()) { //TODO: This needs to calculate whether or not the bot has access to the voice channel as well if (!perm.can_voice_move()) return aegis::make_exception_future<gateway::objects::member>(error::no_permission); obj["channel_id"] = channel_id.value();//requires MOVE_MEMBERS } #else if (nick.has_value()) obj["nick"] = nick.value();//requires MANAGE_NICKNAMES if (mute.has_value()) obj["mute"] = mute.value();//requires MUTE_MEMBERS if (deaf.has_value()) obj["deaf"] = deaf.value();//requires DEAFEN_MEMBERS if (roles.has_value()) obj["roles"] = roles.value();//requires MANAGE_ROLES if (channel_id.has_value()) obj["channel_id"] = channel_id.value();//requires MOVE_MEMBERS #endif return _bot->get_ratelimit().post_task<gateway::objects::member>({ fmt::format("/guilds/{}/members/{}", guild_id, user_id), rest::Patch, obj.dump() }); } AEGIS_DECL aegis::future<rest::rest_reply> guild::modify_my_nick(const std::string & newname) { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_change_name()) return aegis::make_exception_future(error::no_permission); #endif json obj = { { "nick", newname } }; return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}/members/@me/nick", guild_id), rest::Patch, obj.dump() }); } AEGIS_DECL aegis::future<rest::rest_reply> guild::add_guild_member_role(snowflake user_id, snowflake role_id) { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_roles()) return aegis::make_exception_future(error::no_permission); #endif return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}/members/{}/roles/{}", guild_id, user_id, role_id), rest::Put }); } AEGIS_DECL aegis::future<rest::rest_reply> guild::remove_guild_member_role(snowflake user_id, snowflake role_id) { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_roles()) return aegis::make_exception_future(error::no_permission); #endif return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}/members/{}/roles/{}", guild_id, user_id, role_id), rest::Delete }); } AEGIS_DECL aegis::future<rest::rest_reply> guild::remove_guild_member(snowflake user_id) { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_kick()) return aegis::make_exception_future(error::no_permission); #endif return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}/members/{}", guild_id, user_id), rest::Delete }); } AEGIS_DECL aegis::future<rest::rest_reply> guild::create_guild_ban(snowflake user_id, int8_t delete_message_days, const std::string & reason) { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_ban()) return aegis::make_exception_future(error::no_permission); #endif std::string query_params = fmt::format("?delete-message-days={}", delete_message_days); if (!reason.empty()) query_params += fmt::format("&reason={}", utility::url_encode(reason)); return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}/bans/{}", guild_id, user_id), rest::Put, {}, {}, {}, {}, query_params }); } AEGIS_DECL aegis::future<rest::rest_reply> guild::remove_guild_ban(snowflake user_id) { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_ban()) return aegis::make_exception_future(error::no_permission); #endif return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}/bans/{}", guild_id, user_id), rest::Delete }); } AEGIS_DECL aegis::future<gateway::objects::role> guild::create_guild_role(const std::string & name, permission _perms, int32_t color, bool hoist, bool mentionable) { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_roles()) return aegis::make_exception_future<gateway::objects::role>(error::no_permission); #endif json obj = { { "name", name },{ "permissions", _perms },{ "color", color },{ "hoist", hoist },{ "mentionable", mentionable } }; return _bot->get_ratelimit().post_task<gateway::objects::role>({ fmt::format("/guilds/{}/roles", guild_id), rest::Post, obj.dump() }); } AEGIS_DECL aegis::future<rest::rest_reply> guild::modify_guild_role_positions(snowflake role_id, int16_t position) { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_roles()) return aegis::make_exception_future(error::no_permission); #endif json obj = { { "id", role_id },{ "position", position } }; return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}/roles", guild_id), rest::Patch, obj.dump() }); } AEGIS_DECL aegis::future<gateway::objects::role> guild::modify_guild_role(snowflake role_id, const std::string & name, permission _perms, int32_t color, bool hoist, bool mentionable) { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_roles()) return aegis::make_exception_future<gateway::objects::role>(error::no_permission); #endif json obj = { { "name", name },{ "permissions", _perms },{ "color", color },{ "hoist", hoist },{ "mentionable", mentionable } }; return _bot->get_ratelimit().post_task<gateway::objects::role>({ fmt::format("/guilds/{}/roles/{}", guild_id, role_id), rest::Post, obj.dump() }); } AEGIS_DECL aegis::future<rest::rest_reply> guild::delete_guild_role(snowflake role_id) { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_roles()) return aegis::make_exception_future(error::no_permission); #endif return _bot->get_ratelimit().post_task({ fmt::format("/guilds/{}/roles/{}", guild_id, role_id), rest::Delete }); } /**\todo Incomplete. Signature may change */ AEGIS_DECL aegis::future<rest::rest_reply> guild::get_guild_prune_count(int16_t days) { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_kick()) return aegis::make_exception_future(error::no_permission); #endif return aegis::make_exception_future(error::not_implemented); } /**\todo Incomplete. Signature may change */ AEGIS_DECL aegis::future<rest::rest_reply> guild::begin_guild_prune(int16_t days) { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_kick()) return aegis::make_exception_future(error::no_permission); #endif return aegis::make_exception_future(error::not_implemented); } /**\todo Incomplete. Signature may change */ AEGIS_DECL aegis::future<rest::rest_reply> guild::get_guild_invites() { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_guild()) return aegis::make_exception_future(error::no_permission); #endif return aegis::make_exception_future(error::not_implemented); } /**\todo Incomplete. Signature may change */ AEGIS_DECL aegis::future<rest::rest_reply> guild::get_guild_integrations() { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_guild()) return aegis::make_exception_future(error::no_permission); #endif return aegis::make_exception_future(error::not_implemented); } /**\todo Incomplete. Signature may change */ AEGIS_DECL aegis::future<rest::rest_reply> guild::create_guild_integration() { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_guild()) return aegis::make_exception_future(error::no_permission); #endif return aegis::make_exception_future(error::not_implemented); } /**\todo Incomplete. Signature may change */ AEGIS_DECL aegis::future<rest::rest_reply> guild::modify_guild_integration() { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_guild()) return aegis::make_exception_future(error::no_permission); #endif return aegis::make_exception_future(error::not_implemented); } /**\todo Incomplete. Signature may change */ AEGIS_DECL aegis::future<rest::rest_reply> guild::delete_guild_integration() { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_guild()) return aegis::make_exception_future(error::no_permission); #endif return aegis::make_exception_future(error::not_implemented); } /**\todo Incomplete. Signature may change */ AEGIS_DECL aegis::future<rest::rest_reply> guild::sync_guild_integration() { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_guild()) return aegis::make_exception_future(error::no_permission); #endif return aegis::make_exception_future(error::not_implemented); } /**\todo Incomplete. Signature may change */ AEGIS_DECL aegis::future<rest::rest_reply> guild::get_guild_embed() { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_guild()) return aegis::make_exception_future(error::no_permission); #endif return aegis::make_exception_future(error::not_implemented); } /**\todo Incomplete. Signature may change */ AEGIS_DECL aegis::future<rest::rest_reply> guild::modify_guild_embed() { #if !defined(AEGIS_DISABLE_ALL_CACHE) if (!perms().can_manage_guild()) return aegis::make_exception_future(error::no_permission); #endif return aegis::make_exception_future(error::not_implemented); } AEGIS_DECL aegis::future<rest::rest_reply> guild::leave() { return _bot->get_ratelimit().post_task({ fmt::format("/users/@me/guilds/{0}", guild_id), rest::Delete }); } }
29,280
10,449
#pragma once #include <vector> #include <spdlog/spdlog.h> struct graphNode { graphNode(int x, int y) : x(x), y(y) {} int x; int y; }; struct graphEdge { graphEdge(int neighbourIndex, float dist) : neighbourIndex(neighbourIndex), dist(dist) {} int neighbourIndex; float dist; }; class Graph { public: Graph(); ~Graph(); //Getters int getNodesCount(); graphNode getNode(int nodeIndex); int nodeIndex(int x, int y); std::vector<int> getStartNodes(); int getStartNodeRandom(); int getEndNode(); std::vector<graphEdge>* getNeighbours(int nodeIndex); //Setters int addNode(int x, int y); //Returns the index at which the node was inserted void addStartNode(int nodeIndex); void addEndNode(int nodeIndex); void addNeighbourTo(int node, int neighbour, float dist); void addNeighbourTo(int node, int neighbour, float dist, bool checkRepetitions); void addNeighbouring(int node1, int node2, float dist); void addNeighbouring(int node1, int node2, float dist, bool checkRepetitions); bool isNeighbourOf(int node, int potentialNeighbour); float distEstimator(int node1); float distEstimator(int node1, int node2); int pickNextNode(int currentNode, int previousNode); //WARNING : should only be used if it is a stochastic graph ! (i.e. wheights of edges starting from a given node always add up to 1) //std::vector<int> trajectory(int startNode, int endNode); private: std::vector<graphNode> nodes; std::vector<int> startNodeIndexes; int endNodeIndex; std::vector<std::vector<graphEdge>*> adjencyLists; //void addNodeToList(graphEdgeList** list, int value, float dist); };
1,597
541
/** @file Http1ClientTransaction.cc - The Client Transaction class for Http1* @section license License 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 "Http1ClientTransaction.h" #include "Http1ClientSession.h" #include "HttpSM.h" void Http1ClientTransaction::release() { _proxy_ssn->clear_session_active(); } void Http1ClientTransaction::transaction_done() { SCOPED_MUTEX_LOCK(lock, this->mutex, this_ethread()); super_type::transaction_done(); if (_proxy_ssn) { static_cast<Http1ClientSession *>(_proxy_ssn)->release_transaction(); } } bool Http1ClientTransaction::allow_half_open() const { bool config_allows_it = (_sm) ? _sm->t_state.txn_conf->allow_half_open > 0 : true; if (config_allows_it) { // Check with the session to make sure the underlying transport allows the half open scenario return static_cast<Http1ClientSession *>(_proxy_ssn)->allow_half_open(); } return false; } void Http1ClientTransaction::increment_transactions_stat() { HTTP_INCREMENT_DYN_STAT(http_current_client_transactions_stat); } void Http1ClientTransaction::decrement_transactions_stat() { HTTP_DECREMENT_DYN_STAT(http_current_client_transactions_stat); }
1,932
599
#include "ag_LegendBody.h" #include <QApplication> /*! \file This file contains the implementation of the LegendBody class. */ namespace ag { //------------------------------------------------------------------------------ // DEFINITION OF STATIC CLASS MEMBERS //------------------------------------------------------------------------------ int LegendBody::d_ticLength(2); QSize LegendBody::d_keySize(20, 10); QSize LegendBody::d_labelOffset(5, 5); //! Returns the length of a tic. /*! \return Length of tic. */ int LegendBody::ticLength() { return d_ticLength; } //! Returns the size of a key. /*! \return Size of key. */ QSize const& LegendBody::keySize() { return d_keySize; } //! Returns the offset of the labels. /*! \return Offset of labels. */ QSize const& LegendBody::labelOffset() { return d_labelOffset; } //------------------------------------------------------------------------------ // DEFINITION OF CLASS MEMBERS //------------------------------------------------------------------------------ //! Constructor. /*! \param parent Parent. */ LegendBody::LegendBody( ViewerType type, QWidget* parent) : QWidget(parent), d_type(type) { } //! Destructor. /*! */ LegendBody::~LegendBody() { } ViewerType LegendBody::viewerType() const { return d_type; } //------------------------------------------------------------------------------ // DEFINITION OF FREE OPERATORS //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // DEFINITION OF FREE FUNCTIONS //------------------------------------------------------------------------------ } // namespace ag
1,765
517
//------------------------------------------------------------------------------ /* This file is part of jbcoind: https://github.com/jbcoin/jbcoind Copyright (c) 2012, 2013 Jbcoin Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <BeastConfig.h> #include <jbcoin/basics/contract.h> #include <jbcoin/json/json_reader.h> #include <algorithm> #include <string> #include <cctype> namespace Json { // Implementation of class Reader // //////////////////////////////// static std::string codePointToUTF8 (unsigned int cp) { std::string result; // based on description from http://en.wikipedia.org/wiki/UTF-8 if (cp <= 0x7f) { result.resize (1); result[0] = static_cast<char> (cp); } else if (cp <= 0x7FF) { result.resize (2); result[1] = static_cast<char> (0x80 | (0x3f & cp)); result[0] = static_cast<char> (0xC0 | (0x1f & (cp >> 6))); } else if (cp <= 0xFFFF) { result.resize (3); result[2] = static_cast<char> (0x80 | (0x3f & cp)); result[1] = 0x80 | static_cast<char> ((0x3f & (cp >> 6))); result[0] = 0xE0 | static_cast<char> ((0xf & (cp >> 12))); } else if (cp <= 0x10FFFF) { result.resize (4); result[3] = static_cast<char> (0x80 | (0x3f & cp)); result[2] = static_cast<char> (0x80 | (0x3f & (cp >> 6))); result[1] = static_cast<char> (0x80 | (0x3f & (cp >> 12))); result[0] = static_cast<char> (0xF0 | (0x7 & (cp >> 18))); } return result; } // Class Reader // ////////////////////////////////////////////////////////////////// Reader::Reader () { } bool Reader::parse ( std::string const& document, Value& root) { document_ = document; const char* begin = document_.c_str (); const char* end = begin + document_.length (); return parse ( begin, end, root ); } bool Reader::parse ( std::istream& sin, Value& root) { //std::istream_iterator<char> begin(sin); //std::istream_iterator<char> end; // Those would allow streamed input from a file, if parse() were a // template function. // Since std::string is reference-counted, this at least does not // create an extra copy. std::string doc; std::getline (sin, doc, (char)EOF); return parse ( doc, root ); } bool Reader::parse ( const char* beginDoc, const char* endDoc, Value& root) { begin_ = beginDoc; end_ = endDoc; current_ = begin_; lastValueEnd_ = 0; lastValue_ = 0; errors_.clear (); while ( !nodes_.empty () ) nodes_.pop (); nodes_.push ( &root ); bool successful = readValue (); Token token; skipCommentTokens ( token ); if ( !root.isArray () && !root.isObject () ) { // Set error location to start of doc, ideally should be first token found in doc token.type_ = tokenError; token.start_ = beginDoc; token.end_ = endDoc; addError ( "A valid JSON document must be either an array or an object value.", token ); return false; } return successful; } bool Reader::readValue () { Token token; skipCommentTokens ( token ); bool successful = true; switch ( token.type_ ) { case tokenObjectBegin: successful = readObject ( token ); break; case tokenArrayBegin: successful = readArray ( token ); break; case tokenInteger: successful = decodeNumber ( token ); break; case tokenDouble: successful = decodeDouble ( token ); break; case tokenString: successful = decodeString ( token ); break; case tokenTrue: currentValue () = true; break; case tokenFalse: currentValue () = false; break; case tokenNull: currentValue () = Value (); break; default: return addError ( "Syntax error: value, object or array expected.", token ); } return successful; } void Reader::skipCommentTokens ( Token& token ) { do { readToken ( token ); } while ( token.type_ == tokenComment ); } bool Reader::expectToken ( TokenType type, Token& token, const char* message ) { readToken ( token ); if ( token.type_ != type ) return addError ( message, token ); return true; } bool Reader::readToken ( Token& token ) { skipSpaces (); token.start_ = current_; Char c = getNextChar (); bool ok = true; switch ( c ) { case '{': token.type_ = tokenObjectBegin; break; case '}': token.type_ = tokenObjectEnd; break; case '[': token.type_ = tokenArrayBegin; break; case ']': token.type_ = tokenArrayEnd; break; case '"': token.type_ = tokenString; ok = readString (); break; case '/': token.type_ = tokenComment; ok = readComment (); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': token.type_ = readNumber (); break; case 't': token.type_ = tokenTrue; ok = match ( "rue", 3 ); break; case 'f': token.type_ = tokenFalse; ok = match ( "alse", 4 ); break; case 'n': token.type_ = tokenNull; ok = match ( "ull", 3 ); break; case ',': token.type_ = tokenArraySeparator; break; case ':': token.type_ = tokenMemberSeparator; break; case 0: token.type_ = tokenEndOfStream; break; default: ok = false; break; } if ( !ok ) token.type_ = tokenError; token.end_ = current_; return true; } void Reader::skipSpaces () { while ( current_ != end_ ) { Char c = *current_; if ( c == ' ' || c == '\t' || c == '\r' || c == '\n' ) ++current_; else break; } } bool Reader::match ( Location pattern, int patternLength ) { if ( end_ - current_ < patternLength ) return false; int index = patternLength; while ( index-- ) if ( current_[index] != pattern[index] ) return false; current_ += patternLength; return true; } bool Reader::readComment () { Char c = getNextChar (); if ( c == '*' ) return readCStyleComment (); if ( c == '/' ) return readCppStyleComment (); return false; } bool Reader::readCStyleComment () { while ( current_ != end_ ) { Char c = getNextChar (); if ( c == '*' && *current_ == '/' ) break; } return getNextChar () == '/'; } bool Reader::readCppStyleComment () { while ( current_ != end_ ) { Char c = getNextChar (); if ( c == '\r' || c == '\n' ) break; } return true; } Reader::TokenType Reader::readNumber () { static char const extended_tokens[] = { '.', 'e', 'E', '+', '-' }; TokenType type = tokenInteger; if ( current_ != end_ ) { if (*current_ == '-') ++current_; while ( current_ != end_ ) { if (!std::isdigit (*current_)) { auto ret = std::find (std::begin (extended_tokens), std::end (extended_tokens), *current_); if (ret == std::end (extended_tokens)) break; type = tokenDouble; } ++current_; } } return type; } bool Reader::readString () { Char c = 0; while ( current_ != end_ ) { c = getNextChar (); if ( c == '\\' ) getNextChar (); else if ( c == '"' ) break; } return c == '"'; } bool Reader::readObject ( Token& tokenStart ) { Token tokenName; std::string name; currentValue () = Value ( objectValue ); while ( readToken ( tokenName ) ) { bool initialTokenOk = true; while ( tokenName.type_ == tokenComment && initialTokenOk ) initialTokenOk = readToken ( tokenName ); if ( !initialTokenOk ) break; if ( tokenName.type_ == tokenObjectEnd && name.empty () ) // empty object return true; if ( tokenName.type_ != tokenString ) break; name = ""; if ( !decodeString ( tokenName, name ) ) return recoverFromError ( tokenObjectEnd ); Token colon; if ( !readToken ( colon ) || colon.type_ != tokenMemberSeparator ) { return addErrorAndRecover ( "Missing ':' after object member name", colon, tokenObjectEnd ); } // Reject duplicate names if (currentValue ().isMember (name)) return addError ( "Key '" + name + "' appears twice.", tokenName ); Value& value = currentValue ()[ name ]; nodes_.push ( &value ); bool ok = readValue (); nodes_.pop (); if ( !ok ) // error already set return recoverFromError ( tokenObjectEnd ); Token comma; if ( !readToken ( comma ) || ( comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator && comma.type_ != tokenComment ) ) { return addErrorAndRecover ( "Missing ',' or '}' in object declaration", comma, tokenObjectEnd ); } bool finalizeTokenOk = true; while ( comma.type_ == tokenComment && finalizeTokenOk ) finalizeTokenOk = readToken ( comma ); if ( comma.type_ == tokenObjectEnd ) return true; } return addErrorAndRecover ( "Missing '}' or object member name", tokenName, tokenObjectEnd ); } bool Reader::readArray ( Token& tokenStart ) { currentValue () = Value ( arrayValue ); skipSpaces (); if ( *current_ == ']' ) // empty array { Token endArray; readToken ( endArray ); return true; } int index = 0; while ( true ) { Value& value = currentValue ()[ index++ ]; nodes_.push ( &value ); bool ok = readValue (); nodes_.pop (); if ( !ok ) // error already set return recoverFromError ( tokenArrayEnd ); Token token; // Accept Comment after last item in the array. ok = readToken ( token ); while ( token.type_ == tokenComment && ok ) { ok = readToken ( token ); } bool badTokenType = ( token.type_ != tokenArraySeparator && token.type_ != tokenArrayEnd ); if ( !ok || badTokenType ) { return addErrorAndRecover ( "Missing ',' or ']' in array declaration", token, tokenArrayEnd ); } if ( token.type_ == tokenArrayEnd ) break; } return true; } bool Reader::decodeNumber ( Token& token ) { Location current = token.start_; bool isNegative = *current == '-'; if ( isNegative ) ++current; if (current == token.end_) { return addError ( "'" + std::string ( token.start_, token.end_ ) + "' is not a valid number.", token ); } // The existing Json integers are 32-bit so using a 64-bit value here avoids // overflows in the conversion code below. std::int64_t value = 0; static_assert(sizeof(value) > sizeof(Value::maxUInt), "The JSON integer overflow logic will need to be reworked."); while (current < token.end_ && (value <= Value::maxUInt)) { Char c = *current++; if ( c < '0' || c > '9' ) { return addError ( "'" + std::string ( token.start_, token.end_ ) + "' is not a number.", token ); } value = (value * 10) + (c - '0'); } // More tokens left -> input is larger than largest possible return value if (current != token.end_) { return addError ( "'" + std::string ( token.start_, token.end_ ) + "' exceeds the allowable range.", token ); } if ( isNegative ) { value = -value; if (value < Value::minInt || value > Value::maxInt) { return addError ( "'" + std::string ( token.start_, token.end_ ) + "' exceeds the allowable range.", token ); } currentValue () = static_cast<Value::Int>( value ); } else { if (value > Value::maxUInt) { return addError ( "'" + std::string ( token.start_, token.end_ ) + "' exceeds the allowable range.", token ); } // If it's representable as a signed integer, construct it as one. if ( value <= Value::maxInt ) currentValue () = static_cast<Value::Int>( value ); else currentValue () = static_cast<Value::UInt>( value ); } return true; } bool Reader::decodeDouble( Token &token ) { double value = 0; const int bufferSize = 32; int count; int length = int(token.end_ - token.start_); // Sanity check to avoid buffer overflow exploits. if (length < 0) { return addError( "Unable to parse token length", token ); } // Avoid using a string constant for the format control string given to // sscanf, as this can cause hard to debug crashes on OS X. See here for more // info: // // http://developer.apple.com/library/mac/#DOCUMENTATION/DeveloperTools/gcc-4.0.1/gcc/Incompatibilities.html char format[] = "%lf"; if ( length <= bufferSize ) { Char buffer[bufferSize+1]; memcpy( buffer, token.start_, length ); buffer[length] = 0; count = sscanf( buffer, format, &value ); } else { std::string buffer( token.start_, token.end_ ); count = sscanf( buffer.c_str(), format, &value ); } if ( count != 1 ) return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token ); currentValue() = value; return true; } bool Reader::decodeString ( Token& token ) { std::string decoded; if ( !decodeString ( token, decoded ) ) return false; currentValue () = decoded; return true; } bool Reader::decodeString ( Token& token, std::string& decoded ) { decoded.reserve ( token.end_ - token.start_ - 2 ); Location current = token.start_ + 1; // skip '"' Location end = token.end_ - 1; // do not include '"' while ( current != end ) { Char c = *current++; if ( c == '"' ) break; else if ( c == '\\' ) { if ( current == end ) return addError ( "Empty escape sequence in string", token, current ); Char escape = *current++; switch ( escape ) { case '"': decoded += '"'; break; case '/': decoded += '/'; break; case '\\': decoded += '\\'; break; case 'b': decoded += '\b'; break; case 'f': decoded += '\f'; break; case 'n': decoded += '\n'; break; case 'r': decoded += '\r'; break; case 't': decoded += '\t'; break; case 'u': { unsigned int unicode; if ( !decodeUnicodeCodePoint ( token, current, end, unicode ) ) return false; decoded += codePointToUTF8 (unicode); } break; default: return addError ( "Bad escape sequence in string", token, current ); } } else { decoded += c; } } return true; } bool Reader::decodeUnicodeCodePoint ( Token& token, Location& current, Location end, unsigned int& unicode ) { if ( !decodeUnicodeEscapeSequence ( token, current, end, unicode ) ) return false; if (unicode >= 0xD800 && unicode <= 0xDBFF) { // surrogate pairs if (end - current < 6) return addError ( "additional six characters expected to parse unicode surrogate pair.", token, current ); unsigned int surrogatePair; if (* (current++) == '\\' && * (current++) == 'u') { if (decodeUnicodeEscapeSequence ( token, current, end, surrogatePair )) { unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF); } else return false; } else return addError ( "expecting another \\u token to begin the second half of a unicode surrogate pair", token, current ); } return true; } bool Reader::decodeUnicodeEscapeSequence ( Token& token, Location& current, Location end, unsigned int& unicode ) { if ( end - current < 4 ) return addError ( "Bad unicode escape sequence in string: four digits expected.", token, current ); unicode = 0; for ( int index = 0; index < 4; ++index ) { Char c = *current++; unicode *= 16; if ( c >= '0' && c <= '9' ) unicode += c - '0'; else if ( c >= 'a' && c <= 'f' ) unicode += c - 'a' + 10; else if ( c >= 'A' && c <= 'F' ) unicode += c - 'A' + 10; else return addError ( "Bad unicode escape sequence in string: hexadecimal digit expected.", token, current ); } return true; } bool Reader::addError ( std::string const& message, Token& token, Location extra ) { ErrorInfo info; info.token_ = token; info.message_ = message; info.extra_ = extra; errors_.push_back ( info ); return false; } bool Reader::recoverFromError ( TokenType skipUntilToken ) { int errorCount = int (errors_.size ()); Token skip; while ( true ) { if ( !readToken (skip) ) errors_.resize ( errorCount ); // discard errors caused by recovery if ( skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream ) break; } errors_.resize ( errorCount ); return false; } bool Reader::addErrorAndRecover ( std::string const& message, Token& token, TokenType skipUntilToken ) { addError ( message, token ); return recoverFromError ( skipUntilToken ); } Value& Reader::currentValue () { return * (nodes_.top ()); } Reader::Char Reader::getNextChar () { if ( current_ == end_ ) return 0; return *current_++; } void Reader::getLocationLineAndColumn ( Location location, int& line, int& column ) const { Location current = begin_; Location lastLineStart = current; line = 0; while ( current < location && current != end_ ) { Char c = *current++; if ( c == '\r' ) { if ( *current == '\n' ) ++current; lastLineStart = current; ++line; } else if ( c == '\n' ) { lastLineStart = current; ++line; } } // column & line start at 1 column = int (location - lastLineStart) + 1; ++line; } std::string Reader::getLocationLineAndColumn ( Location location ) const { int line, column; getLocationLineAndColumn ( location, line, column ); char buffer[18 + 16 + 16 + 1]; sprintf ( buffer, "Line %d, Column %d", line, column ); return buffer; } std::string Reader::getFormatedErrorMessages () const { std::string formattedMessage; for ( Errors::const_iterator itError = errors_.begin (); itError != errors_.end (); ++itError ) { const ErrorInfo& error = *itError; formattedMessage += "* " + getLocationLineAndColumn ( error.token_.start_ ) + "\n"; formattedMessage += " " + error.message_ + "\n"; if ( error.extra_ ) formattedMessage += "See " + getLocationLineAndColumn ( error.extra_ ) + " for detail.\n"; } return formattedMessage; } std::istream& operator>> ( std::istream& sin, Value& root ) { Json::Reader reader; bool ok = reader.parse (sin, root); //JSON_ASSERT( ok ); if (! ok) jbcoin::Throw<std::runtime_error> (reader.getFormatedErrorMessages ()); return sin; } } // namespace Json
22,259
6,671
//============================================================================================================= /** * @file ssvepbci.cpp * @author Viktor Klüber <viktor.klueber@tu-ilmenau.de>; * Lorenz Esch <lorenz.esch@tu-ilmenau.de>; * Matti Hamalainen <msh@nmr.mgh.harvard.edu> * @version 1.0 * @date May, 2016 * * @section LICENSE * * Copyright (C) 2016, Lorenz Esch and Matti Hamalainen. 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 the Massachusetts General Hospital 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 MASSACHUSETTS GENERAL HOSPITAL 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. * * * @brief Contains the implementation of the BCI class. * */ //************************************************************************************************************* //============================================================================================================= // INCLUDES //============================================================================================================= #include "ssvepbci.h" #include <iostream> #include <Eigen/Dense> #include <utils/ioutils.h> //************************************************************************************************************* //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QtCore/QtPlugin> #include <QtCore/QTextStream> #include <QDebug> //************************************************************************************************************* //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace SSVEPBCIPLUGIN; using namespace SCSHAREDLIB; using namespace SCMEASLIB; using namespace IOBUFFER; using namespace FSLIB; using namespace std; //************************************************************************************************************* //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= SsvepBci::SsvepBci() : m_qStringResourcePath(qApp->applicationDirPath()+"/mne_scan_plugins/resources/ssvepbci/") , m_bProcessData(false) , m_dAlpha(0.25) , m_iNumberOfHarmonics(2) , m_bUseMEC(true) , m_bRemovePowerLine(false) , m_iPowerLine(50) , m_bChangeSSVEPParameterFlag(false) , m_bInitializeSource(true) , m_iNumberOfClassHits(15) , m_iClassListSize(20) , m_iNumberOfClassBreaks(30) { // Create configuration action bar item/button m_pActionBCIConfiguration = new QAction(QIcon(":/images/configuration.png"),tr("BCI configuration feature"),this); m_pActionBCIConfiguration->setStatusTip(tr("BCI configuration feature")); connect(m_pActionBCIConfiguration, &QAction::triggered, this, &SsvepBci::showBCIConfiguration); addPluginAction(m_pActionBCIConfiguration); // Create start Stimuli action bar item/button m_pActionSetupStimulus = new QAction(QIcon(":/images/stimulus.png"),tr("setup stimulus feature"),this); m_pActionSetupStimulus->setStatusTip(tr("Setup stimulus feature")); connect(m_pActionSetupStimulus, &QAction::triggered, this, &SsvepBci::showSetupStimulus); addPluginAction(m_pActionSetupStimulus); // Intitalise BCI data m_slChosenChannelsSensor << "9Z" << "8Z" << "7Z" << "6Z" << "9L" << "8L" << "9R" << "8R"; //<< "TEST"; //m_slChosenChannelsSensor << "24" << "25" << "26" << "28" << "29" << "30" << "31" << "32"; m_lElectrodeNumbers << 33 << 34 << 35 << 36 << 40 << 41 << 42 << 43; //m_lElectrodeNumbers << 24 << 25 << 26 << 28 << 29 << 30 << 31 << 32; m_lDesFrequencies << 6.66 << 7.5 <<8.57 << 10 << 12; m_lThresholdValues << 0.12 << 0.12 << 0.12 << 0.12 << 0.12; setFrequencyList(m_lDesFrequencies); } //************************************************************************************************************* SsvepBci::~SsvepBci() { //If the program is closed while the sampling is in process if(this->isRunning()){ this->stop(); } } //************************************************************************************************************* QSharedPointer<IPlugin> SsvepBci::clone() const { QSharedPointer<SsvepBci> pSSVEPClone(new SsvepBci()); return pSSVEPClone; } //************************************************************************************************************* void SsvepBci::init() { m_bIsRunning = false; // Inputs - Source estimates and sensor level m_pRTSEInput = PluginInputData<RealTimeSourceEstimate>::create(this, "BCIInSource", "BCI source input data"); connect(m_pRTSEInput.data(), &PluginInputConnector::notify, this, &SsvepBci::updateSource, Qt::DirectConnection); m_inputConnectors.append(m_pRTSEInput); m_pRTMSAInput = PluginInputData<NewRealTimeMultiSampleArray>::create(this, "BCIInSensor", "SourceLab sensor input data"); connect(m_pRTMSAInput.data(), &PluginInputConnector::notify, this, &SsvepBci::updateSensor, Qt::DirectConnection); m_inputConnectors.append(m_pRTMSAInput); // // Output streams // m_pBCIOutputOne = PluginOutputData<NewRealTimeSampleArray>::create(this, "ControlSignal", "BCI output data One"); // m_pBCIOutputOne->data()->setArraySize(1); // m_pBCIOutputOne->data()->setName("Boundary"); // m_outputConnectors.append(m_pBCIOutputOne); // m_pBCIOutputTwo = PluginOutputData<NewRealTimeSampleArray>::create(this, "ControlSignal", "BCI output data Two"); // m_pBCIOutputTwo->data()->setArraySize(1); // m_pBCIOutputTwo->data()->setName("Left electrode var"); // m_outputConnectors.append(m_pBCIOutputTwo); // m_pBCIOutputThree = PluginOutputData<NewRealTimeSampleArray>::create(this, "ControlSignal", "BCI output data Three"); // m_pBCIOutputThree->data()->setArraySize(1); // m_pBCIOutputThree->data()->setName("Right electrode var"); // m_outputConnectors.append(m_pBCIOutputThree); // m_pBCIOutputFour = PluginOutputData<NewRealTimeSampleArray>::create(this, "ControlSignal", "BCI output data Four"); // m_pBCIOutputFour->data()->setArraySize(1); // m_pBCIOutputFour->data()->setName("Left electrode"); // m_outputConnectors.append(m_pBCIOutputFour); // m_pBCIOutputFive = PluginOutputData<NewRealTimeSampleArray>::create(this, "ControlSignal", "BCI output data Five"); // m_pBCIOutputFive->data()->setArraySize(1); // m_pBCIOutputFive->data()->setName("Right electrode"); // m_outputConnectors.append(m_pBCIOutputFive); // Delete Buffer - will be initailzed with first incoming data m_pBCIBuffer_Sensor = CircularMatrixBuffer<double>::SPtr(); m_pBCIBuffer_Source = CircularMatrixBuffer<double>::SPtr(); // Delete fiff info because the initialisation of the fiff info is seen as the first data acquisition from the input stream m_pFiffInfo_Sensor = FiffInfo::SPtr(); // Intitalise GUI stuff m_bUseSensorData = true; // // Init BCIFeatureWindow for visualization // m_BCIFeatureWindow = QSharedPointer<BCIFeatureWindow>(new BCIFeatureWindow(this)); } //************************************************************************************************************* void SsvepBci::unload() { } //************************************************************************************************************* bool SsvepBci::start() { // Init debug output stream QString path("BCIDebugFile.txt"); path.prepend(m_qStringResourcePath); m_outStreamDebug.open(path.toStdString(), ios::trunc); m_pFiffInfo_Sensor = FiffInfo::SPtr(); // initialize time window parameters m_iWriteIndex = 0; m_iReadIndex = 0; m_iCounter = 0; m_iReadToWriteBuffer = 0; m_iDownSampleIndex = 0; m_iFormerDownSampleIndex = 0; m_iWindowSize = 8; m_bIsRunning = true; // starting the thread for data processing QThread::start(); return true; } //************************************************************************************************************* bool SsvepBci::stop() { m_bIsRunning = false; // Get data buffers out of idle state if they froze in the acquire or release function //In case the semaphore blocks the thread -> Release the QSemaphore and let it exit from the pop function (acquire statement) if(m_bProcessData) // Only clear if buffers have been initialised { m_pBCIBuffer_Sensor->releaseFromPop(); m_pBCIBuffer_Sensor->releaseFromPush(); // m_pBCIBuffer_Source->releaseFromPop(); // m_pBCIBuffer_Source->releaseFromPush(); } // Stop filling buffers with data from the inputs m_bProcessData = false; // Delete all features and classification results clearClassifications(); return true; } //************************************************************************************************************* IPlugin::PluginType SsvepBci::getType() const { return _IAlgorithm; } //************************************************************************************************************* QString SsvepBci::getName() const { return "SSVEP-BCI-EEG"; } //************************************************************************************************************* QWidget* SsvepBci::setupWidget() { SsvepBciWidget* setupWidget = new SsvepBciWidget(this);//widget is later destroyed by CentralWidget - so it has to be created everytime new //init properties dialog setupWidget->initGui(); return setupWidget; } //************************************************************************************************************* void SsvepBci::updateSensor(SCMEASLIB::NewMeasurement::SPtr pMeasurement) { // initialize the sample array which will be filled with raw data QSharedPointer<NewRealTimeMultiSampleArray> pRTMSA = pMeasurement.dynamicCast<NewRealTimeMultiSampleArray>(); if(pRTMSA){ //Check if buffer initialized m_qMutex.lock(); if(!m_pBCIBuffer_Sensor) m_pBCIBuffer_Sensor = CircularMatrixBuffer<double>::SPtr(new CircularMatrixBuffer<double>(64, pRTMSA->getNumChannels(), pRTMSA->getMultiSampleArray()[0].cols())); } //Fiff information if(!m_pFiffInfo_Sensor) { m_pFiffInfo_Sensor = pRTMSA->info(); //emit fiffInfoAvailable(); // QStringList chs = m_pFiffInfo_Sensor->ch_names; //calculating downsampling parameter for incoming data m_iDownSampleIncrement = m_pFiffInfo_Sensor->sfreq/100; m_dSampleFrequency = m_pFiffInfo_Sensor->sfreq/m_iDownSampleIncrement;//m_pFiffInfo_Sensor->sfreq; // determine sliding time window parameters m_iReadSampleSize = 0.1*m_dSampleFrequency; // about 0.1 second long time segment as basic read increment m_iWriteSampleSize = pRTMSA->getMultiSampleArray()[0].cols(); m_iTimeWindowLength = int(5*m_dSampleFrequency) + int(pRTMSA->getMultiSampleArray()[0].cols()/m_iDownSampleIncrement) + 1 ; //m_iTimeWindowSegmentSize = int(5*m_dSampleFrequency / m_iWriteSampleSize) + 1; // 4 seconds long maximal sized window m_matSlidingTimeWindow.resize(m_lElectrodeNumbers.size(), m_iTimeWindowLength);//m_matSlidingTimeWindow.resize(rows, m_iTimeWindowSegmentSize*pRTMSA->getMultiSampleArray()[0].cols()); cout << "Down Sample Increment:" << m_iDownSampleIncrement << endl; cout << "Read Sample Size:" << m_iReadSampleSize << endl; cout << "Downsampled Frequency:" << m_dSampleFrequency << endl; cout << "Write Sample SIze :" << m_iWriteSampleSize<< endl; cout << "Length of the time window:" << m_iTimeWindowLength << endl; } m_qMutex.unlock(); // filling the matrix buffer if(m_bProcessData){ MatrixXd t_mat; for(qint32 i = 0; i < pRTMSA->getMultiArraySize(); ++i){ t_mat = pRTMSA->getMultiSampleArray()[i]; m_pBCIBuffer_Sensor->push(&t_mat); } } } //************************************************************************************************************* void SsvepBci::updateSource(SCMEASLIB::NewMeasurement::SPtr pMeasurement) { QSharedPointer<RealTimeSourceEstimate> pRTSE = pMeasurement.dynamicCast<RealTimeSourceEstimate>(); if(pRTSE) { //Check if buffer initialized if(!m_pBCIBuffer_Source){ m_pBCIBuffer_Source = CircularMatrixBuffer<double>::SPtr(new CircularMatrixBuffer<double>(64, pRTSE->getValue()->data.rows(), pRTSE->getValue()->data.cols())); } if(m_bProcessData) { MatrixXd t_mat(pRTSE->getValue()->data.rows(), pRTSE->getValue()->data.cols()); for(unsigned char i = 0; i < pRTSE->getValue()->data.cols(); ++i) t_mat.col(i) = pRTSE->getValue()->data.col(i); m_pBCIBuffer_Source->push(&t_mat); } } // Initalize parameter for processing BCI on source level if(m_bInitializeSource){ m_bInitializeSource = false; } QList<Label> labels; QList<RowVector4i> labelRGBAs; QSharedPointer<SurfaceSet> SPtrSurfSet = pRTSE->getSurfSet(); SurfaceSet *pSurf = SPtrSurfSet.data(); SurfaceSet surf = *pSurf; qDebug() << "label acquisation successful:" << pRTSE->getAnnotSet()->toLabels(surf, labels, labelRGBAs); foreach(Label label, labels){ qDebug() << "label IDs: " << label.label_id << "\v" << "label name: " << label.name; } QList<VectorXi> vertNo = pRTSE->getFwdSolution()->src.get_vertno(); foreach(VectorXi vector, vertNo){ cout << "vertNo:" << vector << endl; } } //************************************************************************************************************* void SsvepBci::clearClassifications() { m_qMutex.lock(); m_lIndexOfClassResultSensor.clear(); m_qMutex.unlock(); } //************************************************************************************************************* void SsvepBci::setNumClassHits(int numClassHits){ m_iNumberOfClassHits = numClassHits; } //************************************************************************************************************* void SsvepBci::setNumClassBreaks(int numClassBreaks){ m_iNumberOfClassBreaks = numClassBreaks; } //************************************************************************************************************* void SsvepBci::setChangeSSVEPParameterFlag(){ m_bChangeSSVEPParameterFlag = true; } //************************************************************************************************************* void SsvepBci::setSizeClassList(int classListSize){ m_iClassListSize = classListSize; } //************************************************************************************************************* QString SsvepBci::getSsvepBciResourcePath(){ return m_qStringResourcePath; } //************************************************************************************************************* void SsvepBci::showSetupStimulus() { QDesktopWidget Desktop; // Desktop Widget for getting the number of accessible screens if(Desktop.numScreens()> 1){ // Open setup stimulus widget if(m_pSsvepBciSetupStimulusWidget == NULL) m_pSsvepBciSetupStimulusWidget = QSharedPointer<SsvepBciSetupStimulusWidget>(new SsvepBciSetupStimulusWidget(this)); if(!m_pSsvepBciSetupStimulusWidget->isVisible()){ m_pSsvepBciSetupStimulusWidget->setWindowTitle("ssvepBCI - Setup Stimulus"); //m_pSsvepBciSetupStimulusWidget->initGui(); m_pSsvepBciSetupStimulusWidget->show(); m_pSsvepBciSetupStimulusWidget->raise(); } //sets Window to the foreground and activates it for editing m_pSsvepBciSetupStimulusWidget->activateWindow(); } else{ QMessageBox msgBox; msgBox.setText("Only one screen detected!\nFor stimulus visualization attach one more."); msgBox.exec(); return; } } //************************************************************************************************************* void SsvepBci::showBCIConfiguration() { // Open setup stimulus widget if(m_pSsvepBciConfigurationWidget == NULL) m_pSsvepBciConfigurationWidget = QSharedPointer<SsvepBciConfigurationWidget>(new SsvepBciConfigurationWidget(this)); if(!m_pSsvepBciConfigurationWidget->isVisible()){ m_pSsvepBciConfigurationWidget->setWindowTitle("ssvepBCI - Configuration"); m_pSsvepBciConfigurationWidget->show(); m_pSsvepBciConfigurationWidget->raise(); } //sets Window to the foreground and activates it for editing m_pSsvepBciConfigurationWidget->activateWindow(); } //************************************************************************************************************* void SsvepBci::removePowerLine(bool removePowerLine) { m_qMutex.lock(); m_bRemovePowerLine = removePowerLine; m_qMutex.unlock(); } //************************************************************************************************************* void SsvepBci::setPowerLine(int powerLine) { m_qMutex.lock(); m_iPowerLine = powerLine; m_qMutex.unlock(); } //************************************************************************************************************* void SsvepBci::setFeatureExtractionMethod(bool useMEC) { m_qMutex.lock(); m_bUseMEC = useMEC; m_qMutex.unlock(); } //************************************************************************************************************* void SsvepBci::changeSSVEPParameter(){ // update frequency list from setup stimulus widget if activated if(m_pSsvepBciSetupStimulusWidget){ setFrequencyList(m_pSsvepBciSetupStimulusWidget->getFrequencies()); } if(m_pSsvepBciConfigurationWidget){ // update number of harmonics of reference signal m_iNumberOfHarmonics = 1 + m_pSsvepBciConfigurationWidget->getNumOfHarmonics(); // update channel select QStringList channelSelectSensor = m_pSsvepBciConfigurationWidget->getSensorChannelSelection(); if(channelSelectSensor.size() > 0){ // update the list of selected channels m_slChosenChannelsSensor = channelSelectSensor; // get new list of electrode numbers m_lElectrodeNumbers.clear(); foreach(const QString &str, m_slChosenChannelsSensor){ m_lElectrodeNumbers << m_mapElectrodePinningScheme.value(str); } // reset sliding time window parameter m_iWriteIndex = 0; m_iReadIndex = 0; m_iCounter = 0; m_iReadToWriteBuffer = 0; m_iDownSampleIndex = 0; m_iFormerDownSampleIndex = 0; // resize the time window with new electrode numbers m_matSlidingTimeWindow.resize(m_lElectrodeNumbers.size(), m_iTimeWindowLength); } } // reset flag for changing SSVEP parameter m_bChangeSSVEPParameterFlag = false; } //************************************************************************************************************* void SsvepBci::setThresholdValues(MyQList thresholds){ m_lThresholdValues = thresholds; } //************************************************************************************************************* void SsvepBci::run(){ while(m_bIsRunning){ if(m_bUseSensorData){ ssvepBciOnSensor(); } else{ ssvepBciOnSource(); } } } //************************************************************************************************************* void SsvepBci::setFrequencyList(QList<double> frequencyList) { if(!frequencyList.isEmpty()){ // update list of desired frequencies m_lDesFrequencies.clear(); m_lDesFrequencies = frequencyList; // update the list of all frequencies m_lAllFrequencies.clear(); m_lAllFrequencies = m_lDesFrequencies; for(int i = 0; i < m_lDesFrequencies.size() - 1; i++){ m_lAllFrequencies.append((m_lDesFrequencies.at(i) + m_lDesFrequencies.at(i + 1) ) / 2); } // emit novel frequency list emit getFrequencyLabels(m_lDesFrequencies); } } //************************************************************************************************************* QList<double> SsvepBci::getCurrentListOfFrequencies(){ return m_lDesFrequencies; } //************************************************************************************************************* double SsvepBci::MEC(MatrixXd &Y, MatrixXd &X) { // Remove SSVEP harmonic frequencies MatrixXd X_help = X.transpose()*X; MatrixXd Ytilde = Y - X*X_help.inverse()*X.transpose()*Y; // Find eigenvalues and eigenvectors SelfAdjointEigenSolver<MatrixXd> eigensolver(Ytilde.transpose()*Ytilde); // Determine number of channels Ns int Ns; VectorXd cumsum = eigensolver.eigenvalues(); for(int j = 1; j < eigensolver.eigenvalues().size(); j++){ cumsum(j) += cumsum(j - 1); } for(Ns = 0; Ns < eigensolver.eigenvalues().size() ; Ns++){ if(cumsum(Ns)/eigensolver.eigenvalues().sum() > 0.1){ break; } } Ns += 1; // Determine spatial filter matrix W MatrixXd W = eigensolver.eigenvectors().block(0, 0, eigensolver.eigenvectors().rows(), Ns); for(int k = 0; k < Ns; k++){ W.col(k) = W.col(k)*(1/sqrt(eigensolver.eigenvalues()(k))); } // Calcuclate channel signals MatrixXd S = Y*W; // Calculate signal energy MatrixXd P(2, Ns); double power = 0; for(int k = 0; k < m_iNumberOfHarmonics; k++){ P = X.block(0, 2*k, X.rows(), 2).transpose()*S; P = P.array()*P.array(); power += 1 / double(m_iNumberOfHarmonics*Ns) * P.sum(); } return power; } //************************************************************************************************************* double SsvepBci::CCA(MatrixXd &Y, MatrixXd &X) { // CCA parameter int n = X.rows(); int p1 = X.cols(); int p2 = Y.cols(); // center data sets MatrixXd X_center(n, p1); MatrixXd Y_center(n, p2); for(int i = 0; i < p1; i++){ X_center.col(i) = X.col(i).array() - X.col(i).mean(); } for(int i = 0; i < p2; i++){ Y_center.col(i) = Y.col(i).array() - Y.col(i).mean(); } // QR decomposition MatrixXd Q1, Q2; ColPivHouseholderQR<MatrixXd> qr1(X_center), qr2(Y_center); Q1 = qr1.householderQ() * MatrixXd::Identity(n, p1); Q2 = qr2.householderQ() * MatrixXd::Identity(n, p2); // SVD decomposition, determine max correlation JacobiSVD<MatrixXd> svd(Q1.transpose()*Q2); // ComputeThinU | ComputeThinV return svd.singularValues().maxCoeff(); } //************************************************************************************************************* void SsvepBci::readFromSlidingTimeWindow(MatrixXd &data) { data.resize(m_matSlidingTimeWindow.rows(), m_iWindowSize*m_iReadSampleSize); // consider matrix overflow case if(data.cols() > m_iReadIndex + 1){ int width = data.cols() - (m_iReadIndex + 1); data.block(0, 0, data.rows(), width) = m_matSlidingTimeWindow.block(0, m_matSlidingTimeWindow.cols() - width , data.rows(), width ); data.block(0, width, data.rows(), m_iReadIndex + 1) = m_matSlidingTimeWindow.block(0, 0, data.rows(), m_iReadIndex + 1); } else{ data = m_matSlidingTimeWindow.block(0, m_iReadIndex - (data.cols() - 1), data.rows(), data.cols()); // consider case without matrix overflow } // transpose in the same data space and avoiding aliasing data.transposeInPlace(); } //************************************************************************************************************* void SsvepBci::ssvepBciOnSensor() { // Wait for fiff Info if not yet received - this is needed because we have to wait until the buffers are firstly initiated in the update functions while(!m_pFiffInfo_Sensor){ msleep(10); } // reset list of classifiaction results MatrixXd m_matSSVEPProbabilities(m_lDesFrequencies.size(), 0); // Start filling buffers with data from the inputs m_bProcessData = true; MatrixXd t_mat = m_pBCIBuffer_Sensor->pop(); // writing selected feature channels to the time window storage and increase the segment index int writtenSamples = 0; while(m_iDownSampleIndex >= m_iFormerDownSampleIndex){ // write from t_mat to the sliding time window while doing channel select and downsampling m_iFormerDownSampleIndex = m_iDownSampleIndex; for(int i = 0; i < m_lElectrodeNumbers.size(); i++){ m_matSlidingTimeWindow(i, m_iWriteIndex) = t_mat(m_lElectrodeNumbers.at(i), m_iDownSampleIndex); } writtenSamples++; // update counter variables m_iWriteIndex = (m_iWriteIndex + 1) % m_iTimeWindowLength; m_iDownSampleIndex = (m_iDownSampleIndex + m_iDownSampleIncrement ) % m_iWriteSampleSize; } m_iFormerDownSampleIndex = m_iDownSampleIndex; // calculate buffer between read- and write index m_iReadToWriteBuffer = m_iReadToWriteBuffer + writtenSamples; // execute processing loop as long as there is new data to be red from the time window while(m_iReadToWriteBuffer >= m_iReadSampleSize) { if(m_iCounter > m_iNumberOfClassBreaks) { // determine window size according to former counted miss classifications m_iWindowSize = 10; if(m_iCounter <= 50 && m_iCounter > 40){ m_iWindowSize = 20; } if(m_iCounter > 50){ m_iWindowSize = 40; } // create current data matrix Y MatrixXd Y; readFromSlidingTimeWindow(Y); // create realtive timeline according to Y int samples = Y.rows(); ArrayXd t = 2*M_PI/m_dSampleFrequency * ArrayXd::LinSpaced(samples, 1, samples); // Remove 50 Hz Power line signal if(m_bRemovePowerLine){ MatrixXd Zp(samples,2); ArrayXd t_PL = t*m_iPowerLine; Zp.col(0) = t_PL.sin(); Zp.col(1) = t_PL.cos(); MatrixXd Zp_help = Zp.transpose()*Zp; Y = Y - Zp*Zp_help.inverse()*Zp.transpose()*Y; } qDebug() << "size of Matrix:" << Y.rows() << Y.cols(); // apply feature extraction for all frequencies of interest VectorXd ssvepProbabilities(m_lAllFrequencies.size()); for(int i = 0; i < m_lAllFrequencies.size(); i++) { // create reference signal matrix X MatrixXd X(samples, 2*m_iNumberOfHarmonics); for(int k = 0; k < m_iNumberOfHarmonics; k++){ ArrayXd t_k = t*(k+1)*m_lAllFrequencies.at(i); X.col(2*k) = t_k.sin(); X.col(2*k+1) = t_k.cos(); } // extracting the features from the data Y with the reference signal X if(m_bUseMEC){ ssvepProbabilities(i) = MEC(Y, X); // using Minimum Energy Combination as feature-extraction tool } else{ ssvepProbabilities(i) = CCA(Y, X); // using Canonical Correlation Analysis as feature-extraction tool } } // normalize features to probabilities and transfering it into a softmax function ssvepProbabilities = m_dAlpha / ssvepProbabilities.sum() * ssvepProbabilities; ssvepProbabilities = ssvepProbabilities.array().exp(); // softmax function for better distinguishability between the probabilities ssvepProbabilities = 1 / ssvepProbabilities.sum() * ssvepProbabilities; // classify probabilites int index = 0; double maxProbability = ssvepProbabilities.maxCoeff(&index); if(index < m_lDesFrequencies.size()){ //qDebug()<< "index:" << index; if(m_lThresholdValues[index] < maxProbability){ //qDebug() << "comparison: "<< m_lThresholdValues[index] << "and" << maxProbability; m_lIndexOfClassResultSensor.append(index+1); } else{ m_lIndexOfClassResultSensor.append(0); } } else{ m_lIndexOfClassResultSensor.append(0); } // clear classifiaction if it hits its threshold if(m_lIndexOfClassResultSensor.size() > m_iClassListSize){ m_lIndexOfClassResultSensor.pop_front(); } // transfer values to matrix containing all SSVEPProabibilities of desired frequencies of one calculationstep m_matSSVEPProbabilities.conservativeResize(m_lDesFrequencies.size(), m_matSSVEPProbabilities.cols() + 1); m_matSSVEPProbabilities.col( m_matSSVEPProbabilities.cols() - 1) = ssvepProbabilities.head(m_lDesFrequencies.size()); } // update counter and index variables m_iCounter++; m_iReadToWriteBuffer = m_iReadToWriteBuffer - m_iReadSampleSize; m_iReadIndex = (m_iReadIndex + m_iReadSampleSize) % (m_iTimeWindowLength); } // emit classifiaction results if any classifiaction has been done if(!m_lIndexOfClassResultSensor.isEmpty()){ // finding a classifiaction result that satisfies the number of classifiaction hits for(int i = 1; (i <= m_lDesFrequencies.size()) && (!m_lIndexOfClassResultSensor.isEmpty() ); i++){ if(m_lIndexOfClassResultSensor.count(i) >= m_iNumberOfClassHits){ emit classificationResult(m_lDesFrequencies[i - 1]); m_lIndexOfClassResultSensor.clear(); m_iCounter = 0; break; } else{ emit classificationResult(0); } } } // calculate and emit signal of mean probabilities if(m_matSSVEPProbabilities.cols() != 0){ QList<double> meanSSVEPProbabilities; for(int i = 0; i < m_lDesFrequencies.size(); i++){ meanSSVEPProbabilities << m_matSSVEPProbabilities.row(i).mean(); } emit SSVEPprob(meanSSVEPProbabilities); //qDebug() << "emit ssvep:" << meanSSVEPProbabilities; } // change parameter and reset the time window if the change flag has been set if(m_bChangeSSVEPParameterFlag){ changeSSVEPParameter(); } } //************************************************************************************************************* void SsvepBci::ssvepBciOnSource() { }
32,676
10,105
/*! * WTEngine | File: apply.hpp * * \author Matthew Evans * \version 0.7 * \copyright See LICENSE.md for copyright information. * \date 2019-2021 */ #ifndef WTE_MNU_ITEM_APPLY_HPP #define WTE_MNU_ITEM_APPLY_HPP #include <string> #include <vector> #include "wtengine/mnu/item.hpp" #include "wtengine/mgr/menus.hpp" #include "wtengine/mgr/messages.hpp" namespace wte::mnu { /*! * \class apply * \brief An apply option for the menus. */ class apply final : public item { public: /*! * \brief Menu Item Apply constructor. */ apply(); ~apply() = default; //!< Default destructor. private: /* * Set the apply item to cancel. */ void on_left(void) override; /* * Set the apply item to apply. */ void on_right(void) override; /* * On select trigger. */ void on_select(void) override; /* * Return display text for the menu item when rendering. */ const std::vector<std::string> get_text(void) const override; /* * Reset the apply item to the canceled state. */ void reset_to_default(void) override; /* * Set the apply item's default state to canceled. */ void set_default(void) override; /* * Reset the apply item to the canceled state. */ void apply_setting(void) override; bool do_apply; }; } // end namespace wte::mnu #endif
1,549
510
/* * Copyright (C) 2015, UChicago Argonne, LLC * All Rights Reserved * * Generic IO (ANL-15-066) * Hal Finkel, Argonne National Laboratory * * OPEN SOURCE LICENSE * * Under the terms of Contract No. DE-AC02-06CH11357 with UChicago Argonne, * LLC, 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 names of UChicago Argonne, LLC or the Department of Energy * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * ***************************************************************************** * * DISCLAIMER * THE SOFTWARE IS SUPPLIED “AS IS” WITHOUT WARRANTY OF ANY KIND. NEITHER THE * UNTED STATES GOVERNMENT, NOR THE UNITED STATES DEPARTMENT OF ENERGY, NOR * UCHICAGO ARGONNE, LLC, NOR ANY OF THEIR EMPLOYEES, MAKES ANY WARRANTY, * EXPRESS OR IMPLIED, OR ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE * ACCURACY, COMPLETENESS, OR USEFULNESS OF ANY INFORMATION, DATA, APPARATUS, * PRODUCT, OR PROCESS DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE * PRIVATELY OWNED RIGHTS. * * ***************************************************************************** */ #include "gio.h" #include <iostream> void read_gio_float(char* file_name, char* var_name, float* data, int field_count) { read_gio<float>(file_name, var_name, data, field_count); } void read_gio_double(char* file_name, char* var_name, double* data, int field_count) { read_gio<double>(file_name, var_name, data, field_count); } void read_gio_int32(char* file_name, char* var_name, int* data, int field_count) { read_gio<int>(file_name, var_name, data, field_count); } void read_gio_int64(char* file_name, char* var_name, int64_t* data, int field_count) { read_gio<int64_t>(file_name, var_name, data, field_count); } void read_gio_oct_float(char* file_name, int leaf_id, char* var_name, float* data) { read_gio_rankLeaf<float>(file_name, leaf_id, var_name, data); } void read_gio_oct_double(char* file_name, int leaf_id, char* var_name, double* data) { read_gio_rankLeaf<double>(file_name, leaf_id, var_name, data); } void read_gio_oct_int32(char* file_name, int leaf_id, char* var_name, int* data) { read_gio_rankLeaf<int>(file_name, leaf_id, var_name, data); } void read_gio_oct_int64(char* file_name, int leaf_id, char* var_name, int64_t* data) { read_gio_rankLeaf<int64_t>(file_name, leaf_id, var_name, data); } int64_t get_elem_num(char* file_name) { gio::GenericIO reader(file_name); reader.openAndReadHeader(gio::GenericIO::MismatchAllowed); int num_ranks = reader.readNRanks(); uint64_t size = 0; for(int i =0;i<num_ranks;++i) size +=reader.readNumElems(i); reader.close(); return size; } int64_t get_elem_num_in_leaf(char* file_name, int leaf_id) { gio::GenericIO reader(file_name); reader.openAndReadHeader(gio::GenericIO::MismatchAllowed); GIOOctree tempOctree = reader.getOctree(); reader.close(); return tempOctree.getCount(leaf_id); } void inspect_gio(char* file_name) { int64_t size = get_elem_num(file_name); gio::GenericIO reader(file_name); std::vector<gio::GenericIO::VariableInfo> VI; reader.openAndReadHeader(gio::GenericIO::MismatchAllowed); reader.getVariableInfo(VI); std::cout << "Number of Elements: " << size << std::endl; int num = VI.size(); std::cout << "[data type] Variable name" << std::endl; std::cout << "---------------------------------------------" << std::endl; for (int i = 0; i < num; ++i) { gio::GenericIO::VariableInfo vinfo = VI[i]; if (vinfo.IsFloat) std::cout << "[f"; else std::cout << "[i"; int NumElements = vinfo.Size / vinfo.ElementSize; std::cout << " " << vinfo.ElementSize * 8; if (NumElements > 1) std::cout << "x" << NumElements; std::cout << "] "; std::cout << vinfo.Name << std::endl; } std::cout << "\n(i=integer,f=floating point, number bits size)" << std::endl; if (reader.isOctree()) { std::cout << "---------------------------------------------" << std::endl; std::cout << "Octree info:" << std::endl; reader.printOctree(); } } var_type get_variable_type(char* file_name, char* var_name) { gio::GenericIO reader(file_name); std::vector<gio::GenericIO::VariableInfo> VI; reader.openAndReadHeader(gio::GenericIO::MismatchAllowed); reader.getVariableInfo(VI); int num = VI.size(); for (int i = 0; i < num; ++i) { gio::GenericIO::VariableInfo vinfo = VI[i]; if (vinfo.Name == var_name) { if (vinfo.IsFloat && vinfo.ElementSize == 4) return float_type; else if (vinfo.IsFloat && vinfo.ElementSize == 8) return double_type; else if (!vinfo.IsFloat && vinfo.ElementSize == 4) return int32_type; else if (!vinfo.IsFloat && vinfo.ElementSize == 8) return int64_type; else return type_not_found; } } return var_not_found; } int get_variable_field_count(char* file_name, char* var_name) { gio::GenericIO reader(file_name); std::vector<gio::GenericIO::VariableInfo> VI; reader.openAndReadHeader(gio::GenericIO::MismatchAllowed); reader.getVariableInfo(VI); int num = VI.size(); for (int i = 0; i < num; ++i) { gio::GenericIO::VariableInfo vinfo = VI[i]; if (vinfo.Name == var_name) { return vinfo.Size / vinfo.ElementSize; } } return 0; } int64_t get_num_variables(char* file_name) { gio::GenericIO reader(file_name); reader.openAndReadHeader(gio::GenericIO::MismatchAllowed); std::vector<gio::GenericIO::VariableInfo> VI; reader.getVariableInfo(VI); return VI.size(); } char* get_octree(char* file_name) { gio::GenericIO reader(file_name); reader.openAndReadHeader(gio::GenericIO::MismatchAllowed); std::string octreeStr; if (reader.isOctree()) octreeStr = (reader.getOctree()).getOctreeStr(); char *temp_name = new char[octreeStr.size() + 1]; strcpy(temp_name, octreeStr.c_str()); return temp_name; } char* get_variable(char* file_name, int var) { gio::GenericIO reader(file_name); reader.openAndReadHeader(gio::GenericIO::MismatchAllowed); std::vector<gio::GenericIO::VariableInfo> VI; reader.getVariableInfo(VI); std::string scaler_name = VI[var].Name; char *temp_name = new char[scaler_name.size() + 1]; strcpy(temp_name, scaler_name.c_str()); return temp_name; } int get_num_octree_leaves(char* file_name, int extents[]) { gio::GenericIO reader(file_name); reader.openAndReadHeader(gio::GenericIO::MismatchAllowed); std::vector<int> intersectedLeaves; GIOOctree tempOctree = reader.getOctree(); for (int i=0; i<tempOctree.rows.size(); i++) if ( tempOctree.rows[i].intersect(extents) ) intersectedLeaves.push_back(i); return intersectedLeaves.size(); } int* get_octree_leaves(char* file_name, int extents[]) { gio::GenericIO reader(file_name); reader.openAndReadHeader(gio::GenericIO::MismatchAllowed); std::vector<int> intersectedLeaves; GIOOctree tempOctree = reader.getOctree(); for (int i=0; i<tempOctree.rows.size(); i++) if ( tempOctree.rows[i].intersect(extents) ) intersectedLeaves.push_back(i); int *x = new int[intersectedLeaves.size()]; std::copy(intersectedLeaves.begin(), intersectedLeaves.end(), x); return x; }
8,413
2,916
/* Copyright 2005-2012 Intel Corporation. All Rights Reserved. This file is part of Threading Building Blocks. Threading Building Blocks is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. Threading Building Blocks 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 Threading Building Blocks; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA As a special exception, you may use this file as part of a free software library without restriction. Specifically, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other files to produce an executable, this file does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ #if __TBB_CPF_BUILD // undefine __TBB_CPF_BUILD to simulate user's setup #undef __TBB_CPF_BUILD #define TBB_PREVIEW_TASK_ARENA 1 #include "tbb/task_arena.h" #include "tbb/task_scheduler_observer.h" #include "tbb/task_scheduler_init.h" #include <cstdlib> #include "harness_assert.h" #include <cstdio> #include "harness.h" #include "harness_barrier.h" #include "harness_concurrency_tracker.h" #include "tbb/parallel_for.h" #include "tbb/blocked_range.h" #include "tbb/enumerable_thread_specific.h" #if _MSC_VER // plays around __TBB_NO_IMPLICIT_LINKAGE. __TBB_LIB_NAME should be defined (in makefiles) #pragma comment(lib, __TBB_STRING(__TBB_LIB_NAME)) #endif typedef tbb::blocked_range<int> Range; class ConcurrencyTrackingBody { public: void operator() ( const Range& ) const { Harness::ConcurrencyTracker ct; for ( volatile int i = 0; i < 1000000; ++i ) ; } }; Harness::SpinBarrier our_barrier; static tbb::enumerable_thread_specific<int> local_id, old_id; void ResetTLS() { local_id.clear(); old_id.clear(); } class ArenaObserver : public tbb::task_scheduler_observer { int myId; tbb::atomic<int> myTrappedSlot; /*override*/ void on_scheduler_entry( bool is_worker ) { REMARK("a %s #%p is entering arena %d from %d\n", is_worker?"worker":"master", &local_id.local(), myId, local_id.local()); ASSERT(!old_id.local(), "double-call to on_scheduler_entry"); old_id.local() = local_id.local(); ASSERT(old_id.local() != myId, "double-entry to the same arena"); local_id.local() = myId; if(is_worker) ASSERT(tbb::task_arena::current_slot()>0, NULL); else ASSERT(tbb::task_arena::current_slot()==0, NULL); } /*override*/ void on_scheduler_exit( bool is_worker ) { REMARK("a %s #%p is leaving arena %d to %d\n", is_worker?"worker":"master", &local_id.local(), myId, old_id.local()); //ASSERT(old_id.local(), "call to on_scheduler_exit without prior entry"); ASSERT(local_id.local() == myId, "nesting of arenas is broken"); local_id.local() = old_id.local(); old_id.local() = 0; } /*override*/ bool on_scheduler_leaving() { return tbb::task_arena::current_slot() >= myTrappedSlot; } public: ArenaObserver(tbb::task_arena &a, int id, int trap = 0) : tbb::task_scheduler_observer(a) { observe(true); ASSERT(id, NULL); myId = id; myTrappedSlot = trap; } ~ArenaObserver () { ASSERT(!old_id.local(), "inconsistent observer state"); } }; struct AsynchronousWork : NoAssign { Harness::SpinBarrier &my_barrier; bool my_is_blocking; AsynchronousWork(Harness::SpinBarrier &a_barrier, bool blocking = true) : my_barrier(a_barrier), my_is_blocking(blocking) {} void operator()() const { ASSERT(local_id.local() != 0, "not in explicit arena"); tbb::parallel_for(Range(0,35), ConcurrencyTrackingBody()); if(my_is_blocking) my_barrier.timed_wait(10); // must be asynchronous to master thread else my_barrier.signal_nowait(); } }; void TestConcurrentArenas(int p) { //Harness::ConcurrencyTracker::Reset(); tbb::task_arena a1(1); ArenaObserver o1(a1, p*2+1); tbb::task_arena a2(2); ArenaObserver o2(a2, p*2+2); Harness::SpinBarrier barrier(2); AsynchronousWork work(barrier); a1.enqueue(work); // put async work barrier.timed_wait(10); a2.enqueue(work); // another work a2.execute(work); // my_barrier.timed_wait(10) inside a1.wait_until_empty(); a2.wait_until_empty(); } class MultipleMastersBody : NoAssign { tbb::task_arena &my_a; Harness::SpinBarrier &my_b; public: MultipleMastersBody(tbb::task_arena &a, Harness::SpinBarrier &b) : my_a(a), my_b(b) {} void operator()(int) const { my_a.execute(AsynchronousWork(my_b, /*blocking=*/false)); my_a.wait_until_empty(); } }; void TestMultipleMasters(int p) { REMARK("multiple masters\n"); tbb::task_arena a(1); ArenaObserver o(a, 1); Harness::SpinBarrier barrier(p+1); NativeParallelFor( p, MultipleMastersBody(a, barrier) ); a.wait_until_empty(); barrier.timed_wait(10); } int TestMain () { // TODO: a workaround for temporary p-1 issue in market tbb::task_scheduler_init init_market_p_plus_one(MaxThread+1); for( int p=MinThread; p<=MaxThread; ++p ) { REMARK("testing with %d threads\n", p ); NativeParallelFor( p, &TestConcurrentArenas ); ResetTLS(); TestMultipleMasters( p ); ResetTLS(); } return Harness::Done; } #else // __TBB_CPF_BUILD #include "harness.h" int TestMain () { return Harness::Skipped; } #endif
6,132
2,159
/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2013 Steven Lovegrove * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <pangolin/handler/handler.h> #include <pangolin/display/display_internal.h> #include <pangolin/display/view.h> namespace pangolin { // Pointer to context defined in display.cpp extern __thread PangolinGl* context; void Handler::Keyboard(View& d, unsigned char key, int x, int y, bool pressed) { View* child = d.FindChild(x,y); if( child) { context->activeDisplay = child; if( child->handler) child->handler->Keyboard(*child,key,x,y,pressed); } } void Handler::Mouse(View& d, MouseButton button, int x, int y, bool pressed, int button_state) { View* child = d.FindChild(x,y); if( child ) { context->activeDisplay = child; if( child->handler) child->handler->Mouse(*child,button,x,y,pressed,button_state); } } void Handler::MouseMotion(View& d, int x, int y, int button_state) { View* child = d.FindChild(x,y); if( child ) { context->activeDisplay = child; if( child->handler) child->handler->MouseMotion(*child,x,y,button_state); } } void Handler::PassiveMouseMotion(View& d, int x, int y, int button_state) { View* child = d.FindChild(x,y); if( child ) { if( child->handler) child->handler->PassiveMouseMotion(*child,x,y,button_state); } } void Handler::Special(View& d, InputSpecial inType, float x, float y, float p1, float p2, float p3, float p4, int button_state) { View* child = d.FindChild( (int)x, (int)y); if( child ) { context->activeDisplay = child; if( child->handler) child->handler->Special(*child,inType, x,y, p1, p2, p3, p4, button_state); } } void HandlerScroll::Mouse(View& d, MouseButton button, int x, int y, bool pressed, int button_state) { if( pressed && (button == MouseWheelUp || button == MouseWheelDown) ) { if( button == MouseWheelUp) d.scroll_offset -= 1; if( button == MouseWheelDown) d.scroll_offset += 1; d.scroll_offset = std::max(0, std::min(d.scroll_offset, (int)d.NumVisibleChildren()-1) ); d.ResizeChildren(); }else{ Handler::Mouse(d,button,x,y,pressed,button_state); } } void HandlerScroll::Special(View& d, InputSpecial inType, float x, float y, float p1, float p2, float p3, float p4, int button_state) { if( inType == InputSpecialScroll ) { d.scroll_offset -= (int)(p2 / fabs(p2)); d.scroll_offset = std::max(0, std::min(d.scroll_offset, (int)d.NumVisibleChildren()-1) ); d.ResizeChildren(); }else{ Handler::Special(d,inType,x,y,p1,p2,p3,p4,button_state); } } Handler3D::Handler3D(OpenGlRenderState& cam_state, AxisDirection enforce_up, float trans_scale, float zoom_fraction) : cam_state(&cam_state), enforce_up(enforce_up), tf(trans_scale), zf(zoom_fraction), cameraspec(CameraSpecOpenGl), last_z(0.8) { SetZero<3,1>(rot_center); } void Handler3D::Keyboard(View&, unsigned char /*key*/, int /*x*/, int /*y*/, bool /*pressed*/) { // TODO: hooks for reset / changing mode (perspective / ortho etc) } bool Handler3D::ValidWinDepth(GLprecision depth) { return depth != 1; } void Handler3D::PixelUnproject( View& view, GLprecision winx, GLprecision winy, GLprecision winz, GLprecision Pc[3]) { const GLint viewport[4] = {view.v.l,view.v.b,view.v.w,view.v.h}; const pangolin::OpenGlMatrix proj = cam_state->GetProjectionMatrix(); #ifdef HAVE_GLES glUnProject(winx, winy, winz, Identity4f, proj.m, viewport, &Pc[0], &Pc[1], &Pc[2]); #else glUnProject(winx, winy, winz, Identity4d, proj.m, viewport, &Pc[0], &Pc[1], &Pc[2]); #endif } void Handler3D::GetPosNormal(pangolin::View& view, int winx, int winy, GLprecision p[3], GLprecision Pw[3], GLprecision Pc[3], GLprecision nw[3], GLprecision default_z) { // TODO: Get to work on android const int zl = (hwin*2+1); const int zsize = zl*zl; GLfloat zs[zsize]; #ifndef HAVE_GLES glReadBuffer(GL_FRONT); glReadPixels(winx-hwin,winy-hwin,zl,zl,GL_DEPTH_COMPONENT,GL_FLOAT,zs); #else std::fill(zs,zs+zsize, 1); #endif GLfloat mindepth = *(std::min_element(zs,zs+zsize)); if(mindepth == 1) mindepth = (GLfloat)default_z; p[0] = winx; p[1] = winy; p[2] = mindepth; PixelUnproject(view, winx, winy, mindepth, Pc); const pangolin::OpenGlMatrix mv = cam_state->GetModelViewMatrix(); GLprecision T_wc[3*4]; LieSE3from4x4(T_wc, mv.Inverse().m ); LieApplySE3vec(Pw, T_wc, Pc); // Neighboring points in camera coordinates GLprecision Pl[3]; GLprecision Pr[3]; GLprecision Pb[3]; GLprecision Pt[3]; PixelUnproject(view, winx-hwin, winy, zs[hwin*zl + 0], Pl ); PixelUnproject(view, winx+hwin, winy, zs[hwin*zl + zl-1], Pr ); PixelUnproject(view, winx, winy-hwin, zs[hwin+1], Pb ); PixelUnproject(view, winx, winy+hwin, zs[zsize-(hwin+1)], Pt ); // n = ((Pr-Pl).cross(Pt-Pb)).normalized(); GLprecision PrmPl[3]; GLprecision PtmPb[3]; MatSub<3,1>(PrmPl,Pr,Pl); MatSub<3,1>(PtmPb,Pt,Pb); GLprecision nc[3]; CrossProduct(nc, PrmPl, PtmPb); Normalise<3>(nc); // T_wc is col major, so the rotation component is first. LieApplySO3(nw,T_wc,nc); } void Handler3D::Mouse(View& display, MouseButton button, int x, int y, bool pressed, int button_state) { // mouse down last_pos[0] = (float)x; last_pos[1] = (float)y; GLprecision T_nc[3*4]; LieSetIdentity(T_nc); funcKeyState = 0; if( pressed ) { GetPosNormal(display,x,y,p,Pw,Pc,n,last_z); if( ValidWinDepth(p[2]) ) { last_z = p[2]; std::copy(Pc,Pc+3,rot_center); } if( button == MouseWheelUp || button == MouseWheelDown) { LieSetIdentity(T_nc); const GLprecision t[3] = { 0,0,(button==MouseWheelUp?1:-1)*100*tf}; LieSetTranslation<>(T_nc,t); if( !(button_state & MouseButtonRight) && !(rot_center[0]==0 && rot_center[1]==0 && rot_center[2]==0) ) { LieSetTranslation<>(T_nc,rot_center); const GLprecision s = (button==MouseWheelUp?-1.0:1.0) * zf; MatMul<3,1>(T_nc+(3*3), s); } OpenGlMatrix& spec = cam_state->GetModelViewMatrix(); LieMul4x4bySE3<>(spec.m,T_nc,spec.m); } funcKeyState = button_state; } } void Handler3D::MouseMotion(View& display, int x, int y, int button_state) { const GLprecision rf = 0.01; const float delta[2] = { (float)x - last_pos[0], (float)y - last_pos[1] }; const float mag = delta[0]*delta[0] + delta[1]*delta[1]; if((button_state & KeyModifierCtrl) && (button_state & KeyModifierShift)) { GLprecision T_nc[3 * 4]; LieSetIdentity(T_nc); GetPosNormal(display, x, y, p, Pw, Pc, n, last_z); if(ValidWinDepth(p[2])) { last_z = p[2]; std::copy(Pc, Pc + 3, rot_center); } funcKeyState = button_state; } else { funcKeyState = 0; } // TODO: convert delta to degrees based of fov // TODO: make transformation with respect to cam spec if( mag < 50.0f*50.0f ) { OpenGlMatrix& mv = cam_state->GetModelViewMatrix(); const GLprecision* up = AxisDirectionVector[enforce_up]; GLprecision T_nc[3*4]; LieSetIdentity(T_nc); bool rotation_changed = false; if( button_state == MouseButtonMiddle ) { // Middle Drag: Rotate around view // Try to correct for different coordinate conventions. GLprecision aboutx = -rf * delta[1]; GLprecision abouty = rf * delta[0]; OpenGlMatrix& pm = cam_state->GetProjectionMatrix(); abouty *= -pm.m[2 * 4 + 3]; Rotation<>(T_nc, aboutx, abouty, (GLprecision)0.0); }else if( button_state == MouseButtonLeft ) { // Left Drag: in plane translate if( ValidWinDepth(last_z) ) { GLprecision np[3]; PixelUnproject(display, x, y, last_z, np); const GLprecision t[] = { np[0] - rot_center[0], np[1] - rot_center[1], 0}; LieSetTranslation<>(T_nc,t); std::copy(np,np+3,rot_center); }else{ const GLprecision t[] = { -10*delta[0]*tf, 10*delta[1]*tf, 0}; LieSetTranslation<>(T_nc,t); } }else if( button_state == (MouseButtonLeft | MouseButtonRight) ) { // Left and Right Drag: in plane rotate about object // Rotation<>(T_nc,0.0,0.0, delta[0]*0.01); GLprecision T_2c[3*4]; Rotation<>(T_2c, (GLprecision)0.0, (GLprecision)0.0, delta[0]*rf); GLprecision mrotc[3]; MatMul<3,1>(mrotc, rot_center, (GLprecision)-1.0); LieApplySO3<>(T_2c+(3*3),T_2c,mrotc); GLprecision T_n2[3*4]; LieSetIdentity<>(T_n2); LieSetTranslation<>(T_n2,rot_center); LieMulSE3(T_nc, T_n2, T_2c ); rotation_changed = true; }else if( button_state == MouseButtonRight) { GLprecision aboutx = -rf * delta[1]; GLprecision abouty = -rf * delta[0]; // Try to correct for different coordinate conventions. if(cam_state->GetProjectionMatrix().m[2*4+3] <= 0) { abouty *= -1; } if(enforce_up) { // Special case if view direction is parallel to up vector const GLprecision updotz = mv.m[2]*up[0] + mv.m[6]*up[1] + mv.m[10]*up[2]; if(updotz > 0.98) aboutx = std::min(aboutx, (GLprecision)0.0); if(updotz <-0.98) aboutx = std::max(aboutx, (GLprecision)0.0); // Module rotation around y so we don't spin too fast! abouty *= (1-0.6*fabs(updotz)); } // Right Drag: object centric rotation GLprecision T_2c[3*4]; Rotation<>(T_2c, aboutx, abouty, (GLprecision)0.0); GLprecision mrotc[3]; MatMul<3,1>(mrotc, rot_center, (GLprecision)-1.0); LieApplySO3<>(T_2c+(3*3),T_2c,mrotc); GLprecision T_n2[3*4]; LieSetIdentity<>(T_n2); LieSetTranslation<>(T_n2,rot_center); LieMulSE3(T_nc, T_n2, T_2c ); rotation_changed = true; } LieMul4x4bySE3<>(mv.m,T_nc,mv.m); if(enforce_up != AxisNone && rotation_changed) { EnforceUpT_cw(mv.m, up); } } last_pos[0] = (float)x; last_pos[1] = (float)y; } void Handler3D::Special(View& display, InputSpecial inType, float x, float y, float p1, float p2, float /*p3*/, float /*p4*/, int button_state) { if( !(inType == InputSpecialScroll || inType == InputSpecialRotate) ) return; // mouse down last_pos[0] = x; last_pos[1] = y; GLprecision T_nc[3*4]; LieSetIdentity(T_nc); GetPosNormal(display, (int)x, (int)y, p, Pw, Pc, n, last_z); if(p[2] < 1.0) { last_z = p[2]; std::copy(Pc,Pc+3,rot_center); } if( inType == InputSpecialScroll ) { if(button_state & KeyModifierCmd) { const GLprecision rx = -p2 / 1000; const GLprecision ry = -p1 / 1000; Rotation<>(T_nc,rx, ry, (GLprecision)0.0); OpenGlMatrix& spec = cam_state->GetModelViewMatrix(); LieMul4x4bySE3<>(spec.m,T_nc,spec.m); }else{ const GLprecision scrolly = p2/10; LieSetIdentity(T_nc); const GLprecision t[] = { 0,0, -scrolly*100*tf}; LieSetTranslation<>(T_nc,t); if( !(button_state & MouseButtonRight) && !(rot_center[0]==0 && rot_center[1]==0 && rot_center[2]==0) ) { LieSetTranslation<>(T_nc,rot_center); MatMul<3,1>(T_nc+(3*3), -scrolly * zf); } OpenGlMatrix& spec = cam_state->GetModelViewMatrix(); LieMul4x4bySE3<>(spec.m,T_nc,spec.m); } }else if(inType == InputSpecialRotate) { const GLprecision r = p1 / 20; GLprecision T_2c[3*4]; Rotation<>(T_2c, (GLprecision)0.0, (GLprecision)0.0, r); GLprecision mrotc[3]; MatMul<3,1>(mrotc, rot_center, (GLprecision)-1.0); LieApplySO3<>(T_2c+(3*3),T_2c,mrotc); GLprecision T_n2[3*4]; LieSetIdentity<>(T_n2); LieSetTranslation<>(T_n2,rot_center); LieMulSE3(T_nc, T_n2, T_2c ); OpenGlMatrix& spec = cam_state->GetModelViewMatrix(); LieMul4x4bySE3<>(spec.m,T_nc,spec.m); } } }
14,098
5,226
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #include "pch.h" #include "common.h" #include "Vector.h" #include "TreeViewDragItemsCompletedEventArgs.h" TreeViewDragItemsCompletedEventArgs::TreeViewDragItemsCompletedEventArgs(const winrt::DragItemsCompletedEventArgs& args, const winrt::IInspectable& newParentItem) { m_dragItemsCompletedEventArgs = args; m_newParentItem = newParentItem; } DataPackageOperation TreeViewDragItemsCompletedEventArgs::DropResult() const { return m_dragItemsCompletedEventArgs.DropResult(); } winrt::IVectorView<winrt::IInspectable> TreeViewDragItemsCompletedEventArgs::Items() { return m_dragItemsCompletedEventArgs.Items(); } winrt::IInspectable TreeViewDragItemsCompletedEventArgs::NewParentItem() { return m_newParentItem; }
921
262
/** * __author__ = anonymized * __date__ = 2019-05 * __copyright__ = Creative Commons CC0 */ #include <array> #include <vector> #include <stdint.h> #include <stdlib.h> #include "ciphers/random_function.h" #include "ciphers/small_aes_present_sbox.h" #include "ciphers/small_state.h" #include "ciphers/speck64.h" #include "utils/argparse.h" #include "utils/utils.h" #include "utils/xorshift1024.h" using ciphers::small_aes_ctx_t; using ciphers::small_aes_state_t; using ciphers::small_aes_key_t; using ciphers::SmallState; using ciphers::speck64_context_t; using ciphers::speck64_96_key_t; using ciphers::speck64_state_t; using utils::assert_equal; using utils::compute_mean; using utils::compute_variance; using utils::xor_arrays; using utils::ArgumentParser; // --------------------------------------------------------- static const size_t NUM_CONSIDERED_ROUNDS = 5; static const size_t NUM_TEXTS_IN_DELTA_SET = 16; // --------------------------------------------------------- typedef struct { small_aes_key_t key; small_aes_ctx_t cipher_ctx; size_t num_keys; size_t num_sets_per_key; std::vector<size_t> num_matches; bool use_prp = false; bool use_all_delta_sets_from_diagonal = false; } ExperimentContext; typedef struct { std::vector<size_t> num_collisions_per_set; size_t num_collisions; } ExperimentResult; typedef size_t (*experiment_function_t)(ExperimentContext *); typedef std::vector<SmallState> SmallStatesVector; // --------------------------------------------------------- static void generate_base_plaintext(small_aes_state_t plaintext) { utils::get_random_bytes(plaintext, SMALL_AES_NUM_STATE_BYTES); } // --------------------------------------------------------- static void get_text_from_delta_set(small_aes_state_t base_text, const size_t i) { base_text[0] = (uint8_t) ((i << 4) & 0xF0); } // --------------------------------------------------------- static void generate_base_plaintext_in_diagonal(small_aes_state_t plaintext, const size_t set_index_in_diagonal, const size_t byte_index_in_diagonal) { if (byte_index_in_diagonal == 0) { plaintext[2] = (uint8_t) (((set_index_in_diagonal >> 8) & 0x0F) | (plaintext[2] & 0xF0)); plaintext[5] = (uint8_t) ((set_index_in_diagonal & 0xF0) | (plaintext[5] & 0x0F)); plaintext[7] = (uint8_t) ((set_index_in_diagonal & 0x0F) | (plaintext[7] & 0xF0)); } else if (byte_index_in_diagonal == 1) { plaintext[0] = (uint8_t) (((set_index_in_diagonal >> 4) & 0xF0) | (plaintext[0] & 0x0F)); plaintext[5] = (uint8_t) ((set_index_in_diagonal & 0xF0) | (plaintext[5] & 0x0F)); plaintext[7] = (uint8_t) ((set_index_in_diagonal & 0x0F) | (plaintext[7] & 0xF0)); } else if (byte_index_in_diagonal == 2) { plaintext[0] = (uint8_t) (((set_index_in_diagonal >> 4) & 0xF0) | (plaintext[0] & 0x0F)); plaintext[2] = (uint8_t) (((set_index_in_diagonal >> 4) & 0x0F) | (plaintext[2] & 0xF0)); plaintext[7] = (uint8_t) ((set_index_in_diagonal & 0x0F) | (plaintext[7] & 0xF0)); } else if (byte_index_in_diagonal == 3) { plaintext[0] = (uint8_t) (((set_index_in_diagonal >> 4) & 0xF0) | (plaintext[0] & 0x0F)); plaintext[2] = (uint8_t) (((set_index_in_diagonal >> 4) & 0x0F) | (plaintext[2] & 0xF0)); plaintext[5] = (uint8_t) ((set_index_in_diagonal & 0xF0) | (plaintext[5] & 0x0F)); } } // --------------------------------------------------------- static void get_text_from_diagonal_delta_set(small_aes_state_t plaintext, const size_t byte_index_in_diagonal, const size_t index_in_delta_set) { if (byte_index_in_diagonal == 0) { plaintext[0] = (uint8_t) ((plaintext[0] & 0x0F) | ((index_in_delta_set << 4) & 0xF0)); } else if (byte_index_in_diagonal == 1) { plaintext[2] = (uint8_t) ((plaintext[2] & 0xF0) | (index_in_delta_set & 0x0F)); } else if (byte_index_in_diagonal == 2) { plaintext[5] = (uint8_t) ((plaintext[5] & 0x0F) | ((index_in_delta_set << 4) & 0xF0)); } else if (byte_index_in_diagonal == 3) { plaintext[7] = (uint8_t) ((plaintext[7] & 0xF0) | (index_in_delta_set & 0x0F)); } } // --------------------------------------------------------- static void encrypt(const small_aes_ctx_t *aes_context, small_aes_state_t plaintext, SmallState &ciphertext) { small_aes_present_sbox_encrypt_rounds_only_sbox_in_final( aes_context, plaintext, ciphertext.state, NUM_CONSIDERED_ROUNDS ); } // --------------------------------------------------------- bool has_zero_column(const small_aes_state_t state) { return ((state[0] == 0) && (state[1] == 0)) || ((state[2] == 0) && (state[3] == 0)) || ((state[4] == 0) && (state[5] == 0)) || ((state[6] == 0) && (state[7] == 0)); } // --------------------------------------------------------- static size_t find_num_collisions(SmallStatesVector &ciphertexts) { const size_t num_texts = ciphertexts.size(); size_t num_collisions = 0; small_aes_state_t temp; for (size_t i = 0; i != num_texts; ++i) { const SmallState left = ciphertexts[i]; for (size_t j = i + 1; j != num_texts; ++j) { const SmallState right = ciphertexts[j]; xor_arrays(temp, left.state, right.state, SMALL_AES_NUM_STATE_BYTES); if (has_zero_column(temp)) { num_collisions++; } } } return num_collisions; } // --------------------------------------------------------- static size_t perform_experiment(ExperimentContext *context) { small_aes_ctx_t cipher_ctx = context->cipher_ctx; small_aes_key_t key; utils::get_random_bytes(key, SMALL_AES_NUM_KEY_BYTES); small_aes_key_setup(&cipher_ctx, key); utils::print_hex("# Key", key, SMALL_AES_NUM_KEY_BYTES); size_t num_collisions = 0; for (size_t i = 0; i < context->num_sets_per_key; ++i) { SmallStatesVector ciphertexts; small_aes_state_t plaintext; generate_base_plaintext(plaintext); for (size_t j = 0; j < NUM_TEXTS_IN_DELTA_SET; ++j) { SmallState ciphertext; get_text_from_delta_set(plaintext, j); encrypt(&cipher_ctx, plaintext, ciphertext); ciphertexts.push_back(ciphertext); } num_collisions += find_num_collisions(ciphertexts); if (i > 0) { if ((i & 0xFFFFF) == 0) { printf("# Tested %8zu sets. Collisions: %8zu\n", i, num_collisions); } } } return num_collisions; } // --------------------------------------------------------- static size_t perform_experiment_from_diagonal(ExperimentContext *context) { small_aes_ctx_t cipher_ctx = context->cipher_ctx; small_aes_key_t key; utils::get_random_bytes(key, SMALL_AES_NUM_KEY_BYTES); small_aes_key_setup(&cipher_ctx, key); utils::print_hex("# Key", key, SMALL_AES_NUM_KEY_BYTES); size_t num_collisions = 0; const size_t num_sets_in_diagonal = 1L << 12; const size_t num_bytes_in_diagonal = 4; small_aes_state_t plaintext; generate_base_plaintext(plaintext); for (size_t i = 0; i < num_sets_in_diagonal; ++i) { for (size_t m = 0; m < num_bytes_in_diagonal; ++m) { generate_base_plaintext_in_diagonal(plaintext, i, m); SmallStatesVector ciphertexts; for (size_t j = 0; j < NUM_TEXTS_IN_DELTA_SET; ++j) { SmallState ciphertext; get_text_from_diagonal_delta_set(plaintext, m, j); encrypt(&cipher_ctx, plaintext, ciphertext); ciphertexts.push_back(ciphertext); } num_collisions += find_num_collisions(ciphertexts); } if (i > 0) { if ((i & 0xFFFFF) == 0) { printf("# Tested %8zu sets. Collisions: %8zu\n", i, num_collisions); } } } return num_collisions; } // --------------------------------------------------------- static size_t perform_experiment_with_prp(ExperimentContext *context) { speck64_context_t cipher_ctx; speck64_96_key_t key; utils::get_random_bytes(key, SPECK_64_96_NUM_KEY_BYTES); utils::print_hex("# Key", key, SPECK_64_96_NUM_KEY_BYTES); speck64_96_key_schedule(&cipher_ctx, key); size_t num_collisions = 0; for (size_t i = 0; i < context->num_sets_per_key; ++i) { SmallStatesVector ciphertexts; speck64_state_t plaintext; generate_base_plaintext(plaintext); for (size_t j = 0; j < NUM_TEXTS_IN_DELTA_SET; ++j) { SmallState ciphertext; get_text_from_delta_set(plaintext, j); speck64_encrypt(&cipher_ctx, plaintext, ciphertext.state); ciphertexts.push_back(ciphertext); } num_collisions += find_num_collisions(ciphertexts); if (i > 0) { if ((i & 0xFFFFF) == 0) { printf("# Tested %8zu sets. Collisions: %8zu\n", i, num_collisions); } } } return num_collisions; } // --------------------------------------------------------- static void perform_experiments(ExperimentContext *context) { experiment_function_t experiment_function = nullptr; if (context->use_prp) { experiment_function = &perform_experiment_with_prp; } else if (!context->use_prp && !context->use_all_delta_sets_from_diagonal) { experiment_function = &perform_experiment; } else if (!context->use_prp && context->use_all_delta_sets_from_diagonal) { experiment_function = &perform_experiment_from_diagonal; } ExperimentResult all_results; all_results.num_collisions = 0; printf("#%8zu Experiments\n", context->num_keys); printf("#%8zu Sets/key\n", context->num_sets_per_key); printf("# Key Collisions Mean Variance \n"); for (size_t i = 0; i < context->num_keys; ++i) { const size_t num_collisions = experiment_function(context); const double mean = (double) num_collisions / (double) context->num_sets_per_key; all_results.num_collisions += num_collisions; all_results.num_collisions_per_set.push_back(num_collisions); printf("%4zu %8zu %8.4f\n", i + 1, num_collisions, mean); } const double mean = compute_mean(all_results.num_collisions_per_set); const double variance = compute_variance( all_results.num_collisions_per_set); printf("# Total Keys Collisions Mean Variance \n"); printf("# %4zu %8zu %8.4f %8.8f\n", context->num_keys, all_results.num_collisions, mean, variance); } // --------------------------------------------------------- // Argument parsing // --------------------------------------------------------- static void parse_args(ExperimentContext *context, int argc, const char **argv) { ArgumentParser parser; parser.appName("Test for the Small-AES five-round distinguisher." "If -d 1 -r 0 is set, uses all 4 * 2^12 * binom(16, 2) " "delta-sets from diagonals, but only for the Small-AES, " "not for the PRP."); parser.addArgument("-k", "--num_keys", 1, false); parser.addArgument("-s", "--num_sets_per_key", 1, false); parser.addArgument("-r", "--use_random_function", 1, false); parser.addArgument("-d", "--use_diagonals", 1, false); try { parser.parse((size_t) argc, argv); context->num_sets_per_key = static_cast<const size_t>(1L << parser.retrieveAsLong("s")); context->num_keys = parser.retrieveAsLong("k"); context->use_prp = (bool) parser.retrieveAsInt("r"); context->use_all_delta_sets_from_diagonal = (bool) parser.retrieveAsInt( "d"); } catch (...) { fprintf(stderr, "%s\n", parser.usage().c_str()); exit(EXIT_FAILURE); } printf("#Keys %8zu\n", context->num_keys); printf("#Sets/Key (log) %8zu\n", context->num_sets_per_key); printf("#Uses PRP %8d\n", context->use_prp); printf("#Uses Diagonal %8d\n", context->use_all_delta_sets_from_diagonal); } // --------------------------------------------------------- int main(int argc, const char **argv) { ExperimentContext context; parse_args(&context, argc, argv); perform_experiments(&context); return EXIT_SUCCESS; }
13,245
4,693
#include <cassert> #include <string.h> #include "EEdims.h" #include "EEfeeDataBlock.h" ClassImp(EEfeeDataBlock) const int EEfeeDataBlock::DefaultMaxHead=4; const int EEfeeDataBlock::DefaultMaxData=192; //-------------------------------------------------- //-------------------------------------------------- //-------------------------------------------------- EEfeeDataBlock :: EEfeeDataBlock() { MaxHead = DefaultMaxHead; MaxData = 0 ; head = new UShort_t[MaxHead]; data = NULL; sanity=0xff; } EEfeeDataBlock::EEfeeDataBlock(const EEfeeDataBlock *b) { MaxData = b->getDataLen(); MaxHead = b->getHeadLen(); head=0; if(MaxHead>0) head = new UShort_t[MaxHead]; data=0; if(MaxData>0) data = new UShort_t[MaxData]; set(b); } //-------------------------------------------------- //-------------------------------------------------- //-------------------------------------------------- EEfeeDataBlock :: ~EEfeeDataBlock() { if(head) delete [] head; if(data) delete [] data; } //-------------------------------------------------- //-------------------------------------------------- //-------------------------------------------------- void EEfeeDataBlock :: print(int flag){ printf("feeDataBlock Head: 0x%04hx 0x%04hx 0x%04hx 0x%04hx ",head[0],head[1],head[2],head[3]); printf("\n --> token=0x%2x crateID=0x%x trigComm=0x%x lenCount=0x%x errFlag=0x%x\n NpositiveData=%d sanity=0x%02x\n", getToken(),getCrateID(),getTrigComm(),getLenCount(),getErrFlag(),getNData(0),sanity); if(flag<=0) return; int nd=getDataLen(); printf("Data[%3d]:",nd); for(int i=0;i<nd;i++) { if( i%8 == 0 ) printf("\n"); printf("0x%04hx ",data[i]); } printf("\n"); } //-------------------------------------------------- //-------------------------------------------------- //-------------------------------------------------- void EEfeeDataBlock :: set(const EEfeeDataBlock *b) { setHead(b->getHead()); setDataArray(b->getData(),b->getDataLen()); } //-------------------------------------------------- //-------------------------------------------------- //-------------------------------------------------- void EEfeeDataBlock ::setHead(const UShort_t *h) { if(h) memcpy(head,h,sizeof(head[0])*MaxHead); else // empty header==>clear memset(head,0,sizeof(head[0])*MaxHead); } //-------------------------------------------------- //-------------------------------------------------- //-------------------------------------------------- int EEfeeDataBlock ::getNData(int thres) const { int n=0; int i; const int nd=getValidDataLen(); for(i=0;i<nd;i++) if(data[i]>thres) n++; return n; } //-------------------------------------------------- //-------------------------------------------------- //-------------------------------------------------- void EEfeeDataBlock ::setDataArray(const UShort_t *dIn, int size) { const UShort_t x=0,*d=&x; if(dIn) { d=dIn; } else { size =1; } if(size!=MaxData) { // tmp, was '>' if(data) delete [] data; MaxData = size; data = new UShort_t[MaxData]; } else { memset(data,0x0,sizeof(data[0])*MaxData); } memcpy(data,d,size*sizeof(data[0])); } //-------------------------------------------------- //-------------------------------------------------- //-------------------------------------------------- void EEfeeDataBlock ::setData(int chan, UShort_t d){ assert(chan>=0); if(chan>=MaxData) { Int_t newsize = MaxData + DefaultMaxData; UShort_t *newdata = new UShort_t[newsize]; if(data) { memcpy(newdata,data,MaxData); delete [] data; } data = newdata; MaxData = newsize; } data[chan]=d; } //-------------------------------------------------- //-------------------------------------------------- //-------------------------------------------------- void EEfeeDataBlock :: clear(){ if(head) memset(head,0,sizeof(head[0])*MaxHead); if(data) memset(data,0,sizeof(data[0])*MaxData); sanity=0xff; // reset to full corruption } //-------------------------------------------------- //-------------------------------------------------- //-------------------------------------------------- UChar_t EEfeeDataBlock ::isHeadValid(int token, int crId, int len, int trigComm, int errFlag){ // encode failure all test as subsequent bits unsigned char ret=0; ret|=(getCrateID()!=crId)<<0; ret|=(getToken()!=token)<<1; ret|=(getLenCount()!=len)<<2; ret|=(getTrigComm()!=trigComm)<<3; ret|=(getErrFlag()!=errFlag)<<4; sanity=ret; #if 0 printf("\nask/0x: %x %x %x %x %x\n", token,crId,len,trigComm,errFlag); print(0); printf("getCrateID()/0x = %x %x\n",getCrateID(),crId); printf("getToken()/0x = %x %x\n",getToken(),token); printf("getLenCount()/0x = %x %x\n",getLenCount(),len); printf("getTrigComm()/0x = %x %x\n",getTrigComm(),trigComm); printf("getErrFlag()/0x = %x %x\n",getErrFlag(),errFlag); #endif return ret; // zero==good header } /* * $Log: EEfeeDataBlock.cxx,v $ * Revision 1.16 2007/07/12 19:30:13 fisyak * Add includes for ROOT 5.16 * * Revision 1.15 2004/06/21 19:50:21 balewski * mre detailed monitoring of data corruption * * Revision 1.14 2004/06/01 16:05:18 balewski * forgoten update of data block headers check * * Revision 1.13 2004/04/16 17:26:46 balewski * more header checking, some mess introduced * * Revision 1.12 2004/04/02 06:38:52 balewski * *** empty log message *** * * Revision 1.11 2004/03/25 16:54:58 balewski * cleanup of arguments * * Revision 1.10 2004/03/20 20:25:55 balewski * *** empty log message *** * * Revision 1.9 2004/01/27 07:09:37 balewski * slower but simpler * * Revision 1.8 2003/12/03 18:55:41 zolnie * fixed yet another bug * * Revision 1.7 2003/12/02 17:22:07 balewski * fix after version mixup * * Revision 1.5 2003/11/24 05:40:55 balewski * new stuff for miniDaq * * Revision 1.4 2003/11/20 16:01:46 balewski * towars run 4 * */
6,003
2,238
#include <bits/stdc++.h> #define MM 1002 using namespace std; string a, b; int c; int main(){ getline(cin,a); getline(cin,b); cin >> c; for(int i = 0; i < a.length(); i++){ if(a[i] != b[i]){ if(a[i] == ' ' || b[i] == ' '){ c = -1; break; } c--; if(c < 0) break; } } printf( c < 0? "No plagiarism":"Plagiarized"); return 0; }
486
187
#include <string> #include "Carolija.h" Carolija::Carolija(std::string ime, int cost) : Karta(ime, cost) { } std::string Carolija::GetCategory() const { return "CAROLIJA"; }
178
75
/* This is a Replicated Module. A plug-in for running PrimaryProtonGun-based event generator for running in MT art. It produces a GenParticleCollection of primary protons using the PrimaryProtonGun. These Collections are used in Mu2eG4_module.cc. Original author Lisa Goodenough */ // Mu2e includes. #include "ConfigTools/inc/SimpleConfig.hh" #include "MCDataProducts/inc/GenId.hh" #include "MCDataProducts/inc/GenParticleCollection.hh" // Particular generators that this code knows about. #include "EventGenerator/inc/PrimaryProtonGun.hh" #include "SeedService/inc/SeedService.hh" // Includes from art and its toolchain. #include "art/Framework/Core/ReplicatedProducer.h" #include "art/Framework/Principal/Event.h" #include "art/Framework/Core/ModuleMacros.h" #include "art/Framework/Services/Registry/ServiceHandle.h" #include "art/Framework/Principal/Handle.h" #include "fhiclcpp/ParameterSet.h" #include "messagefacility/MessageLogger/MessageLogger.h" // C++ includes. #include <iostream> #include <sstream> #include <string> #include <vector> using namespace std; namespace mu2e { class PrimaryProtonGunR : public art::ReplicatedProducer { public: explicit PrimaryProtonGunR(fhicl::ParameterSet const& pS, art::ProcessingFrame const& pF); // Accept compiler written d'tor. Modules are never moved or copied. virtual void produce (art::Event& e, art::ProcessingFrame const& pF) override; virtual void beginRun(art::Run const& r, art::ProcessingFrame const& pF) override; private: // Name of the run-time configuration file. string _configfile; bool _allowReplacement; bool _messageOnReplacement; bool _messageOnDefault; int _configStatsVerbosity; // Print final config file after all replacements. bool _printConfig; CLHEP::HepJamesRandom _engine; std::unique_ptr<PrimaryProtonGun> _primaryProtonGunGenerator; // Number of times BeginRun is called on this module int ncalls = 0; }; PrimaryProtonGunR::PrimaryProtonGunR(fhicl::ParameterSet const& pSet, art::ProcessingFrame const& procFrame): art::ReplicatedProducer{pSet,procFrame}, _configfile( pSet.get<std::string> ("inputfile")), _allowReplacement( pSet.get<bool> ("allowReplacement", true)), _messageOnReplacement( pSet.get<bool> ("messageOnReplacement", false)), _messageOnDefault( pSet.get<bool> ("messageOnDefault", false)), _configStatsVerbosity( pSet.get<int> ("configStatsVerbosity", 0)), _printConfig( pSet.get<bool> ("printConfig", false)), _engine{art::ServiceHandle<SeedService>{}->getSeed()} { produces<GenParticleCollection>(); } void PrimaryProtonGunR::beginRun(art::Run const& run, art::ProcessingFrame const& procFrame){ // The configuration of the PPG Generator does not change within a job. if ( ++ncalls > 1){ mf::LogInfo("PrimaryProtonGunR") << "For Schedule: " << procFrame.scheduleID() << ", PrimaryProtonGunR Generator does not change state at beginRun. Hope that's OK."; return; } // We don't want to print this out more than once, // regardless of the number of instances/schedules running. std::string schedID = std::to_string(procFrame.scheduleID().id()); if ( schedID == "0"){ cout << "Event generator configuration file: " << _configfile << "\n" << endl; } // Load the configuration, make modifications if required, and print if desired. SimpleConfig config(_configfile, _allowReplacement, _messageOnReplacement, _messageOnDefault ); if ( _printConfig ){ config.print(cout,"PrimaryProtonGunR: "); } config.printAllSummaries( cout, _configStatsVerbosity, "PrimaryProtonGunR: "); // Instantiate generator for this run. _primaryProtonGunGenerator = std::make_unique <PrimaryProtonGun>( _engine, run, config); }//beginRun void PrimaryProtonGunR::produce(art::Event& evt, art::ProcessingFrame const& procFrame) { // Make the collections to hold the output. unique_ptr<GenParticleCollection> genParticles(new GenParticleCollection); // Run the generator and put the generated particles into the event. _primaryProtonGunGenerator->generate(*genParticles); evt.put(std::move(genParticles)); }//produce() } DEFINE_ART_MODULE(mu2e::PrimaryProtonGunR);
4,624
1,398
#ifndef PYTHONIC_NUMPY_ONESLIKE_HPP #define PYTHONIC_NUMPY_ONESLIKE_HPP #include "pythonic/include/numpy/ones_like.hpp" #include "pythonic/utils/functor.hpp" #include "pythonic/numpy/ones.hpp" PYTHONIC_NS_BEGIN namespace numpy { template <class E, class dtype> auto ones_like(E const &expr, dtype d) -> decltype(ones(expr.shape(), d)) { return ones(expr.shape(), d); } template <class E> auto ones_like(E const &expr, types::none_type) -> decltype(ones(expr.shape(), types::dtype_t<typename E::dtype>())) { return ones(expr.shape(), types::dtype_t<typename E::dtype>()); } } PYTHONIC_NS_END #endif
635
257
/* * Copyright (c) 2014 The WebM 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 <math.h> #include <stdlib.h> #include <string.h> #include "third_party/googletest/src/include/gtest/gtest.h" #include "./vp9_rtcd.h" #include "./vpx_config.h" #include "./vpx_dsp_rtcd.h" #include "test/acm_random.h" #include "test/buffer.h" #include "test/clear_system_state.h" #include "test/register_state_check.h" #include "test/util.h" #include "vp9/common/vp9_entropy.h" #include "vp9/common/vp9_scan.h" #include "vpx/vpx_codec.h" #include "vpx/vpx_integer.h" #include "vpx_ports/vpx_timer.h" using libvpx_test::ACMRandom; using libvpx_test::Buffer; namespace { const int number_of_iterations = 100; typedef void (*QuantizeFunc)(const tran_low_t *coeff, intptr_t count, int skip_block, const int16_t *zbin, const int16_t *round, const int16_t *quant, const int16_t *quant_shift, tran_low_t *qcoeff, tran_low_t *dqcoeff, const int16_t *dequant, uint16_t *eob, const int16_t *scan, const int16_t *iscan); typedef ::testing::tuple<QuantizeFunc, QuantizeFunc, vpx_bit_depth_t, int /*max_size*/, bool /*is_fp*/> QuantizeParam; // Wrapper for FP version which does not use zbin or quant_shift. typedef void (*QuantizeFPFunc)(const tran_low_t *coeff, intptr_t count, int skip_block, const int16_t *round, const int16_t *quant, tran_low_t *qcoeff, tran_low_t *dqcoeff, const int16_t *dequant, uint16_t *eob, const int16_t *scan, const int16_t *iscan); template <QuantizeFPFunc fn> void QuantFPWrapper(const tran_low_t *coeff, intptr_t count, int skip_block, const int16_t *zbin, const int16_t *round, const int16_t *quant, const int16_t *quant_shift, tran_low_t *qcoeff, tran_low_t *dqcoeff, const int16_t *dequant, uint16_t *eob, const int16_t *scan, const int16_t *iscan) { (void)zbin; (void)quant_shift; fn(coeff, count, skip_block, round, quant, qcoeff, dqcoeff, dequant, eob, scan, iscan); } class VP9QuantizeBase { public: VP9QuantizeBase(vpx_bit_depth_t bit_depth, int max_size, bool is_fp) : bit_depth_(bit_depth), max_size_(max_size), is_fp_(is_fp) { max_value_ = (1 << bit_depth_) - 1; zbin_ptr_ = reinterpret_cast<int16_t *>(vpx_memalign(16, 8 * sizeof(*zbin_ptr_))); round_fp_ptr_ = reinterpret_cast<int16_t *>( vpx_memalign(16, 8 * sizeof(*round_fp_ptr_))); quant_fp_ptr_ = reinterpret_cast<int16_t *>( vpx_memalign(16, 8 * sizeof(*quant_fp_ptr_))); round_ptr_ = reinterpret_cast<int16_t *>(vpx_memalign(16, 8 * sizeof(*round_ptr_))); quant_ptr_ = reinterpret_cast<int16_t *>(vpx_memalign(16, 8 * sizeof(*quant_ptr_))); quant_shift_ptr_ = reinterpret_cast<int16_t *>( vpx_memalign(16, 8 * sizeof(*quant_shift_ptr_))); dequant_ptr_ = reinterpret_cast<int16_t *>( vpx_memalign(16, 8 * sizeof(*dequant_ptr_))); } ~VP9QuantizeBase() { vpx_free(zbin_ptr_); vpx_free(round_fp_ptr_); vpx_free(quant_fp_ptr_); vpx_free(round_ptr_); vpx_free(quant_ptr_); vpx_free(quant_shift_ptr_); vpx_free(dequant_ptr_); zbin_ptr_ = NULL; round_fp_ptr_ = NULL; quant_fp_ptr_ = NULL; round_ptr_ = NULL; quant_ptr_ = NULL; quant_shift_ptr_ = NULL; dequant_ptr_ = NULL; libvpx_test::ClearSystemState(); } protected: int16_t *zbin_ptr_; int16_t *round_fp_ptr_; int16_t *quant_fp_ptr_; int16_t *round_ptr_; int16_t *quant_ptr_; int16_t *quant_shift_ptr_; int16_t *dequant_ptr_; const vpx_bit_depth_t bit_depth_; int max_value_; const int max_size_; const bool is_fp_; }; class VP9QuantizeTest : public VP9QuantizeBase, public ::testing::TestWithParam<QuantizeParam> { public: VP9QuantizeTest() : VP9QuantizeBase(GET_PARAM(2), GET_PARAM(3), GET_PARAM(4)), quantize_op_(GET_PARAM(0)), ref_quantize_op_(GET_PARAM(1)) {} protected: const QuantizeFunc quantize_op_; const QuantizeFunc ref_quantize_op_; }; // This quantizer compares the AC coefficients to the quantization step size to // determine if further multiplication operations are needed. // Based on vp9_quantize_fp_sse2(). inline void quant_fp_nz(const tran_low_t *coeff_ptr, intptr_t n_coeffs, int skip_block, const int16_t *round_ptr, const int16_t *quant_ptr, tran_low_t *qcoeff_ptr, tran_low_t *dqcoeff_ptr, const int16_t *dequant_ptr, uint16_t *eob_ptr, const int16_t *scan, const int16_t *iscan, int is_32x32) { int i, eob = -1; const int thr = dequant_ptr[1] >> (1 + is_32x32); (void)iscan; (void)skip_block; assert(!skip_block); // Quantization pass: All coefficients with index >= zero_flag are // skippable. Note: zero_flag can be zero. for (i = 0; i < n_coeffs; i += 16) { int y; int nzflag_cnt = 0; int abs_coeff[16]; int coeff_sign[16]; // count nzflag for each row (16 tran_low_t) for (y = 0; y < 16; ++y) { const int rc = i + y; const int coeff = coeff_ptr[rc]; coeff_sign[y] = (coeff >> 31); abs_coeff[y] = (coeff ^ coeff_sign[y]) - coeff_sign[y]; // The first 16 are skipped in the sse2 code. Do the same here to match. if (i >= 16 && (abs_coeff[y] <= thr)) { nzflag_cnt++; } } for (y = 0; y < 16; ++y) { const int rc = i + y; // If all of the AC coeffs in a row has magnitude less than the // quantization step_size/2, quantize to zero. if (nzflag_cnt < 16) { int tmp; int _round; if (is_32x32) { _round = ROUND_POWER_OF_TWO(round_ptr[rc != 0], 1); } else { _round = round_ptr[rc != 0]; } tmp = clamp(abs_coeff[y] + _round, INT16_MIN, INT16_MAX); tmp = (tmp * quant_ptr[rc != 0]) >> (16 - is_32x32); qcoeff_ptr[rc] = (tmp ^ coeff_sign[y]) - coeff_sign[y]; dqcoeff_ptr[rc] = qcoeff_ptr[rc] * dequant_ptr[rc != 0]; if (is_32x32) { dqcoeff_ptr[rc] = qcoeff_ptr[rc] * dequant_ptr[rc != 0] / 2; } else { dqcoeff_ptr[rc] = qcoeff_ptr[rc] * dequant_ptr[rc != 0]; } } else { qcoeff_ptr[rc] = 0; dqcoeff_ptr[rc] = 0; } } } // Scan for eob. for (i = 0; i < n_coeffs; i++) { // Use the scan order to find the correct eob. const int rc = scan[i]; if (qcoeff_ptr[rc]) { eob = i; } } *eob_ptr = eob + 1; } void quantize_fp_nz_c(const tran_low_t *coeff_ptr, intptr_t n_coeffs, int skip_block, const int16_t *round_ptr, const int16_t *quant_ptr, tran_low_t *qcoeff_ptr, tran_low_t *dqcoeff_ptr, const int16_t *dequant_ptr, uint16_t *eob_ptr, const int16_t *scan, const int16_t *iscan) { quant_fp_nz(coeff_ptr, n_coeffs, skip_block, round_ptr, quant_ptr, qcoeff_ptr, dqcoeff_ptr, dequant_ptr, eob_ptr, scan, iscan, 0); } void quantize_fp_32x32_nz_c(const tran_low_t *coeff_ptr, intptr_t n_coeffs, int skip_block, const int16_t *round_ptr, const int16_t *quant_ptr, tran_low_t *qcoeff_ptr, tran_low_t *dqcoeff_ptr, const int16_t *dequant_ptr, uint16_t *eob_ptr, const int16_t *scan, const int16_t *iscan) { quant_fp_nz(coeff_ptr, n_coeffs, skip_block, round_ptr, quant_ptr, qcoeff_ptr, dqcoeff_ptr, dequant_ptr, eob_ptr, scan, iscan, 1); } void GenerateHelperArrays(ACMRandom *rnd, int16_t *zbin, int16_t *round, int16_t *quant, int16_t *quant_shift, int16_t *dequant, int16_t *round_fp, int16_t *quant_fp) { // Max when q == 0. Otherwise, it is 48 for Y and 42 for U/V. const int max_qrounding_factor_fp = 64; for (int j = 0; j < 2; j++) { // The range is 4 to 1828 in the VP9 tables. const int qlookup = rnd->RandRange(1825) + 4; round_fp[j] = (max_qrounding_factor_fp * qlookup) >> 7; quant_fp[j] = (1 << 16) / qlookup; // Values determined by deconstructing vp9_init_quantizer(). // zbin may be up to 1143 for 8 and 10 bit Y values, or 1200 for 12 bit Y // values or U/V values of any bit depth. This is because y_delta is not // factored into the vp9_ac_quant() call. zbin[j] = rnd->RandRange(1200); // round may be up to 685 for Y values or 914 for U/V. round[j] = rnd->RandRange(914); // quant ranges from 1 to -32703 quant[j] = static_cast<int>(rnd->RandRange(32704)) - 32703; // quant_shift goes up to 1 << 16. quant_shift[j] = rnd->RandRange(16384); // dequant maxes out at 1828 for all cases. dequant[j] = rnd->RandRange(1828); } for (int j = 2; j < 8; j++) { zbin[j] = zbin[1]; round_fp[j] = round_fp[1]; quant_fp[j] = quant_fp[1]; round[j] = round[1]; quant[j] = quant[1]; quant_shift[j] = quant_shift[1]; dequant[j] = dequant[1]; } } TEST_P(VP9QuantizeTest, OperationCheck) { ACMRandom rnd(ACMRandom::DeterministicSeed()); Buffer<tran_low_t> coeff = Buffer<tran_low_t>(max_size_, max_size_, 0, 16); ASSERT_TRUE(coeff.Init()); Buffer<tran_low_t> qcoeff = Buffer<tran_low_t>(max_size_, max_size_, 0, 32); ASSERT_TRUE(qcoeff.Init()); Buffer<tran_low_t> dqcoeff = Buffer<tran_low_t>(max_size_, max_size_, 0, 32); ASSERT_TRUE(dqcoeff.Init()); Buffer<tran_low_t> ref_qcoeff = Buffer<tran_low_t>(max_size_, max_size_, 0, 32); ASSERT_TRUE(ref_qcoeff.Init()); Buffer<tran_low_t> ref_dqcoeff = Buffer<tran_low_t>(max_size_, max_size_, 0, 32); ASSERT_TRUE(ref_dqcoeff.Init()); uint16_t eob, ref_eob; for (int i = 0; i < number_of_iterations; ++i) { // Test skip block for the first three iterations to catch all the different // sizes. const int skip_block = 0; TX_SIZE sz; if (max_size_ == 16) { sz = static_cast<TX_SIZE>(i % 3); // TX_4X4, TX_8X8 TX_16X16 } else { sz = TX_32X32; } const TX_TYPE tx_type = static_cast<TX_TYPE>((i >> 2) % 3); const scan_order *scan_order = &vp9_scan_orders[sz][tx_type]; const int count = (4 << sz) * (4 << sz); coeff.Set(&rnd, -max_value_, max_value_); GenerateHelperArrays(&rnd, zbin_ptr_, round_ptr_, quant_ptr_, quant_shift_ptr_, dequant_ptr_, round_fp_ptr_, quant_fp_ptr_); int16_t *r_ptr = (is_fp_) ? round_fp_ptr_ : round_ptr_; int16_t *q_ptr = (is_fp_) ? quant_fp_ptr_ : quant_ptr_; ref_quantize_op_(coeff.TopLeftPixel(), count, skip_block, zbin_ptr_, r_ptr, q_ptr, quant_shift_ptr_, ref_qcoeff.TopLeftPixel(), ref_dqcoeff.TopLeftPixel(), dequant_ptr_, &ref_eob, scan_order->scan, scan_order->iscan); ASM_REGISTER_STATE_CHECK(quantize_op_( coeff.TopLeftPixel(), count, skip_block, zbin_ptr_, r_ptr, q_ptr, quant_shift_ptr_, qcoeff.TopLeftPixel(), dqcoeff.TopLeftPixel(), dequant_ptr_, &eob, scan_order->scan, scan_order->iscan)); EXPECT_TRUE(qcoeff.CheckValues(ref_qcoeff)); EXPECT_TRUE(dqcoeff.CheckValues(ref_dqcoeff)); EXPECT_EQ(eob, ref_eob); if (HasFailure()) { printf("Failure on iteration %d.\n", i); qcoeff.PrintDifference(ref_qcoeff); dqcoeff.PrintDifference(ref_dqcoeff); return; } } } TEST_P(VP9QuantizeTest, EOBCheck) { ACMRandom rnd(ACMRandom::DeterministicSeed()); Buffer<tran_low_t> coeff = Buffer<tran_low_t>(max_size_, max_size_, 0, 16); ASSERT_TRUE(coeff.Init()); Buffer<tran_low_t> qcoeff = Buffer<tran_low_t>(max_size_, max_size_, 0, 32); ASSERT_TRUE(qcoeff.Init()); Buffer<tran_low_t> dqcoeff = Buffer<tran_low_t>(max_size_, max_size_, 0, 32); ASSERT_TRUE(dqcoeff.Init()); Buffer<tran_low_t> ref_qcoeff = Buffer<tran_low_t>(max_size_, max_size_, 0, 32); ASSERT_TRUE(ref_qcoeff.Init()); Buffer<tran_low_t> ref_dqcoeff = Buffer<tran_low_t>(max_size_, max_size_, 0, 32); ASSERT_TRUE(ref_dqcoeff.Init()); uint16_t eob, ref_eob; for (int i = 0; i < number_of_iterations; ++i) { const int skip_block = 0; TX_SIZE sz; if (max_size_ == 16) { sz = static_cast<TX_SIZE>(i % 3); // TX_4X4, TX_8X8 TX_16X16 } else { sz = TX_32X32; } const TX_TYPE tx_type = static_cast<TX_TYPE>((i >> 2) % 3); const scan_order *scan_order = &vp9_scan_orders[sz][tx_type]; int count = (4 << sz) * (4 << sz); // Two random entries coeff.Set(0); coeff.TopLeftPixel()[rnd(count)] = static_cast<int>(rnd.RandRange(max_value_ * 2)) - max_value_; coeff.TopLeftPixel()[rnd(count)] = static_cast<int>(rnd.RandRange(max_value_ * 2)) - max_value_; GenerateHelperArrays(&rnd, zbin_ptr_, round_ptr_, quant_ptr_, quant_shift_ptr_, dequant_ptr_, round_fp_ptr_, quant_fp_ptr_); int16_t *r_ptr = (is_fp_) ? round_fp_ptr_ : round_ptr_; int16_t *q_ptr = (is_fp_) ? quant_fp_ptr_ : quant_ptr_; ref_quantize_op_(coeff.TopLeftPixel(), count, skip_block, zbin_ptr_, r_ptr, q_ptr, quant_shift_ptr_, ref_qcoeff.TopLeftPixel(), ref_dqcoeff.TopLeftPixel(), dequant_ptr_, &ref_eob, scan_order->scan, scan_order->iscan); ASM_REGISTER_STATE_CHECK(quantize_op_( coeff.TopLeftPixel(), count, skip_block, zbin_ptr_, r_ptr, q_ptr, quant_shift_ptr_, qcoeff.TopLeftPixel(), dqcoeff.TopLeftPixel(), dequant_ptr_, &eob, scan_order->scan, scan_order->iscan)); EXPECT_TRUE(qcoeff.CheckValues(ref_qcoeff)); EXPECT_TRUE(dqcoeff.CheckValues(ref_dqcoeff)); EXPECT_EQ(eob, ref_eob); if (HasFailure()) { printf("Failure on iteration %d.\n", i); qcoeff.PrintDifference(ref_qcoeff); dqcoeff.PrintDifference(ref_dqcoeff); return; } } } TEST_P(VP9QuantizeTest, DISABLED_Speed) { ACMRandom rnd(ACMRandom::DeterministicSeed()); Buffer<tran_low_t> coeff = Buffer<tran_low_t>(max_size_, max_size_, 0, 16); ASSERT_TRUE(coeff.Init()); Buffer<tran_low_t> qcoeff = Buffer<tran_low_t>(max_size_, max_size_, 0, 32); ASSERT_TRUE(qcoeff.Init()); Buffer<tran_low_t> dqcoeff = Buffer<tran_low_t>(max_size_, max_size_, 0, 32); ASSERT_TRUE(dqcoeff.Init()); uint16_t eob; TX_SIZE starting_sz, ending_sz; if (max_size_ == 16) { starting_sz = TX_4X4; ending_sz = TX_16X16; } else { starting_sz = TX_32X32; ending_sz = TX_32X32; } for (TX_SIZE sz = starting_sz; sz <= ending_sz; ++sz) { // zbin > coeff, zbin < coeff. for (int i = 0; i < 2; ++i) { const int skip_block = 0; // TX_TYPE defines the scan order. That is not relevant to the speed test. // Pick the first one. const TX_TYPE tx_type = DCT_DCT; const scan_order *scan_order = &vp9_scan_orders[sz][tx_type]; const int count = (4 << sz) * (4 << sz); GenerateHelperArrays(&rnd, zbin_ptr_, round_ptr_, quant_ptr_, quant_shift_ptr_, dequant_ptr_, round_fp_ptr_, quant_fp_ptr_); int16_t *r_ptr = (is_fp_) ? round_fp_ptr_ : round_ptr_; int16_t *q_ptr = (is_fp_) ? quant_fp_ptr_ : quant_ptr_; if (i == 0) { // When |coeff values| are less than zbin the results are 0. int threshold = 100; if (max_size_ == 32) { // For 32x32, the threshold is halved. Double it to keep the values // from clearing it. threshold = 200; } for (int j = 0; j < 8; ++j) zbin_ptr_[j] = threshold; coeff.Set(&rnd, -99, 99); } else if (i == 1) { for (int j = 0; j < 8; ++j) zbin_ptr_[j] = 50; coeff.Set(&rnd, -500, 500); } vpx_usec_timer timer; vpx_usec_timer_start(&timer); for (int j = 0; j < 100000000 / count; ++j) { quantize_op_(coeff.TopLeftPixel(), count, skip_block, zbin_ptr_, r_ptr, q_ptr, quant_shift_ptr_, qcoeff.TopLeftPixel(), dqcoeff.TopLeftPixel(), dequant_ptr_, &eob, scan_order->scan, scan_order->iscan); } vpx_usec_timer_mark(&timer); const int elapsed_time = static_cast<int>(vpx_usec_timer_elapsed(&timer)); if (i == 0) printf("Bypass calculations.\n"); if (i == 1) printf("Full calculations.\n"); printf("Quantize %dx%d time: %5d ms\n", 4 << sz, 4 << sz, elapsed_time / 1000); } printf("\n"); } } using ::testing::make_tuple; #if HAVE_SSE2 #if CONFIG_VP9_HIGHBITDEPTH // TODO(johannkoenig): Fix vpx_quantize_b_sse2 in highbitdepth builds. // make_tuple(&vpx_quantize_b_sse2, &vpx_highbd_quantize_b_c, VPX_BITS_8), INSTANTIATE_TEST_CASE_P( SSE2, VP9QuantizeTest, ::testing::Values( make_tuple(&vpx_highbd_quantize_b_sse2, &vpx_highbd_quantize_b_c, VPX_BITS_8, 16, false), make_tuple(&vpx_highbd_quantize_b_sse2, &vpx_highbd_quantize_b_c, VPX_BITS_10, 16, false), make_tuple(&vpx_highbd_quantize_b_sse2, &vpx_highbd_quantize_b_c, VPX_BITS_12, 16, false), make_tuple(&vpx_highbd_quantize_b_32x32_sse2, &vpx_highbd_quantize_b_32x32_c, VPX_BITS_8, 32, false), make_tuple(&vpx_highbd_quantize_b_32x32_sse2, &vpx_highbd_quantize_b_32x32_c, VPX_BITS_10, 32, false), make_tuple(&vpx_highbd_quantize_b_32x32_sse2, &vpx_highbd_quantize_b_32x32_c, VPX_BITS_12, 32, false))); #else INSTANTIATE_TEST_CASE_P( SSE2, VP9QuantizeTest, ::testing::Values(make_tuple(&vpx_quantize_b_sse2, &vpx_quantize_b_c, VPX_BITS_8, 16, false), make_tuple(&QuantFPWrapper<vp9_quantize_fp_sse2>, &QuantFPWrapper<quantize_fp_nz_c>, VPX_BITS_8, 16, true))); #endif // CONFIG_VP9_HIGHBITDEPTH #endif // HAVE_SSE2 #if HAVE_SSSE3 && !CONFIG_VP9_HIGHBITDEPTH #if ARCH_X86_64 INSTANTIATE_TEST_CASE_P( SSSE3, VP9QuantizeTest, ::testing::Values(make_tuple(&vpx_quantize_b_ssse3, &vpx_quantize_b_c, VPX_BITS_8, 16, false), make_tuple(&QuantFPWrapper<vp9_quantize_fp_ssse3>, &QuantFPWrapper<quantize_fp_nz_c>, VPX_BITS_8, 16, true), make_tuple(&QuantFPWrapper<vp9_quantize_fp_32x32_ssse3>, &QuantFPWrapper<quantize_fp_32x32_nz_c>, VPX_BITS_8, 32, true))); #else INSTANTIATE_TEST_CASE_P(SSSE3, VP9QuantizeTest, ::testing::Values(make_tuple(&vpx_quantize_b_ssse3, &vpx_quantize_b_c, VPX_BITS_8, 16, false))); #endif #if ARCH_X86_64 // TODO(johannkoenig): SSSE3 optimizations do not yet pass this test. INSTANTIATE_TEST_CASE_P(DISABLED_SSSE3, VP9QuantizeTest, ::testing::Values(make_tuple( &vpx_quantize_b_32x32_ssse3, &vpx_quantize_b_32x32_c, VPX_BITS_8, 32, false))); #endif // ARCH_X86_64 #endif // HAVE_SSSE3 && !CONFIG_VP9_HIGHBITDEPTH // TODO(johannkoenig): AVX optimizations do not yet pass the 32x32 test or // highbitdepth configurations. #if HAVE_AVX && !CONFIG_VP9_HIGHBITDEPTH INSTANTIATE_TEST_CASE_P( AVX, VP9QuantizeTest, ::testing::Values(make_tuple(&vpx_quantize_b_avx, &vpx_quantize_b_c, VPX_BITS_8, 16, false), // Even though SSSE3 and AVX do not match the reference // code, we can keep them in sync with each other. make_tuple(&vpx_quantize_b_32x32_avx, &vpx_quantize_b_32x32_ssse3, VPX_BITS_8, 32, false))); #endif // HAVE_AVX && !CONFIG_VP9_HIGHBITDEPTH #if ARCH_X86_64 && HAVE_AVX2 INSTANTIATE_TEST_CASE_P( AVX2, VP9QuantizeTest, ::testing::Values(make_tuple(&QuantFPWrapper<vp9_quantize_fp_avx2>, &QuantFPWrapper<quantize_fp_nz_c>, VPX_BITS_8, 16, true))); #endif // HAVE_AVX2 && !CONFIG_VP9_HIGHBITDEPTH // TODO(webm:1448): dqcoeff is not handled correctly in HBD builds. #if HAVE_NEON && !CONFIG_VP9_HIGHBITDEPTH INSTANTIATE_TEST_CASE_P( NEON, VP9QuantizeTest, ::testing::Values(make_tuple(&vpx_quantize_b_neon, &vpx_quantize_b_c, VPX_BITS_8, 16, false), make_tuple(&vpx_quantize_b_32x32_neon, &vpx_quantize_b_32x32_c, VPX_BITS_8, 32, false), make_tuple(&QuantFPWrapper<vp9_quantize_fp_neon>, &QuantFPWrapper<vp9_quantize_fp_c>, VPX_BITS_8, 16, true), make_tuple(&QuantFPWrapper<vp9_quantize_fp_32x32_neon>, &QuantFPWrapper<vp9_quantize_fp_32x32_c>, VPX_BITS_8, 32, true))); #endif // HAVE_NEON && !CONFIG_VP9_HIGHBITDEPTH #if HAVE_VSX && !CONFIG_VP9_HIGHBITDEPTH INSTANTIATE_TEST_CASE_P(VSX, VP9QuantizeTest, ::testing::Values(make_tuple(&vpx_quantize_b_vsx, &vpx_quantize_b_c, VPX_BITS_8, 16, false), make_tuple(&vpx_quantize_b_32x32_vsx, &vpx_quantize_b_32x32_c, VPX_BITS_8, 32, false))); #endif // HAVE_VSX && !CONFIG_VP9_HIGHBITDEPTH // Only useful to compare "Speed" test results. INSTANTIATE_TEST_CASE_P( DISABLED_C, VP9QuantizeTest, ::testing::Values( make_tuple(&vpx_quantize_b_c, &vpx_quantize_b_c, VPX_BITS_8, 16, false), make_tuple(&vpx_quantize_b_32x32_c, &vpx_quantize_b_32x32_c, VPX_BITS_8, 32, false), make_tuple(&QuantFPWrapper<vp9_quantize_fp_c>, &QuantFPWrapper<vp9_quantize_fp_c>, VPX_BITS_8, 16, true), make_tuple(&QuantFPWrapper<quantize_fp_nz_c>, &QuantFPWrapper<quantize_fp_nz_c>, VPX_BITS_8, 16, true), make_tuple(&QuantFPWrapper<quantize_fp_32x32_nz_c>, &QuantFPWrapper<quantize_fp_32x32_nz_c>, VPX_BITS_8, 32, true), make_tuple(&QuantFPWrapper<vp9_quantize_fp_32x32_c>, &QuantFPWrapper<vp9_quantize_fp_32x32_c>, VPX_BITS_8, 32, true))); } // namespace
23,687
9,535
/****************************************************************************** * Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source * Project (AJOSP) Contributors and others. * * SPDX-License-Identifier: Apache-2.0 * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/LICENSE-2.0 * * Copyright (c) Open Connectivity Foundation and Contributors to AllSeen * Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. * ******************************************************************************/ #include <qcc/Debug.h> #include "XJavaDelegator.h" #include "XControllerServiceManagerCallback.h" #define QCC_MODULE "AJN-LSF-JNI" namespace lsf { XControllerServiceManagerCallback::XControllerServiceManagerCallback(jobject jobj) { // Get the JNIEnv for the current native thread JScopedEnv env; /* * Be careful when using a weak global reference. They can only be * passed to NewLocalRef, NewGlobalRef and DeleteWeakGlobalRef. */ QCC_DbgPrintf(("Taking weak global reference to Java object %p", jobj)); jdelegate = env->NewWeakGlobalRef(jobj); if (env->ExceptionCheck() || !jdelegate) { QCC_LogError(ER_FAIL, ("NewWeakGlobalRef() failed")); return; } } XControllerServiceManagerCallback::~XControllerServiceManagerCallback() { // Get the JNIEnv for the current native thread JScopedEnv env; env->DeleteWeakGlobalRef(jdelegate); if (env->ExceptionCheck()) { QCC_LogError(ER_FAIL, ("DeleteWeakGlobalRef() failed")); return; } } void XControllerServiceManagerCallback::GetControllerServiceVersionReplyCB(const uint32_t& version) { XJavaDelegator::Call_Void_UInt32(jdelegate, __func__, version); } void XControllerServiceManagerCallback::LightingResetControllerServiceReplyCB(const LSFResponseCode& responseCode) { XJavaDelegator::Call_Void_ResponseCode(jdelegate, __func__, responseCode); } void XControllerServiceManagerCallback::ControllerServiceLightingResetCB(void) { XJavaDelegator::Call_Void(jdelegate, __func__); } void XControllerServiceManagerCallback::ControllerServiceNameChangedCB(const LSFString& controllerServiceDeviceID, const LSFString& controllerServiceName) { XJavaDelegator::Call_Void_String_String(jdelegate, __func__, controllerServiceDeviceID, controllerServiceName); } } /* namespace lsf */
3,341
1,020
//%Header { /***************************************************************************** * * File: src/MushGame/MushGameMessageControlInfo.cpp * * Author: Andy Southgate 2002-2005 * * This file contains original work by Andy Southgate. The author and his * employer (Mushware Limited) irrevocably waive all of their copyright rights * vested in this particular version of this file to the furthest extent * permitted. The author and Mushware Limited also irrevocably waive any and * all of their intellectual property rights arising from said file and its * creation that would otherwise restrict the rights of any party to use and/or * distribute the use of, the techniques and methods used herein. A written * waiver can be obtained via http://www.mushware.com/. * * This software carries NO WARRANTY of any kind. * ****************************************************************************/ //%Header } w1/s8yA5XXvqhMRSZQYCrg /* * $Id: MushGameMessageControlInfo.cpp,v 1.1 2005/07/06 19:08:27 southa Exp $ * $Log: MushGameMessageControlInfo.cpp,v $ * Revision 1.1 2005/07/06 19:08:27 southa * Adanaxis control work * */ #include "MushGameMessageControlInfo.h" //%outOfLineFunctions { const char *MushGameMessageControlInfo::AutoName(void) const { return "MushGameMessageControlInfo"; } MushcoreVirtualObject *MushGameMessageControlInfo::AutoClone(void) const { return new MushGameMessageControlInfo(*this); } MushcoreVirtualObject *MushGameMessageControlInfo::AutoCreate(void) const { return new MushGameMessageControlInfo; } MushcoreVirtualObject *MushGameMessageControlInfo::AutoVirtualFactory(void) { return new MushGameMessageControlInfo; } namespace { void AutoInstall(void) { MushcoreFactory::Sgl().FactoryAdd("MushGameMessageControlInfo", MushGameMessageControlInfo::AutoVirtualFactory); } MushcoreInstaller AutoInstaller(AutoInstall); } // end anonymous namespace void MushGameMessageControlInfo::AutoPrint(std::ostream& ioOut) const { ioOut << "["; MushGameMessage::AutoPrint(ioOut); ioOut << "timestamp=" << m_timestamp << ", "; ioOut << "axisEvents=" << m_axisEvents << ", "; ioOut << "keyEvents=" << m_keyEvents; ioOut << "]"; } bool MushGameMessageControlInfo::AutoXMLDataProcess(MushcoreXMLIStream& ioIn, const std::string& inTagStr) { if (inTagStr == "obj") { AutoInputPrologue(ioIn); ioIn >> *this; AutoInputEpilogue(ioIn); } else if (inTagStr == "timestamp") { ioIn >> m_timestamp; } else if (inTagStr == "axisEvents") { ioIn >> m_axisEvents; } else if (inTagStr == "keyEvents") { ioIn >> m_keyEvents; } else if (MushGameMessage::AutoXMLDataProcess(ioIn, inTagStr)) { // Tag consumed by base class } else { return false; } return true; } void MushGameMessageControlInfo::AutoXMLPrint(MushcoreXMLOStream& ioOut) const { MushGameMessage::AutoXMLPrint(ioOut); ioOut.TagSet("timestamp"); ioOut << m_timestamp; ioOut.TagSet("axisEvents"); ioOut << m_axisEvents; ioOut.TagSet("keyEvents"); ioOut << m_keyEvents; } //%outOfLineFunctions } 2pzNQJVGzbzqSBE8BGC1KA
3,225
1,053
/* * Copyright (c) 1998, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ // output_h.cpp - Class HPP file output routines for architecture definition #include "adlc.hpp" // The comment delimiter used in format statements after assembler instructions. #define commentSeperator "!" // Generate the #define that describes the number of registers. static void defineRegCount(FILE *fp, RegisterForm *registers) { if (registers) { int regCount = AdlcVMDeps::Physical + registers->_rdefs.count(); fprintf(fp,"\n"); fprintf(fp,"// the number of reserved registers + machine registers.\n"); fprintf(fp,"#define REG_COUNT %d\n", regCount); } } // Output enumeration of machine register numbers // (1) // // Enumerate machine registers starting after reserved regs. // // in the order of occurrence in the register block. // enum MachRegisterNumbers { // EAX_num = 0, // ... // _last_Mach_Reg // } void ArchDesc::buildMachRegisterNumbers(FILE *fp_hpp) { if (_register) { RegDef *reg_def = NULL; // Output a #define for the number of machine registers defineRegCount(fp_hpp, _register); // Count all the Save_On_Entry and Always_Save registers int saved_on_entry = 0; int c_saved_on_entry = 0; _register->reset_RegDefs(); while( (reg_def = _register->iter_RegDefs()) != NULL ) { if( strcmp(reg_def->_callconv,"SOE") == 0 || strcmp(reg_def->_callconv,"AS") == 0 ) ++saved_on_entry; if( strcmp(reg_def->_c_conv,"SOE") == 0 || strcmp(reg_def->_c_conv,"AS") == 0 ) ++c_saved_on_entry; } fprintf(fp_hpp, "\n"); fprintf(fp_hpp, "// the number of save_on_entry + always_saved registers.\n"); fprintf(fp_hpp, "#define MAX_SAVED_ON_ENTRY_REG_COUNT %d\n", max(saved_on_entry,c_saved_on_entry)); fprintf(fp_hpp, "#define SAVED_ON_ENTRY_REG_COUNT %d\n", saved_on_entry); fprintf(fp_hpp, "#define C_SAVED_ON_ENTRY_REG_COUNT %d\n", c_saved_on_entry); // (1) // Build definition for enumeration of register numbers fprintf(fp_hpp, "\n"); fprintf(fp_hpp, "// Enumerate machine register numbers starting after reserved regs.\n"); fprintf(fp_hpp, "// in the order of occurrence in the register block.\n"); fprintf(fp_hpp, "enum MachRegisterNumbers {\n"); // Output the register number for each register in the allocation classes _register->reset_RegDefs(); int i = 0; while( (reg_def = _register->iter_RegDefs()) != NULL ) { fprintf(fp_hpp," %s_num,", reg_def->_regname); for (int j = 0; j < 20-(int)strlen(reg_def->_regname); j++) fprintf(fp_hpp, " "); fprintf(fp_hpp," // enum %3d, regnum %3d, reg encode %3s\n", i++, reg_def->register_num(), reg_def->register_encode()); } // Finish defining enumeration fprintf(fp_hpp, " _last_Mach_Reg // %d\n", i); fprintf(fp_hpp, "};\n"); } fprintf(fp_hpp, "\n// Size of register-mask in ints\n"); fprintf(fp_hpp, "#define RM_SIZE %d\n",RegisterForm::RegMask_Size()); fprintf(fp_hpp, "// Unroll factor for loops over the data in a RegMask\n"); fprintf(fp_hpp, "#define FORALL_BODY "); int len = RegisterForm::RegMask_Size(); for( int i = 0; i < len; i++ ) fprintf(fp_hpp, "BODY(%d) ",i); fprintf(fp_hpp, "\n\n"); fprintf(fp_hpp,"class RegMask;\n"); // All RegMasks are declared "extern const ..." in ad_<arch>.hpp // fprintf(fp_hpp,"extern RegMask STACK_OR_STACK_SLOTS_mask;\n\n"); } // Output enumeration of machine register encodings // (2) // // Enumerate machine registers starting after reserved regs. // // in the order of occurrence in the alloc_class(es). // enum MachRegisterEncodes { // EAX_enc = 0x00, // ... // } void ArchDesc::buildMachRegisterEncodes(FILE *fp_hpp) { if (_register) { RegDef *reg_def = NULL; RegDef *reg_def_next = NULL; // (2) // Build definition for enumeration of encode values fprintf(fp_hpp, "\n"); fprintf(fp_hpp, "// Enumerate machine registers starting after reserved regs.\n"); fprintf(fp_hpp, "// in the order of occurrence in the alloc_class(es).\n"); fprintf(fp_hpp, "enum MachRegisterEncodes {\n"); // Find max enum string length. size_t maxlen = 0; _register->reset_RegDefs(); reg_def = _register->iter_RegDefs(); while (reg_def != NULL) { size_t len = strlen(reg_def->_regname); if (len > maxlen) maxlen = len; reg_def = _register->iter_RegDefs(); } // Output the register encoding for each register in the allocation classes _register->reset_RegDefs(); reg_def_next = _register->iter_RegDefs(); while( (reg_def = reg_def_next) != NULL ) { reg_def_next = _register->iter_RegDefs(); fprintf(fp_hpp," %s_enc", reg_def->_regname); for (size_t i = strlen(reg_def->_regname); i < maxlen; i++) fprintf(fp_hpp, " "); fprintf(fp_hpp," = %3s%s\n", reg_def->register_encode(), reg_def_next == NULL? "" : "," ); } // Finish defining enumeration fprintf(fp_hpp, "};\n"); } // Done with register form } // Declare an array containing the machine register names, strings. static void declareRegNames(FILE *fp, RegisterForm *registers) { if (registers) { // fprintf(fp,"\n"); // fprintf(fp,"// An array of character pointers to machine register names.\n"); // fprintf(fp,"extern const char *regName[];\n"); } } // Declare an array containing the machine register sizes in 32-bit words. void ArchDesc::declareRegSizes(FILE *fp) { // regSize[] is not used } // Declare an array containing the machine register encoding values static void declareRegEncodes(FILE *fp, RegisterForm *registers) { if (registers) { // // // // fprintf(fp,"\n"); // fprintf(fp,"// An array containing the machine register encode values\n"); // fprintf(fp,"extern const char regEncode[];\n"); } } // --------------------------------------------------------------------------- //------------------------------Utilities to build Instruction Classes-------- // --------------------------------------------------------------------------- static void out_RegMask(FILE *fp) { fprintf(fp," virtual const RegMask &out_RegMask() const;\n"); } // --------------------------------------------------------------------------- //--------Utilities to build MachOper and MachNode derived Classes------------ // --------------------------------------------------------------------------- //------------------------------Utilities to build Operand Classes------------ static void in_RegMask(FILE *fp) { fprintf(fp," virtual const RegMask *in_RegMask(int index) const;\n"); } static void declareConstStorage(FILE *fp, FormDict &globals, OperandForm *oper) { int i = 0; Component *comp; if (oper->num_consts(globals) == 0) return; // Iterate over the component list looking for constants oper->_components.reset(); if ((comp = oper->_components.iter()) == NULL) { assert(oper->num_consts(globals) == 1, "Bad component list detected.\n"); const char *type = oper->ideal_type(globals); if (!strcmp(type, "ConI")) { if (i > 0) fprintf(fp,", "); fprintf(fp," int32 _c%d;\n", i); } else if (!strcmp(type, "ConP")) { if (i > 0) fprintf(fp,", "); fprintf(fp," const TypePtr *_c%d;\n", i); } else if (!strcmp(type, "ConN")) { if (i > 0) fprintf(fp,", "); fprintf(fp," const TypeNarrowOop *_c%d;\n", i); } else if (!strcmp(type, "ConL")) { if (i > 0) fprintf(fp,", "); fprintf(fp," jlong _c%d;\n", i); } else if (!strcmp(type, "ConF")) { if (i > 0) fprintf(fp,", "); fprintf(fp," jfloat _c%d;\n", i); } else if (!strcmp(type, "ConD")) { if (i > 0) fprintf(fp,", "); fprintf(fp," jdouble _c%d;\n", i); } else if (!strcmp(type, "Bool")) { fprintf(fp,"private:\n"); fprintf(fp," BoolTest::mask _c%d;\n", i); fprintf(fp,"public:\n"); } else { assert(0, "Non-constant operand lacks component list."); } } // end if NULL else { oper->_components.reset(); while ((comp = oper->_components.iter()) != NULL) { if (!strcmp(comp->base_type(globals), "ConI")) { fprintf(fp," jint _c%d;\n", i); i++; } else if (!strcmp(comp->base_type(globals), "ConP")) { fprintf(fp," const TypePtr *_c%d;\n", i); i++; } else if (!strcmp(comp->base_type(globals), "ConN")) { fprintf(fp," const TypePtr *_c%d;\n", i); i++; } else if (!strcmp(comp->base_type(globals), "ConL")) { fprintf(fp," jlong _c%d;\n", i); i++; } else if (!strcmp(comp->base_type(globals), "ConF")) { fprintf(fp," jfloat _c%d;\n", i); i++; } else if (!strcmp(comp->base_type(globals), "ConD")) { fprintf(fp," jdouble _c%d;\n", i); i++; } } } } // Declare constructor. // Parameters start with condition code, then all other constants // // (0) public: // (1) MachXOper(int32 ccode, int32 c0, int32 c1, ..., int32 cn) // (2) : _ccode(ccode), _c0(c0), _c1(c1), ..., _cn(cn) { } // static void defineConstructor(FILE *fp, const char *name, uint num_consts, ComponentList &lst, bool is_ideal_bool, Form::DataType constant_type, FormDict &globals) { fprintf(fp,"public:\n"); // generate line (1) fprintf(fp," %sOper(", name); if( num_consts == 0 ) { fprintf(fp,") {}\n"); return; } // generate parameters for constants uint i = 0; Component *comp; lst.reset(); if ((comp = lst.iter()) == NULL) { assert(num_consts == 1, "Bad component list detected.\n"); switch( constant_type ) { case Form::idealI : { fprintf(fp,is_ideal_bool ? "BoolTest::mask c%d" : "int32 c%d", i); break; } case Form::idealN : { fprintf(fp,"const TypeNarrowOop *c%d", i); break; } case Form::idealP : { fprintf(fp,"const TypePtr *c%d", i); break; } case Form::idealL : { fprintf(fp,"jlong c%d", i); break; } case Form::idealF : { fprintf(fp,"jfloat c%d", i); break; } case Form::idealD : { fprintf(fp,"jdouble c%d", i); break; } default: assert(!is_ideal_bool, "Non-constant operand lacks component list."); break; } } // end if NULL else { lst.reset(); while((comp = lst.iter()) != NULL) { if (!strcmp(comp->base_type(globals), "ConI")) { if (i > 0) fprintf(fp,", "); fprintf(fp,"int32 c%d", i); i++; } else if (!strcmp(comp->base_type(globals), "ConP")) { if (i > 0) fprintf(fp,", "); fprintf(fp,"const TypePtr *c%d", i); i++; } else if (!strcmp(comp->base_type(globals), "ConN")) { if (i > 0) fprintf(fp,", "); fprintf(fp,"const TypePtr *c%d", i); i++; } else if (!strcmp(comp->base_type(globals), "ConL")) { if (i > 0) fprintf(fp,", "); fprintf(fp,"jlong c%d", i); i++; } else if (!strcmp(comp->base_type(globals), "ConF")) { if (i > 0) fprintf(fp,", "); fprintf(fp,"jfloat c%d", i); i++; } else if (!strcmp(comp->base_type(globals), "ConD")) { if (i > 0) fprintf(fp,", "); fprintf(fp,"jdouble c%d", i); i++; } else if (!strcmp(comp->base_type(globals), "Bool")) { if (i > 0) fprintf(fp,", "); fprintf(fp,"BoolTest::mask c%d", i); i++; } } } // finish line (1) and start line (2) fprintf(fp,") : "); // generate initializers for constants i = 0; fprintf(fp,"_c%d(c%d)", i, i); for( i = 1; i < num_consts; ++i) { fprintf(fp,", _c%d(c%d)", i, i); } // The body for the constructor is empty fprintf(fp," {}\n"); } // --------------------------------------------------------------------------- // Utilities to generate format rules for machine operands and instructions // --------------------------------------------------------------------------- // Generate the format rule for condition codes static void defineCCodeDump(OperandForm* oper, FILE *fp, int i) { assert(oper != NULL, "what"); CondInterface* cond = oper->_interface->is_CondInterface(); fprintf(fp, " if( _c%d == BoolTest::eq ) st->print(\"%s\");\n",i,cond->_equal_format); fprintf(fp, " else if( _c%d == BoolTest::ne ) st->print(\"%s\");\n",i,cond->_not_equal_format); fprintf(fp, " else if( _c%d == BoolTest::le ) st->print(\"%s\");\n",i,cond->_less_equal_format); fprintf(fp, " else if( _c%d == BoolTest::ge ) st->print(\"%s\");\n",i,cond->_greater_equal_format); fprintf(fp, " else if( _c%d == BoolTest::lt ) st->print(\"%s\");\n",i,cond->_less_format); fprintf(fp, " else if( _c%d == BoolTest::gt ) st->print(\"%s\");\n",i,cond->_greater_format); } // Output code that dumps constant values, increment "i" if type is constant static uint dump_spec_constant(FILE *fp, const char *ideal_type, uint i, OperandForm* oper) { if (!strcmp(ideal_type, "ConI")) { fprintf(fp," st->print(\"#%%d\", _c%d);\n", i); fprintf(fp," st->print(\"/0x%%08x\", _c%d);\n", i); ++i; } else if (!strcmp(ideal_type, "ConP")) { fprintf(fp," _c%d->dump_on(st);\n", i); ++i; } else if (!strcmp(ideal_type, "ConN")) { fprintf(fp," _c%d->dump_on(st);\n", i); ++i; } else if (!strcmp(ideal_type, "ConL")) { fprintf(fp," st->print(\"#\" INT64_FORMAT, _c%d);\n", i); fprintf(fp," st->print(\"/\" PTR64_FORMAT, _c%d);\n", i); ++i; } else if (!strcmp(ideal_type, "ConF")) { fprintf(fp," st->print(\"#%%f\", _c%d);\n", i); fprintf(fp," jint _c%di = JavaValue(_c%d).get_jint();\n", i, i); fprintf(fp," st->print(\"/0x%%x/\", _c%di);\n", i); ++i; } else if (!strcmp(ideal_type, "ConD")) { fprintf(fp," st->print(\"#%%f\", _c%d);\n", i); fprintf(fp," jlong _c%dl = JavaValue(_c%d).get_jlong();\n", i, i); fprintf(fp," st->print(\"/\" PTR64_FORMAT, _c%dl);\n", i); ++i; } else if (!strcmp(ideal_type, "Bool")) { defineCCodeDump(oper, fp,i); ++i; } return i; } // Generate the format rule for an operand void gen_oper_format(FILE *fp, FormDict &globals, OperandForm &oper, bool for_c_file = false) { if (!for_c_file) { // invoked after output #ifndef PRODUCT to ad_<arch>.hpp // compile the bodies separately, to cut down on recompilations fprintf(fp," virtual void int_format(PhaseRegAlloc *ra, const MachNode *node, outputStream *st) const;\n"); fprintf(fp," virtual void ext_format(PhaseRegAlloc *ra, const MachNode *node, int idx, outputStream *st) const;\n"); return; } // Local pointer indicates remaining part of format rule int idx = 0; // position of operand in match rule // Generate internal format function, used when stored locally fprintf(fp, "\n#ifndef PRODUCT\n"); fprintf(fp,"void %sOper::int_format(PhaseRegAlloc *ra, const MachNode *node, outputStream *st) const {\n", oper._ident); // Generate the user-defined portion of the format if (oper._format) { if ( oper._format->_strings.count() != 0 ) { // No initialization code for int_format // Build the format from the entries in strings and rep_vars const char *string = NULL; oper._format->_rep_vars.reset(); oper._format->_strings.reset(); while ( (string = oper._format->_strings.iter()) != NULL ) { // Check if this is a standard string or a replacement variable if ( string != NameList::_signal ) { // Normal string // Pass through to st->print fprintf(fp," st->print(\"%s\");\n", string); } else { // Replacement variable const char *rep_var = oper._format->_rep_vars.iter(); // Check that it is a local name, and an operand const Form* form = oper._localNames[rep_var]; if (form == NULL) { globalAD->syntax_err(oper._linenum, "\'%s\' not found in format for %s\n", rep_var, oper._ident); assert(form, "replacement variable was not found in local names"); } OperandForm *op = form->is_operand(); // Get index if register or constant if ( op->_matrule && op->_matrule->is_base_register(globals) ) { idx = oper.register_position( globals, rep_var); } else if (op->_matrule && op->_matrule->is_base_constant(globals)) { idx = oper.constant_position( globals, rep_var); } else { idx = 0; } // output invocation of "$..."s format function if ( op != NULL ) op->int_format(fp, globals, idx); if ( idx == -1 ) { fprintf(stderr, "Using a name, %s, that isn't in match rule\n", rep_var); assert( strcmp(op->_ident,"label")==0, "Unimplemented"); } } // Done with a replacement variable } // Done with all format strings } else { // Default formats for base operands (RegI, RegP, ConI, ConP, ...) oper.int_format(fp, globals, 0); } } else { // oper._format == NULL // Provide a few special case formats where the AD writer cannot. if ( strcmp(oper._ident,"Universe")==0 ) { fprintf(fp, " st->print(\"$$univ\");\n"); } // labelOper::int_format is defined in ad_<...>.cpp } // ALWAYS! Provide a special case output for condition codes. if( oper.is_ideal_bool() ) { defineCCodeDump(&oper, fp,0); } fprintf(fp,"}\n"); // Generate external format function, when data is stored externally fprintf(fp,"void %sOper::ext_format(PhaseRegAlloc *ra, const MachNode *node, int idx, outputStream *st) const {\n", oper._ident); // Generate the user-defined portion of the format if (oper._format) { if ( oper._format->_strings.count() != 0 ) { // Check for a replacement string "$..." if ( oper._format->_rep_vars.count() != 0 ) { // Initialization code for ext_format } // Build the format from the entries in strings and rep_vars const char *string = NULL; oper._format->_rep_vars.reset(); oper._format->_strings.reset(); while ( (string = oper._format->_strings.iter()) != NULL ) { // Check if this is a standard string or a replacement variable if ( string != NameList::_signal ) { // Normal string // Pass through to st->print fprintf(fp," st->print(\"%s\");\n", string); } else { // Replacement variable const char *rep_var = oper._format->_rep_vars.iter(); // Check that it is a local name, and an operand const Form* form = oper._localNames[rep_var]; if (form == NULL) { globalAD->syntax_err(oper._linenum, "\'%s\' not found in format for %s\n", rep_var, oper._ident); assert(form, "replacement variable was not found in local names"); } OperandForm *op = form->is_operand(); // Get index if register or constant if ( op->_matrule && op->_matrule->is_base_register(globals) ) { idx = oper.register_position( globals, rep_var); } else if (op->_matrule && op->_matrule->is_base_constant(globals)) { idx = oper.constant_position( globals, rep_var); } else { idx = 0; } // output invocation of "$..."s format function if ( op != NULL ) op->ext_format(fp, globals, idx); // Lookup the index position of the replacement variable idx = oper._components.operand_position_format(rep_var, &oper); if ( idx == -1 ) { fprintf(stderr, "Using a name, %s, that isn't in match rule\n", rep_var); assert( strcmp(op->_ident,"label")==0, "Unimplemented"); } } // Done with a replacement variable } // Done with all format strings } else { // Default formats for base operands (RegI, RegP, ConI, ConP, ...) oper.ext_format(fp, globals, 0); } } else { // oper._format == NULL // Provide a few special case formats where the AD writer cannot. if ( strcmp(oper._ident,"Universe")==0 ) { fprintf(fp, " st->print(\"$$univ\");\n"); } // labelOper::ext_format is defined in ad_<...>.cpp } // ALWAYS! Provide a special case output for condition codes. if( oper.is_ideal_bool() ) { defineCCodeDump(&oper, fp,0); } fprintf(fp, "}\n"); fprintf(fp, "#endif\n"); } // Generate the format rule for an instruction void gen_inst_format(FILE *fp, FormDict &globals, InstructForm &inst, bool for_c_file = false) { if (!for_c_file) { // compile the bodies separately, to cut down on recompilations // #ifndef PRODUCT region generated by caller fprintf(fp," virtual void format(PhaseRegAlloc *ra, outputStream *st) const;\n"); return; } // Define the format function fprintf(fp, "#ifndef PRODUCT\n"); fprintf(fp, "void %sNode::format(PhaseRegAlloc *ra, outputStream *st) const {\n", inst._ident); // Generate the user-defined portion of the format if( inst._format ) { // If there are replacement variables, // Generate index values needed for determining the operand position if( inst._format->_rep_vars.count() ) inst.index_temps(fp, globals); // Build the format from the entries in strings and rep_vars const char *string = NULL; inst._format->_rep_vars.reset(); inst._format->_strings.reset(); while( (string = inst._format->_strings.iter()) != NULL ) { fprintf(fp," "); // Check if this is a standard string or a replacement variable if( string == NameList::_signal ) { // Replacement variable const char* rep_var = inst._format->_rep_vars.iter(); inst.rep_var_format( fp, rep_var); } else if( string == NameList::_signal3 ) { // Replacement variable in raw text const char* rep_var = inst._format->_rep_vars.iter(); const Form *form = inst._localNames[rep_var]; if (form == NULL) { fprintf(stderr, "unknown replacement variable in format statement: '%s'\n", rep_var); assert(false, "ShouldNotReachHere()"); } OpClassForm *opc = form->is_opclass(); assert( opc, "replacement variable was not found in local names"); // Lookup the index position of the replacement variable int idx = inst.operand_position_format(rep_var); if ( idx == -1 ) { assert( strcmp(opc->_ident,"label")==0, "Unimplemented"); assert( false, "ShouldNotReachHere()"); } if (inst.is_noninput_operand(idx)) { assert( false, "ShouldNotReachHere()"); } else { // Output the format call for this operand fprintf(fp,"opnd_array(%d)",idx); } rep_var = inst._format->_rep_vars.iter(); inst._format->_strings.iter(); if ( strcmp(rep_var,"$constant") == 0 && opc->is_operand()) { Form::DataType constant_type = form->is_operand()->is_base_constant(globals); if ( constant_type == Form::idealD ) { fprintf(fp,"->constantD()"); } else if ( constant_type == Form::idealF ) { fprintf(fp,"->constantF()"); } else if ( constant_type == Form::idealL ) { fprintf(fp,"->constantL()"); } else { fprintf(fp,"->constant()"); } } else if ( strcmp(rep_var,"$cmpcode") == 0) { fprintf(fp,"->ccode()"); } else { assert( false, "ShouldNotReachHere()"); } } else if( string == NameList::_signal2 ) // Raw program text fputs(inst._format->_strings.iter(), fp); else fprintf(fp,"st->print(\"%s\");\n", string); } // Done with all format strings } // Done generating the user-defined portion of the format // Add call debug info automatically Form::CallType call_type = inst.is_ideal_call(); if( call_type != Form::invalid_type ) { switch( call_type ) { case Form::JAVA_DYNAMIC: fprintf(fp," _method->print_short_name(st);\n"); break; case Form::JAVA_STATIC: fprintf(fp," if( _method ) _method->print_short_name(st);\n"); fprintf(fp," else st->print(\" wrapper for: %%s\", _name);\n"); fprintf(fp," if( !_method ) dump_trap_args(st);\n"); break; case Form::JAVA_COMPILED: case Form::JAVA_INTERP: break; case Form::JAVA_RUNTIME: case Form::JAVA_LEAF: case Form::JAVA_NATIVE: fprintf(fp," st->print(\" %%s\", _name);"); break; default: assert(0,"ShouldNotReachHere"); } fprintf(fp, " st->print_cr(\"\");\n" ); fprintf(fp, " if (_jvms) _jvms->format(ra, this, st); else st->print_cr(\" No JVM State Info\");\n" ); fprintf(fp, " st->print(\" # \");\n" ); fprintf(fp, " if( _jvms && _oop_map ) _oop_map->print_on(st);\n"); } else if(inst.is_ideal_safepoint()) { fprintf(fp, " st->print(\"\");\n" ); fprintf(fp, " if (_jvms) _jvms->format(ra, this, st); else st->print_cr(\" No JVM State Info\");\n" ); fprintf(fp, " st->print(\" # \");\n" ); fprintf(fp, " if( _jvms && _oop_map ) _oop_map->print_on(st);\n"); } else if( inst.is_ideal_if() ) { fprintf(fp, " st->print(\" P=%%f C=%%f\",_prob,_fcnt);\n" ); } else if( inst.is_ideal_mem() ) { // Print out the field name if available to improve readability fprintf(fp, " if (ra->C->alias_type(adr_type())->field() != NULL) {\n"); fprintf(fp, " ciField* f = ra->C->alias_type(adr_type())->field();\n"); fprintf(fp, " st->print(\" %s Field: \");\n", commentSeperator); fprintf(fp, " if (f->is_volatile())\n"); fprintf(fp, " st->print(\"volatile \");\n"); fprintf(fp, " f->holder()->name()->print_symbol_on(st);\n"); fprintf(fp, " st->print(\".\");\n"); fprintf(fp, " f->name()->print_symbol_on(st);\n"); fprintf(fp, " if (f->is_constant())\n"); fprintf(fp, " st->print(\" (constant)\");\n"); fprintf(fp, " } else {\n"); // Make sure 'Volatile' gets printed out fprintf(fp, " if (ra->C->alias_type(adr_type())->is_volatile())\n"); fprintf(fp, " st->print(\" volatile!\");\n"); fprintf(fp, " }\n"); } // Complete the definition of the format function fprintf(fp, "}\n#endif\n"); } void ArchDesc::declare_pipe_classes(FILE *fp_hpp) { if (!_pipeline) return; fprintf(fp_hpp, "\n"); fprintf(fp_hpp, "// Pipeline_Use_Cycle_Mask Class\n"); fprintf(fp_hpp, "class Pipeline_Use_Cycle_Mask {\n"); if (_pipeline->_maxcycleused <= #ifdef SPARC 64 #else 32 #endif ) { fprintf(fp_hpp, "protected:\n"); fprintf(fp_hpp, " %s _mask;\n\n", _pipeline->_maxcycleused <= 32 ? "uint" : "uint64_t" ); fprintf(fp_hpp, "public:\n"); fprintf(fp_hpp, " Pipeline_Use_Cycle_Mask() : _mask(0) {}\n\n"); if (_pipeline->_maxcycleused <= 32) fprintf(fp_hpp, " Pipeline_Use_Cycle_Mask(uint mask) : _mask(mask) {}\n\n"); else { fprintf(fp_hpp, " Pipeline_Use_Cycle_Mask(uint mask1, uint mask2) : _mask((((uint64_t)mask1) << 32) | mask2) {}\n\n"); fprintf(fp_hpp, " Pipeline_Use_Cycle_Mask(uint64_t mask) : _mask(mask) {}\n\n"); } fprintf(fp_hpp, " Pipeline_Use_Cycle_Mask& operator=(const Pipeline_Use_Cycle_Mask &in) {\n"); fprintf(fp_hpp, " _mask = in._mask;\n"); fprintf(fp_hpp, " return *this;\n"); fprintf(fp_hpp, " }\n\n"); fprintf(fp_hpp, " bool overlaps(const Pipeline_Use_Cycle_Mask &in2) const {\n"); fprintf(fp_hpp, " return ((_mask & in2._mask) != 0);\n"); fprintf(fp_hpp, " }\n\n"); fprintf(fp_hpp, " Pipeline_Use_Cycle_Mask& operator<<=(int n) {\n"); fprintf(fp_hpp, " _mask <<= n;\n"); fprintf(fp_hpp, " return *this;\n"); fprintf(fp_hpp, " }\n\n"); fprintf(fp_hpp, " void Or(const Pipeline_Use_Cycle_Mask &in2) {\n"); fprintf(fp_hpp, " _mask |= in2._mask;\n"); fprintf(fp_hpp, " }\n\n"); fprintf(fp_hpp, " friend Pipeline_Use_Cycle_Mask operator&(const Pipeline_Use_Cycle_Mask &, const Pipeline_Use_Cycle_Mask &);\n"); fprintf(fp_hpp, " friend Pipeline_Use_Cycle_Mask operator|(const Pipeline_Use_Cycle_Mask &, const Pipeline_Use_Cycle_Mask &);\n\n"); } else { fprintf(fp_hpp, "protected:\n"); uint masklen = (_pipeline->_maxcycleused + 31) >> 5; uint l; fprintf(fp_hpp, " uint "); for (l = 1; l <= masklen; l++) fprintf(fp_hpp, "_mask%d%s", l, l < masklen ? ", " : ";\n\n"); fprintf(fp_hpp, "public:\n"); fprintf(fp_hpp, " Pipeline_Use_Cycle_Mask() : "); for (l = 1; l <= masklen; l++) fprintf(fp_hpp, "_mask%d(0)%s", l, l < masklen ? ", " : " {}\n\n"); fprintf(fp_hpp, " Pipeline_Use_Cycle_Mask("); for (l = 1; l <= masklen; l++) fprintf(fp_hpp, "uint mask%d%s", l, l < masklen ? ", " : ") : "); for (l = 1; l <= masklen; l++) fprintf(fp_hpp, "_mask%d(mask%d)%s", l, l, l < masklen ? ", " : " {}\n\n"); fprintf(fp_hpp, " Pipeline_Use_Cycle_Mask& operator=(const Pipeline_Use_Cycle_Mask &in) {\n"); for (l = 1; l <= masklen; l++) fprintf(fp_hpp, " _mask%d = in._mask%d;\n", l, l); fprintf(fp_hpp, " return *this;\n"); fprintf(fp_hpp, " }\n\n"); fprintf(fp_hpp, " Pipeline_Use_Cycle_Mask intersect(const Pipeline_Use_Cycle_Mask &in2) {\n"); fprintf(fp_hpp, " Pipeline_Use_Cycle_Mask out;\n"); for (l = 1; l <= masklen; l++) fprintf(fp_hpp, " out._mask%d = _mask%d & in2._mask%d;\n", l, l, l); fprintf(fp_hpp, " return out;\n"); fprintf(fp_hpp, " }\n\n"); fprintf(fp_hpp, " bool overlaps(const Pipeline_Use_Cycle_Mask &in2) const {\n"); fprintf(fp_hpp, " return ("); for (l = 1; l <= masklen; l++) fprintf(fp_hpp, "((_mask%d & in2._mask%d) != 0)%s", l, l, l < masklen ? " || " : ""); fprintf(fp_hpp, ") ? true : false;\n"); fprintf(fp_hpp, " }\n\n"); fprintf(fp_hpp, " Pipeline_Use_Cycle_Mask& operator<<=(int n) {\n"); fprintf(fp_hpp, " if (n >= 32)\n"); fprintf(fp_hpp, " do {\n "); for (l = masklen; l > 1; l--) fprintf(fp_hpp, " _mask%d = _mask%d;", l, l-1); fprintf(fp_hpp, " _mask%d = 0;\n", 1); fprintf(fp_hpp, " } while ((n -= 32) >= 32);\n\n"); fprintf(fp_hpp, " if (n > 0) {\n"); fprintf(fp_hpp, " uint m = 32 - n;\n"); fprintf(fp_hpp, " uint mask = (1 << n) - 1;\n"); fprintf(fp_hpp, " uint temp%d = mask & (_mask%d >> m); _mask%d <<= n;\n", 2, 1, 1); for (l = 2; l < masklen; l++) { fprintf(fp_hpp, " uint temp%d = mask & (_mask%d >> m); _mask%d <<= n; _mask%d |= temp%d;\n", l+1, l, l, l, l); } fprintf(fp_hpp, " _mask%d <<= n; _mask%d |= temp%d;\n", masklen, masklen, masklen); fprintf(fp_hpp, " }\n"); fprintf(fp_hpp, " return *this;\n"); fprintf(fp_hpp, " }\n\n"); fprintf(fp_hpp, " void Or(const Pipeline_Use_Cycle_Mask &);\n\n"); fprintf(fp_hpp, " friend Pipeline_Use_Cycle_Mask operator&(const Pipeline_Use_Cycle_Mask &, const Pipeline_Use_Cycle_Mask &);\n"); fprintf(fp_hpp, " friend Pipeline_Use_Cycle_Mask operator|(const Pipeline_Use_Cycle_Mask &, const Pipeline_Use_Cycle_Mask &);\n\n"); } fprintf(fp_hpp, " friend class Pipeline_Use;\n\n"); fprintf(fp_hpp, " friend class Pipeline_Use_Element;\n\n"); fprintf(fp_hpp, "};\n\n"); uint rescount = 0; const char *resource; for ( _pipeline->_reslist.reset(); (resource = _pipeline->_reslist.iter()) != NULL; ) { int mask = _pipeline->_resdict[resource]->is_resource()->mask(); if ((mask & (mask-1)) == 0) rescount++; } fprintf(fp_hpp, "// Pipeline_Use_Element Class\n"); fprintf(fp_hpp, "class Pipeline_Use_Element {\n"); fprintf(fp_hpp, "protected:\n"); fprintf(fp_hpp, " // Mask of used functional units\n"); fprintf(fp_hpp, " uint _used;\n\n"); fprintf(fp_hpp, " // Lower and upper bound of functional unit number range\n"); fprintf(fp_hpp, " uint _lb, _ub;\n\n"); fprintf(fp_hpp, " // Indicates multiple functionals units available\n"); fprintf(fp_hpp, " bool _multiple;\n\n"); fprintf(fp_hpp, " // Mask of specific used cycles\n"); fprintf(fp_hpp, " Pipeline_Use_Cycle_Mask _mask;\n\n"); fprintf(fp_hpp, "public:\n"); fprintf(fp_hpp, " Pipeline_Use_Element() {}\n\n"); fprintf(fp_hpp, " Pipeline_Use_Element(uint used, uint lb, uint ub, bool multiple, Pipeline_Use_Cycle_Mask mask)\n"); fprintf(fp_hpp, " : _used(used), _lb(lb), _ub(ub), _multiple(multiple), _mask(mask) {}\n\n"); fprintf(fp_hpp, " uint used() const { return _used; }\n\n"); fprintf(fp_hpp, " uint lowerBound() const { return _lb; }\n\n"); fprintf(fp_hpp, " uint upperBound() const { return _ub; }\n\n"); fprintf(fp_hpp, " bool multiple() const { return _multiple; }\n\n"); fprintf(fp_hpp, " Pipeline_Use_Cycle_Mask mask() const { return _mask; }\n\n"); fprintf(fp_hpp, " bool overlaps(const Pipeline_Use_Element &in2) const {\n"); fprintf(fp_hpp, " return ((_used & in2._used) != 0 && _mask.overlaps(in2._mask));\n"); fprintf(fp_hpp, " }\n\n"); fprintf(fp_hpp, " void step(uint cycles) {\n"); fprintf(fp_hpp, " _used = 0;\n"); fprintf(fp_hpp, " _mask <<= cycles;\n"); fprintf(fp_hpp, " }\n\n"); fprintf(fp_hpp, " friend class Pipeline_Use;\n"); fprintf(fp_hpp, "};\n\n"); fprintf(fp_hpp, "// Pipeline_Use Class\n"); fprintf(fp_hpp, "class Pipeline_Use {\n"); fprintf(fp_hpp, "protected:\n"); fprintf(fp_hpp, " // These resources can be used\n"); fprintf(fp_hpp, " uint _resources_used;\n\n"); fprintf(fp_hpp, " // These resources are used; excludes multiple choice functional units\n"); fprintf(fp_hpp, " uint _resources_used_exclusively;\n\n"); fprintf(fp_hpp, " // Number of elements\n"); fprintf(fp_hpp, " uint _count;\n\n"); fprintf(fp_hpp, " // This is the array of Pipeline_Use_Elements\n"); fprintf(fp_hpp, " Pipeline_Use_Element * _elements;\n\n"); fprintf(fp_hpp, "public:\n"); fprintf(fp_hpp, " Pipeline_Use(uint resources_used, uint resources_used_exclusively, uint count, Pipeline_Use_Element *elements)\n"); fprintf(fp_hpp, " : _resources_used(resources_used)\n"); fprintf(fp_hpp, " , _resources_used_exclusively(resources_used_exclusively)\n"); fprintf(fp_hpp, " , _count(count)\n"); fprintf(fp_hpp, " , _elements(elements)\n"); fprintf(fp_hpp, " {}\n\n"); fprintf(fp_hpp, " uint resourcesUsed() const { return _resources_used; }\n\n"); fprintf(fp_hpp, " uint resourcesUsedExclusively() const { return _resources_used_exclusively; }\n\n"); fprintf(fp_hpp, " uint count() const { return _count; }\n\n"); fprintf(fp_hpp, " Pipeline_Use_Element * element(uint i) const { return &_elements[i]; }\n\n"); fprintf(fp_hpp, " uint full_latency(uint delay, const Pipeline_Use &pred) const;\n\n"); fprintf(fp_hpp, " void add_usage(const Pipeline_Use &pred);\n\n"); fprintf(fp_hpp, " void reset() {\n"); fprintf(fp_hpp, " _resources_used = _resources_used_exclusively = 0;\n"); fprintf(fp_hpp, " };\n\n"); fprintf(fp_hpp, " void step(uint cycles) {\n"); fprintf(fp_hpp, " reset();\n"); fprintf(fp_hpp, " for (uint i = 0; i < %d; i++)\n", rescount); fprintf(fp_hpp, " (&_elements[i])->step(cycles);\n"); fprintf(fp_hpp, " };\n\n"); fprintf(fp_hpp, " static const Pipeline_Use elaborated_use;\n"); fprintf(fp_hpp, " static const Pipeline_Use_Element elaborated_elements[%d];\n\n", rescount); fprintf(fp_hpp, " friend class Pipeline;\n"); fprintf(fp_hpp, "};\n\n"); fprintf(fp_hpp, "// Pipeline Class\n"); fprintf(fp_hpp, "class Pipeline {\n"); fprintf(fp_hpp, "public:\n"); fprintf(fp_hpp, " static bool enabled() { return %s; }\n\n", _pipeline ? "true" : "false" ); assert( _pipeline->_maxInstrsPerBundle && ( _pipeline->_instrUnitSize || _pipeline->_bundleUnitSize) && _pipeline->_instrFetchUnitSize && _pipeline->_instrFetchUnits, "unspecified pipeline architecture units"); uint unitSize = _pipeline->_instrUnitSize ? _pipeline->_instrUnitSize : _pipeline->_bundleUnitSize; fprintf(fp_hpp, " enum {\n"); fprintf(fp_hpp, " _variable_size_instructions = %d,\n", _pipeline->_variableSizeInstrs ? 1 : 0); fprintf(fp_hpp, " _fixed_size_instructions = %d,\n", _pipeline->_variableSizeInstrs ? 0 : 1); fprintf(fp_hpp, " _branch_has_delay_slot = %d,\n", _pipeline->_branchHasDelaySlot ? 1 : 0); fprintf(fp_hpp, " _max_instrs_per_bundle = %d,\n", _pipeline->_maxInstrsPerBundle); fprintf(fp_hpp, " _max_bundles_per_cycle = %d,\n", _pipeline->_maxBundlesPerCycle); fprintf(fp_hpp, " _max_instrs_per_cycle = %d\n", _pipeline->_maxBundlesPerCycle * _pipeline->_maxInstrsPerBundle); fprintf(fp_hpp, " };\n\n"); fprintf(fp_hpp, " static bool instr_has_unit_size() { return %s; }\n\n", _pipeline->_instrUnitSize != 0 ? "true" : "false" ); if( _pipeline->_bundleUnitSize != 0 ) if( _pipeline->_instrUnitSize != 0 ) fprintf(fp_hpp, "// Individual Instructions may be bundled together by the hardware\n\n"); else fprintf(fp_hpp, "// Instructions exist only in bundles\n\n"); else fprintf(fp_hpp, "// Bundling is not supported\n\n"); if( _pipeline->_instrUnitSize != 0 ) fprintf(fp_hpp, " // Size of an instruction\n"); else fprintf(fp_hpp, " // Size of an individual instruction does not exist - unsupported\n"); fprintf(fp_hpp, " static uint instr_unit_size() {"); if( _pipeline->_instrUnitSize == 0 ) fprintf(fp_hpp, " assert( false, \"Instructions are only in bundles\" );"); fprintf(fp_hpp, " return %d; };\n\n", _pipeline->_instrUnitSize); if( _pipeline->_bundleUnitSize != 0 ) fprintf(fp_hpp, " // Size of a bundle\n"); else fprintf(fp_hpp, " // Bundles do not exist - unsupported\n"); fprintf(fp_hpp, " static uint bundle_unit_size() {"); if( _pipeline->_bundleUnitSize == 0 ) fprintf(fp_hpp, " assert( false, \"Bundles are not supported\" );"); fprintf(fp_hpp, " return %d; };\n\n", _pipeline->_bundleUnitSize); fprintf(fp_hpp, " static bool requires_bundling() { return %s; }\n\n", _pipeline->_bundleUnitSize != 0 && _pipeline->_instrUnitSize == 0 ? "true" : "false" ); fprintf(fp_hpp, "private:\n"); fprintf(fp_hpp, " Pipeline(); // Not a legal constructor\n"); fprintf(fp_hpp, "\n"); fprintf(fp_hpp, " const unsigned char _read_stage_count;\n"); fprintf(fp_hpp, " const unsigned char _write_stage;\n"); fprintf(fp_hpp, " const unsigned char _fixed_latency;\n"); fprintf(fp_hpp, " const unsigned char _instruction_count;\n"); fprintf(fp_hpp, " const bool _has_fixed_latency;\n"); fprintf(fp_hpp, " const bool _has_branch_delay;\n"); fprintf(fp_hpp, " const bool _has_multiple_bundles;\n"); fprintf(fp_hpp, " const bool _force_serialization;\n"); fprintf(fp_hpp, " const bool _may_have_no_code;\n"); fprintf(fp_hpp, " const enum machPipelineStages * const _read_stages;\n"); fprintf(fp_hpp, " const enum machPipelineStages * const _resource_stage;\n"); fprintf(fp_hpp, " const uint * const _resource_cycles;\n"); fprintf(fp_hpp, " const Pipeline_Use _resource_use;\n"); fprintf(fp_hpp, "\n"); fprintf(fp_hpp, "public:\n"); fprintf(fp_hpp, " Pipeline(uint write_stage,\n"); fprintf(fp_hpp, " uint count,\n"); fprintf(fp_hpp, " bool has_fixed_latency,\n"); fprintf(fp_hpp, " uint fixed_latency,\n"); fprintf(fp_hpp, " uint instruction_count,\n"); fprintf(fp_hpp, " bool has_branch_delay,\n"); fprintf(fp_hpp, " bool has_multiple_bundles,\n"); fprintf(fp_hpp, " bool force_serialization,\n"); fprintf(fp_hpp, " bool may_have_no_code,\n"); fprintf(fp_hpp, " enum machPipelineStages * const dst,\n"); fprintf(fp_hpp, " enum machPipelineStages * const stage,\n"); fprintf(fp_hpp, " uint * const cycles,\n"); fprintf(fp_hpp, " Pipeline_Use resource_use)\n"); fprintf(fp_hpp, " : _write_stage(write_stage)\n"); fprintf(fp_hpp, " , _read_stage_count(count)\n"); fprintf(fp_hpp, " , _has_fixed_latency(has_fixed_latency)\n"); fprintf(fp_hpp, " , _fixed_latency(fixed_latency)\n"); fprintf(fp_hpp, " , _read_stages(dst)\n"); fprintf(fp_hpp, " , _resource_stage(stage)\n"); fprintf(fp_hpp, " , _resource_cycles(cycles)\n"); fprintf(fp_hpp, " , _resource_use(resource_use)\n"); fprintf(fp_hpp, " , _instruction_count(instruction_count)\n"); fprintf(fp_hpp, " , _has_branch_delay(has_branch_delay)\n"); fprintf(fp_hpp, " , _has_multiple_bundles(has_multiple_bundles)\n"); fprintf(fp_hpp, " , _force_serialization(force_serialization)\n"); fprintf(fp_hpp, " , _may_have_no_code(may_have_no_code)\n"); fprintf(fp_hpp, " {};\n"); fprintf(fp_hpp, "\n"); fprintf(fp_hpp, " uint writeStage() const {\n"); fprintf(fp_hpp, " return (_write_stage);\n"); fprintf(fp_hpp, " }\n"); fprintf(fp_hpp, "\n"); fprintf(fp_hpp, " enum machPipelineStages readStage(int ndx) const {\n"); fprintf(fp_hpp, " return (ndx < _read_stage_count ? _read_stages[ndx] : stage_undefined);"); fprintf(fp_hpp, " }\n\n"); fprintf(fp_hpp, " uint resourcesUsed() const {\n"); fprintf(fp_hpp, " return _resource_use.resourcesUsed();\n }\n\n"); fprintf(fp_hpp, " uint resourcesUsedExclusively() const {\n"); fprintf(fp_hpp, " return _resource_use.resourcesUsedExclusively();\n }\n\n"); fprintf(fp_hpp, " bool hasFixedLatency() const {\n"); fprintf(fp_hpp, " return (_has_fixed_latency);\n }\n\n"); fprintf(fp_hpp, " uint fixedLatency() const {\n"); fprintf(fp_hpp, " return (_fixed_latency);\n }\n\n"); fprintf(fp_hpp, " uint functional_unit_latency(uint start, const Pipeline *pred) const;\n\n"); fprintf(fp_hpp, " uint operand_latency(uint opnd, const Pipeline *pred) const;\n\n"); fprintf(fp_hpp, " const Pipeline_Use& resourceUse() const {\n"); fprintf(fp_hpp, " return (_resource_use); }\n\n"); fprintf(fp_hpp, " const Pipeline_Use_Element * resourceUseElement(uint i) const {\n"); fprintf(fp_hpp, " return (&_resource_use._elements[i]); }\n\n"); fprintf(fp_hpp, " uint resourceUseCount() const {\n"); fprintf(fp_hpp, " return (_resource_use._count); }\n\n"); fprintf(fp_hpp, " uint instructionCount() const {\n"); fprintf(fp_hpp, " return (_instruction_count); }\n\n"); fprintf(fp_hpp, " bool hasBranchDelay() const {\n"); fprintf(fp_hpp, " return (_has_branch_delay); }\n\n"); fprintf(fp_hpp, " bool hasMultipleBundles() const {\n"); fprintf(fp_hpp, " return (_has_multiple_bundles); }\n\n"); fprintf(fp_hpp, " bool forceSerialization() const {\n"); fprintf(fp_hpp, " return (_force_serialization); }\n\n"); fprintf(fp_hpp, " bool mayHaveNoCode() const {\n"); fprintf(fp_hpp, " return (_may_have_no_code); }\n\n"); fprintf(fp_hpp, "//const Pipeline_Use_Cycle_Mask& resourceUseMask(int resource) const {\n"); fprintf(fp_hpp, "// return (_resource_use_masks[resource]); }\n\n"); fprintf(fp_hpp, "\n#ifndef PRODUCT\n"); fprintf(fp_hpp, " static const char * stageName(uint i);\n"); fprintf(fp_hpp, "#endif\n"); fprintf(fp_hpp, "};\n\n"); fprintf(fp_hpp, "// Bundle class\n"); fprintf(fp_hpp, "class Bundle {\n"); uint mshift = 0; for (uint msize = _pipeline->_maxInstrsPerBundle * _pipeline->_maxBundlesPerCycle; msize != 0; msize >>= 1) mshift++; uint rshift = rescount; fprintf(fp_hpp, "protected:\n"); fprintf(fp_hpp, " enum {\n"); fprintf(fp_hpp, " _unused_delay = 0x%x,\n", 0); fprintf(fp_hpp, " _use_nop_delay = 0x%x,\n", 1); fprintf(fp_hpp, " _use_unconditional_delay = 0x%x,\n", 2); fprintf(fp_hpp, " _use_conditional_delay = 0x%x,\n", 3); fprintf(fp_hpp, " _used_in_conditional_delay = 0x%x,\n", 4); fprintf(fp_hpp, " _used_in_unconditional_delay = 0x%x,\n", 5); fprintf(fp_hpp, " _used_in_all_conditional_delays = 0x%x,\n", 6); fprintf(fp_hpp, "\n"); fprintf(fp_hpp, " _use_delay = 0x%x,\n", 3); fprintf(fp_hpp, " _used_in_delay = 0x%x\n", 4); fprintf(fp_hpp, " };\n\n"); fprintf(fp_hpp, " uint _flags : 3,\n"); fprintf(fp_hpp, " _starts_bundle : 1,\n"); fprintf(fp_hpp, " _instr_count : %d,\n", mshift); fprintf(fp_hpp, " _resources_used : %d;\n", rshift); fprintf(fp_hpp, "public:\n"); fprintf(fp_hpp, " Bundle() : _flags(_unused_delay), _starts_bundle(0), _instr_count(0), _resources_used(0) {}\n\n"); fprintf(fp_hpp, " void set_instr_count(uint i) { _instr_count = i; }\n"); fprintf(fp_hpp, " void set_resources_used(uint i) { _resources_used = i; }\n"); fprintf(fp_hpp, " void clear_usage() { _flags = _unused_delay; }\n"); fprintf(fp_hpp, " void set_starts_bundle() { _starts_bundle = true; }\n"); fprintf(fp_hpp, " uint flags() const { return (_flags); }\n"); fprintf(fp_hpp, " uint instr_count() const { return (_instr_count); }\n"); fprintf(fp_hpp, " uint resources_used() const { return (_resources_used); }\n"); fprintf(fp_hpp, " bool starts_bundle() const { return (_starts_bundle != 0); }\n"); fprintf(fp_hpp, " void set_use_nop_delay() { _flags = _use_nop_delay; }\n"); fprintf(fp_hpp, " void set_use_unconditional_delay() { _flags = _use_unconditional_delay; }\n"); fprintf(fp_hpp, " void set_use_conditional_delay() { _flags = _use_conditional_delay; }\n"); fprintf(fp_hpp, " void set_used_in_unconditional_delay() { _flags = _used_in_unconditional_delay; }\n"); fprintf(fp_hpp, " void set_used_in_conditional_delay() { _flags = _used_in_conditional_delay; }\n"); fprintf(fp_hpp, " void set_used_in_all_conditional_delays() { _flags = _used_in_all_conditional_delays; }\n"); fprintf(fp_hpp, " bool use_nop_delay() { return (_flags == _use_nop_delay); }\n"); fprintf(fp_hpp, " bool use_unconditional_delay() { return (_flags == _use_unconditional_delay); }\n"); fprintf(fp_hpp, " bool use_conditional_delay() { return (_flags == _use_conditional_delay); }\n"); fprintf(fp_hpp, " bool used_in_unconditional_delay() { return (_flags == _used_in_unconditional_delay); }\n"); fprintf(fp_hpp, " bool used_in_conditional_delay() { return (_flags == _used_in_conditional_delay); }\n"); fprintf(fp_hpp, " bool used_in_all_conditional_delays() { return (_flags == _used_in_all_conditional_delays); }\n"); fprintf(fp_hpp, " bool use_delay() { return ((_flags & _use_delay) != 0); }\n"); fprintf(fp_hpp, " bool used_in_delay() { return ((_flags & _used_in_delay) != 0); }\n\n"); fprintf(fp_hpp, " enum {\n"); fprintf(fp_hpp, " _nop_count = %d\n", _pipeline->_nopcnt); fprintf(fp_hpp, " };\n\n"); fprintf(fp_hpp, " static void initialize_nops(MachNode *nop_list[%d], Compile* C);\n\n", _pipeline->_nopcnt); fprintf(fp_hpp, "#ifndef PRODUCT\n"); fprintf(fp_hpp, " void dump(outputStream *st = tty) const;\n"); fprintf(fp_hpp, "#endif\n"); fprintf(fp_hpp, "};\n\n"); // const char *classname; // for (_pipeline->_classlist.reset(); (classname = _pipeline->_classlist.iter()) != NULL; ) { // PipeClassForm *pipeclass = _pipeline->_classdict[classname]->is_pipeclass(); // fprintf(fp_hpp, "// Pipeline Class Instance for \"%s\"\n", classname); // } } //------------------------------declareClasses--------------------------------- // Construct the class hierarchy of MachNode classes from the instruction & // operand lists void ArchDesc::declareClasses(FILE *fp) { // Declare an array containing the machine register names, strings. declareRegNames(fp, _register); // Declare an array containing the machine register encoding values declareRegEncodes(fp, _register); // Generate declarations for the total number of operands fprintf(fp,"\n"); fprintf(fp,"// Total number of operands defined in architecture definition\n"); int num_operands = 0; OperandForm *op; for (_operands.reset(); (op = (OperandForm*)_operands.iter()) != NULL; ) { // Ensure this is a machine-world instruction if (op->ideal_only()) continue; ++num_operands; } int first_operand_class = num_operands; OpClassForm *opc; for (_opclass.reset(); (opc = (OpClassForm*)_opclass.iter()) != NULL; ) { // Ensure this is a machine-world instruction if (opc->ideal_only()) continue; ++num_operands; } fprintf(fp,"#define FIRST_OPERAND_CLASS %d\n", first_operand_class); fprintf(fp,"#define NUM_OPERANDS %d\n", num_operands); fprintf(fp,"\n"); // Generate declarations for the total number of instructions fprintf(fp,"// Total number of instructions defined in architecture definition\n"); fprintf(fp,"#define NUM_INSTRUCTIONS %d\n",instructFormCount()); // Generate Machine Classes for each operand defined in AD file fprintf(fp,"\n"); fprintf(fp,"//----------------------------Declare classes derived from MachOper----------\n"); // Iterate through all operands _operands.reset(); OperandForm *oper; for( ; (oper = (OperandForm*)_operands.iter()) != NULL;) { // Ensure this is a machine-world instruction if (oper->ideal_only() ) continue; // The declaration of labelOper is in machine-independent file: machnode if ( strcmp(oper->_ident,"label") == 0 ) continue; // The declaration of methodOper is in machine-independent file: machnode if ( strcmp(oper->_ident,"method") == 0 ) continue; // Build class definition for this operand fprintf(fp,"\n"); fprintf(fp,"class %sOper : public MachOper { \n",oper->_ident); fprintf(fp,"private:\n"); // Operand definitions that depend upon number of input edges { uint num_edges = oper->num_edges(_globalNames); if( num_edges != 1 ) { // Use MachOper::num_edges() {return 1;} fprintf(fp," virtual uint num_edges() const { return %d; }\n", num_edges ); } if( num_edges > 0 ) { in_RegMask(fp); } } // Support storing constants inside the MachOper declareConstStorage(fp,_globalNames,oper); // Support storage of the condition codes if( oper->is_ideal_bool() ) { fprintf(fp," virtual int ccode() const { \n"); fprintf(fp," switch (_c0) {\n"); fprintf(fp," case BoolTest::eq : return equal();\n"); fprintf(fp," case BoolTest::gt : return greater();\n"); fprintf(fp," case BoolTest::lt : return less();\n"); fprintf(fp," case BoolTest::ne : return not_equal();\n"); fprintf(fp," case BoolTest::le : return less_equal();\n"); fprintf(fp," case BoolTest::ge : return greater_equal();\n"); fprintf(fp," default : ShouldNotReachHere(); return 0;\n"); fprintf(fp," }\n"); fprintf(fp," };\n"); } // Support storage of the condition codes if( oper->is_ideal_bool() ) { fprintf(fp," virtual void negate() { \n"); fprintf(fp," _c0 = (BoolTest::mask)((int)_c0^0x4); \n"); fprintf(fp," };\n"); } // Declare constructor. // Parameters start with condition code, then all other constants // // (1) MachXOper(int32 ccode, int32 c0, int32 c1, ..., int32 cn) // (2) : _ccode(ccode), _c0(c0), _c1(c1), ..., _cn(cn) { } // Form::DataType constant_type = oper->simple_type(_globalNames); defineConstructor(fp, oper->_ident, oper->num_consts(_globalNames), oper->_components, oper->is_ideal_bool(), constant_type, _globalNames); // Clone function fprintf(fp," virtual MachOper *clone(Compile* C) const;\n"); // Support setting a spill offset into a constant operand. // We only support setting an 'int' offset, while in the // LP64 build spill offsets are added with an AddP which // requires a long constant. Thus we don't support spilling // in frames larger than 4Gig. if( oper->has_conI(_globalNames) || oper->has_conL(_globalNames) ) fprintf(fp, " virtual void set_con( jint c0 ) { _c0 = c0; }\n"); // virtual functions for encoding and format // fprintf(fp," virtual void encode() const {\n %s }\n", // (oper->_encrule)?(oper->_encrule->_encrule):""); // Check the interface type, and generate the correct query functions // encoding queries based upon MEMORY_INTER, REG_INTER, CONST_INTER. fprintf(fp," virtual uint opcode() const { return %s; }\n", machOperEnum(oper->_ident)); // virtual function to look up ideal return type of machine instruction // // (1) virtual const Type *type() const { return .....; } // if ((oper->_matrule) && (oper->_matrule->_lChild == NULL) && (oper->_matrule->_rChild == NULL)) { unsigned int position = 0; const char *opret, *opname, *optype; oper->_matrule->base_operand(position,_globalNames,opret,opname,optype); fprintf(fp," virtual const Type *type() const {"); const char *type = getIdealType(optype); if( type != NULL ) { Form::DataType data_type = oper->is_base_constant(_globalNames); // Check if we are an ideal pointer type if( data_type == Form::idealP || data_type == Form::idealN ) { // Return the ideal type we already have: <TypePtr *> fprintf(fp," return _c0;"); } else { // Return the appropriate bottom type fprintf(fp," return %s;", getIdealType(optype)); } } else { fprintf(fp," ShouldNotCallThis(); return Type::BOTTOM;"); } fprintf(fp," }\n"); } else { // Check for user-defined stack slots, based upon sRegX Form::DataType data_type = oper->is_user_name_for_sReg(); if( data_type != Form::none ){ const char *type = NULL; switch( data_type ) { case Form::idealI: type = "TypeInt::INT"; break; case Form::idealP: type = "TypePtr::BOTTOM";break; case Form::idealF: type = "Type::FLOAT"; break; case Form::idealD: type = "Type::DOUBLE"; break; case Form::idealL: type = "TypeLong::LONG"; break; case Form::none: // fall through default: assert( false, "No support for this type of stackSlot"); } fprintf(fp," virtual const Type *type() const { return %s; } // stackSlotX\n", type); } } // // virtual functions for defining the encoding interface. // // Access the linearized ideal register mask, // map to physical register encoding if ( oper->_matrule && oper->_matrule->is_base_register(_globalNames) ) { // Just use the default virtual 'reg' call } else if ( oper->ideal_to_sReg_type(oper->_ident) != Form::none ) { // Special handling for operand 'sReg', a Stack Slot Register. // Map linearized ideal register mask to stack slot number fprintf(fp," virtual int reg(PhaseRegAlloc *ra_, const Node *node) const {\n"); fprintf(fp," return (int)OptoReg::reg2stack(ra_->get_reg_first(node));/* sReg */\n"); fprintf(fp," }\n"); fprintf(fp," virtual int reg(PhaseRegAlloc *ra_, const Node *node, int idx) const {\n"); fprintf(fp," return (int)OptoReg::reg2stack(ra_->get_reg_first(node->in(idx)));/* sReg */\n"); fprintf(fp," }\n"); } // Output the operand specific access functions used by an enc_class // These are only defined when we want to override the default virtual func if (oper->_interface != NULL) { fprintf(fp,"\n"); // Check if it is a Memory Interface if ( oper->_interface->is_MemInterface() != NULL ) { MemInterface *mem_interface = oper->_interface->is_MemInterface(); const char *base = mem_interface->_base; if( base != NULL ) { define_oper_interface(fp, *oper, _globalNames, "base", base); } char *index = mem_interface->_index; if( index != NULL ) { define_oper_interface(fp, *oper, _globalNames, "index", index); } const char *scale = mem_interface->_scale; if( scale != NULL ) { define_oper_interface(fp, *oper, _globalNames, "scale", scale); } const char *disp = mem_interface->_disp; if( disp != NULL ) { define_oper_interface(fp, *oper, _globalNames, "disp", disp); oper->disp_is_oop(fp, _globalNames); } if( oper->stack_slots_only(_globalNames) ) { // should not call this: fprintf(fp," virtual int constant_disp() const { return Type::OffsetBot; }"); } else if ( disp != NULL ) { define_oper_interface(fp, *oper, _globalNames, "constant_disp", disp); } } // end Memory Interface // Check if it is a Conditional Interface else if (oper->_interface->is_CondInterface() != NULL) { CondInterface *cInterface = oper->_interface->is_CondInterface(); const char *equal = cInterface->_equal; if( equal != NULL ) { define_oper_interface(fp, *oper, _globalNames, "equal", equal); } const char *not_equal = cInterface->_not_equal; if( not_equal != NULL ) { define_oper_interface(fp, *oper, _globalNames, "not_equal", not_equal); } const char *less = cInterface->_less; if( less != NULL ) { define_oper_interface(fp, *oper, _globalNames, "less", less); } const char *greater_equal = cInterface->_greater_equal; if( greater_equal != NULL ) { define_oper_interface(fp, *oper, _globalNames, "greater_equal", greater_equal); } const char *less_equal = cInterface->_less_equal; if( less_equal != NULL ) { define_oper_interface(fp, *oper, _globalNames, "less_equal", less_equal); } const char *greater = cInterface->_greater; if( greater != NULL ) { define_oper_interface(fp, *oper, _globalNames, "greater", greater); } } // end Conditional Interface // Check if it is a Constant Interface else if (oper->_interface->is_ConstInterface() != NULL ) { assert( oper->num_consts(_globalNames) == 1, "Must have one constant when using CONST_INTER encoding"); if (!strcmp(oper->ideal_type(_globalNames), "ConI")) { // Access the locally stored constant fprintf(fp," virtual intptr_t constant() const {"); fprintf(fp, " return (intptr_t)_c0;"); fprintf(fp," }\n"); } else if (!strcmp(oper->ideal_type(_globalNames), "ConP")) { // Access the locally stored constant fprintf(fp," virtual intptr_t constant() const {"); fprintf(fp, " return _c0->get_con();"); fprintf(fp, " }\n"); // Generate query to determine if this pointer is an oop fprintf(fp," virtual bool constant_is_oop() const {"); fprintf(fp, " return _c0->isa_oop_ptr();"); fprintf(fp, " }\n"); } else if (!strcmp(oper->ideal_type(_globalNames), "ConN")) { // Access the locally stored constant fprintf(fp," virtual intptr_t constant() const {"); fprintf(fp, " return _c0->get_ptrtype()->get_con();"); fprintf(fp, " }\n"); // Generate query to determine if this pointer is an oop fprintf(fp," virtual bool constant_is_oop() const {"); fprintf(fp, " return _c0->get_ptrtype()->isa_oop_ptr();"); fprintf(fp, " }\n"); } else if (!strcmp(oper->ideal_type(_globalNames), "ConL")) { fprintf(fp," virtual intptr_t constant() const {"); // We don't support addressing modes with > 4Gig offsets. // Truncate to int. fprintf(fp, " return (intptr_t)_c0;"); fprintf(fp, " }\n"); fprintf(fp," virtual jlong constantL() const {"); fprintf(fp, " return _c0;"); fprintf(fp, " }\n"); } else if (!strcmp(oper->ideal_type(_globalNames), "ConF")) { fprintf(fp," virtual intptr_t constant() const {"); fprintf(fp, " ShouldNotReachHere(); return 0; "); fprintf(fp, " }\n"); fprintf(fp," virtual jfloat constantF() const {"); fprintf(fp, " return (jfloat)_c0;"); fprintf(fp, " }\n"); } else if (!strcmp(oper->ideal_type(_globalNames), "ConD")) { fprintf(fp," virtual intptr_t constant() const {"); fprintf(fp, " ShouldNotReachHere(); return 0; "); fprintf(fp, " }\n"); fprintf(fp," virtual jdouble constantD() const {"); fprintf(fp, " return _c0;"); fprintf(fp, " }\n"); } } else if (oper->_interface->is_RegInterface() != NULL) { // make sure that a fixed format string isn't used for an // operand which might be assiged to multiple registers. // Otherwise the opto assembly output could be misleading. if (oper->_format->_strings.count() != 0 && !oper->is_bound_register()) { syntax_err(oper->_linenum, "Only bound registers can have fixed formats: %s\n", oper->_ident); } } else { assert( false, "ShouldNotReachHere();"); } } fprintf(fp,"\n"); // // Currently all XXXOper::hash() methods are identical (990820) // declare_hash(fp); // // Currently all XXXOper::Cmp() methods are identical (990820) // declare_cmp(fp); // Do not place dump_spec() and Name() into PRODUCT code // int_format and ext_format are not needed in PRODUCT code either fprintf(fp, "#ifndef PRODUCT\n"); // Declare int_format() and ext_format() gen_oper_format(fp, _globalNames, *oper); // Machine independent print functionality for debugging // IF we have constants, create a dump_spec function for the derived class // // (1) virtual void dump_spec() const { // (2) st->print("#%d", _c#); // Constant != ConP // OR _c#->dump_on(st); // Type ConP // ... // (3) } uint num_consts = oper->num_consts(_globalNames); if( num_consts > 0 ) { // line (1) fprintf(fp, " virtual void dump_spec(outputStream *st) const {\n"); // generate format string for st->print // Iterate over the component list & spit out the right thing uint i = 0; const char *type = oper->ideal_type(_globalNames); Component *comp; oper->_components.reset(); if ((comp = oper->_components.iter()) == NULL) { assert(num_consts == 1, "Bad component list detected.\n"); i = dump_spec_constant( fp, type, i, oper ); // Check that type actually matched assert( i != 0, "Non-constant operand lacks component list."); } // end if NULL else { // line (2) // dump all components oper->_components.reset(); while((comp = oper->_components.iter()) != NULL) { type = comp->base_type(_globalNames); i = dump_spec_constant( fp, type, i, NULL ); } } // finish line (3) fprintf(fp," }\n"); } fprintf(fp," virtual const char *Name() const { return \"%s\";}\n", oper->_ident); fprintf(fp,"#endif\n"); // Close definition of this XxxMachOper fprintf(fp,"};\n"); } // Generate Machine Classes for each instruction defined in AD file fprintf(fp,"\n"); fprintf(fp,"//----------------------------Declare classes for Pipelines-----------------\n"); declare_pipe_classes(fp); // Generate Machine Classes for each instruction defined in AD file fprintf(fp,"\n"); fprintf(fp,"//----------------------------Declare classes derived from MachNode----------\n"); _instructions.reset(); InstructForm *instr; for( ; (instr = (InstructForm*)_instructions.iter()) != NULL; ) { // Ensure this is a machine-world instruction if ( instr->ideal_only() ) continue; // Build class definition for this instruction fprintf(fp,"\n"); fprintf(fp,"class %sNode : public %s { \n", instr->_ident, instr->mach_base_class(_globalNames) ); fprintf(fp,"private:\n"); fprintf(fp," MachOper *_opnd_array[%d];\n", instr->num_opnds() ); if ( instr->is_ideal_jump() ) { fprintf(fp, " GrowableArray<Label*> _index2label;\n"); } fprintf(fp,"public:\n"); fprintf(fp," MachOper *opnd_array(uint operand_index) const {\n"); fprintf(fp," assert(operand_index < _num_opnds, \"invalid _opnd_array index\");\n"); fprintf(fp," return _opnd_array[operand_index];\n"); fprintf(fp," }\n"); fprintf(fp," void set_opnd_array(uint operand_index, MachOper *operand) {\n"); fprintf(fp," assert(operand_index < _num_opnds, \"invalid _opnd_array index\");\n"); fprintf(fp," _opnd_array[operand_index] = operand;\n"); fprintf(fp," }\n"); fprintf(fp,"private:\n"); if ( instr->is_ideal_jump() ) { fprintf(fp," virtual void add_case_label(int index_num, Label* blockLabel) {\n"); fprintf(fp," _index2label.at_put_grow(index_num, blockLabel);\n"); fprintf(fp," }\n"); } if( can_cisc_spill() && (instr->cisc_spill_alternate() != NULL) ) { fprintf(fp," const RegMask *_cisc_RegMask;\n"); } out_RegMask(fp); // output register mask fprintf(fp," virtual uint rule() const { return %s_rule; }\n", instr->_ident); // If this instruction contains a labelOper // Declare Node::methods that set operand Label's contents int label_position = instr->label_position(); if( label_position != -1 ) { // Set/Save the label, stored in labelOper::_branch_label fprintf(fp," virtual void label_set( Label* label, uint block_num );\n"); fprintf(fp," virtual void save_label( Label** label, uint* block_num );\n"); } // If this instruction contains a methodOper // Declare Node::methods that set operand method's contents int method_position = instr->method_position(); if( method_position != -1 ) { // Set the address method, stored in methodOper::_method fprintf(fp," virtual void method_set( intptr_t method );\n"); } // virtual functions for attributes // // Each instruction attribute results in a virtual call of same name. // The ins_cost is not handled here. Attribute *attr = instr->_attribs; bool avoid_back_to_back = false; while (attr != NULL) { if (strcmp(attr->_ident,"ins_cost") && strcmp(attr->_ident,"ins_short_branch")) { fprintf(fp," int %s() const { return %s; }\n", attr->_ident, attr->_val); } // Check value for ins_avoid_back_to_back, and if it is true (1), set the flag if (!strcmp(attr->_ident,"ins_avoid_back_to_back") && attr->int_val(*this) != 0) avoid_back_to_back = true; attr = (Attribute *)attr->_next; } // virtual functions for encode and format // Virtual function for evaluating the constant. if (instr->is_mach_constant()) { fprintf(fp," virtual void eval_constant(Compile* C);\n"); } // Output the opcode function and the encode function here using the // encoding class information in the _insencode slot. if ( instr->_insencode ) { fprintf(fp," virtual void emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const;\n"); } // virtual function for getting the size of an instruction if ( instr->_size ) { fprintf(fp," virtual uint size(PhaseRegAlloc *ra_) const;\n"); } // Return the top-level ideal opcode. // Use MachNode::ideal_Opcode() for nodes based on MachNode class // if the ideal_Opcode == Op_Node. if ( strcmp("Node", instr->ideal_Opcode(_globalNames)) != 0 || strcmp("MachNode", instr->mach_base_class(_globalNames)) != 0 ) { fprintf(fp," virtual int ideal_Opcode() const { return Op_%s; }\n", instr->ideal_Opcode(_globalNames) ); } // Allow machine-independent optimization, invert the sense of the IF test if( instr->is_ideal_if() ) { fprintf(fp," virtual void negate() { \n"); // Identify which operand contains the negate(able) ideal condition code int idx = 0; instr->_components.reset(); for( Component *comp; (comp = instr->_components.iter()) != NULL; ) { // Check that component is an operand Form *form = (Form*)_globalNames[comp->_type]; OperandForm *opForm = form ? form->is_operand() : NULL; if( opForm == NULL ) continue; // Lookup the position of the operand in the instruction. if( opForm->is_ideal_bool() ) { idx = instr->operand_position(comp->_name, comp->_usedef); assert( idx != NameList::Not_in_list, "Did not find component in list that contained it."); break; } } fprintf(fp," opnd_array(%d)->negate();\n", idx); fprintf(fp," _prob = 1.0f - _prob;\n"); fprintf(fp," };\n"); } // Identify which input register matches the input register. uint matching_input = instr->two_address(_globalNames); // Generate the method if it returns != 0 otherwise use MachNode::two_adr() if( matching_input != 0 ) { fprintf(fp," virtual uint two_adr() const "); fprintf(fp,"{ return oper_input_base()"); for( uint i = 2; i <= matching_input; i++ ) fprintf(fp," + opnd_array(%d)->num_edges()",i-1); fprintf(fp,"; }\n"); } // Declare cisc_version, if applicable // MachNode *cisc_version( int offset /* ,... */ ); instr->declare_cisc_version(*this, fp); // If there is an explicit peephole rule, build it if ( instr->peepholes() != NULL ) { fprintf(fp," virtual MachNode *peephole(Block *block, int block_index, PhaseRegAlloc *ra_, int &deleted, Compile *C);\n"); } // Output the declaration for number of relocation entries if ( instr->reloc(_globalNames) != 0 ) { fprintf(fp," virtual int reloc() const;\n"); } if (instr->alignment() != 1) { fprintf(fp," virtual int alignment_required() const { return %d; }\n", instr->alignment()); fprintf(fp," virtual int compute_padding(int current_offset) const;\n"); } // Starting point for inputs matcher wants. // Use MachNode::oper_input_base() for nodes based on MachNode class // if the base == 1. if ( instr->oper_input_base(_globalNames) != 1 || strcmp("MachNode", instr->mach_base_class(_globalNames)) != 0 ) { fprintf(fp," virtual uint oper_input_base() const { return %d; }\n", instr->oper_input_base(_globalNames)); } // Make the constructor and following methods 'public:' fprintf(fp,"public:\n"); // Constructor if ( instr->is_ideal_jump() ) { fprintf(fp," %sNode() : _index2label(MinJumpTableSize*2) { ", instr->_ident); } else { fprintf(fp," %sNode() { ", instr->_ident); if( can_cisc_spill() && (instr->cisc_spill_alternate() != NULL) ) { fprintf(fp,"_cisc_RegMask = NULL; "); } } fprintf(fp," _num_opnds = %d; _opnds = _opnd_array; ", instr->num_opnds()); bool node_flags_set = false; // flag: if this instruction matches an ideal 'Copy*' node if ( instr->is_ideal_copy() != 0 ) { fprintf(fp,"init_flags(Flag_is_Copy"); node_flags_set = true; } // Is an instruction is a constant? If so, get its type Form::DataType data_type; const char *opType = NULL; const char *result = NULL; data_type = instr->is_chain_of_constant(_globalNames, opType, result); // Check if this instruction is a constant if ( data_type != Form::none ) { if ( node_flags_set ) { fprintf(fp," | Flag_is_Con"); } else { fprintf(fp,"init_flags(Flag_is_Con"); node_flags_set = true; } } // flag: if this instruction is cisc alternate if ( can_cisc_spill() && instr->is_cisc_alternate() ) { if ( node_flags_set ) { fprintf(fp," | Flag_is_cisc_alternate"); } else { fprintf(fp,"init_flags(Flag_is_cisc_alternate"); node_flags_set = true; } } // flag: if this instruction has short branch form if ( instr->has_short_branch_form() ) { if ( node_flags_set ) { fprintf(fp," | Flag_may_be_short_branch"); } else { fprintf(fp,"init_flags(Flag_may_be_short_branch"); node_flags_set = true; } } // flag: if this instruction should not be generated back to back. if ( avoid_back_to_back ) { if ( node_flags_set ) { fprintf(fp," | Flag_avoid_back_to_back"); } else { fprintf(fp,"init_flags(Flag_avoid_back_to_back"); node_flags_set = true; } } // Check if machine instructions that USE memory, but do not DEF memory, // depend upon a node that defines memory in machine-independent graph. if ( instr->needs_anti_dependence_check(_globalNames) ) { if ( node_flags_set ) { fprintf(fp," | Flag_needs_anti_dependence_check"); } else { fprintf(fp,"init_flags(Flag_needs_anti_dependence_check"); node_flags_set = true; } } // flag: if this instruction is implemented with a call if ( instr->_has_call ) { if ( node_flags_set ) { fprintf(fp," | Flag_has_call"); } else { fprintf(fp,"init_flags(Flag_has_call"); node_flags_set = true; } } if ( node_flags_set ) { fprintf(fp,"); "); } fprintf(fp,"}\n"); // size_of, used by base class's clone to obtain the correct size. fprintf(fp," virtual uint size_of() const {"); fprintf(fp, " return sizeof(%sNode);", instr->_ident); fprintf(fp, " }\n"); // Virtual methods which are only generated to override base class if( instr->expands() || instr->needs_projections() || instr->has_temps() || instr->is_mach_constant() || instr->_matrule != NULL && instr->num_opnds() != instr->num_unique_opnds() ) { fprintf(fp," virtual MachNode *Expand(State *state, Node_List &proj_list, Node* mem);\n"); } if (instr->is_pinned(_globalNames)) { fprintf(fp," virtual bool pinned() const { return "); if (instr->is_parm(_globalNames)) { fprintf(fp,"_in[0]->pinned();"); } else { fprintf(fp,"true;"); } fprintf(fp," }\n"); } if (instr->is_projection(_globalNames)) { fprintf(fp," virtual const Node *is_block_proj() const { return this; }\n"); } if ( instr->num_post_match_opnds() != 0 || instr->is_chain_of_constant(_globalNames) ) { fprintf(fp," friend MachNode *State::MachNodeGenerator(int opcode, Compile* C);\n"); } if ( instr->rematerialize(_globalNames, get_registers()) ) { fprintf(fp," // Rematerialize %s\n", instr->_ident); } // Declare short branch methods, if applicable instr->declare_short_branch_methods(fp); // See if there is an "ins_pipe" declaration for this instruction if (instr->_ins_pipe) { fprintf(fp," static const Pipeline *pipeline_class();\n"); fprintf(fp," virtual const Pipeline *pipeline() const;\n"); } // Generate virtual function for MachNodeX::bottom_type when necessary // // Note on accuracy: Pointer-types of machine nodes need to be accurate, // or else alias analysis on the matched graph may produce bad code. // Moreover, the aliasing decisions made on machine-node graph must be // no less accurate than those made on the ideal graph, or else the graph // may fail to schedule. (Reason: Memory ops which are reordered in // the ideal graph might look interdependent in the machine graph, // thereby removing degrees of scheduling freedom that the optimizer // assumed would be available.) // // %%% We should handle many of these cases with an explicit ADL clause: // instruct foo() %{ ... bottom_type(TypeRawPtr::BOTTOM); ... %} if( data_type != Form::none ) { // A constant's bottom_type returns a Type containing its constant value // !!!!! // Convert all ints, floats, ... to machine-independent TypeXs // as is done for pointers // // Construct appropriate constant type containing the constant value. fprintf(fp," virtual const class Type *bottom_type() const {\n"); switch( data_type ) { case Form::idealI: fprintf(fp," return TypeInt::make(opnd_array(1)->constant());\n"); break; case Form::idealP: case Form::idealN: fprintf(fp," return opnd_array(1)->type();\n"); break; case Form::idealD: fprintf(fp," return TypeD::make(opnd_array(1)->constantD());\n"); break; case Form::idealF: fprintf(fp," return TypeF::make(opnd_array(1)->constantF());\n"); break; case Form::idealL: fprintf(fp," return TypeLong::make(opnd_array(1)->constantL());\n"); break; default: assert( false, "Unimplemented()" ); break; } fprintf(fp," };\n"); } /* else if ( instr->_matrule && instr->_matrule->_rChild && ( strcmp("ConvF2I",instr->_matrule->_rChild->_opType)==0 || strcmp("ConvD2I",instr->_matrule->_rChild->_opType)==0 ) ) { // !!!!! !!!!! // Provide explicit bottom type for conversions to int // On Intel the result operand is a stackSlot, untyped. fprintf(fp," virtual const class Type *bottom_type() const {"); fprintf(fp, " return TypeInt::INT;"); fprintf(fp, " };\n"); }*/ else if( instr->is_ideal_copy() && !strcmp(instr->_matrule->_lChild->_opType,"stackSlotP") ) { // !!!!! // Special hack for ideal Copy of pointer. Bottom type is oop or not depending on input. fprintf(fp," const Type *bottom_type() const { return in(1)->bottom_type(); } // Copy?\n"); } else if( instr->is_ideal_loadPC() ) { // LoadPCNode provides the return address of a call to native code. // Define its bottom type to be TypeRawPtr::BOTTOM instead of TypePtr::BOTTOM // since it is a pointer to an internal VM location and must have a zero offset. // Allocation detects derived pointers, in part, by their non-zero offsets. fprintf(fp," const Type *bottom_type() const { return TypeRawPtr::BOTTOM; } // LoadPC?\n"); } else if( instr->is_ideal_box() ) { // BoxNode provides the address of a stack slot. // Define its bottom type to be TypeRawPtr::BOTTOM instead of TypePtr::BOTTOM // This prevent s insert_anti_dependencies from complaining. It will // complain if it sees that the pointer base is TypePtr::BOTTOM since // it doesn't understand what that might alias. fprintf(fp," const Type *bottom_type() const { return TypeRawPtr::BOTTOM; } // Box?\n"); } else if( instr->_matrule && instr->_matrule->_rChild && !strcmp(instr->_matrule->_rChild->_opType,"CMoveP") ) { int offset = 1; // Special special hack to see if the Cmp? has been incorporated in the conditional move MatchNode *rl = instr->_matrule->_rChild->_lChild; if( rl && !strcmp(rl->_opType, "Binary") ) { MatchNode *rlr = rl->_rChild; if (rlr && strncmp(rlr->_opType, "Cmp", 3) == 0) offset = 2; } // Special hack for ideal CMoveP; ideal type depends on inputs fprintf(fp," const Type *bottom_type() const { const Type *t = in(oper_input_base()+%d)->bottom_type(); return (req() <= oper_input_base()+%d) ? t : t->meet(in(oper_input_base()+%d)->bottom_type()); } // CMoveP\n", offset, offset+1, offset+1); } else if( instr->_matrule && instr->_matrule->_rChild && !strcmp(instr->_matrule->_rChild->_opType,"CMoveN") ) { int offset = 1; // Special special hack to see if the Cmp? has been incorporated in the conditional move MatchNode *rl = instr->_matrule->_rChild->_lChild; if( rl && !strcmp(rl->_opType, "Binary") ) { MatchNode *rlr = rl->_rChild; if (rlr && strncmp(rlr->_opType, "Cmp", 3) == 0) offset = 2; } // Special hack for ideal CMoveN; ideal type depends on inputs fprintf(fp," const Type *bottom_type() const { const Type *t = in(oper_input_base()+%d)->bottom_type(); return (req() <= oper_input_base()+%d) ? t : t->meet(in(oper_input_base()+%d)->bottom_type()); } // CMoveN\n", offset, offset+1, offset+1); } else if (instr->is_tls_instruction()) { // Special hack for tlsLoadP fprintf(fp," const Type *bottom_type() const { return TypeRawPtr::BOTTOM; } // tlsLoadP\n"); } else if ( instr->is_ideal_if() ) { fprintf(fp," const Type *bottom_type() const { return TypeTuple::IFBOTH; } // matched IfNode\n"); } else if ( instr->is_ideal_membar() ) { fprintf(fp," const Type *bottom_type() const { return TypeTuple::MEMBAR; } // matched MemBar\n"); } // Check where 'ideal_type' must be customized /* if ( instr->_matrule && instr->_matrule->_rChild && ( strcmp("ConvF2I",instr->_matrule->_rChild->_opType)==0 || strcmp("ConvD2I",instr->_matrule->_rChild->_opType)==0 ) ) { fprintf(fp," virtual uint ideal_reg() const { return Compile::current()->matcher()->base2reg[Type::Int]; }\n"); }*/ // Analyze machine instructions that either USE or DEF memory. int memory_operand = instr->memory_operand(_globalNames); // Some guys kill all of memory if ( instr->is_wide_memory_kill(_globalNames) ) { memory_operand = InstructForm::MANY_MEMORY_OPERANDS; } if ( memory_operand != InstructForm::NO_MEMORY_OPERAND ) { if( memory_operand == InstructForm::MANY_MEMORY_OPERANDS ) { fprintf(fp," virtual const TypePtr *adr_type() const;\n"); } fprintf(fp," virtual const MachOper *memory_operand() const;\n"); } fprintf(fp, "#ifndef PRODUCT\n"); // virtual function for generating the user's assembler output gen_inst_format(fp, _globalNames,*instr); // Machine independent print functionality for debugging fprintf(fp," virtual const char *Name() const { return \"%s\";}\n", instr->_ident); fprintf(fp, "#endif\n"); // Close definition of this XxxMachNode fprintf(fp,"};\n"); }; } void ArchDesc::defineStateClass(FILE *fp) { static const char *state__valid = "_valid[((uint)index) >> 5] & (0x1 << (((uint)index) & 0x0001F))"; static const char *state__set_valid= "_valid[((uint)index) >> 5] |= (0x1 << (((uint)index) & 0x0001F))"; fprintf(fp,"\n"); fprintf(fp,"// MACROS to inline and constant fold State::valid(index)...\n"); fprintf(fp,"// when given a constant 'index' in dfa_<arch>.cpp\n"); fprintf(fp,"// uint word = index >> 5; // Shift out bit position\n"); fprintf(fp,"// uint bitpos = index & 0x0001F; // Mask off word bits\n"); fprintf(fp,"#define STATE__VALID(index) "); fprintf(fp," (%s)\n", state__valid); fprintf(fp,"\n"); fprintf(fp,"#define STATE__NOT_YET_VALID(index) "); fprintf(fp," ( (%s) == 0 )\n", state__valid); fprintf(fp,"\n"); fprintf(fp,"#define STATE__VALID_CHILD(state,index) "); fprintf(fp," ( state && (state->%s) )\n", state__valid); fprintf(fp,"\n"); fprintf(fp,"#define STATE__SET_VALID(index) "); fprintf(fp," (%s)\n", state__set_valid); fprintf(fp,"\n"); fprintf(fp, "//---------------------------State-------------------------------------------\n"); fprintf(fp,"// State contains an integral cost vector, indexed by machine operand opcodes,\n"); fprintf(fp,"// a rule vector consisting of machine operand/instruction opcodes, and also\n"); fprintf(fp,"// indexed by machine operand opcodes, pointers to the children in the label\n"); fprintf(fp,"// tree generated by the Label routines in ideal nodes (currently limited to\n"); fprintf(fp,"// two for convenience, but this could change).\n"); fprintf(fp,"class State : public ResourceObj {\n"); fprintf(fp,"public:\n"); fprintf(fp," int _id; // State identifier\n"); fprintf(fp," Node *_leaf; // Ideal (non-machine-node) leaf of match tree\n"); fprintf(fp," State *_kids[2]; // Children of state node in label tree\n"); fprintf(fp," unsigned int _cost[_LAST_MACH_OPER]; // Cost vector, indexed by operand opcodes\n"); fprintf(fp," unsigned int _rule[_LAST_MACH_OPER]; // Rule vector, indexed by operand opcodes\n"); fprintf(fp," unsigned int _valid[(_LAST_MACH_OPER/32)+1]; // Bit Map of valid Cost/Rule entries\n"); fprintf(fp,"\n"); fprintf(fp," State(void); // Constructor\n"); fprintf(fp," DEBUG_ONLY( ~State(void); ) // Destructor\n"); fprintf(fp,"\n"); fprintf(fp," // Methods created by ADLC and invoked by Reduce\n"); fprintf(fp," MachOper *MachOperGenerator( int opcode, Compile* C );\n"); fprintf(fp," MachNode *MachNodeGenerator( int opcode, Compile* C );\n"); fprintf(fp,"\n"); fprintf(fp," // Assign a state to a node, definition of method produced by ADLC\n"); fprintf(fp," bool DFA( int opcode, const Node *ideal );\n"); fprintf(fp,"\n"); fprintf(fp," // Access function for _valid bit vector\n"); fprintf(fp," bool valid(uint index) {\n"); fprintf(fp," return( STATE__VALID(index) != 0 );\n"); fprintf(fp," }\n"); fprintf(fp,"\n"); fprintf(fp," // Set function for _valid bit vector\n"); fprintf(fp," void set_valid(uint index) {\n"); fprintf(fp," STATE__SET_VALID(index);\n"); fprintf(fp," }\n"); fprintf(fp,"\n"); fprintf(fp,"#ifndef PRODUCT\n"); fprintf(fp," void dump(); // Debugging prints\n"); fprintf(fp," void dump(int depth);\n"); fprintf(fp,"#endif\n"); if (_dfa_small) { // Generate the routine name we'll need for (int i = 1; i < _last_opcode; i++) { if (_mlistab[i] == NULL) continue; fprintf(fp, " void _sub_Op_%s(const Node *n);\n", NodeClassNames[i]); } } fprintf(fp,"};\n"); fprintf(fp,"\n"); fprintf(fp,"\n"); } //---------------------------buildMachOperEnum--------------------------------- // Build enumeration for densely packed operands. // This enumeration is used to index into the arrays in the State objects // that indicate cost and a successfull rule match. // Information needed to generate the ReduceOp mapping for the DFA class OutputMachOperands : public OutputMap { public: OutputMachOperands(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD) : OutputMap(hpp, cpp, globals, AD, "MachOperands") {}; void declaration() { } void definition() { fprintf(_cpp, "enum MachOperands {\n"); } void closing() { fprintf(_cpp, " _LAST_MACH_OPER\n"); OutputMap::closing(); } void map(OpClassForm &opc) { const char* opc_ident_to_upper = _AD.machOperEnum(opc._ident); fprintf(_cpp, " %s", opc_ident_to_upper); delete[] opc_ident_to_upper; } void map(OperandForm &oper) { const char* oper_ident_to_upper = _AD.machOperEnum(oper._ident); fprintf(_cpp, " %s", oper_ident_to_upper); delete[] oper_ident_to_upper; } void map(char *name) { const char* name_to_upper = _AD.machOperEnum(name); fprintf(_cpp, " %s", name_to_upper); delete[] name_to_upper; } bool do_instructions() { return false; } void map(InstructForm &inst){ assert( false, "ShouldNotCallThis()"); } }; void ArchDesc::buildMachOperEnum(FILE *fp_hpp) { // Construct the table for MachOpcodes OutputMachOperands output_mach_operands(fp_hpp, fp_hpp, _globalNames, *this); build_map(output_mach_operands); } //---------------------------buildMachEnum---------------------------------- // Build enumeration for all MachOpers and all MachNodes // Information needed to generate the ReduceOp mapping for the DFA class OutputMachOpcodes : public OutputMap { int begin_inst_chain_rule; int end_inst_chain_rule; int begin_rematerialize; int end_rematerialize; int end_instructions; public: OutputMachOpcodes(FILE *hpp, FILE *cpp, FormDict &globals, ArchDesc &AD) : OutputMap(hpp, cpp, globals, AD, "MachOpcodes"), begin_inst_chain_rule(-1), end_inst_chain_rule(-1), end_instructions(-1) {}; void declaration() { } void definition() { fprintf(_cpp, "enum MachOpcodes {\n"); } void closing() { if( begin_inst_chain_rule != -1 ) fprintf(_cpp, " _BEGIN_INST_CHAIN_RULE = %d,\n", begin_inst_chain_rule); if( end_inst_chain_rule != -1 ) fprintf(_cpp, " _END_INST_CHAIN_RULE = %d,\n", end_inst_chain_rule); if( begin_rematerialize != -1 ) fprintf(_cpp, " _BEGIN_REMATERIALIZE = %d,\n", begin_rematerialize); if( end_rematerialize != -1 ) fprintf(_cpp, " _END_REMATERIALIZE = %d,\n", end_rematerialize); // always execute since do_instructions() is true, and avoids trailing comma fprintf(_cpp, " _last_Mach_Node = %d \n", end_instructions); OutputMap::closing(); } void map(OpClassForm &opc) { fprintf(_cpp, " %s_rule", opc._ident ); } void map(OperandForm &oper) { fprintf(_cpp, " %s_rule", oper._ident ); } void map(char *name) { if (name) fprintf(_cpp, " %s_rule", name); else fprintf(_cpp, " 0"); } void map(InstructForm &inst) {fprintf(_cpp, " %s_rule", inst._ident ); } void record_position(OutputMap::position place, int idx ) { switch(place) { case OutputMap::BEGIN_INST_CHAIN_RULES : begin_inst_chain_rule = idx; break; case OutputMap::END_INST_CHAIN_RULES : end_inst_chain_rule = idx; break; case OutputMap::BEGIN_REMATERIALIZE : begin_rematerialize = idx; break; case OutputMap::END_REMATERIALIZE : end_rematerialize = idx; break; case OutputMap::END_INSTRUCTIONS : end_instructions = idx; break; default: break; } } }; void ArchDesc::buildMachOpcodesEnum(FILE *fp_hpp) { // Construct the table for MachOpcodes OutputMachOpcodes output_mach_opcodes(fp_hpp, fp_hpp, _globalNames, *this); build_map(output_mach_opcodes); } // Generate an enumeration of the pipeline states, and both // the functional units (resources) and the masks for // specifying resources void ArchDesc::build_pipeline_enums(FILE *fp_hpp) { int stagelen = (int)strlen("undefined"); int stagenum = 0; if (_pipeline) { // Find max enum string length const char *stage; for ( _pipeline->_stages.reset(); (stage = _pipeline->_stages.iter()) != NULL; ) { int len = (int)strlen(stage); if (stagelen < len) stagelen = len; } } // Generate a list of stages fprintf(fp_hpp, "\n"); fprintf(fp_hpp, "// Pipeline Stages\n"); fprintf(fp_hpp, "enum machPipelineStages {\n"); fprintf(fp_hpp, " stage_%-*s = 0,\n", stagelen, "undefined"); if( _pipeline ) { const char *stage; for ( _pipeline->_stages.reset(); (stage = _pipeline->_stages.iter()) != NULL; ) fprintf(fp_hpp, " stage_%-*s = %d,\n", stagelen, stage, ++stagenum); } fprintf(fp_hpp, " stage_%-*s = %d\n", stagelen, "count", stagenum); fprintf(fp_hpp, "};\n"); fprintf(fp_hpp, "\n"); fprintf(fp_hpp, "// Pipeline Resources\n"); fprintf(fp_hpp, "enum machPipelineResources {\n"); int rescount = 0; if( _pipeline ) { const char *resource; int reslen = 0; // Generate a list of resources, and masks for ( _pipeline->_reslist.reset(); (resource = _pipeline->_reslist.iter()) != NULL; ) { int len = (int)strlen(resource); if (reslen < len) reslen = len; } for ( _pipeline->_reslist.reset(); (resource = _pipeline->_reslist.iter()) != NULL; ) { const ResourceForm *resform = _pipeline->_resdict[resource]->is_resource(); int mask = resform->mask(); if ((mask & (mask-1)) == 0) fprintf(fp_hpp, " resource_%-*s = %d,\n", reslen, resource, rescount++); } fprintf(fp_hpp, "\n"); for ( _pipeline->_reslist.reset(); (resource = _pipeline->_reslist.iter()) != NULL; ) { const ResourceForm *resform = _pipeline->_resdict[resource]->is_resource(); fprintf(fp_hpp, " res_mask_%-*s = 0x%08x,\n", reslen, resource, resform->mask()); } fprintf(fp_hpp, "\n"); } fprintf(fp_hpp, " resource_count = %d\n", rescount); fprintf(fp_hpp, "};\n"); }
95,213
32,841
// Copyright 2017 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 "chrome/browser/android/preferences/prefs.h" #include "base/stl_util.h" #include "chrome/browser/android/preferences/pref_service_bridge.h" #include "chrome/common/pref_names.h" #include "testing/gtest/include/gtest/gtest.h" namespace { class PrefsTest : public ::testing::Test { protected: const char* GetPrefName(Pref pref) { pref_count_++; return PrefServiceBridge::GetPrefNameExposedToJava(pref); } int pref_count_; }; TEST_F(PrefsTest, TestIndex) { pref_count_ = 0; // If one of these checks fails, most likely the Pref enum and // |kPrefExposedToJava| are out of sync. EXPECT_EQ(Pref::PREF_NUM_PREFS, base::size(kPrefsExposedToJava)); EXPECT_EQ(prefs::kAllowDeletingBrowserHistory, GetPrefName(ALLOW_DELETING_BROWSER_HISTORY)); EXPECT_EQ(prefs::kIncognitoModeAvailability, GetPrefName(INCOGNITO_MODE_AVAILABILITY)); EXPECT_EQ(feed::prefs::kEnableSnippets, GetPrefName(NTP_ARTICLES_SECTION_ENABLED)); EXPECT_EQ(feed::prefs::kArticlesListVisible, GetPrefName(NTP_ARTICLES_LIST_VISIBLE)); EXPECT_EQ(prefs::kPromptForDownloadAndroid, GetPrefName(PROMPT_FOR_DOWNLOAD_ANDROID)); EXPECT_EQ(dom_distiller::prefs::kReaderForAccessibility, GetPrefName(READER_FOR_ACCESSIBILITY_ENABLED)); EXPECT_EQ(prefs::kShowMissingSdCardErrorAndroid, GetPrefName(SHOW_MISSING_SD_CARD_ERROR_ANDROID)); EXPECT_EQ(payments::kCanMakePaymentEnabled, GetPrefName(CAN_MAKE_PAYMENT_ENABLED)); EXPECT_EQ(prefs::kContextualSearchEnabled, GetPrefName(CONTEXTUAL_SEARCH_ENABLED)); EXPECT_EQ(autofill::prefs::kAutofillProfileEnabled, GetPrefName(AUTOFILL_PROFILE_ENABLED)); EXPECT_EQ(autofill::prefs::kAutofillCreditCardEnabled, GetPrefName(AUTOFILL_CREDIT_CARD_ENABLED)); EXPECT_EQ(prefs::kUsageStatsEnabled, GetPrefName(USAGE_STATS_ENABLED)); EXPECT_EQ(offline_pages::prefetch_prefs::kUserSettingEnabled, GetPrefName(OFFLINE_PREFETCH_USER_SETTING_ENABLED)); EXPECT_EQ(prefs::kSafeBrowsingExtendedReportingOptInAllowed, GetPrefName(SAFE_BROWSING_EXTENDED_REPORTING_OPT_IN_ALLOWED)); EXPECT_EQ(prefs::kSafeBrowsingEnabled, GetPrefName(SAFE_BROWSING_ENABLED)); EXPECT_EQ(password_manager::prefs::kPasswordManagerOnboardingState, GetPrefName(PASSWORD_MANAGER_ONBOARDING_STATE)); EXPECT_EQ(prefs::kSearchSuggestEnabled, GetPrefName(SEARCH_SUGGEST_ENABLED)); EXPECT_EQ(password_manager::prefs::kCredentialsEnableService, GetPrefName(REMEMBER_PASSWORDS_ENABLED)); EXPECT_EQ(password_manager::prefs::kCredentialsEnableAutosignin, GetPrefName(PASSWORD_MANAGER_AUTO_SIGNIN_ENABLED)); EXPECT_EQ(password_manager::prefs::kPasswordLeakDetectionEnabled, GetPrefName(PASSWORD_MANAGER_LEAK_DETECTION_ENABLED)); EXPECT_EQ(prefs::kSupervisedUserSafeSites, GetPrefName(SUPERVISED_USER_SAFE_SITES)); EXPECT_EQ(prefs::kDefaultSupervisedUserFilteringBehavior, GetPrefName(DEFAULT_SUPERVISED_USER_FILTERING_BEHAVIOR)); EXPECT_EQ(prefs::kSupervisedUserId, GetPrefName(SUPERVISED_USER_ID)); EXPECT_EQ(prefs::kSupervisedUserCustodianEmail, GetPrefName(SUPERVISED_USER_CUSTODIAN_EMAIL)); EXPECT_EQ(prefs::kSupervisedUserSecondCustodianName, GetPrefName(SUPERVISED_USER_SECOND_CUSTODIAN_NAME)); EXPECT_EQ(prefs::kSupervisedUserSecondCustodianEmail, GetPrefName(SUPERVISED_USER_SECOND_CUSTODIAN_EMAIL)); EXPECT_EQ(prefs::kClickedUpdateMenuItem, GetPrefName(CLICKED_UPDATE_MENU_ITEM)); EXPECT_EQ(prefs::kLatestVersionWhenClickedUpdateMenuItem, GetPrefName(LATEST_VERSION_WHEN_CLICKED_UPDATE_MENU_ITEM)); EXPECT_EQ(prefs::kBlockThirdPartyCookies, GetPrefName(BLOCK_THIRD_PARTY_COOKIES)); EXPECT_EQ(prefs::kCookieControlsMode, GetPrefName(COOKIE_CONTROLS_MODE)); EXPECT_EQ(prefs::kEnableDoNotTrack, GetPrefName(ENABLE_DO_NOT_TRACK)); EXPECT_EQ(prefs::kPrintingEnabled, GetPrefName(PRINTING_ENABLED)); EXPECT_EQ(prefs::kOfferTranslateEnabled, GetPrefName(OFFER_TRANSLATE_ENABLED)); EXPECT_EQ(prefs::kNotificationsVibrateEnabled, GetPrefName(NOTIFICATIONS_VIBRATE_ENABLED)); EXPECT_EQ(embedder_support::kAlternateErrorPagesEnabled, GetPrefName(ALTERNATE_ERROR_PAGES_ENABLED)); EXPECT_EQ(prefs::kGoogleServicesLastUsername, GetPrefName(SYNC_LAST_ACCOUNT_NAME)); EXPECT_EQ(prefs::kWebKitPasswordEchoEnabled, GetPrefName(WEBKIT_PASSWORD_ECHO_ENABLED)); EXPECT_EQ(prefs::kWebKitForceDarkModeEnabled, GetPrefName(WEBKIT_FORCE_DARK_MODE_ENABLED)); EXPECT_EQ(prefs::kHomePage, GetPrefName(HOME_PAGE)); EXPECT_EQ(autofill::prefs::kAutofillCreditCardFidoAuthEnabled, GetPrefName(AUTOFILL_CREDIT_CARD_FIDO_AUTH_ENABLED)); EXPECT_EQ(prefs::kEnableQuietNotificationPermissionUi, GetPrefName(ENABLE_QUIET_NOTIFICATION_PERMISSION_UI)); // If this check fails, a pref is missing a test case above. EXPECT_EQ(Pref::PREF_NUM_PREFS, pref_count_); } } // namespace
5,273
2,076
/* Copyright 2016 Emanuele Vespa, Imperial College London 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 copyright holder 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 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. */ #ifndef OCTREE_COLLISION_HPP #define OCTREE_COLLISION_HPP #include "../node.hpp" #include "../octree.hpp" #include "aabb_collision.hpp" namespace se { template<typename T> using VoxelBlockType = typename T::VoxelBlockType; namespace geometry { enum class collision_status { occupied, unseen, empty }; /*! \brief Implements a simple state machine to update the collision status. * The importance order is given as follows in ascending order: * Empty, Unseen, Occupied. * \param previous_status * \param new_status */ inline collision_status update_status(const collision_status previous_status, const collision_status new_status) { switch(previous_status) { case collision_status::unseen: if(new_status != collision_status::occupied) return previous_status; else return new_status; break; case collision_status::occupied: return previous_status; break; default: return new_status; break; } } /*! \brief Perform a collision test for each voxel value in the input voxel * block. The test function test takes as input a voxel value and returns a * collision_status. This is used to distinguish between seen-empty voxels and * occupied voxels. * \param block voxel block of type FieldType * \param test function that takes a voxel and returns a collision_status value */ template <typename FieldType, template <typename FieldT> class VoxelBlockT, typename TestVoxelF> collision_status collides_with(const VoxelBlockT<FieldType>* block, const Eigen::Vector3i bbox_coord, const Eigen::Vector3i size, TestVoxelF test) { collision_status status = collision_status::empty; const Eigen::Vector3i block_coord = block->coordinates(); int x, y, z, block_size; block_size = (int) VoxelBlockT<FieldType>::size_li; int x_last = block_coord.x() + block_size; int y_last = block_coord.y() + block_size; int z_last = block_coord.z() + block_size; for(z = block_coord.z(); z < z_last; ++z){ for (y = block_coord.y(); y < y_last; ++y){ for (x = block_coord.x(); x < x_last; ++x){ typename VoxelBlockT<FieldType>::VoxelData data; const Eigen::Vector3i voxel_coord{x, y, z}; if(!geometry::aabb_aabb_collision(bbox_coord, size, voxel_coord, Eigen::Vector3i::Constant(1))) continue; data = block->data(Eigen::Vector3i(x, y, z)); status = update_status(status, test(data)); } } } return status; } /*! \brief Perform a collision test between the input octree map and the * input axis aligned bounding box bbox_coord of extension size. The test function * test takes as input a voxel data and returns a collision_status. This is * used to distinguish between seen-empty voxels and occupied voxels. * \param octree octree map * \param bbox_coord test bounding box lower bottom corner * \param size extension in number of voxels of the bounding box * \param test function that takes a voxel and returns a collision_status data */ template <typename FieldType, typename TestVoxelF> collision_status collides_with(const Octree<FieldType>& octree, const Eigen::Vector3i bbox_coord, const Eigen::Vector3i bbox_size, TestVoxelF test) { typedef struct stack_entry { se::Node<FieldType>* node_ptr; Eigen::Vector3i coordinates; int size; typename se::Node<FieldType>::VoxelData parent_data; } stack_entry; stack_entry stack[Octree<FieldType>::max_voxel_depth * 8 + 1]; size_t stack_idx = 0; se::Node<FieldType>* node = octree.root(); if(!node) return collision_status::unseen; stack_entry current; current.node_ptr = node; current.size = octree.size(); current.coordinates = {0, 0, 0}; current.parent_data = FieldType::initData(); stack[stack_idx++] = current; collision_status status = collision_status::empty; while(stack_idx != 0){ node = current.node_ptr; if(node->isBlock()){ status = collides_with(static_cast<VoxelBlockType<FieldType>*>(node), bbox_coord, bbox_size, test); } if(node->children_mask() == 0) { current = stack[--stack_idx]; continue; } for(int child_idx = 0; child_idx < 8; ++child_idx){ se::Node<FieldType>* child = node->child(child_idx); stack_entry child_descr; child_descr.node_ptr = nullptr; child_descr.size = current.size / 2; child_descr.coordinates = Eigen::Vector3i(current.coordinates.x() + child_descr.size*((child_idx & 1) > 0), current.coordinates.y() + child_descr.size*((child_idx & 2) > 0), current.coordinates.z() + child_descr.size*((child_idx & 4) > 0)); const bool overlaps = geometry::aabb_aabb_collision(bbox_coord, bbox_size, child_descr.coordinates, Eigen::Vector3i::Constant(child_descr.size)); if(overlaps && child != nullptr) { child_descr.node_ptr = child; child_descr.parent_data = node->childData(0); stack[stack_idx++] = child_descr; } else if(overlaps && child == nullptr) { status = update_status(status, test(node->childData(0))); } } current = stack[--stack_idx]; } return status; } } } #endif
6,744
2,255
/* Masstree * Eddie Kohler, Yandong Mao, Robert Morris * Copyright (c) 2012-2016 President and Fellows of Harvard College * Copyright (c) 2012-2016 Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, subject to the conditions * listed in the Masstree LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Masstree LICENSE file; the license in that file * is legally binding. */ #ifndef MASSTREE_REMOVE_HH #define MASSTREE_REMOVE_HH #include "masstree_get.hh" #include "btree_leaflink.hh" #include "circular_int.hh" namespace Masstree { template <typename P> bool tcursor<P>::gc_layer(threadinfo& ti) { find_locked(ti); masstree_precondition(!n_->deleted() && !n_->deleted_layer()); // find_locked might return early if another gc_layer attempt has // succeeded at removing multiple tree layers. So check that the whole // key has been consumed if (ka_.has_suffix()) return false; // find the slot for the child tree // ka_ is a multiple of ikey_size bytes long. We are looking for the entry // for the next tree layer, which has keylenx_ corresponding to ikey_size+1. // So if has_value(), then we found an entry for the same ikey, but with // length ikey_size; we need to adjust ki_. kx_.i += has_value(); if (kx_.i >= n_->size()) return false; permuter_type perm(n_->permutation_); kx_.p = perm[kx_.i]; if (n_->ikey0_[kx_.p] != ka_.ikey() || !n_->is_layer(kx_.p)) return false; // remove redundant internode layers node_type *layer; while (1) { layer = n_->lv_[kx_.p].layer(); if (!layer->is_root()) { n_->lv_[kx_.p] = layer->maybe_parent(); continue; } if (layer->isleaf()) break; internode_type *in = static_cast<internode_type *>(layer); if (in->size() > 0) return false; in->lock(*layer, ti.lock_fence(tc_internode_lock)); if (!in->is_root() || in->size() > 0) goto unlock_layer; node_type *child = in->child_[0]; child->make_layer_root(); n_->lv_[kx_.p] = child; in->mark_split(); in->set_parent(child); // ensure concurrent reader finds true root // NB: now in->parent() might weirdly be a LEAF! in->unlock(); in->deallocate_rcu(ti); } { leaf_type* lf = static_cast<leaf_type*>(layer); if (lf->size() > 0) return false; lf->lock(*lf, ti.lock_fence(tc_leaf_lock)); if (!lf->is_root() || lf->size() > 0) goto unlock_layer; // child is an empty leaf: kill it masstree_invariant(!lf->prev_ && !lf->next_.ptr); masstree_invariant(!lf->deleted()); masstree_invariant(!lf->deleted_layer()); if (P::need_phantom_epoch && circular_int<typename P::phantom_epoch_type>::less(n_->phantom_epoch_[0], lf->phantom_epoch_[0])) n_->phantom_epoch_[0] = lf->phantom_epoch_[0]; lf->mark_deleted_layer(); // NB DO NOT mark as deleted (see above) lf->unlock(); lf->deallocate_rcu(ti); return true; } unlock_layer: layer->unlock(); return false; } template <typename P> struct gc_layer_rcu_callback : public P::threadinfo_type::mrcu_callback { typedef typename P::threadinfo_type threadinfo; node_base<P>* root_; int len_; char s_[0]; gc_layer_rcu_callback(node_base<P>* root, Str prefix) : root_(root), len_(prefix.length()) { memcpy(s_, prefix.data(), len_); } void operator()(threadinfo& ti); size_t size() const { return len_ + sizeof(*this); } static void make(node_base<P>* root, Str prefix, threadinfo& ti); }; template <typename P> void gc_layer_rcu_callback<P>::operator()(threadinfo& ti) { while (!root_->is_root()) root_ = root_->maybe_parent(); if (!root_->deleted()) { // if not destroying tree... tcursor<P> lp(root_, s_, len_); bool do_remove = lp.gc_layer(ti); if (!do_remove || !lp.finish_remove(ti)) lp.n_->unlock(); ti.deallocate(this, size(), memtag_masstree_gc); } } template <typename P> void gc_layer_rcu_callback<P>::make(node_base<P>* root, Str prefix, threadinfo& ti) { size_t sz = prefix.len + sizeof(gc_layer_rcu_callback<P>); void *data = ti.allocate(sz, memtag_masstree_gc); gc_layer_rcu_callback<P> *cb = new(data) gc_layer_rcu_callback<P>(root, prefix); ti.rcu_register(cb); } template <typename P> bool tcursor<P>::finish_remove(threadinfo& ti) { if (n_->modstate_ == leaf<P>::modstate_insert) { n_->mark_insert(); n_->modstate_ = leaf<P>::modstate_remove; } permuter_type perm(n_->permutation_); perm.remove(kx_.i); n_->permutation_ = perm.value(); if (perm.size()) return false; else return remove_leaf(n_, root_, ka_.prefix_string(), ti); } template <typename P> bool tcursor<P>::remove_leaf(leaf_type* leaf, node_type* root, Str prefix, threadinfo& ti) { if (!leaf->prev_) { if (!leaf->next_.ptr && !prefix.empty()) gc_layer_rcu_callback<P>::make(root, prefix, ti); return false; } // mark leaf deleted, RCU-free leaf->mark_deleted(); leaf->deallocate_rcu(ti); // Ensure node that becomes responsible for our keys has its phantom epoch // kept up to date while (P::need_phantom_epoch) { leaf_type *prev = leaf->prev_; typename P::phantom_epoch_type prev_ts = prev->phantom_epoch(); while (circular_int<typename P::phantom_epoch_type>::less(prev_ts, leaf->phantom_epoch()) && !bool_cmpxchg(&prev->phantom_epoch_[0], prev_ts, leaf->phantom_epoch())) prev_ts = prev->phantom_epoch(); fence(); if (prev == leaf->prev_) break; } // Unlink leaf from doubly-linked leaf list btree_leaflink<leaf_type>::unlink(leaf); // Remove leaf from tree. This is simple unless the leaf is the first // child of its parent, in which case we need to traverse up until we find // its key. node_type *n = leaf; ikey_type ikey = leaf->ikey_bound(); while (1) { internode_type *p = n->locked_parent(ti); masstree_invariant(p); n->unlock(); int kp = internode_type::bound_type::upper(ikey, *p); masstree_invariant(kp == 0 || p->compare_key(ikey, kp - 1) == 0); if (kp > 0) { p->mark_insert(); p->shift_down(kp - 1, kp, p->nkeys_ - kp); --p->nkeys_; if (kp > 1 || p->child_[0]) return collapse(p, ikey, root, prefix, ti); } if (p->size() == 0) { p->mark_deleted(); p->deallocate_rcu(ti); } else return reshape(p, ikey, root, prefix, ti); n = p; } } template <typename P> bool tcursor<P>::reshape(internode_type* n, ikey_type ikey, node_type* root, Str prefix, threadinfo& ti) { masstree_precondition(n && n->locked()); n->child_[0] = 0; ikey_type patchkey = n->ikey0_[0]; while (1) { internode_type *p = n->locked_parent(ti); masstree_invariant(p); n->unlock(); int kp = internode_type::bound_type::upper(ikey, *p); masstree_invariant(kp == 0 || p->compare_key(ikey, kp - 1) == 0); if (kp > 0) { p->mark_insert(); p->ikey0_[kp - 1] = patchkey; if (kp > 1 || p->child_[0]) return collapse(p, ikey, root, prefix, ti); } n = p; } } template <typename P> bool tcursor<P>::collapse(internode_type* n, ikey_type ikey, node_type* root, Str prefix, threadinfo& ti) { masstree_precondition(n && n->locked()); while (n->size() == 0) { internode_type *p = n->locked_parent(ti); if (!n->parent_exists(p)) { if (!prefix.empty()) gc_layer_rcu_callback<P>::make(root, prefix, ti); break; } int kp = key_upper_bound(ikey, *p); masstree_invariant(p->child_[kp] == n); p->child_[kp] = n->child_[0]; n->child_[0]->set_parent(p); n->mark_deleted(); n->unlock(); n->deallocate_rcu(ti); n = p; } n->unlock(); return true; } template <typename P> struct destroy_rcu_callback : public P::threadinfo_type::mrcu_callback { typedef typename P::threadinfo_type threadinfo; typedef typename node_base<P>::leaf_type leaf_type; typedef typename node_base<P>::internode_type internode_type; node_base<P>* root_; int count_; destroy_rcu_callback(node_base<P>* root) : root_(root), count_(0) { } void operator()(threadinfo& ti); static void make(node_base<P>* root, Str prefix, threadinfo& ti); private: static inline node_base<P>** link_ptr(node_base<P>* n); static inline void enqueue(node_base<P>* n, node_base<P>**& tailp); }; template <typename P> inline node_base<P>** destroy_rcu_callback<P>::link_ptr(node_base<P>* n) { if (n->isleaf()) return &static_cast<leaf_type*>(n)->parent_; else return &static_cast<internode_type*>(n)->parent_; } template <typename P> inline void destroy_rcu_callback<P>::enqueue(node_base<P>* n, node_base<P>**& tailp) { *tailp = n; tailp = link_ptr(n); } template <typename P> void destroy_rcu_callback<P>::operator()(threadinfo& ti) { if (++count_ == 1) { while (!root_->is_root()) root_ = root_->maybe_parent(); root_->lock(); root_->mark_deleted_tree(); // i.e., deleted but not splitting root_->unlock(); ti.rcu_register(this); return; } node_base<P>* workq; node_base<P>** tailp = &workq; enqueue(root_, tailp); while (node_base<P>* n = workq) { node_base<P>** linkp = link_ptr(n); if (linkp != tailp) workq = *linkp; else { workq = 0; tailp = &workq; } if (n->isleaf()) { leaf_type* l = static_cast<leaf_type*>(n); typename leaf_type::permuter_type perm = l->permutation(); for (int i = 0; i != l->size(); ++i) { int p = perm[i]; if (l->is_layer(p)) enqueue(l->lv_[p].layer(), tailp); } l->deallocate(ti); } else { internode_type* in = static_cast<internode_type*>(n); for (int i = 0; i != in->size() + 1; ++i) if (in->child_[i]) enqueue(in->child_[i], tailp); in->deallocate(ti); } } ti.deallocate(this, sizeof(this), memtag_masstree_gc); } template <typename P> void basic_table<P>::destroy(threadinfo& ti) { if (root_) { void* data = ti.allocate(sizeof(destroy_rcu_callback<P>), memtag_masstree_gc); destroy_rcu_callback<P>* cb = new(data) destroy_rcu_callback<P>(root_); ti.rcu_register(cb); root_ = 0; } } } // namespace Masstree #endif
11,711
4,067
//////////////////////////////////////////////////////////////////////////////// //! \file Common.hpp //! \brief File to include the most commonly used headers. //! \author Chris Oldwood // Check for previous inclusion #ifndef APP_COMMON_HPP #define APP_COMMON_HPP #if _MSC_VER > 1000 #pragma once #endif #include <Core/Common.hpp> #include <iostream> #endif // APP_COMMON_HPP
384
129
/** * -=-<[ Bismillahirrahmanirrahim ]>-=- * Date : 2021-01-11 06:31:32 * Author : Dahir Muhammad Dahir (dahirmuhammad3@gmail.com) * About : Compile with g++ */ #include <iostream> #include <string> #include <sstream> using namespace std; class Student { private: int age; string first_name; string last_name; int standard; public: int get_age(){ return age; } void set_age(int new_age) { age = new_age; } string get_first_name() { return first_name; } void set_first_name(string new_first_name) { first_name = new_first_name; } string get_last_name() { return last_name; } void set_last_name(string new_last_name) { last_name = new_last_name; } int get_standard() { return standard; } void set_standard(int new_standard) { standard = new_standard; } string to_string(){ stringstream my_string_stream; string stringed; my_string_stream << age << ',' << first_name << ',' << last_name << ',' << standard; my_string_stream >> stringed; return stringed; } }; int main(){ //pass return 0; }
1,387
438
/** * @file SedFunctionalRange.cpp * @brief Implementation of the SedFunctionalRange class. * @author DEVISER * * <!-------------------------------------------------------------------------- * This file is part of libSEDML. Please visit http://sed-ml.org for more * information about SED-ML. The latest version of libSEDML can be found on * github: https://github.com/fbergmann/libSEDML/ * * Copyright (c) 2013-2019, Frank T. Bergmann * 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. * * 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. A copy of the license agreement is provided in the * file named "LICENSE.txt" included with this software distribution and also * available online as http://sbml.org/software/libsbml/license.html * ------------------------------------------------------------------------ --> */ #include <sedml/SedFunctionalRange.h> #include <sedml/SedVariable.h> #include <sbml/xml/XMLInputStream.h> #include <sbml/math/MathML.h> using namespace std; LIBSEDML_CPP_NAMESPACE_BEGIN #ifdef __cplusplus /* * Creates a new SedFunctionalRange using the given SED-ML Level and @ p version * values. */ SedFunctionalRange::SedFunctionalRange(unsigned int level, unsigned int version) : SedRange(level, version) , mRange ("") , mMath (NULL) , mVariables (level, version) , mParameters (level, version) { setSedNamespacesAndOwn(new SedNamespaces(level, version)); connectToChild(); } /* * Creates a new SedFunctionalRange using the given SedNamespaces object @p * sedmlns. */ SedFunctionalRange::SedFunctionalRange(SedNamespaces *sedmlns) : SedRange(sedmlns) , mRange ("") , mMath (NULL) , mVariables (sedmlns) , mParameters (sedmlns) { setElementNamespace(sedmlns->getURI()); connectToChild(); } /* * Copy constructor for SedFunctionalRange. */ SedFunctionalRange::SedFunctionalRange(const SedFunctionalRange& orig) : SedRange( orig ) , mRange ( orig.mRange ) , mMath ( NULL ) , mVariables ( orig.mVariables ) , mParameters ( orig.mParameters ) { if (orig.mMath != NULL) { mMath = orig.mMath->deepCopy(); } connectToChild(); } /* * Assignment operator for SedFunctionalRange. */ SedFunctionalRange& SedFunctionalRange::operator=(const SedFunctionalRange& rhs) { if (&rhs != this) { SedRange::operator=(rhs); mRange = rhs.mRange; mVariables = rhs.mVariables; mParameters = rhs.mParameters; delete mMath; if (rhs.mMath != NULL) { mMath = rhs.mMath->deepCopy(); } else { mMath = NULL; } connectToChild(); } return *this; } /* * Creates and returns a deep copy of this SedFunctionalRange object. */ SedFunctionalRange* SedFunctionalRange::clone() const { return new SedFunctionalRange(*this); } /* * Destructor for SedFunctionalRange. */ SedFunctionalRange::~SedFunctionalRange() { delete mMath; mMath = NULL; } /* * Returns the value of the "range" attribute of this SedFunctionalRange. */ const std::string& SedFunctionalRange::getRange() const { return mRange; } /* * Predicate returning @c true if this SedFunctionalRange's "range" attribute * is set. */ bool SedFunctionalRange::isSetRange() const { return (mRange.empty() == false); } /* * Sets the value of the "range" attribute of this SedFunctionalRange. */ int SedFunctionalRange::setRange(const std::string& range) { if (!(SyntaxChecker::isValidInternalSId(range))) { return LIBSEDML_INVALID_ATTRIBUTE_VALUE; } else { mRange = range; return LIBSEDML_OPERATION_SUCCESS; } } /* * Unsets the value of the "range" attribute of this SedFunctionalRange. */ int SedFunctionalRange::unsetRange() { mRange.erase(); if (mRange.empty() == true) { return LIBSEDML_OPERATION_SUCCESS; } else { return LIBSEDML_OPERATION_FAILED; } } /* * Returns the value of the "math" element of this SedFunctionalRange. */ const LIBSBML_CPP_NAMESPACE_QUALIFIER ASTNode* SedFunctionalRange::getMath() const { return mMath; } /* * Returns the value of the "math" element of this SedFunctionalRange. */ LIBSBML_CPP_NAMESPACE_QUALIFIER ASTNode* SedFunctionalRange::getMath() { return mMath; } /* * Predicate returning @c true if this SedFunctionalRange's "math" element is * set. */ bool SedFunctionalRange::isSetMath() const { return (mMath != NULL); } /* * Sets the value of the "math" element of this SedFunctionalRange. */ int SedFunctionalRange::setMath(const LIBSBML_CPP_NAMESPACE_QUALIFIER ASTNode* math) { if (mMath == math) { return LIBSEDML_OPERATION_SUCCESS; } else if (math == NULL) { delete mMath; mMath = NULL; return LIBSEDML_OPERATION_SUCCESS; } else if (!(math->isWellFormedASTNode())) { return LIBSEDML_INVALID_OBJECT; } else { delete mMath; mMath = (math != NULL) ? math->deepCopy() : NULL; return LIBSEDML_OPERATION_SUCCESS; } } /* * Unsets the value of the "math" element of this SedFunctionalRange. */ int SedFunctionalRange::unsetMath() { delete mMath; mMath = NULL; return LIBSEDML_OPERATION_SUCCESS; } /* * Returns the SedListOfVariables from this SedFunctionalRange. */ const SedListOfVariables* SedFunctionalRange::getListOfVariables() const { return &mVariables; } /* * Returns the SedListOfVariables from this SedFunctionalRange. */ SedListOfVariables* SedFunctionalRange::getListOfVariables() { return &mVariables; } /* * Get a SedVariable from the SedFunctionalRange. */ SedVariable* SedFunctionalRange::getVariable(unsigned int n) { return mVariables.get(n); } /* * Get a SedVariable from the SedFunctionalRange. */ const SedVariable* SedFunctionalRange::getVariable(unsigned int n) const { return mVariables.get(n); } /* * Get a SedVariable from the SedFunctionalRange based on its identifier. */ SedVariable* SedFunctionalRange::getVariable(const std::string& sid) { return mVariables.get(sid); } /* * Get a SedVariable from the SedFunctionalRange based on its identifier. */ const SedVariable* SedFunctionalRange::getVariable(const std::string& sid) const { return mVariables.get(sid); } /* * Get a SedVariable from the SedFunctionalRange based on the TaskReference to * which it refers. */ const SedVariable* SedFunctionalRange::getVariableByTaskReference(const std::string& sid) const { return mVariables.getByTaskReference(sid); } /* * Get a SedVariable from the SedFunctionalRange based on the TaskReference to * which it refers. */ SedVariable* SedFunctionalRange::getVariableByTaskReference(const std::string& sid) { return mVariables.getByTaskReference(sid); } /* * Get a SedVariable from the SedFunctionalRange based on the ModelReference to * which it refers. */ const SedVariable* SedFunctionalRange::getVariableByModelReference(const std::string& sid) const { return mVariables.getByModelReference(sid); } /* * Get a SedVariable from the SedFunctionalRange based on the ModelReference to * which it refers. */ SedVariable* SedFunctionalRange::getVariableByModelReference(const std::string& sid) { return mVariables.getByModelReference(sid); } /* * Adds a copy of the given SedVariable to this SedFunctionalRange. */ int SedFunctionalRange::addVariable(const SedVariable* sv) { if (sv == NULL) { return LIBSEDML_OPERATION_FAILED; } else if (sv->hasRequiredAttributes() == false) { return LIBSEDML_INVALID_OBJECT; } else if (getLevel() != sv->getLevel()) { return LIBSEDML_LEVEL_MISMATCH; } else if (getVersion() != sv->getVersion()) { return LIBSEDML_VERSION_MISMATCH; } else if (matchesRequiredSedNamespacesForAddition(static_cast<const SedBase*>(sv)) == false) { return LIBSEDML_NAMESPACES_MISMATCH; } else if (sv->isSetId() && (mVariables.get(sv->getId())) != NULL) { return LIBSEDML_DUPLICATE_OBJECT_ID; } else { return mVariables.append(sv); } } /* * Get the number of SedVariable objects in this SedFunctionalRange. */ unsigned int SedFunctionalRange::getNumVariables() const { return mVariables.size(); } /* * Creates a new SedVariable object, adds it to this SedFunctionalRange object * and returns the SedVariable object created. */ SedVariable* SedFunctionalRange::createVariable() { SedVariable* sv = NULL; try { sv = new SedVariable(getSedNamespaces()); } catch (...) { } if (sv != NULL) { mVariables.appendAndOwn(sv); } return sv; } /* * Removes the nth SedVariable from this SedFunctionalRange and returns a * pointer to it. */ SedVariable* SedFunctionalRange::removeVariable(unsigned int n) { return mVariables.remove(n); } /* * Removes the SedVariable from this SedFunctionalRange based on its identifier * and returns a pointer to it. */ SedVariable* SedFunctionalRange::removeVariable(const std::string& sid) { return mVariables.remove(sid); } /* * Returns the SedListOfParameters from this SedFunctionalRange. */ const SedListOfParameters* SedFunctionalRange::getListOfParameters() const { return &mParameters; } /* * Returns the SedListOfParameters from this SedFunctionalRange. */ SedListOfParameters* SedFunctionalRange::getListOfParameters() { return &mParameters; } /* * Get a SedParameter from the SedFunctionalRange. */ SedParameter* SedFunctionalRange::getParameter(unsigned int n) { return mParameters.get(n); } /* * Get a SedParameter from the SedFunctionalRange. */ const SedParameter* SedFunctionalRange::getParameter(unsigned int n) const { return mParameters.get(n); } /* * Get a SedParameter from the SedFunctionalRange based on its identifier. */ SedParameter* SedFunctionalRange::getParameter(const std::string& sid) { return mParameters.get(sid); } /* * Get a SedParameter from the SedFunctionalRange based on its identifier. */ const SedParameter* SedFunctionalRange::getParameter(const std::string& sid) const { return mParameters.get(sid); } /* * Adds a copy of the given SedParameter to this SedFunctionalRange. */ int SedFunctionalRange::addParameter(const SedParameter* sp) { if (sp == NULL) { return LIBSEDML_OPERATION_FAILED; } else if (sp->hasRequiredAttributes() == false) { return LIBSEDML_INVALID_OBJECT; } else if (getLevel() != sp->getLevel()) { return LIBSEDML_LEVEL_MISMATCH; } else if (getVersion() != sp->getVersion()) { return LIBSEDML_VERSION_MISMATCH; } else if (matchesRequiredSedNamespacesForAddition(static_cast<const SedBase*>(sp)) == false) { return LIBSEDML_NAMESPACES_MISMATCH; } else if (sp->isSetId() && (mParameters.get(sp->getId())) != NULL) { return LIBSEDML_DUPLICATE_OBJECT_ID; } else { return mParameters.append(sp); } } /* * Get the number of SedParameter objects in this SedFunctionalRange. */ unsigned int SedFunctionalRange::getNumParameters() const { return mParameters.size(); } /* * Creates a new SedParameter object, adds it to this SedFunctionalRange object * and returns the SedParameter object created. */ SedParameter* SedFunctionalRange::createParameter() { SedParameter* sp = NULL; try { sp = new SedParameter(getSedNamespaces()); } catch (...) { } if (sp != NULL) { mParameters.appendAndOwn(sp); } return sp; } /* * Removes the nth SedParameter from this SedFunctionalRange and returns a * pointer to it. */ SedParameter* SedFunctionalRange::removeParameter(unsigned int n) { return mParameters.remove(n); } /* * Removes the SedParameter from this SedFunctionalRange based on its * identifier and returns a pointer to it. */ SedParameter* SedFunctionalRange::removeParameter(const std::string& sid) { return mParameters.remove(sid); } /* * @copydoc doc_renamesidref_common */ void SedFunctionalRange::renameSIdRefs(const std::string& oldid, const std::string& newid) { if (isSetRange() && mRange == oldid) { setRange(newid); } if (isSetMath()) { mMath->renameSIdRefs(oldid, newid); } } /* * Returns the XML element name of this SedFunctionalRange object. */ const std::string& SedFunctionalRange::getElementName() const { static const string name = "functionalRange"; return name; } /* * Returns the libSEDML type code for this SedFunctionalRange object. */ int SedFunctionalRange::getTypeCode() const { return SEDML_RANGE_FUNCTIONALRANGE; } /* * Predicate returning @c true if all the required attributes for this * SedFunctionalRange object have been set. */ bool SedFunctionalRange::hasRequiredAttributes() const { bool allPresent = SedRange::hasRequiredAttributes(); if (isSetRange() == false) { allPresent = false; } return allPresent; } /* * Predicate returning @c true if all the required elements for this * SedFunctionalRange object have been set. */ bool SedFunctionalRange::hasRequiredElements() const { bool allPresent = SedRange::hasRequiredElements(); return allPresent; } /** @cond doxygenLibSEDMLInternal */ /* * Write any contained elements */ void SedFunctionalRange::writeElements(LIBSBML_CPP_NAMESPACE_QUALIFIER XMLOutputStream& stream) const { SedRange::writeElements(stream); if (isSetMath() == true) { writeMathML(getMath(), stream, NULL); } if (getNumVariables() > 0) { mVariables.write(stream); } if (getNumParameters() > 0) { mParameters.write(stream); } } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Accepts the given SedVisitor */ bool SedFunctionalRange::accept(SedVisitor& v) const { return false; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Sets the parent SedDocument */ void SedFunctionalRange::setSedDocument(SedDocument* d) { SedRange::setSedDocument(d); mVariables.setSedDocument(d); mParameters.setSedDocument(d); } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Connects to child elements */ void SedFunctionalRange::connectToChild() { SedRange::connectToChild(); mVariables.connectToParent(this); mParameters.connectToParent(this); } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Gets the value of the "attributeName" attribute of this SedFunctionalRange. */ int SedFunctionalRange::getAttribute(const std::string& attributeName, bool& value) const { int return_value = SedRange::getAttribute(attributeName, value); return return_value; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Gets the value of the "attributeName" attribute of this SedFunctionalRange. */ int SedFunctionalRange::getAttribute(const std::string& attributeName, int& value) const { int return_value = SedRange::getAttribute(attributeName, value); return return_value; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Gets the value of the "attributeName" attribute of this SedFunctionalRange. */ int SedFunctionalRange::getAttribute(const std::string& attributeName, double& value) const { int return_value = SedRange::getAttribute(attributeName, value); return return_value; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Gets the value of the "attributeName" attribute of this SedFunctionalRange. */ int SedFunctionalRange::getAttribute(const std::string& attributeName, unsigned int& value) const { int return_value = SedRange::getAttribute(attributeName, value); return return_value; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Gets the value of the "attributeName" attribute of this SedFunctionalRange. */ int SedFunctionalRange::getAttribute(const std::string& attributeName, std::string& value) const { int return_value = SedRange::getAttribute(attributeName, value); if (return_value == LIBSEDML_OPERATION_SUCCESS) { return return_value; } if (attributeName == "range") { value = getRange(); return_value = LIBSEDML_OPERATION_SUCCESS; } return return_value; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Predicate returning @c true if this SedFunctionalRange's attribute * "attributeName" is set. */ bool SedFunctionalRange::isSetAttribute(const std::string& attributeName) const { bool value = SedRange::isSetAttribute(attributeName); if (attributeName == "range") { value = isSetRange(); } return value; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Sets the value of the "attributeName" attribute of this SedFunctionalRange. */ int SedFunctionalRange::setAttribute(const std::string& attributeName, bool value) { int return_value = SedRange::setAttribute(attributeName, value); return return_value; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Sets the value of the "attributeName" attribute of this SedFunctionalRange. */ int SedFunctionalRange::setAttribute(const std::string& attributeName, int value) { int return_value = SedRange::setAttribute(attributeName, value); return return_value; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Sets the value of the "attributeName" attribute of this SedFunctionalRange. */ int SedFunctionalRange::setAttribute(const std::string& attributeName, double value) { int return_value = SedRange::setAttribute(attributeName, value); return return_value; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Sets the value of the "attributeName" attribute of this SedFunctionalRange. */ int SedFunctionalRange::setAttribute(const std::string& attributeName, unsigned int value) { int return_value = SedRange::setAttribute(attributeName, value); return return_value; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Sets the value of the "attributeName" attribute of this SedFunctionalRange. */ int SedFunctionalRange::setAttribute(const std::string& attributeName, const std::string& value) { int return_value = SedRange::setAttribute(attributeName, value); if (attributeName == "range") { return_value = setRange(value); } return return_value; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Unsets the value of the "attributeName" attribute of this * SedFunctionalRange. */ int SedFunctionalRange::unsetAttribute(const std::string& attributeName) { int value = SedRange::unsetAttribute(attributeName); if (attributeName == "range") { value = unsetRange(); } return value; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Creates and returns an new "elementName" object in this SedFunctionalRange. */ SedBase* SedFunctionalRange::createChildObject(const std::string& elementName) { SedRange* obj = NULL; if (elementName == "variable") { return createVariable(); } if (elementName == "parameter") { return createParameter(); } return obj; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Adds a new "elementName" object to this SedFunctionalRange. */ int SedFunctionalRange::addChildObject(const std::string& elementName, const SedBase* element) { if (elementName == "variable" && element->getTypeCode() == SEDML_VARIABLE) { return addVariable((const SedVariable*)(element)); } else if (elementName == "parameter" && element->getTypeCode() == SEDML_PARAMETER) { return addParameter((const SedParameter*)(element)); } return LIBSBML_OPERATION_FAILED; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Removes and returns the new "elementName" object with the given id in this * SedFunctionalRange. */ SedBase* SedFunctionalRange::removeChildObject(const std::string& elementName, const std::string& id) { if (elementName == "variable") { return removeVariable(id); } else if (elementName == "parameter") { return removeParameter(id); } return NULL; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Returns the number of "elementName" in this SedFunctionalRange. */ unsigned int SedFunctionalRange::getNumObjects(const std::string& elementName) { unsigned int n = 0; if (elementName == "variable") { return getNumVariables(); } else if (elementName == "parameter") { return getNumParameters(); } return n; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Returns the nth object of "objectName" in this SedFunctionalRange. */ SedBase* SedFunctionalRange::getObject(const std::string& elementName, unsigned int index) { SedBase* obj = NULL; if (elementName == "variable") { return getVariable(index); } else if (elementName == "parameter") { return getParameter(index); } return obj; } /** @endcond */ /* * Returns the first child element that has the given @p id in the model-wide * SId namespace, or @c NULL if no such object is found. */ SedBase* SedFunctionalRange::getElementBySId(const std::string& id) { if (id.empty()) { return NULL; } SedBase* obj = NULL; obj = mVariables.getElementBySId(id); if (obj != NULL) { return obj; } obj = mParameters.getElementBySId(id); if (obj != NULL) { return obj; } return obj; } /* * Returns a List of all child SedBase objects, including those nested to an * arbitrary depth. */ List* SedFunctionalRange::getAllElements(SedElementFilter* filter) { List* ret = new List(); List* sublist = NULL; SED_ADD_FILTERED_LIST(ret, sublist, mVariables, filter); SED_ADD_FILTERED_LIST(ret, sublist, mParameters, filter); return ret; } /** @cond doxygenLibSEDMLInternal */ /* * Creates a new object from the next XMLToken on the XMLInputStream */ SedBase* SedFunctionalRange::createObject(LIBSBML_CPP_NAMESPACE_QUALIFIER XMLInputStream& stream) { SedBase* obj = SedRange::createObject(stream); const std::string& name = stream.peek().getName(); if (name == "listOfVariables") { if (getErrorLog() && mVariables.size() != 0) { getErrorLog()->logError(SedmlFunctionalRangeAllowedElements, getLevel(), getVersion(), "", getLine(), getColumn()); } obj = &mVariables; } else if (name == "listOfParameters") { if (getErrorLog() && mParameters.size() != 0) { getErrorLog()->logError(SedmlFunctionalRangeAllowedElements, getLevel(), getVersion(), "", getLine(), getColumn()); } obj = &mParameters; } connectToChild(); return obj; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Adds the expected attributes for this element */ void SedFunctionalRange::addExpectedAttributes(LIBSBML_CPP_NAMESPACE_QUALIFIER ExpectedAttributes& attributes) { SedRange::addExpectedAttributes(attributes); attributes.add("range"); } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Reads the expected attributes into the member data variables */ void SedFunctionalRange::readAttributes( const LIBSBML_CPP_NAMESPACE_QUALIFIER XMLAttributes& attributes, const LIBSBML_CPP_NAMESPACE_QUALIFIER ExpectedAttributes& expectedAttributes) { unsigned int level = getLevel(); unsigned int version = getVersion(); unsigned int numErrs; bool assigned = false; SedErrorLog* log = getErrorLog(); SedRange::readAttributes(attributes, expectedAttributes); if (log) { numErrs = log->getNumErrors(); for (int n = numErrs-1; n >= 0; n--) { if (log->getError(n)->getErrorId() == SedUnknownCoreAttribute) { const std::string details = log->getError(n)->getMessage(); log->remove(SedUnknownCoreAttribute); log->logError(SedmlFunctionalRangeAllowedAttributes, level, version, details, getLine(), getColumn()); } } } // // range SIdRef (use = "required" ) // assigned = attributes.readInto("range", mRange); if (assigned == true) { if (mRange.empty() == true) { logEmptyString(mRange, level, version, "<SedFunctionalRange>"); } else if (SyntaxChecker::isValidSBMLSId(mRange) == false) { std::string msg = "The range attribute on the <" + getElementName() + ">"; if (isSetId()) { msg += " with id '" + getId() + "'"; } msg += " is '" + mRange + "', which does not conform to the syntax."; logError(SedmlFunctionalRangeRangeMustBeRange, level, version, msg, getLine(), getColumn()); } } else { if (log) { std::string message = "Sedml attribute 'range' is missing from the " "<SedFunctionalRange> element."; log->logError(SedmlFunctionalRangeAllowedAttributes, level, version, message, getLine(), getColumn()); } } } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Reads other XML such as math/notes etc. */ bool SedFunctionalRange::readOtherXML(LIBSBML_CPP_NAMESPACE_QUALIFIER XMLInputStream& stream) { bool read = false; const string& name = stream.peek().getName(); if (name == "math") { const LIBSBML_CPP_NAMESPACE_QUALIFIER XMLToken elem = stream.peek(); const std::string prefix = checkMathMLNamespace(elem); delete mMath; mMath = readMathML(stream, prefix); read = true; } if (SedRange::readOtherXML(stream)) { read = true; } return read; } /** @endcond */ /** @cond doxygenLibSEDMLInternal */ /* * Writes the attributes to the stream */ void SedFunctionalRange::writeAttributes(LIBSBML_CPP_NAMESPACE_QUALIFIER XMLOutputStream& stream) const { SedRange::writeAttributes(stream); if (isSetRange() == true) { stream.writeAttribute("range", getPrefix(), mRange); } } /** @endcond */ #endif /* __cplusplus */ /* * Creates a new SedFunctionalRange_t using the given SED-ML Level and @ p * version values. */ LIBSEDML_EXTERN SedFunctionalRange_t * SedFunctionalRange_create(unsigned int level, unsigned int version) { return new SedFunctionalRange(level, version); } /* * Creates and returns a deep copy of this SedFunctionalRange_t object. */ LIBSEDML_EXTERN SedFunctionalRange_t* SedFunctionalRange_clone(const SedFunctionalRange_t* sfr) { if (sfr != NULL) { return static_cast<SedFunctionalRange_t*>(sfr->clone()); } else { return NULL; } } /* * Frees this SedFunctionalRange_t object. */ LIBSEDML_EXTERN void SedFunctionalRange_free(SedFunctionalRange_t* sfr) { if (sfr != NULL) { delete sfr; } } /* * Returns the value of the "range" attribute of this SedFunctionalRange_t. */ LIBSEDML_EXTERN char * SedFunctionalRange_getRange(const SedFunctionalRange_t * sfr) { if (sfr == NULL) { return NULL; } return sfr->getRange().empty() ? NULL : safe_strdup(sfr->getRange().c_str()); } /* * Predicate returning @c 1 (true) if this SedFunctionalRange_t's "range" * attribute is set. */ LIBSEDML_EXTERN int SedFunctionalRange_isSetRange(const SedFunctionalRange_t * sfr) { return (sfr != NULL) ? static_cast<int>(sfr->isSetRange()) : 0; } /* * Sets the value of the "range" attribute of this SedFunctionalRange_t. */ LIBSEDML_EXTERN int SedFunctionalRange_setRange(SedFunctionalRange_t * sfr, const char * range) { return (sfr != NULL) ? sfr->setRange(range) : LIBSEDML_INVALID_OBJECT; } /* * Unsets the value of the "range" attribute of this SedFunctionalRange_t. */ LIBSEDML_EXTERN int SedFunctionalRange_unsetRange(SedFunctionalRange_t * sfr) { return (sfr != NULL) ? sfr->unsetRange() : LIBSEDML_INVALID_OBJECT; } /* * Returns the value of the "math" element of this SedFunctionalRange_t. */ LIBSEDML_EXTERN const LIBSBML_CPP_NAMESPACE_QUALIFIER ASTNode_t* SedFunctionalRange_getMath(const SedFunctionalRange_t * sfr) { if (sfr == NULL) { return NULL; } return (LIBSBML_CPP_NAMESPACE_QUALIFIER ASTNode_t*)(sfr->getMath()); } /* * Predicate returning @c 1 (true) if this SedFunctionalRange_t's "math" * element is set. */ LIBSEDML_EXTERN int SedFunctionalRange_isSetMath(const SedFunctionalRange_t * sfr) { return (sfr != NULL) ? static_cast<int>(sfr->isSetMath()) : 0; } /* * Sets the value of the "math" element of this SedFunctionalRange_t. */ LIBSEDML_EXTERN int SedFunctionalRange_setMath(SedFunctionalRange_t * sfr, const LIBSBML_CPP_NAMESPACE_QUALIFIER ASTNode_t* math) { return (sfr != NULL) ? sfr->setMath(math) : LIBSEDML_INVALID_OBJECT; } /* * Unsets the value of the "math" element of this SedFunctionalRange_t. */ LIBSEDML_EXTERN int SedFunctionalRange_unsetMath(SedFunctionalRange_t * sfr) { return (sfr != NULL) ? sfr->unsetMath() : LIBSEDML_INVALID_OBJECT; } /* * Returns a ListOf_t * containing SedVariable_t objects from this * SedFunctionalRange_t. */ LIBSEDML_EXTERN SedListOf_t* SedFunctionalRange_getListOfVariables(SedFunctionalRange_t* sfr) { return (sfr != NULL) ? sfr->getListOfVariables() : NULL; } /* * Get a SedVariable_t from the SedFunctionalRange_t. */ LIBSEDML_EXTERN SedVariable_t* SedFunctionalRange_getVariable(SedFunctionalRange_t* sfr, unsigned int n) { return (sfr != NULL) ? sfr->getVariable(n) : NULL; } /* * Get a SedVariable_t from the SedFunctionalRange_t based on its identifier. */ LIBSEDML_EXTERN SedVariable_t* SedFunctionalRange_getVariableById(SedFunctionalRange_t* sfr, const char *sid) { return (sfr != NULL && sid != NULL) ? sfr->getVariable(sid) : NULL; } /* * Get a SedVariable_t from the SedFunctionalRange_t based on the TaskReference * to which it refers. */ LIBSEDML_EXTERN SedVariable_t* SedFunctionalRange_getVariableByTaskReference(SedFunctionalRange_t* sfr, const char *sid) { return (sfr != NULL && sid != NULL) ? sfr->getVariableByTaskReference(sid) : NULL; } /* * Get a SedVariable_t from the SedFunctionalRange_t based on the * ModelReference to which it refers. */ LIBSEDML_EXTERN SedVariable_t* SedFunctionalRange_getVariableByModelReference(SedFunctionalRange_t* sfr, const char *sid) { return (sfr != NULL && sid != NULL) ? sfr->getVariableByModelReference(sid) : NULL; } /* * Adds a copy of the given SedVariable_t to this SedFunctionalRange_t. */ LIBSEDML_EXTERN int SedFunctionalRange_addVariable(SedFunctionalRange_t* sfr, const SedVariable_t* sv) { return (sfr != NULL) ? sfr->addVariable(sv) : LIBSEDML_INVALID_OBJECT; } /* * Get the number of SedVariable_t objects in this SedFunctionalRange_t. */ LIBSEDML_EXTERN unsigned int SedFunctionalRange_getNumVariables(SedFunctionalRange_t* sfr) { return (sfr != NULL) ? sfr->getNumVariables() : SEDML_INT_MAX; } /* * Creates a new SedVariable_t object, adds it to this SedFunctionalRange_t * object and returns the SedVariable_t object created. */ LIBSEDML_EXTERN SedVariable_t* SedFunctionalRange_createVariable(SedFunctionalRange_t* sfr) { return (sfr != NULL) ? sfr->createVariable() : NULL; } /* * Removes the nth SedVariable_t from this SedFunctionalRange_t and returns a * pointer to it. */ LIBSEDML_EXTERN SedVariable_t* SedFunctionalRange_removeVariable(SedFunctionalRange_t* sfr, unsigned int n) { return (sfr != NULL) ? sfr->removeVariable(n) : NULL; } /* * Removes the SedVariable_t from this SedFunctionalRange_t based on its * identifier and returns a pointer to it. */ LIBSEDML_EXTERN SedVariable_t* SedFunctionalRange_removeVariableById(SedFunctionalRange_t* sfr, const char* sid) { return (sfr != NULL && sid != NULL) ? sfr->removeVariable(sid) : NULL; } /* * Returns a ListOf_t * containing SedParameter_t objects from this * SedFunctionalRange_t. */ LIBSEDML_EXTERN SedListOf_t* SedFunctionalRange_getListOfParameters(SedFunctionalRange_t* sfr) { return (sfr != NULL) ? sfr->getListOfParameters() : NULL; } /* * Get a SedParameter_t from the SedFunctionalRange_t. */ LIBSEDML_EXTERN SedParameter_t* SedFunctionalRange_getParameter(SedFunctionalRange_t* sfr, unsigned int n) { return (sfr != NULL) ? sfr->getParameter(n) : NULL; } /* * Get a SedParameter_t from the SedFunctionalRange_t based on its identifier. */ LIBSEDML_EXTERN SedParameter_t* SedFunctionalRange_getParameterById(SedFunctionalRange_t* sfr, const char *sid) { return (sfr != NULL && sid != NULL) ? sfr->getParameter(sid) : NULL; } /* * Adds a copy of the given SedParameter_t to this SedFunctionalRange_t. */ LIBSEDML_EXTERN int SedFunctionalRange_addParameter(SedFunctionalRange_t* sfr, const SedParameter_t* sp) { return (sfr != NULL) ? sfr->addParameter(sp) : LIBSEDML_INVALID_OBJECT; } /* * Get the number of SedParameter_t objects in this SedFunctionalRange_t. */ LIBSEDML_EXTERN unsigned int SedFunctionalRange_getNumParameters(SedFunctionalRange_t* sfr) { return (sfr != NULL) ? sfr->getNumParameters() : SEDML_INT_MAX; } /* * Creates a new SedParameter_t object, adds it to this SedFunctionalRange_t * object and returns the SedParameter_t object created. */ LIBSEDML_EXTERN SedParameter_t* SedFunctionalRange_createParameter(SedFunctionalRange_t* sfr) { return (sfr != NULL) ? sfr->createParameter() : NULL; } /* * Removes the nth SedParameter_t from this SedFunctionalRange_t and returns a * pointer to it. */ LIBSEDML_EXTERN SedParameter_t* SedFunctionalRange_removeParameter(SedFunctionalRange_t* sfr, unsigned int n) { return (sfr != NULL) ? sfr->removeParameter(n) : NULL; } /* * Removes the SedParameter_t from this SedFunctionalRange_t based on its * identifier and returns a pointer to it. */ LIBSEDML_EXTERN SedParameter_t* SedFunctionalRange_removeParameterById(SedFunctionalRange_t* sfr, const char* sid) { return (sfr != NULL && sid != NULL) ? sfr->removeParameter(sid) : NULL; } /* * Predicate returning @c 1 (true) if all the required attributes for this * SedFunctionalRange_t object have been set. */ LIBSEDML_EXTERN int SedFunctionalRange_hasRequiredAttributes(const SedFunctionalRange_t * sfr) { return (sfr != NULL) ? static_cast<int>(sfr->hasRequiredAttributes()) : 0; } /* * Predicate returning @c 1 (true) if all the required elements for this * SedFunctionalRange_t object have been set. */ LIBSEDML_EXTERN int SedFunctionalRange_hasRequiredElements(const SedFunctionalRange_t * sfr) { return (sfr != NULL) ? static_cast<int>(sfr->hasRequiredElements()) : 0; } LIBSEDML_CPP_NAMESPACE_END
35,534
12,083
/* Copyright (c) 2008-present Advanced Micro Devices, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <mutex> #if defined(USE_COMGR_LIBRARY) #include "top.hpp" #include "amd_comgr.h" namespace amd { typedef void (*t_amd_comgr_get_version)(size_t *major, size_t *minor); typedef amd_comgr_status_t (*t_amd_comgr_status_string)(amd_comgr_status_t status, const char ** status_string); typedef amd_comgr_status_t (*t_amd_comgr_get_isa_count)(size_t *count); typedef amd_comgr_status_t (*t_amd_comgr_get_isa_name)(size_t index, const char **isa_name); typedef amd_comgr_status_t (*t_amd_comgr_get_isa_metadata)(const char *isa_name, amd_comgr_metadata_node_t *metadata); typedef amd_comgr_status_t (*t_amd_comgr_create_data)(amd_comgr_data_kind_t kind, amd_comgr_data_t *data); typedef amd_comgr_status_t (*t_amd_comgr_release_data)(amd_comgr_data_t data); typedef amd_comgr_status_t (*t_amd_comgr_get_data_kind)(amd_comgr_data_t data, amd_comgr_data_kind_t *kind); typedef amd_comgr_status_t (*t_amd_comgr_set_data)(amd_comgr_data_t data, size_t size, const char* bytes); typedef amd_comgr_status_t (*t_amd_comgr_set_data_name)(amd_comgr_data_t data, const char* name); typedef amd_comgr_status_t (*t_amd_comgr_get_data)(amd_comgr_data_t data, size_t *size, char *bytes); typedef amd_comgr_status_t (*t_amd_comgr_get_data_name)(amd_comgr_data_t data, size_t *size, char *name); typedef amd_comgr_status_t (*t_amd_comgr_get_data_isa_name)(amd_comgr_data_t data, size_t *size, char *isa_name); typedef amd_comgr_status_t (*t_amd_comgr_get_data_metadata)(amd_comgr_data_t data, amd_comgr_metadata_node_t *metadata); typedef amd_comgr_status_t (*t_amd_comgr_destroy_metadata)(amd_comgr_metadata_node_t metadata); typedef amd_comgr_status_t (*t_amd_comgr_create_data_set)(amd_comgr_data_set_t *data_set); typedef amd_comgr_status_t (*t_amd_comgr_destroy_data_set)(amd_comgr_data_set_t data_set); typedef amd_comgr_status_t (*t_amd_comgr_data_set_add)(amd_comgr_data_set_t data_set, amd_comgr_data_t data); typedef amd_comgr_status_t (*t_amd_comgr_data_set_remove)(amd_comgr_data_set_t data_set, amd_comgr_data_kind_t data_kind); typedef amd_comgr_status_t (*t_amd_comgr_action_data_count)(amd_comgr_data_set_t data_set, amd_comgr_data_kind_t data_kind, size_t *count); typedef amd_comgr_status_t (*t_amd_comgr_action_data_get_data)(amd_comgr_data_set_t data_set, amd_comgr_data_kind_t data_kind, size_t index, amd_comgr_data_t *data); typedef amd_comgr_status_t (*t_amd_comgr_create_action_info)(amd_comgr_action_info_t *action_info); typedef amd_comgr_status_t (*t_amd_comgr_destroy_action_info)(amd_comgr_action_info_t action_info); typedef amd_comgr_status_t (*t_amd_comgr_action_info_set_isa_name)(amd_comgr_action_info_t action_info, const char *isa_name); typedef amd_comgr_status_t (*t_amd_comgr_action_info_get_isa_name)(amd_comgr_action_info_t action_info, size_t *size, char *isa_name); typedef amd_comgr_status_t (*t_amd_comgr_action_info_set_language)(amd_comgr_action_info_t action_info, amd_comgr_language_t language); typedef amd_comgr_status_t (*t_amd_comgr_action_info_get_language)(amd_comgr_action_info_t action_info, amd_comgr_language_t *language); typedef amd_comgr_status_t (*t_amd_comgr_action_info_set_option_list)(amd_comgr_action_info_t action_info, const char *options[], size_t count); typedef amd_comgr_status_t (*t_amd_comgr_action_info_get_option_list_count)(amd_comgr_action_info_t action_info, size_t *count); typedef amd_comgr_status_t (*t_amd_comgr_action_info_get_option_list_item)(amd_comgr_action_info_t action_info, size_t index, size_t *size, char *option); typedef amd_comgr_status_t (*t_amd_comgr_action_info_set_working_directory_path)(amd_comgr_action_info_t action_info, const char *path); typedef amd_comgr_status_t (*t_amd_comgr_action_info_get_working_directory_path)(amd_comgr_action_info_t action_info, size_t *size, char *path); typedef amd_comgr_status_t (*t_amd_comgr_action_info_set_logging)(amd_comgr_action_info_t action_info, bool logging); typedef amd_comgr_status_t (*t_amd_comgr_action_info_get_logging)(amd_comgr_action_info_t action_info, bool *logging); typedef amd_comgr_status_t (*t_amd_comgr_do_action)(amd_comgr_action_kind_t kind, amd_comgr_action_info_t info, amd_comgr_data_set_t input, amd_comgr_data_set_t result); typedef amd_comgr_status_t (*t_amd_comgr_get_metadata_kind)(amd_comgr_metadata_node_t metadata, amd_comgr_metadata_kind_t *kind); typedef amd_comgr_status_t (*t_amd_comgr_get_metadata_string)(amd_comgr_metadata_node_t metadata, size_t *size, char *string); typedef amd_comgr_status_t (*t_amd_comgr_get_metadata_map_size)(amd_comgr_metadata_node_t metadata, size_t *size); typedef amd_comgr_status_t (*t_amd_comgr_iterate_map_metadata)(amd_comgr_metadata_node_t metadata, amd_comgr_status_t(*callback)(amd_comgr_metadata_node_t key, amd_comgr_metadata_node_t value, void *user_data), void *user_data); typedef amd_comgr_status_t (*t_amd_comgr_metadata_lookup)(amd_comgr_metadata_node_t metadata, const char *key, amd_comgr_metadata_node_t *value); typedef amd_comgr_status_t (*t_amd_comgr_get_metadata_list_size)(amd_comgr_metadata_node_t metadata, size_t *size); typedef amd_comgr_status_t (*t_amd_comgr_index_list_metadata)(amd_comgr_metadata_node_t metadata, size_t index, amd_comgr_metadata_node_t *value); typedef amd_comgr_status_t (*t_amd_comgr_iterate_symbols)(amd_comgr_data_t data, amd_comgr_status_t(*callback)(amd_comgr_symbol_t symbol, void *user_data), void *user_data); typedef amd_comgr_status_t (*t_amd_comgr_symbol_lookup)(amd_comgr_data_t data, const char *name, amd_comgr_symbol_t *symbol); typedef amd_comgr_status_t (*t_amd_comgr_symbol_get_info)(amd_comgr_symbol_t symbol, amd_comgr_symbol_info_t attribute, void *value); struct ComgrEntryPoints { void* handle; t_amd_comgr_get_version amd_comgr_get_version; t_amd_comgr_status_string amd_comgr_status_string; t_amd_comgr_get_isa_count amd_comgr_get_isa_count; t_amd_comgr_get_isa_name amd_comgr_get_isa_name; t_amd_comgr_get_isa_metadata amd_comgr_get_isa_metadata; t_amd_comgr_create_data amd_comgr_create_data; t_amd_comgr_release_data amd_comgr_release_data; t_amd_comgr_get_data_kind amd_comgr_get_data_kind; t_amd_comgr_set_data amd_comgr_set_data; t_amd_comgr_set_data_name amd_comgr_set_data_name; t_amd_comgr_get_data amd_comgr_get_data; t_amd_comgr_get_data_name amd_comgr_get_data_name; t_amd_comgr_get_data_isa_name amd_comgr_get_data_isa_name; t_amd_comgr_get_data_metadata amd_comgr_get_data_metadata; t_amd_comgr_destroy_metadata amd_comgr_destroy_metadata; t_amd_comgr_create_data_set amd_comgr_create_data_set; t_amd_comgr_destroy_data_set amd_comgr_destroy_data_set; t_amd_comgr_data_set_add amd_comgr_data_set_add; t_amd_comgr_data_set_remove amd_comgr_data_set_remove; t_amd_comgr_action_data_count amd_comgr_action_data_count; t_amd_comgr_action_data_get_data amd_comgr_action_data_get_data; t_amd_comgr_create_action_info amd_comgr_create_action_info; t_amd_comgr_destroy_action_info amd_comgr_destroy_action_info; t_amd_comgr_action_info_set_isa_name amd_comgr_action_info_set_isa_name; t_amd_comgr_action_info_get_isa_name amd_comgr_action_info_get_isa_name; t_amd_comgr_action_info_set_language amd_comgr_action_info_set_language; t_amd_comgr_action_info_get_language amd_comgr_action_info_get_language; t_amd_comgr_action_info_set_option_list amd_comgr_action_info_set_option_list; t_amd_comgr_action_info_get_option_list_count amd_comgr_action_info_get_option_list_count; t_amd_comgr_action_info_get_option_list_item amd_comgr_action_info_get_option_list_item; t_amd_comgr_action_info_set_working_directory_path amd_comgr_action_info_set_working_directory_path; t_amd_comgr_action_info_get_working_directory_path amd_comgr_action_info_get_working_directory_path; t_amd_comgr_action_info_set_logging amd_comgr_action_info_set_logging; t_amd_comgr_action_info_get_logging amd_comgr_action_info_get_logging; t_amd_comgr_do_action amd_comgr_do_action; t_amd_comgr_get_metadata_kind amd_comgr_get_metadata_kind; t_amd_comgr_get_metadata_string amd_comgr_get_metadata_string; t_amd_comgr_get_metadata_map_size amd_comgr_get_metadata_map_size; t_amd_comgr_iterate_map_metadata amd_comgr_iterate_map_metadata; t_amd_comgr_metadata_lookup amd_comgr_metadata_lookup; t_amd_comgr_get_metadata_list_size amd_comgr_get_metadata_list_size; t_amd_comgr_index_list_metadata amd_comgr_index_list_metadata; t_amd_comgr_iterate_symbols amd_comgr_iterate_symbols; t_amd_comgr_symbol_lookup amd_comgr_symbol_lookup; t_amd_comgr_symbol_get_info amd_comgr_symbol_get_info; }; #ifdef COMGR_DYN_DLL #define COMGR_DYN(NAME) cep_.NAME #define GET_COMGR_SYMBOL(NAME) cep_.NAME = \ reinterpret_cast<t_##NAME>(Os::getSymbol(cep_.handle, #NAME)); \ if (nullptr == cep_.NAME) { return false; } #else #define COMGR_DYN(NAME) NAME #define GET_COMGR_SYMBOL(NAME) #endif class Comgr : public amd::AllStatic { public: static std::once_flag initialized; static bool LoadLib(); static bool IsReady() { return is_ready_; } static void get_version(size_t *major, size_t *minor) { COMGR_DYN(amd_comgr_get_version)(major, minor); } static amd_comgr_status_t status_string(amd_comgr_status_t status, const char ** status_string) { return COMGR_DYN(amd_comgr_status_string)(status, status_string); } static amd_comgr_status_t get_isa_count(size_t *count) { return COMGR_DYN(amd_comgr_get_isa_count)(count); } static amd_comgr_status_t get_isa_name(size_t index, const char **isa_name) { return COMGR_DYN(amd_comgr_get_isa_name)(index, isa_name); } static amd_comgr_status_t get_isa_metadata(const char *isa_name, amd_comgr_metadata_node_t *metadata) { return COMGR_DYN(amd_comgr_get_isa_metadata)(isa_name, metadata); } static amd_comgr_status_t create_data(amd_comgr_data_kind_t kind, amd_comgr_data_t *data) { return COMGR_DYN(amd_comgr_create_data)(kind, data); } static amd_comgr_status_t release_data(amd_comgr_data_t data) { return COMGR_DYN(amd_comgr_release_data)(data); } static amd_comgr_status_t get_data_kind(amd_comgr_data_t data, amd_comgr_data_kind_t *kind) { return COMGR_DYN(amd_comgr_get_data_kind)(data, kind); } static amd_comgr_status_t set_data(amd_comgr_data_t data, size_t size, const char* bytes) { return COMGR_DYN(amd_comgr_set_data)(data, size, bytes); } static amd_comgr_status_t set_data_name(amd_comgr_data_t data, const char* name) { return COMGR_DYN(amd_comgr_set_data_name)(data, name); } static amd_comgr_status_t get_data(amd_comgr_data_t data, size_t *size, char *bytes) { return COMGR_DYN(amd_comgr_get_data)(data, size, bytes); } static amd_comgr_status_t get_data_name(amd_comgr_data_t data, size_t *size, char *name) { return COMGR_DYN(amd_comgr_get_data_name)(data, size, name); } static amd_comgr_status_t get_data_isa_name(amd_comgr_data_t data, size_t *size, char *isa_name) { return COMGR_DYN(amd_comgr_get_data_isa_name)(data, size, isa_name); } static amd_comgr_status_t get_data_metadata(amd_comgr_data_t data, amd_comgr_metadata_node_t *metadata) { return COMGR_DYN(amd_comgr_get_data_metadata)(data, metadata); } static amd_comgr_status_t destroy_metadata(amd_comgr_metadata_node_t metadata) { return COMGR_DYN(amd_comgr_destroy_metadata)(metadata); } static amd_comgr_status_t create_data_set(amd_comgr_data_set_t *data_set) { return COMGR_DYN(amd_comgr_create_data_set)(data_set); } static amd_comgr_status_t destroy_data_set(amd_comgr_data_set_t data_set) { return COMGR_DYN(amd_comgr_destroy_data_set)(data_set); } static amd_comgr_status_t data_set_add(amd_comgr_data_set_t data_set, amd_comgr_data_t data) { return COMGR_DYN(amd_comgr_data_set_add)(data_set, data); } static amd_comgr_status_t data_set_remove(amd_comgr_data_set_t data_set, amd_comgr_data_kind_t data_kind) { return COMGR_DYN(amd_comgr_data_set_remove)(data_set, data_kind); } static amd_comgr_status_t action_data_count(amd_comgr_data_set_t data_set, amd_comgr_data_kind_t data_kind, size_t *count) { return COMGR_DYN(amd_comgr_action_data_count)(data_set, data_kind, count); } static amd_comgr_status_t action_data_get_data(amd_comgr_data_set_t data_set, amd_comgr_data_kind_t data_kind, size_t index, amd_comgr_data_t *data) { return COMGR_DYN(amd_comgr_action_data_get_data)(data_set, data_kind, index, data); } static amd_comgr_status_t create_action_info(amd_comgr_action_info_t *action_info) { return COMGR_DYN(amd_comgr_create_action_info)(action_info); } static amd_comgr_status_t destroy_action_info(amd_comgr_action_info_t action_info) { return COMGR_DYN(amd_comgr_destroy_action_info)(action_info); } static amd_comgr_status_t action_info_set_isa_name(amd_comgr_action_info_t action_info, const char *isa_name) { return COMGR_DYN(amd_comgr_action_info_set_isa_name)(action_info, isa_name); } static amd_comgr_status_t action_info_get_isa_name(amd_comgr_action_info_t action_info, size_t *size, char *isa_name) { return COMGR_DYN(amd_comgr_action_info_get_isa_name)(action_info, size, isa_name); } static amd_comgr_status_t action_info_set_language(amd_comgr_action_info_t action_info, amd_comgr_language_t language) { return COMGR_DYN(amd_comgr_action_info_set_language)(action_info, language); } static amd_comgr_status_t action_info_get_language(amd_comgr_action_info_t action_info, amd_comgr_language_t *language) { return COMGR_DYN(amd_comgr_action_info_get_language)(action_info, language); } static amd_comgr_status_t action_info_set_option_list(amd_comgr_action_info_t action_info, const char *options[], size_t count) { return COMGR_DYN(amd_comgr_action_info_set_option_list)(action_info, options, count); } static amd_comgr_status_t action_info_get_option_list_count(amd_comgr_action_info_t action_info, size_t *count) { return COMGR_DYN(amd_comgr_action_info_get_option_list_count)(action_info, count); } static amd_comgr_status_t action_info_get_option_list_item(amd_comgr_action_info_t action_info, size_t index, size_t *size, char *option) { return COMGR_DYN(amd_comgr_action_info_get_option_list_item)(action_info, index, size, option); } static amd_comgr_status_t action_info_set_working_directory_path(amd_comgr_action_info_t action_info, const char *path) { return COMGR_DYN(amd_comgr_action_info_set_working_directory_path)(action_info, path); } static amd_comgr_status_t action_info_get_working_directory_path(amd_comgr_action_info_t action_info, size_t *size, char *path) { return COMGR_DYN(amd_comgr_action_info_get_working_directory_path)(action_info, size, path); } static amd_comgr_status_t action_info_set_logging(amd_comgr_action_info_t action_info, bool logging) { return COMGR_DYN(amd_comgr_action_info_set_logging)(action_info, logging); } static amd_comgr_status_t action_info_get_logging(amd_comgr_action_info_t action_info, bool *logging) { return COMGR_DYN(amd_comgr_action_info_get_logging)(action_info, logging); } static amd_comgr_status_t do_action(amd_comgr_action_kind_t kind, amd_comgr_action_info_t info, amd_comgr_data_set_t input, amd_comgr_data_set_t result) { return COMGR_DYN(amd_comgr_do_action)(kind, info, input, result); } static amd_comgr_status_t get_metadata_kind(amd_comgr_metadata_node_t metadata, amd_comgr_metadata_kind_t *kind) { return COMGR_DYN(amd_comgr_get_metadata_kind)(metadata, kind); } static amd_comgr_status_t get_metadata_string(amd_comgr_metadata_node_t metadata, size_t *size, char *string) { return COMGR_DYN(amd_comgr_get_metadata_string)(metadata, size, string); } static amd_comgr_status_t get_metadata_map_size(amd_comgr_metadata_node_t metadata, size_t *size) { return COMGR_DYN(amd_comgr_get_metadata_map_size)(metadata, size); } static amd_comgr_status_t iterate_map_metadata(amd_comgr_metadata_node_t metadata, amd_comgr_status_t(*callback)(amd_comgr_metadata_node_t key, amd_comgr_metadata_node_t value, void *user_data), void *user_data) { return COMGR_DYN(amd_comgr_iterate_map_metadata)(metadata, callback, user_data); } static amd_comgr_status_t metadata_lookup(amd_comgr_metadata_node_t metadata, const char *key, amd_comgr_metadata_node_t *value) { return COMGR_DYN(amd_comgr_metadata_lookup)(metadata, key, value); } static amd_comgr_status_t get_metadata_list_size(amd_comgr_metadata_node_t metadata, size_t *size) { return COMGR_DYN(amd_comgr_get_metadata_list_size)(metadata, size); } static amd_comgr_status_t index_list_metadata(amd_comgr_metadata_node_t metadata, size_t index, amd_comgr_metadata_node_t *value) { return COMGR_DYN(amd_comgr_index_list_metadata)(metadata, index, value); } static amd_comgr_status_t iterate_symbols(amd_comgr_data_t data, amd_comgr_status_t(*callback)(amd_comgr_symbol_t symbol, void *user_data), void *user_data) { return COMGR_DYN(amd_comgr_iterate_symbols)(data, callback, user_data); } static amd_comgr_status_t symbol_lookup(amd_comgr_data_t data, const char *name, amd_comgr_symbol_t *symbol) { return COMGR_DYN(amd_comgr_symbol_lookup)(data, name, symbol); } static amd_comgr_status_t symbol_get_info(amd_comgr_symbol_t symbol, amd_comgr_symbol_info_t attribute, void *value) { return COMGR_DYN(amd_comgr_symbol_get_info)(symbol, attribute, value); } private: static ComgrEntryPoints cep_; static bool is_ready_; }; } #endif
18,883
7,522
//+--------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation, 1998. // // File: EDUTIL.CXX // // Contents: Utility functions for CMsHtmled // // History: 15-Jan-98 raminh Created // // Notes: This file contains some utility functions from Trident, // such as LoadLibrary, which have been modified to eliminate // dependencies. In addition, it provides the implementation // for editing commands such as InsertObject etc. //------------------------------------------------------------------------ #include "headers.hxx" #pragma MARK_DATA(__FILE__) #pragma MARK_CODE(__FILE__) #pragma MARK_CONST(__FILE__) #ifndef X_SLOAD_HXX_ #define X_SLOAD_HXX_ #include "sload.hxx" #endif #ifndef X_EDEVENT_HXX_ #define X_EDEVENT_HXX_ #include "edevent.hxx" #endif #ifndef X_EDUTIL_HXX_ #define X_EDUTIL_HXX_ #include "edutil.hxx" #endif #ifndef X_EDCMD_HXX_ #define X_EDCMD_HXX_ #include "edcmd.hxx" #endif #ifndef X_BLOCKCMD_HXX_ #define X_BLOCKCMD_HXX_ #include "blockcmd.hxx" #endif #ifndef X_SELMAN_HXX_ #define X_SELMAN_HXX_ #include "selman.hxx" #endif #ifndef X_EDUNDO_HXX_ #define X_EDUNDO_HXX_ #include "edundo.hxx" #endif #ifndef X_INPUTTXT_H_ #define X_INPUTTXT_H_ #include "inputtxt.h" #endif #ifndef X_TEXTAREA_H_ #define X_TEXTAREA_H_ #include "textarea.h" #endif #ifndef X_SELSERV_HXX_ #define X_SELSERV_HXX_ #include "selserv.hxx" #endif using namespace EdUtil; using namespace MshtmledUtil; DYNLIB g_dynlibSHDOCVW = { NULL, NULL, "SHDOCVW.DLL" }; // This line is required for linking with wrappers.lib LCID g_lcidUserDefault = 0; // Required for linking with formsary.obj #if DBG == 1 && !defined(WIN16) // // Global vars for use by the DYNCAST macro // char g_achDynCastMsg[200]; char *g_pszDynMsg = "Invalid Static Cast -- Attempt to cast object " "of type %s to type %s."; char *g_pszDynMsg2 = "Dynamic Cast Attempted --- " "Attempt to cast between two base classes of %s. " "The cast was to class %s from some other base class " "pointer. This cast will not succeed in a retail build."; #endif static DYNLIB * s_pdynlibHead; // List used by LoadProcedure and DeiIntDynamic libraries // // Forward references // int edWsprintf(LPTSTR pstrOut, LPCTSTR pstrFormat, LPCTSTR pstrParam); HRESULT GetLastWin32Error(); void DeinitDynamicLibraries(); HRESULT DoInsertObjectUI (HWND hwnd, DWORD * pdwResult, LPTSTR * pstrResult); HRESULT CreateHtmlFromIDM (UINT cmd, LPTSTR pstrParam, LPTSTR pstrHtml); //+------------------------------------------------------------------------ // // Function: ReleaseInterface // // Synopsis: Releases an interface pointer if it is non-NULL // // Arguments: [pUnk] // //------------------------------------------------------------------------- void ReleaseInterface(IUnknown * pUnk) { if (pUnk) pUnk->Release(); } //+------------------------------------------------------------------------ // // Function: edNlstrlenW // // Synopsis: This function takes a string and count the characters (WCHAR) // contained in that string until either NULL termination is // encountered or cchLimit is reached. // // Returns: Number of characters in pstrIn // //------------------------------------------------------------------------- LONG edNlstrlenW(LPWSTR pstrIn, LONG cchLimit ) { Assert(pstrIn); Assert(cchLimit >= 0); LONG cchCount = 0; while (*pstrIn && cchLimit) { cchCount ++; cchLimit --; ++pstrIn; } return cchCount; } //+------------------------------------------------------------------------ // // Function: edWsprintf // // Synopsis: This function is a replacement for a simple version of sprintf. // Since using Format() links in a lot of extra code and since // wsprintf does not work under Win95, this simple alternative // is being used. // // Returns: Number of characters written to pstrOut // //------------------------------------------------------------------------- int edWsprintf(LPTSTR pstrOut, LPCTSTR pstrFormat, LPCTSTR pstrParam) { TCHAR * pstrPercentS; ULONG cLength; if (!pstrFormat) goto Cleanup; pstrPercentS = _tcsstr( pstrFormat, _T( "%s" ) ); if (!pstrPercentS) { _tcscpy( pstrOut, pstrFormat ); } else { if (!pstrParam) goto Cleanup; cLength = PTR_DIFF( pstrPercentS, pstrFormat ); _tcsncpy( pstrOut, pstrFormat, cLength ); pstrOut[ cLength ] = _T( '\0' ); ++pstrPercentS; ++pstrPercentS; // Increment pstrPercentS passed "%s" _tcscat( pstrOut, pstrParam ); _tcscat( pstrOut, pstrPercentS ); } return _tcslen(pstrOut); Cleanup: return 0; } //+------------------------------------------------------------------------ // // Function: GetLastWin32Error from misc.cxx // // Synopsis: Returns the last Win32 error, converted to an HRESULT. // // Returns: HRESULT // //------------------------------------------------------------------------- HRESULT GetLastWin32Error( ) { #ifdef WIN16 return E_FAIL; #else // Win 95 can return 0, even when there's an error. DWORD dw = GetLastError(); return dw ? HRESULT_FROM_WIN32(dw) : E_FAIL; #endif } //+--------------------------------------------------------------------------- // // Function: LoadProcedure // // Synopsis: Load library and get address of procedure. // // Declare DYNLIB and DYNPROC globals describing the procedure. // Note that several DYNPROC structures can point to a single // DYNLIB structure. // // DYNLIB g_dynlibOLEDLG = { NULL, "OLEDLG.DLL" }; // DYNPROC g_dynprocOleUIInsertObjectA = // { NULL, &g_dynlibOLEDLG, "OleUIInsertObjectA" }; // DYNPROC g_dynprocOleUIPasteSpecialA = // { NULL, &g_dynlibOLEDLG, "OleUIPasteSpecialA" }; // // Call LoadProcedure to load the library and get the procedure // address. LoadProcedure returns immediatly if the procedure // has already been loaded. // // hr = LoadProcedure(&g_dynprocOLEUIInsertObjectA); // if (hr) // goto Error; // // uiResult = (*(UINT (__stdcall *)(LPOLEUIINSERTOBJECTA)) // g_dynprocOLEUIInsertObjectA.pfn)(&ouiio); // // Release the library at shutdown. // // void DllProcessDetach() // { // DeinitDynamicLibraries(); // } // // Arguments: pdynproc Descrition of library and procedure to load. // // Returns: HRESULT // //---------------------------------------------------------------------------- HRESULT LoadProcedure(DYNPROC *pdynproc) { HINSTANCE hinst; DYNLIB * pdynlib = pdynproc->pdynlib; DWORD dwError; if (pdynproc->pfn && pdynlib->hinst) return S_OK; if (!pdynlib->hinst) { // Try to load the library using the normal mechanism. hinst = LoadLibraryA(pdynlib->achName); #ifdef WINCE if (!hinst) { goto Error; } #endif // WINCE #ifdef WIN16 if ( (UINT) hinst < 32 ) { // jumping to error won't work, // since GetLastError is currently always 0. //goto Error; // instead, return a bogus (but non-zero) error code. // (What should we return? I got 0x7e on one test.) // --mblain27feb97 RRETURN(hinst ? (DWORD) hinst : (DWORD) ~0); } #endif // WIN16 #if !defined(WIN16) && !defined(WINCE) // If that failed because the module was not be found, // then try to find the module in the directory we were // loaded from. dwError = GetLastError(); if (!hinst) { goto Error; } #endif // !defined(WIN16) && !defined(WINCE) // Link into list for DeinitDynamicLibraries { if (pdynlib->hinst) FreeLibrary(hinst); else { pdynlib->hinst = hinst; pdynlib->pdynlibNext = s_pdynlibHead; s_pdynlibHead = pdynlib; } } } pdynproc->pfn = GetProcAddress(pdynlib->hinst, pdynproc->achName); if (!pdynproc->pfn) { goto Error; } return S_OK; Error: RRETURN(GetLastWin32Error()); } //+--------------------------------------------------------------------------- // // Function: DeinitDynamicLibraries // // Synopsis: Undoes the work of LoadProcedure. // //---------------------------------------------------------------------------- void DeinitDynamicLibraries() { DYNLIB * pdynlib; for (pdynlib = s_pdynlibHead; pdynlib; pdynlib = pdynlib->pdynlibNext) { if (pdynlib->hinst) { FreeLibrary(pdynlib->hinst); pdynlib->hinst = NULL; } } s_pdynlibHead = NULL; } // // EnumElements() and EnumVARIANT() are methods of CImplAry class that are // implemented in cenum.cxx. MshtmlEd does not currently use these methods // hence the stubs below are provided to avoid linking code unnecessarily. // If these methods are ever used, MshtmlEd shall link with cenum.cxx. // //+--------------------------------------------------------------------------- // // Member: CImplAry::EnumElements // //---------------------------------------------------------------------------- HRESULT CImplAry::EnumElements( size_t cb, REFIID iid, void ** ppv, BOOL fAddRef, BOOL fCopy, BOOL fDelete) { return E_NOTIMPL; } //+--------------------------------------------------------------------------- // // Member: CImplAry::EnumVARIANT // //---------------------------------------------------------------------------- HRESULT CImplAry::EnumVARIANT( size_t cb, VARTYPE vt, IEnumVARIANT ** ppenum, BOOL fCopy, BOOL fDelete) { return E_NOTIMPL; } //+------------------------------------------------------------------------ // // Function: ReplaceInterfaceFn // // Synopsis: Replaces an interface pointer with a new interface, // following proper ref counting rules: // // = *ppUnk is set to pUnk // = if *ppUnk was not NULL initially, it is Release'd // = if pUnk is not NULL, it is AddRef'd // // Effectively, this allows pointer assignment for ref-counted // pointers. // // Arguments: [ppUnk] // [pUnk] // //------------------------------------------------------------------------- void ReplaceInterfaceFn(IUnknown ** ppUnk, IUnknown * pUnk) { IUnknown * pUnkOld = *ppUnk; *ppUnk = pUnk; // Note that we do AddRef before Release; this avoids // accidentally destroying an object if this function // is passed two aliases to it if (pUnk) pUnk->AddRef(); if (pUnkOld) pUnkOld->Release(); } //+------------------------------------------------------------------------ // // Function: ClearInterfaceFn // // Synopsis: Sets an interface pointer to NULL, after first calling // Release if the pointer was not NULL initially // // Arguments: [ppUnk] *ppUnk is cleared // //------------------------------------------------------------------------- void ClearInterfaceFn(IUnknown ** ppUnk) { IUnknown * pUnk; pUnk = *ppUnk; *ppUnk = NULL; if (pUnk) pUnk->Release(); } Direction Reverse( Direction iDir ) { if( iDir == LEFT ) return RIGHT; else if (iDir == RIGHT) return LEFT; else return iDir; } //+=================================================================================== // Method: MoveWord // // Synopsis: Moves the pointer to the previous or next word. This method takes into // account block and site ends. // // Parameters: // eDir [in] Direction to move // pfNotAtBOL [out] What line is pointer on after move? (optional) // pfAtLogcialBOL [out] Is pointer at lbol after move? (otional) //+=================================================================================== HRESULT CHTMLEditor::MoveWord( IDisplayPointer *pDispPointer, Direction eDir) { HRESULT hr = S_OK; if( eDir == LEFT ) hr = THR( MoveUnit( pDispPointer, eDir, MOVEUNIT_PREVWORDBEGIN )); else hr = THR( MoveUnit( pDispPointer,eDir, MOVEUNIT_NEXTWORDBEGIN )); RRETURN( hr ); } //+=================================================================================== // Method: MoveCharacter // // Synopsis: Moves the pointer to the previous or next character. This method takes // into account block and site ends. // // Parameters: // eDir [in] Direction to move // pfNotAtBOL [out] What line is pointer on after move? (optional) // pfAtLogcialBOL [out] Is pointer at lbol after move? (otional) //+=================================================================================== HRESULT CHTMLEditor::MoveCharacter( IDisplayPointer *pDispPointer, Direction eDir) { HRESULT hr = S_OK; BOOL fNearText = FALSE; CEditPointer tLooker(this); DWORD dwBreak = BREAK_CONDITION_OMIT_PHRASE-BREAK_CONDITION_Anchor; DWORD dwFound = BREAK_CONDITION_None; IFC( pDispPointer->PositionMarkupPointer(tLooker) ); IFC( tLooker.Scan( eDir, dwBreak, &dwFound )); fNearText = CheckFlag( dwFound, BREAK_CONDITION_Text ); if( eDir == LEFT ) { if( fNearText ) { hr = THR( MoveUnit( pDispPointer, eDir, MOVEUNIT_PREVCLUSTERBEGIN )); } else { hr = THR( MoveUnit( pDispPointer, eDir, MOVEUNIT_PREVCLUSTEREND )); } } else { if( fNearText ) { hr = THR( MoveUnit( pDispPointer, eDir, MOVEUNIT_NEXTCLUSTEREND )); } else { hr = THR( MoveUnit( pDispPointer, eDir, MOVEUNIT_NEXTCLUSTERBEGIN )); } } Cleanup: RRETURN( hr ); } //+=================================================================================== // Method: MoveUnit // // Synopsis: Moves the pointer to the previous or next character. This method takes // into account block and site ends. // // Parameters: // eDir [in] Direction to move // pfNotAtBOL [out] What line is pointer on after move? (optional) // pfAtLogcialBOL [out] Is pointer at lbol after move? (otional) // // // //+=================================================================================== HRESULT CHTMLEditor::MoveUnit( IDisplayPointer *pDispPointer, Direction eDir, MOVEUNIT_ACTION eUnit ) { HRESULT hr = S_OK; BOOL fBeyondThisLine; BOOL fAtEdgeOfLine; BOOL fThereIsAnotherLine = FALSE; BOOL fBeyondNextLine = FALSE; BOOL fLineBreakDueToTextWrapping = FALSE; BOOL fHackedLineBreak = FALSE; DWORD dwBreak = BREAK_CONDITION_Site | BREAK_CONDITION_NoScopeSite | BREAK_CONDITION_Control; DWORD dwFound = BREAK_CONDITION_None; SP_IHTMLElement spSite; CEditPointer epDestination(this); CEditPointer epBoundary(this); CEditPointer epNextLine(this); CEditPointer epWalker(this); SP_IDisplayPointer spDispPointer; IFC( pDispPointer->PositionMarkupPointer(epDestination) ); IFC( pDispPointer->PositionMarkupPointer(epNextLine) ); IFC( pDispPointer->PositionMarkupPointer(epWalker) ); IFC( pDispPointer->PositionMarkupPointer(epBoundary) ); IFC( GetDisplayServices()->CreateDisplayPointer(&spDispPointer) ); IFC( spDispPointer->SetDisplayGravity(DISPLAY_GRAVITY_PreviousLine) ); IFC( epDestination->MoveUnit( eUnit )); if( eDir == LEFT ) { DWORD dwIgnore = BREAK_CONDITION_Phrase | BREAK_CONDITION_Anchor | BREAK_CONDITION_NoLayoutSpan; IFC( spDispPointer->MoveToPointer(pDispPointer) ); IFC( spDispPointer->MoveUnit(DISPLAY_MOVEUNIT_CurrentLineStart, -1) ); IFC( spDispPointer->PositionMarkupPointer(epBoundary) ); fLineBreakDueToTextWrapping = TRUE; hr = THR( spDispPointer->MoveUnit(DISPLAY_MOVEUNIT_PreviousLine, -1) ); if (SUCCEEDED(hr)) { hr = THR( spDispPointer->MoveUnit(DISPLAY_MOVEUNIT_CurrentLineEnd, -1) ); if (SUCCEEDED(hr)) { fThereIsAnotherLine = TRUE; IFC( spDispPointer->PositionMarkupPointer(epNextLine) ); IFC( AdjustOut(epNextLine, RIGHT) ); { // // HACKHACK: To fix bug #98353, we need to make sure epNextLine // does not go beyond this line. AdjustOut is very buggy but // we don't want to make a big modification as of now. So we do // a little hacking here. [zhenbinx] // SP_IDisplayPointer spDispAdjusted; IFC( GetDisplayServices()->CreateDisplayPointer(&spDispAdjusted) ); if (S_FALSE == spDispAdjusted->MoveToMarkupPointer(epNextLine, spDispPointer)) { CEditPointer epScan(this); DWORD dwScanFound; epScan->MoveToPointer(epNextLine); epScan.Scan(LEFT, BREAK_CONDITION_OMIT_PHRASE, &dwScanFound); epScan.Scan(RIGHT, BREAK_CONDITION_OMIT_PHRASE, &dwScanFound); epNextLine->MoveToPointer(epScan); } } IFC( epDestination->IsLeftOf( epNextLine, &fBeyondNextLine )); } } // // HACKHACK: When glyph is turned on, we use the non-adjusted line start instead // of adjusted line start for epBoundary. So we need to handle it specially. // if (!_fIgnoreGlyphs) { DWORD dwLBSearch = BREAK_CONDITION_Content; DWORD dwLBFound; CEditPointer epLBScan(this); IFC( epLBScan->MoveToPointer(epBoundary) ); IFC( epLBScan.Scan(LEFT, dwLBSearch, &dwLBFound) ); if ( (CheckFlag(dwLBFound, BREAK_CONDITION_EnterBlock) && CheckFlag(dwLBFound, BREAK_CONDITION_EnterSite)) ) { // // HACKHACK: // since we use non-adjusted line start. We need // to hack this to FALSE. // fLineBreakDueToTextWrapping = FALSE; fHackedLineBreak = TRUE; } } if (!fHackedLineBreak) { // If the current line start and previous line end are the same point // in the markup, we are breaking the line due to wrapping IFC( epNextLine->IsEqualTo( epBoundary, &fLineBreakDueToTextWrapping )); } IFC( epDestination->IsLeftOf( epBoundary, &fBeyondThisLine )); IFC( epWalker.IsLeftOfOrEqualTo( epBoundary, dwIgnore, &fAtEdgeOfLine )); if (!_fIgnoreGlyphs) { // // IEV6-6553-2000/08/08/-zhenbinx // some positions are not valid even if glyph is turned on. // This is because the caret is considered to be "valid // for input". To maintain this assumption, Some glyphs // should be ingored since inserting text into such position // would have resulted in incorrect HTML. // We should have a better glyph story in the future. // SP_IHTMLElement spIElem; ELEMENT_TAG_ID eTag; IFC( CurrentScopeOrMaster(epWalker, &spIElem) ); IFC( GetMarkupServices()->GetElementTagId(spIElem, & eTag) ); if (EdUtil::IsListItem(eTag)) // add more invalid positions here... { // // In theory, this could have skipped over too much // however LI is not surround by any element in normal cases // DWORD dwAdjustedIgnore = dwIgnore|BREAK_CONDITION_Glyph|BREAK_CONDITION_Block; IFC( epWalker.IsLeftOfOrEqualTo(epBoundary, dwAdjustedIgnore, &fAtEdgeOfLine) ); } } } else { DWORD dwIgnore = BREAK_CONDITION_Phrase | BREAK_CONDITION_Anchor | BREAK_CONDITION_NoScope | BREAK_CONDITION_NoLayoutSpan; IFC( spDispPointer->MoveToPointer(pDispPointer) ); IFC( spDispPointer->MoveUnit(DISPLAY_MOVEUNIT_CurrentLineEnd, -1) ); IFC( spDispPointer->PositionMarkupPointer(epBoundary) ); fLineBreakDueToTextWrapping = TRUE; IFC( spDispPointer->MoveToPointer(pDispPointer) ); hr = THR( spDispPointer->MoveUnit(DISPLAY_MOVEUNIT_NextLine, -1) ); if (SUCCEEDED(hr)) { hr = THR( spDispPointer->MoveUnit(DISPLAY_MOVEUNIT_CurrentLineStart, -1) ); if (SUCCEEDED(hr)) { fThereIsAnotherLine = TRUE; IFC( spDispPointer->PositionMarkupPointer(epNextLine) ); IFC( AdjustOut(epNextLine, LEFT) ); { // // HACKHACK: To fix bug #108383, we need to make sure epNextLine // does not go beyond this line. AdjustOut is very buggy but // we don't want to make a big modification as of now. So we do // a little hacking here. [zhenbinx] // SP_IDisplayPointer spDispAdjusted; IFC( GetDisplayServices()->CreateDisplayPointer(&spDispAdjusted) ); if (S_FALSE == spDispAdjusted->MoveToMarkupPointer(epNextLine, spDispPointer)) { CEditPointer epScan(this); DWORD dwScanFound; epScan->MoveToPointer(epNextLine); epScan.Scan(RIGHT, BREAK_CONDITION_OMIT_PHRASE, &dwScanFound); epScan.Scan(LEFT, BREAK_CONDITION_OMIT_PHRASE, &dwScanFound); epNextLine->MoveToPointer(epScan); } } IFC( epDestination->IsRightOf( epNextLine, &fBeyondNextLine )); } } // // HACKHACK: When glyph is turned on, we use the non-adjusted line end instead // of adjusted line end for epBoundary. So we need to handle it specially. // if (!_fIgnoreGlyphs) { DWORD dwLBSearch = BREAK_CONDITION_Content; DWORD dwLBFound; CEditPointer epLBScan(this); IFC( epLBScan->MoveToPointer(epBoundary) ); IFC( epLBScan.Scan(RIGHT, dwLBSearch, &dwLBFound) ); if ( (CheckFlag(dwLBFound, BREAK_CONDITION_EnterBlock) && CheckFlag(dwLBFound, BREAK_CONDITION_EnterSite)) ) { // // HACKHACK: // We have a block and a glyph right before it // since we use non-adjusted line end. We need // to hack this to FALSE. // fLineBreakDueToTextWrapping = FALSE; fHackedLineBreak = TRUE; } } if (!fHackedLineBreak) { // If the current line END and next line START are the same point // in the markup, we are breaking the line due to wrapping IFC( epNextLine->IsEqualTo( epBoundary, &fLineBreakDueToTextWrapping )); } IFC( epDestination->IsRightOf( epBoundary, &fBeyondThisLine )); IFC( epWalker.IsRightOfOrEqualTo( epBoundary, dwIgnore, &fAtEdgeOfLine )); } // // If I'm not at the edge of the line, my destination is the edge of the line. // if( ! fAtEdgeOfLine && fBeyondThisLine ) { IFC( epDestination->MoveToPointer( epBoundary )); } // // If I am at the edge of the line and there is another line, and my destination // is beyond that line - my destination is that line. // if( fAtEdgeOfLine && fBeyondThisLine && fBeyondNextLine && ! fLineBreakDueToTextWrapping ) { // we are at the edge of the line and our destination is beyond the next line boundary // so move our destination to that line boundary. IFC( epDestination->MoveToPointer( epNextLine )); } // // Scan towards my destination. If I hit a site boundary, move to the other // side of it and be done. Otherwise, move to the next line. // IFC( epWalker.SetBoundaryForDirection( eDir, epDestination )); hr = THR( epWalker.Scan( eDir, dwBreak, &dwFound, &spSite )); if( CheckFlag( dwFound, BREAK_CONDITION_NoScopeSite ) || CheckFlag( dwFound, BREAK_CONDITION_EnterControl )) { IFC( epWalker->MoveAdjacentToElement( spSite , eDir == LEFT ? ELEM_ADJ_BeforeBegin : ELEM_ADJ_AfterEnd )); goto CalcBOL; } else if( CheckFlag( dwFound, BREAK_CONDITION_ExitControl )) { // do not move at all goto Cleanup; } else if( CheckFlag( dwFound, BREAK_CONDITION_Site )) { ELEMENT_TAG_ID tagId; IFC( GetMarkupServices()->GetElementTagId(spSite, &tagId) ); if (tagId == TAGID_BODY) goto Cleanup; // don't exit the body IFC( EnterTables(epWalker, eDir) ); // move wherever scan put us... if( eDir == LEFT ) { IFC( pDispPointer->SetDisplayGravity(DISPLAY_GRAVITY_PreviousLine) ); } else { IFC( pDispPointer->SetDisplayGravity(DISPLAY_GRAVITY_NextLine) ); } goto Done; } else if( CheckFlag( dwFound, BREAK_CONDITION_Boundary )) { // No site transitions between here and our destination. if( fBeyondThisLine && fAtEdgeOfLine && ! fLineBreakDueToTextWrapping ) { // If our destination pointer is on another line than our start pointer... IFC( spDispPointer->MoveToPointer(pDispPointer) ); if( eDir == LEFT ) { hr = THR( spDispPointer->MoveUnit(DISPLAY_MOVEUNIT_PreviousLine, -1) ); if (SUCCEEDED(hr)) { hr = THR( spDispPointer->MoveUnit(DISPLAY_MOVEUNIT_CurrentLineEnd, -1) ); if (SUCCEEDED(hr)) { IFC( spDispPointer->PositionMarkupPointer(epWalker) ); IFC( AdjustOut(epWalker, RIGHT) ); { // // HACKHACK: To fix bug #98353, we need to make sure epNextLine // does not go beyond this line. AdjustOut is very buggy but // we don't want to make a big modification as of now. So we do // a little hacking here. [zhenbinx] // SP_IDisplayPointer spDispAdjusted; IFC( GetDisplayServices()->CreateDisplayPointer(&spDispAdjusted) ); if (S_FALSE == spDispAdjusted->MoveToMarkupPointer(epWalker, spDispPointer) ) { CEditPointer epScan(this); DWORD dwScanFound; epScan->MoveToPointer(epWalker); epScan.Scan(LEFT, BREAK_CONDITION_OMIT_PHRASE, &dwScanFound); epScan.Scan(RIGHT, BREAK_CONDITION_OMIT_PHRASE, &dwScanFound); epWalker->MoveToPointer(epScan); } } IFC( EnterTables(epWalker, LEFT) ); IFC( pDispPointer->MoveToMarkupPointer(epWalker, NULL) ); { // // HACKHACK: // // We might just moved into an empty line!!! // Consider the case of "\r\rA" where we are moving // from between '\r' and 'A' to between two '\r's, // // In this case CurrentLineEnd will be before the 2nd // 'r' !!! (this is our current design)!!!!!!!!!! // // We are moving into an ambigious position at an // empty line. Do not set display gravity to PreviousLine // in this case! Note in this case fLineBreakDueToTextWrapping // is set to FALSE // // [zhenbinx] // CEditPointer epScan(this); DWORD dwSearch = BREAK_CONDITION_OMIT_PHRASE; DWORD dwScanFound = BREAK_CONDITION_None; WCHAR wch; IFC( pDispPointer->PositionMarkupPointer(epScan) ); IFC( epScan.Scan(RIGHT, dwSearch, &dwScanFound, NULL, NULL, &wch) ); if (CheckFlag(dwScanFound, BREAK_CONDITION_NoScopeBlock) && wch == L'\r') { IFC( pDispPointer->SetDisplayGravity(DISPLAY_GRAVITY_NextLine) ); } else { IFC( pDispPointer->SetDisplayGravity(DISPLAY_GRAVITY_PreviousLine) ); } } } } } else { hr = THR( spDispPointer->MoveUnit(DISPLAY_MOVEUNIT_NextLine, -1) ); if (SUCCEEDED(hr)) { hr = THR( spDispPointer->MoveUnit(DISPLAY_MOVEUNIT_CurrentLineStart, -1) ); if (SUCCEEDED(hr)) { IFC( spDispPointer->PositionMarkupPointer(epWalker) ); IFC( AdjustOut(epWalker, LEFT) ); { // // HACKHACK: To fix bug #108383, we need to make sure epNextLine // does not go beyond this line. AdjustOut is very buggy but // we don't want to make a big modification as of now. So we do // a little hacking here. [zhenbinx] // SP_IDisplayPointer spDispAdjusted; IFC( GetDisplayServices()->CreateDisplayPointer(&spDispAdjusted) ); if (S_FALSE == spDispAdjusted->MoveToMarkupPointer(epWalker, spDispPointer) ) { CEditPointer epScan(this); DWORD dwScanFound; epScan->MoveToPointer(epWalker); epScan.Scan(RIGHT, BREAK_CONDITION_OMIT_PHRASE, &dwScanFound); epScan.Scan(LEFT, BREAK_CONDITION_OMIT_PHRASE, &dwScanFound); epWalker->MoveToPointer(epScan); } } IFC( EnterTables(epWalker, RIGHT) ); IFC( pDispPointer->MoveToMarkupPointer(epWalker, NULL) ); IFC( pDispPointer->SetDisplayGravity(DISPLAY_GRAVITY_NextLine) ); } } } goto Cleanup; } else { // We started and ended on same line with no little stops along the way - move to destination... IFC( epWalker->MoveToPointer( epDestination )); } } else { // we hit some sort of error, go to cleanup hr = E_FAIL; goto Cleanup; } CalcBOL: // // Fix up fNotAtBOL - if the cp we are at is between lines, we should // always be at the beginning of the line. One exception - if we are to the // left of a layout, we should render on the previous line. If we are to the // right of a layout, we should render on the next line. // { CEditPointer tPointer( this ); BOOL fAtNextLineFuzzy = FALSE; DWORD dwScanBreak = BREAK_CONDITION_OMIT_PHRASE - BREAK_CONDITION_Anchor; DWORD dwScanFound = BREAK_CONDITION_None; IFC( tPointer.MoveToPointer( epWalker )); IFC( tPointer.Scan( RIGHT, dwScanBreak, &dwScanFound )); if( fThereIsAnotherLine ) IFC( tPointer.IsEqualTo( epNextLine, BREAK_CONDITION_Phrase | BREAK_CONDITION_Anchor, & fAtNextLineFuzzy )); if( ! CheckFlag( dwScanFound, BREAK_CONDITION_Site ) && ! fAtNextLineFuzzy ) { // No site to the right of me and I'm not right next to the next line, // render at the bol. IFC( pDispPointer->SetDisplayGravity(DISPLAY_GRAVITY_NextLine) ); } else { // there was a site to my right - render at the end of the line IFC( pDispPointer->SetDisplayGravity(DISPLAY_GRAVITY_PreviousLine) ); } } Done: IFC( pDispPointer->MoveToMarkupPointer(epWalker, NULL) ); Cleanup: RRETURN( hr ); } // // General markup services helpers // //+---------------------------------------------------------------------------- // Method: CSegmentListIter::CSegmentListIter // Synopsis: ctor //----------------------------------------------------------------------------- CSegmentListIter::CSegmentListIter() { _pLeft = _pRight = NULL; _pSegmentList = NULL; _pIter = NULL; } //+---------------------------------------------------------------------------- // Method: CSegmentListIter::CSegmentListIter // Synopsis: dtor //----------------------------------------------------------------------------- CSegmentListIter::~CSegmentListIter() { ReleaseInterface(_pLeft); ReleaseInterface(_pRight); ReleaseInterface(_pSegmentList); ReleaseInterface(_pIter); } //+---------------------------------------------------------------------------- // Method: CSegmentListIter::Init // Synopsis: init method //----------------------------------------------------------------------------- HRESULT CSegmentListIter::Init(CEditorDoc *pEditorDoc, ISegmentList *pSegmentList) { HRESULT hr; // // Set up pointers // ReleaseInterface(_pLeft); ReleaseInterface(_pRight); ReleaseInterface(_pSegmentList); ReleaseInterface(_pIter); IFC( pSegmentList->CreateIterator(&_pIter) ); hr = THR(CreateMarkupPointer2(pEditorDoc, &_pLeft)); if (FAILED(hr)) goto Cleanup; hr = THR(CreateMarkupPointer2(pEditorDoc, &_pRight)); if (FAILED(hr)) goto Cleanup; // Cache segment list _pSegmentList = pSegmentList; _pSegmentList->AddRef(); Cleanup: RRETURN1(hr, S_FALSE); } //+---------------------------------------------------------------------------- // Method: CSegmentListIter::Next // Synopsis: Move pointers to next segment. // Returns S_FALSE if last segment //----------------------------------------------------------------------------- HRESULT CSegmentListIter::Next(IMarkupPointer **ppLeft, IMarkupPointer **ppRight) { SP_ISegment spSegment; HRESULT hr; // // Advance to next segment // if( _pIter->IsDone() == S_FALSE ) { IFC( _pIter->Current(&spSegment) ); IFC( spSegment->GetPointers( _pLeft, _pRight ) ); *ppLeft = _pLeft; *ppRight = _pRight; IFC( _pIter->Advance() ); } else { hr = S_FALSE; } Cleanup: RRETURN1(hr, S_FALSE); } //+---------------------------------------------------------------------------- // Method: CBreakContainer::Add // Synopsis: Add an element to the break container //----------------------------------------------------------------------------- VOID CBreakContainer::Set(ELEMENT_TAG_ID tagId, Mask mask) { if (mask & BreakOnStart) bitFieldStart.Set(tagId); else bitFieldStart.Clear(tagId); if (mask & BreakOnEnd) bitFieldEnd.Set(tagId); else bitFieldEnd.Clear(tagId); } //+---------------------------------------------------------------------------- // Method: CBreakContainer::Test // Synopsis: Tests an element in the break container //----------------------------------------------------------------------------- VOID CBreakContainer::Clear(ELEMENT_TAG_ID tagId, Mask mask) { if (mask & BreakOnStart) bitFieldStart.Clear(tagId); if (mask & BreakOnEnd) bitFieldEnd.Clear(tagId); } //+---------------------------------------------------------------------------- // Method: CBreakContainer::Clear // Synopsis: Clears an element in the break container //----------------------------------------------------------------------------- BOOL CBreakContainer::Test(ELEMENT_TAG_ID tagId, Mask mask) { BOOL bResult = FALSE; switch (mask) { case BreakOnStart: bResult = bitFieldStart.Test(tagId); break; case BreakOnEnd: bResult = bitFieldEnd.Test(tagId); break; case BreakOnBoth: bResult = bitFieldStart.Test(tagId) && bitFieldEnd.Test(tagId) ; break; } return bResult; } #if DBG==1 void AssertPositioned(IMarkupPointer *pPointer) { HRESULT hr; BOOL fIsPositioned; hr = pPointer->IsPositioned(&fIsPositioned); Assert(hr == S_OK); Assert(fIsPositioned); } #endif HRESULT MshtmledUtil::GetEditResourceLibrary( HINSTANCE *hResourceLibrary) { if (!g_hEditLibInstance) { g_hEditLibInstance = MLLoadLibrary(_T("mshtmler.dll"), g_hInstance, ML_CROSSCODEPAGE); } *hResourceLibrary = g_hEditLibInstance; if (!g_hEditLibInstance) return E_FAIL; // TODO: can we convert GetLastError() to an HRESULT? return S_OK; } //+---------------------------------------------------------------------------+ // // // Currently only deal with writing-mode: tb-rl // // styleWritingMode // styleWritingModeLrtb // styleWritingModeTbrl // styleWritingModeNotSet // // //+---------------------------------------------------------------------------+ HRESULT MshtmledUtil::IsElementInVerticalLayout(IHTMLElement *pElement, BOOL *fRet ) { HRESULT hr = S_OK; SP_IHTMLElement2 spElem2; SP_IHTMLCurrentStyle spStyle; SP_IHTMLCurrentStyle2 spStyle2; BSTR bstrWritingMode=NULL; Assert( pElement ); Assert( fRet ); IFC( pElement->QueryInterface(IID_IHTMLElement2, reinterpret_cast<LPVOID *>(&spElem2)) ); IFC( spElem2->get_currentStyle(&spStyle) ); if (!spStyle) goto Cleanup; IFC( spStyle->QueryInterface(IID_IHTMLCurrentStyle2, reinterpret_cast<LPVOID *>(&spStyle2)) ); IFC( spStyle2->get_writingMode(&bstrWritingMode) ); // // TODO: Should not hard-code strings however cannot find a way around! // *fRet = bstrWritingMode && !_tcscmp(bstrWritingMode, _T("tb-rl")); Cleanup: ::SysFreeString(bstrWritingMode); RRETURN(hr); } // // Synoposis: This function moves the markuppointer according to editing rules. // It manipulates the markup pointer according to the visual box tree // // HRESULT MshtmledUtil::MoveMarkupPointerToBlockLimit( CHTMLEditor *pEditor, Direction direction, // LEFT -- START of BLOCK RIGHT -- END of BLOCK IMarkupPointer *pMarkupPointer, ELEMENT_ADJACENCY elemAdj ) { Assert( pEditor ); Assert( pMarkupPointer ); HRESULT hr = S_OK; CBlockPointer bpStBlock(pEditor); CBlockPointer bpEndBlock(pEditor); CBlockPointer bpWkBlock(pEditor); BOOL fEmpty; IFC( bpStBlock.MoveTo(pMarkupPointer, direction) ); IFC( bpStBlock.IsEmpty(&fEmpty) ); if (!fEmpty) { IFC( bpStBlock.MoveToFirstNodeInBlock() ); } if (LEFT == direction) { IFC( bpStBlock.MovePointerTo(pMarkupPointer, elemAdj) ); goto Cleanup; } // // Fall through -- RIGHT == direction // IFC( bpWkBlock.MoveTo(&bpStBlock) ); if (!fEmpty) { IFC( bpWkBlock.MoveToLastNodeInBlock() ); } IFC( bpEndBlock.MoveTo(&bpWkBlock) ); if (ELEM_ADJ_AfterEnd == elemAdj) { if (S_FALSE == bpEndBlock.MoveToSibling(RIGHT)) { if (bpEndBlock.IsLeafNode()) { IFC( bpEndBlock.MoveToParent() ); } } IFC( bpEndBlock.MovePointerTo(pMarkupPointer, ELEM_ADJ_AfterEnd) ); } else { Assert( ELEM_ADJ_BeforeEnd == elemAdj ); IFC( bpEndBlock.MovePointerTo(pMarkupPointer, ELEM_ADJ_BeforeEnd) ); } Cleanup: RRETURN(hr); } // // CEdUndoHelper helper // CEdUndoHelper::CEdUndoHelper(CHTMLEditor *pEd) { _pEd= pEd; _fOpen = FALSE; } CEdUndoHelper::~CEdUndoHelper() { if (_fOpen) IGNORE_HR(_pEd->GetUndoManagerHelper()->EndUndoUnit()); } HRESULT CEdUndoHelper::Begin(UINT uiStringId, CBatchParentUndoUnit *pBatchPUU) { HRESULT hr; Assert(!_fOpen); hr = THR(_pEd->GetUndoManagerHelper()->BeginUndoUnit(uiStringId, pBatchPUU)); _fOpen = SUCCEEDED(hr); RRETURN(hr); } // // CStringCache // CStringCache::CStringCache(UINT uiStart, UINT uiEnd) { _uiStart = uiStart; _uiEnd = uiEnd; _pCache = new CacheEntry[_uiEnd - _uiStart + 1]; if (_pCache) { for (UINT i = 0; i < (_uiEnd - _uiStart + 1); i++) { _pCache[i].pchString = NULL; } } } CStringCache::~CStringCache() { for (UINT i = 0; i < (_uiEnd - _uiStart + 1); i++) { delete [] _pCache[i].pchString; } delete [] _pCache; } TCHAR * CStringCache::GetString(UINT uiStringId) { HRESULT hr; CacheEntry *pEntry; HINSTANCE hinstEditResDLL; INT iResult; const int iBufferSize = 1024; Assert(_pCache); if (!_pCache || uiStringId < _uiStart || uiStringId > _uiEnd) return NULL; // error pEntry = &_pCache[uiStringId - _uiStart]; if (pEntry->pchString == NULL) { TCHAR pchBuffer[iBufferSize]; IFC( MshtmledUtil::GetEditResourceLibrary(&hinstEditResDLL) ); pchBuffer[iBufferSize-1] = 0; // so we are always 0 terminated iResult = LoadString( hinstEditResDLL, uiStringId, pchBuffer, ARRAY_SIZE(pchBuffer)-1 ); if (!iResult) goto Cleanup; pEntry->pchString = new TCHAR[_tcslen(pchBuffer)+1]; if (pEntry->pchString) StrCpy(pEntry->pchString, pchBuffer); } return pEntry->pchString; Cleanup: return NULL; } #if DBG==1 // // Debugging aid - this little hack lets us look at the CElement from inside the debugger. // #include <initguid.h> DEFINE_GUID(CLSID_CElement, 0x3050f233, 0x98b5, 0x11cf, 0xbb, 0x82, 0x00, 0xaa, 0x00, 0xbd, 0xce, 0x0b); DEBUG_HELPER CElement *_(IHTMLElement *pIElement) { CElement *pElement = NULL; pIElement->QueryInterface(CLSID_CElement, (LPVOID *)&pElement); return pElement; } // // Helpers to dump the tree // DEBUG_HELPER VOID dt(IUnknown* pUnknown) { IOleCommandTarget *pCmdTarget = NULL; IMarkupPointer *pMarkupPointer = NULL; if (SUCCEEDED(pUnknown->QueryInterface(IID_IOleCommandTarget, (LPVOID *)&pCmdTarget))) { IGNORE_HR(pCmdTarget->Exec( &CGID_MSHTML, IDM_DEBUG_DUMPTREE, 0, NULL, NULL)); ReleaseInterface(pCmdTarget); } else if (SUCCEEDED(pUnknown->QueryInterface(IID_IMarkupPointer, (LPVOID *)&pMarkupPointer))) { IMarkupContainer *pContainer = NULL; if (SUCCEEDED(pMarkupPointer->GetContainer(&pContainer))) { dt(pContainer); ReleaseInterface(pContainer); } ReleaseInterface(pMarkupPointer); } } DEBUG_HELPER VOID dt(SP_IMarkupPointer &spPointer) { dt(spPointer.p); } #endif
47,119
15,029
#include "RemoteAdministrator.h" #include <interfaces/IKeyHandler.h> #include <libudev.h> #include <linux/uinput.h> namespace WPEFramework { namespace Plugin { static char Locator[] = _T("/dev/input"); class LinuxDevice : public Exchange::IKeyProducer, Core::Thread { private: LinuxDevice(const LinuxDevice&) = delete; LinuxDevice& operator=(const LinuxDevice&) = delete; public: LinuxDevice() : Core::Thread(Core::Thread::DefaultStackSize(), _T("LinuxInputSystem")) , _devices() , _monitor(nullptr) , _update(-1) , _callback(nullptr) { _pipe[0] = -1; _pipe[1] = -1; if (::pipe(_pipe) < 0) { // Pipe not successfully opened. Close, if needed; if (_pipe[0] != -1) { close(_pipe[0]); } if (_pipe[1] != -1) { close(_pipe[1]); } _pipe[0] = -1; _pipe[1] = -1; } else { struct udev* udev = udev_new(); // Set up a monitor to monitor event devices _monitor = udev_monitor_new_from_netlink(udev, "udev"); udev_monitor_filter_add_match_subsystem_devtype(_monitor, "input", nullptr); udev_monitor_enable_receiving(_monitor); // Get the file descriptor (fd) for the monitor _update = udev_monitor_get_fd(_monitor); udev_unref(udev); Remotes::RemoteAdministrator::Instance().Announce(*this); } } virtual ~LinuxDevice() { Block(); Clear(); if (_pipe[0] != -1) { Remotes::RemoteAdministrator::Instance().Revoke(*this); close(_pipe[0]); close(_pipe[1]); } if (_update != -1) { ::close(_update); } if (_monitor != nullptr) { udev_monitor_unref(_monitor); } } public: virtual const TCHAR* Name() const { return (_T("DevInput")); } virtual void Configure(const string&) { Pair(); } virtual bool Pair() { // Make sure we are not processing anything. Block(); Refresh(); // We are done, start observing again. Run(); return (true); } virtual bool Unpair(string bindingId) { // Make sure we are not processing anything. Block(); Refresh(); // We are done, start observing again. Run(); return (true); } virtual uint32_t Callback(Exchange::IKeyHandler* callback) { ASSERT((callback == nullptr) ^ (_callback == nullptr)); if (callback == nullptr) { // We are unlinked. Deinitialize the stuff. _callback = nullptr; } else { TRACE_L1("%s: callback=%p _callback=%p", __FUNCTION__, callback, _callback); _callback = callback; } return (Core::ERROR_NONE); } virtual uint32_t Error() const { return (Core::ERROR_NONE); } virtual string MetaData() const { return (Name()); } BEGIN_INTERFACE_MAP(LinuxDevice) INTERFACE_ENTRY(Exchange::IKeyProducer) END_INTERFACE_MAP private: void Refresh() { // Remove all current open devices. Clear(); // find devices in /dev/input/ Core::Directory dir(Locator); while (dir.Next() == true) { Core::File entry(dir.Current(), false); if ((entry.IsDirectory() == false) && (entry.FileName().substr(0, 5) == _T("event"))) { TRACE(Trace::Information, (_T("Opening input device: %s"), entry.Name().c_str())); if (entry.Open(true) == true) { _devices.push_back(entry.DuplicateHandle()); } } } } void Clear() { for (std::vector<int>::const_iterator it = _devices.begin(), end = _devices.end(); it != end; ++it) { close(*it); } _devices.clear(); } void Block() { Core::Thread::Block(); write(_pipe[1], " ", 1); Wait(Core::Thread::INITIALIZED | Core::Thread::BLOCKED | Core::Thread::STOPPED, Core::infinite); } virtual uint32_t Worker() { while (IsRunning() == true) { fd_set readset; FD_ZERO(&readset); FD_SET(_pipe[0], &readset); FD_SET(_update, &readset); int result = std::max(_pipe[0], _update); // set up all the input devices for (std::vector<int>::const_iterator index = _devices.begin(), end = _devices.end(); index != end; ++index) { FD_SET(*index, &readset); result = std::max(result, *index); } result = select(result + 1, &readset, 0, 0, nullptr); if (result > 0) { if (FD_ISSET(_pipe[0], &readset)) { char buff; (void)read(_pipe[0], &buff, 1); } if (FD_ISSET(_update, &readset)) { // Make the call to receive the device. select() ensured that this will not block. udev_device* dev = udev_monitor_receive_device(_monitor); if (dev) { const char* nodeId = udev_device_get_devnode(dev); bool reload = ((nodeId != nullptr) && (strncmp(Locator, nodeId, sizeof(Locator) - 1) == 0)); udev_device_unref(dev); TRACE_L1("Changes from udev perspective. Reload (%s)", reload ? _T("true") : _T("false")); if (reload == true) { Refresh(); } } } // find the devices to read from std::vector<int>::iterator index = _devices.begin(); while (index != _devices.end()) { if (FD_ISSET(*index, &readset)) { if (HandleInput(*index) == false) { // fd closed? close(*index); index = _devices.erase(index); } else { ++index; } } else { ++index; } } } } return (Core::infinite); } bool HandleInput(const int fd) { input_event entry[16]; int index = 0; int result = ::read(fd, entry, sizeof(entry)); if (result > 0) { while (result >= static_cast<int>(sizeof(input_event))) { ASSERT(index < static_cast<int>((sizeof(entry) / sizeof(input_event)))); // If it is a KEY and it is *NOT* a repeat, send it.. // Repeat gets constructed by the framework anyway. if ((entry[index].type == EV_KEY) && (entry[index].value != 2)) { const uint16_t code = entry[index].code; const bool pressed = entry[index].value != 0; TRACE(Trace::Information, (_T("Sending pressed: %s, code: 0x%04X"), (pressed ? _T("true") : _T("false")), code)); _callback->KeyEvent(pressed, code, Name()); } index++; result -= sizeof(input_event); } } return (result >= 0); } private: std::vector<int> _devices; int _pipe[2]; udev_monitor* _monitor; int _update; Exchange::IKeyHandler* _callback; static LinuxDevice* _singleton; }; /* static */ LinuxDevice* LinuxDevice::_singleton = Core::Service<LinuxDevice>::Create<LinuxDevice>(); } }
8,710
2,347
/** * @file colorChange.cpp * @brief mex interface for cv::colorChange * @ingroup photo * @author Amro * @date 2015 */ #include "mexopencv.hpp" #include "opencv2/photo.hpp" using namespace std; using namespace cv; /** * Main entry called from Matlab * @param nlhs number of left-hand-side arguments * @param plhs pointers to mxArrays in the left-hand-side * @param nrhs number of right-hand-side arguments * @param prhs pointers to mxArrays in the right-hand-side */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // Check the number of arguments nargchk(nrhs>=2 && (nrhs%2)==0 && nlhs<=1); // Argument vector vector<MxArray> rhs(prhs, prhs+nrhs); // Option processing float red_mul = 1.0f; float green_mul = 1.0f; float blue_mul = 1.0f; bool flip = false; for (int i=2; i<nrhs; i+=2) { string key(rhs[i].toString()); if (key == "R") red_mul = rhs[i+1].toFloat(); else if (key == "G") green_mul = rhs[i+1].toFloat(); else if (key == "B") blue_mul = rhs[i+1].toFloat(); else if (key == "FlipChannels") flip = rhs[i+1].toBool(); else mexErrMsgIdAndTxt("mexopencv:error", "Unrecognized option %s", key.c_str()); } // Process Mat src(rhs[0].toMat(CV_8U)), mask(rhs[1].toMat(CV_8U)), dst; // MATLAB's default is RGB while OpenCV's is BGR if (flip) { if (src.channels() == 3) cvtColor(src, src, cv::COLOR_RGB2BGR); if (mask.channels() == 3) cvtColor(mask, mask, cv::COLOR_RGB2BGR); } colorChange(src, mask, dst, red_mul, green_mul, blue_mul); // OpenCV's default is BGR while MATLAB's is RGB if (flip && dst.channels() == 3) cvtColor(dst, dst, cv::COLOR_BGR2RGB); plhs[0] = MxArray(dst); }
1,900
711
// Copyright 2013 the V8 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. #include "src/hydrogen.h" #include <algorithm> #include "src/v8.h" #include "src/allocation-site-scopes.h" #include "src/codegen.h" #include "src/full-codegen.h" #include "src/hashmap.h" #include "src/hydrogen-bce.h" #include "src/hydrogen-bch.h" #include "src/hydrogen-canonicalize.h" #include "src/hydrogen-check-elimination.h" #include "src/hydrogen-dce.h" #include "src/hydrogen-dehoist.h" #include "src/hydrogen-environment-liveness.h" #include "src/hydrogen-escape-analysis.h" #include "src/hydrogen-gvn.h" #include "src/hydrogen-infer-representation.h" #include "src/hydrogen-infer-types.h" #include "src/hydrogen-load-elimination.h" #include "src/hydrogen-mark-deoptimize.h" #include "src/hydrogen-mark-unreachable.h" #include "src/hydrogen-osr.h" #include "src/hydrogen-range-analysis.h" #include "src/hydrogen-redundant-phi.h" #include "src/hydrogen-removable-simulates.h" #include "src/hydrogen-representation-changes.h" #include "src/hydrogen-sce.h" #include "src/hydrogen-store-elimination.h" #include "src/hydrogen-uint32-analysis.h" #include "src/lithium-allocator.h" #include "src/parser.h" #include "src/runtime.h" #include "src/scopeinfo.h" #include "src/scopes.h" #include "src/stub-cache.h" #include "src/typing.h" #if V8_TARGET_ARCH_IA32 #include "src/ia32/lithium-codegen-ia32.h" // NOLINT #elif V8_TARGET_ARCH_X64 #include "src/x64/lithium-codegen-x64.h" // NOLINT #elif V8_TARGET_ARCH_ARM64 #include "src/arm64/lithium-codegen-arm64.h" // NOLINT #elif V8_TARGET_ARCH_ARM #include "src/arm/lithium-codegen-arm.h" // NOLINT #elif V8_TARGET_ARCH_MIPS #include "src/mips/lithium-codegen-mips.h" // NOLINT #elif V8_TARGET_ARCH_X87 #include "src/x87/lithium-codegen-x87.h" // NOLINT #else #error Unsupported target architecture. #endif namespace v8 { namespace internal { HBasicBlock::HBasicBlock(HGraph* graph) : block_id_(graph->GetNextBlockID()), graph_(graph), phis_(4, graph->zone()), first_(NULL), last_(NULL), end_(NULL), loop_information_(NULL), predecessors_(2, graph->zone()), dominator_(NULL), dominated_blocks_(4, graph->zone()), last_environment_(NULL), argument_count_(-1), first_instruction_index_(-1), last_instruction_index_(-1), deleted_phis_(4, graph->zone()), parent_loop_header_(NULL), inlined_entry_block_(NULL), is_inline_return_target_(false), is_reachable_(true), dominates_loop_successors_(false), is_osr_entry_(false), is_ordered_(false) { } Isolate* HBasicBlock::isolate() const { return graph_->isolate(); } void HBasicBlock::MarkUnreachable() { is_reachable_ = false; } void HBasicBlock::AttachLoopInformation() { ASSERT(!IsLoopHeader()); loop_information_ = new(zone()) HLoopInformation(this, zone()); } void HBasicBlock::DetachLoopInformation() { ASSERT(IsLoopHeader()); loop_information_ = NULL; } void HBasicBlock::AddPhi(HPhi* phi) { ASSERT(!IsStartBlock()); phis_.Add(phi, zone()); phi->SetBlock(this); } void HBasicBlock::RemovePhi(HPhi* phi) { ASSERT(phi->block() == this); ASSERT(phis_.Contains(phi)); phi->Kill(); phis_.RemoveElement(phi); phi->SetBlock(NULL); } void HBasicBlock::AddInstruction(HInstruction* instr, HSourcePosition position) { ASSERT(!IsStartBlock() || !IsFinished()); ASSERT(!instr->IsLinked()); ASSERT(!IsFinished()); if (!position.IsUnknown()) { instr->set_position(position); } if (first_ == NULL) { ASSERT(last_environment() != NULL); ASSERT(!last_environment()->ast_id().IsNone()); HBlockEntry* entry = new(zone()) HBlockEntry(); entry->InitializeAsFirst(this); if (!position.IsUnknown()) { entry->set_position(position); } else { ASSERT(!FLAG_hydrogen_track_positions || !graph()->info()->IsOptimizing()); } first_ = last_ = entry; } instr->InsertAfter(last_); } HPhi* HBasicBlock::AddNewPhi(int merged_index) { if (graph()->IsInsideNoSideEffectsScope()) { merged_index = HPhi::kInvalidMergedIndex; } HPhi* phi = new(zone()) HPhi(merged_index, zone()); AddPhi(phi); return phi; } HSimulate* HBasicBlock::CreateSimulate(BailoutId ast_id, RemovableSimulate removable) { ASSERT(HasEnvironment()); HEnvironment* environment = last_environment(); ASSERT(ast_id.IsNone() || ast_id == BailoutId::StubEntry() || environment->closure()->shared()->VerifyBailoutId(ast_id)); int push_count = environment->push_count(); int pop_count = environment->pop_count(); HSimulate* instr = new(zone()) HSimulate(ast_id, pop_count, zone(), removable); #ifdef DEBUG instr->set_closure(environment->closure()); #endif // Order of pushed values: newest (top of stack) first. This allows // HSimulate::MergeWith() to easily append additional pushed values // that are older (from further down the stack). for (int i = 0; i < push_count; ++i) { instr->AddPushedValue(environment->ExpressionStackAt(i)); } for (GrowableBitVector::Iterator it(environment->assigned_variables(), zone()); !it.Done(); it.Advance()) { int index = it.Current(); instr->AddAssignedValue(index, environment->Lookup(index)); } environment->ClearHistory(); return instr; } void HBasicBlock::Finish(HControlInstruction* end, HSourcePosition position) { ASSERT(!IsFinished()); AddInstruction(end, position); end_ = end; for (HSuccessorIterator it(end); !it.Done(); it.Advance()) { it.Current()->RegisterPredecessor(this); } } void HBasicBlock::Goto(HBasicBlock* block, HSourcePosition position, FunctionState* state, bool add_simulate) { bool drop_extra = state != NULL && state->inlining_kind() == NORMAL_RETURN; if (block->IsInlineReturnTarget()) { HEnvironment* env = last_environment(); int argument_count = env->arguments_environment()->parameter_count(); AddInstruction(new(zone()) HLeaveInlined(state->entry(), argument_count), position); UpdateEnvironment(last_environment()->DiscardInlined(drop_extra)); } if (add_simulate) AddNewSimulate(BailoutId::None(), position); HGoto* instr = new(zone()) HGoto(block); Finish(instr, position); } void HBasicBlock::AddLeaveInlined(HValue* return_value, FunctionState* state, HSourcePosition position) { HBasicBlock* target = state->function_return(); bool drop_extra = state->inlining_kind() == NORMAL_RETURN; ASSERT(target->IsInlineReturnTarget()); ASSERT(return_value != NULL); HEnvironment* env = last_environment(); int argument_count = env->arguments_environment()->parameter_count(); AddInstruction(new(zone()) HLeaveInlined(state->entry(), argument_count), position); UpdateEnvironment(last_environment()->DiscardInlined(drop_extra)); last_environment()->Push(return_value); AddNewSimulate(BailoutId::None(), position); HGoto* instr = new(zone()) HGoto(target); Finish(instr, position); } void HBasicBlock::SetInitialEnvironment(HEnvironment* env) { ASSERT(!HasEnvironment()); ASSERT(first() == NULL); UpdateEnvironment(env); } void HBasicBlock::UpdateEnvironment(HEnvironment* env) { last_environment_ = env; graph()->update_maximum_environment_size(env->first_expression_index()); } void HBasicBlock::SetJoinId(BailoutId ast_id) { int length = predecessors_.length(); ASSERT(length > 0); for (int i = 0; i < length; i++) { HBasicBlock* predecessor = predecessors_[i]; ASSERT(predecessor->end()->IsGoto()); HSimulate* simulate = HSimulate::cast(predecessor->end()->previous()); ASSERT(i != 0 || (predecessor->last_environment()->closure().is_null() || predecessor->last_environment()->closure()->shared() ->VerifyBailoutId(ast_id))); simulate->set_ast_id(ast_id); predecessor->last_environment()->set_ast_id(ast_id); } } bool HBasicBlock::Dominates(HBasicBlock* other) const { HBasicBlock* current = other->dominator(); while (current != NULL) { if (current == this) return true; current = current->dominator(); } return false; } bool HBasicBlock::EqualToOrDominates(HBasicBlock* other) const { if (this == other) return true; return Dominates(other); } int HBasicBlock::LoopNestingDepth() const { const HBasicBlock* current = this; int result = (current->IsLoopHeader()) ? 1 : 0; while (current->parent_loop_header() != NULL) { current = current->parent_loop_header(); result++; } return result; } void HBasicBlock::PostProcessLoopHeader(IterationStatement* stmt) { ASSERT(IsLoopHeader()); SetJoinId(stmt->EntryId()); if (predecessors()->length() == 1) { // This is a degenerated loop. DetachLoopInformation(); return; } // Only the first entry into the loop is from outside the loop. All other // entries must be back edges. for (int i = 1; i < predecessors()->length(); ++i) { loop_information()->RegisterBackEdge(predecessors()->at(i)); } } void HBasicBlock::MarkSuccEdgeUnreachable(int succ) { ASSERT(IsFinished()); HBasicBlock* succ_block = end()->SuccessorAt(succ); ASSERT(succ_block->predecessors()->length() == 1); succ_block->MarkUnreachable(); } void HBasicBlock::RegisterPredecessor(HBasicBlock* pred) { if (HasPredecessor()) { // Only loop header blocks can have a predecessor added after // instructions have been added to the block (they have phis for all // values in the environment, these phis may be eliminated later). ASSERT(IsLoopHeader() || first_ == NULL); HEnvironment* incoming_env = pred->last_environment(); if (IsLoopHeader()) { ASSERT(phis()->length() == incoming_env->length()); for (int i = 0; i < phis_.length(); ++i) { phis_[i]->AddInput(incoming_env->values()->at(i)); } } else { last_environment()->AddIncomingEdge(this, pred->last_environment()); } } else if (!HasEnvironment() && !IsFinished()) { ASSERT(!IsLoopHeader()); SetInitialEnvironment(pred->last_environment()->Copy()); } predecessors_.Add(pred, zone()); } void HBasicBlock::AddDominatedBlock(HBasicBlock* block) { ASSERT(!dominated_blocks_.Contains(block)); // Keep the list of dominated blocks sorted such that if there is two // succeeding block in this list, the predecessor is before the successor. int index = 0; while (index < dominated_blocks_.length() && dominated_blocks_[index]->block_id() < block->block_id()) { ++index; } dominated_blocks_.InsertAt(index, block, zone()); } void HBasicBlock::AssignCommonDominator(HBasicBlock* other) { if (dominator_ == NULL) { dominator_ = other; other->AddDominatedBlock(this); } else if (other->dominator() != NULL) { HBasicBlock* first = dominator_; HBasicBlock* second = other; while (first != second) { if (first->block_id() > second->block_id()) { first = first->dominator(); } else { second = second->dominator(); } ASSERT(first != NULL && second != NULL); } if (dominator_ != first) { ASSERT(dominator_->dominated_blocks_.Contains(this)); dominator_->dominated_blocks_.RemoveElement(this); dominator_ = first; first->AddDominatedBlock(this); } } } void HBasicBlock::AssignLoopSuccessorDominators() { // Mark blocks that dominate all subsequent reachable blocks inside their // loop. Exploit the fact that blocks are sorted in reverse post order. When // the loop is visited in increasing block id order, if the number of // non-loop-exiting successor edges at the dominator_candidate block doesn't // exceed the number of previously encountered predecessor edges, there is no // path from the loop header to any block with higher id that doesn't go // through the dominator_candidate block. In this case, the // dominator_candidate block is guaranteed to dominate all blocks reachable // from it with higher ids. HBasicBlock* last = loop_information()->GetLastBackEdge(); int outstanding_successors = 1; // one edge from the pre-header // Header always dominates everything. MarkAsLoopSuccessorDominator(); for (int j = block_id(); j <= last->block_id(); ++j) { HBasicBlock* dominator_candidate = graph_->blocks()->at(j); for (HPredecessorIterator it(dominator_candidate); !it.Done(); it.Advance()) { HBasicBlock* predecessor = it.Current(); // Don't count back edges. if (predecessor->block_id() < dominator_candidate->block_id()) { outstanding_successors--; } } // If more successors than predecessors have been seen in the loop up to // now, it's not possible to guarantee that the current block dominates // all of the blocks with higher IDs. In this case, assume conservatively // that those paths through loop that don't go through the current block // contain all of the loop's dependencies. Also be careful to record // dominator information about the current loop that's being processed, // and not nested loops, which will be processed when // AssignLoopSuccessorDominators gets called on their header. ASSERT(outstanding_successors >= 0); HBasicBlock* parent_loop_header = dominator_candidate->parent_loop_header(); if (outstanding_successors == 0 && (parent_loop_header == this && !dominator_candidate->IsLoopHeader())) { dominator_candidate->MarkAsLoopSuccessorDominator(); } HControlInstruction* end = dominator_candidate->end(); for (HSuccessorIterator it(end); !it.Done(); it.Advance()) { HBasicBlock* successor = it.Current(); // Only count successors that remain inside the loop and don't loop back // to a loop header. if (successor->block_id() > dominator_candidate->block_id() && successor->block_id() <= last->block_id()) { // Backwards edges must land on loop headers. ASSERT(successor->block_id() > dominator_candidate->block_id() || successor->IsLoopHeader()); outstanding_successors++; } } } } int HBasicBlock::PredecessorIndexOf(HBasicBlock* predecessor) const { for (int i = 0; i < predecessors_.length(); ++i) { if (predecessors_[i] == predecessor) return i; } UNREACHABLE(); return -1; } #ifdef DEBUG void HBasicBlock::Verify() { // Check that every block is finished. ASSERT(IsFinished()); ASSERT(block_id() >= 0); // Check that the incoming edges are in edge split form. if (predecessors_.length() > 1) { for (int i = 0; i < predecessors_.length(); ++i) { ASSERT(predecessors_[i]->end()->SecondSuccessor() == NULL); } } } #endif void HLoopInformation::RegisterBackEdge(HBasicBlock* block) { this->back_edges_.Add(block, block->zone()); AddBlock(block); } HBasicBlock* HLoopInformation::GetLastBackEdge() const { int max_id = -1; HBasicBlock* result = NULL; for (int i = 0; i < back_edges_.length(); ++i) { HBasicBlock* cur = back_edges_[i]; if (cur->block_id() > max_id) { max_id = cur->block_id(); result = cur; } } return result; } void HLoopInformation::AddBlock(HBasicBlock* block) { if (block == loop_header()) return; if (block->parent_loop_header() == loop_header()) return; if (block->parent_loop_header() != NULL) { AddBlock(block->parent_loop_header()); } else { block->set_parent_loop_header(loop_header()); blocks_.Add(block, block->zone()); for (int i = 0; i < block->predecessors()->length(); ++i) { AddBlock(block->predecessors()->at(i)); } } } #ifdef DEBUG // Checks reachability of the blocks in this graph and stores a bit in // the BitVector "reachable()" for every block that can be reached // from the start block of the graph. If "dont_visit" is non-null, the given // block is treated as if it would not be part of the graph. "visited_count()" // returns the number of reachable blocks. class ReachabilityAnalyzer BASE_EMBEDDED { public: ReachabilityAnalyzer(HBasicBlock* entry_block, int block_count, HBasicBlock* dont_visit) : visited_count_(0), stack_(16, entry_block->zone()), reachable_(block_count, entry_block->zone()), dont_visit_(dont_visit) { PushBlock(entry_block); Analyze(); } int visited_count() const { return visited_count_; } const BitVector* reachable() const { return &reachable_; } private: void PushBlock(HBasicBlock* block) { if (block != NULL && block != dont_visit_ && !reachable_.Contains(block->block_id())) { reachable_.Add(block->block_id()); stack_.Add(block, block->zone()); visited_count_++; } } void Analyze() { while (!stack_.is_empty()) { HControlInstruction* end = stack_.RemoveLast()->end(); for (HSuccessorIterator it(end); !it.Done(); it.Advance()) { PushBlock(it.Current()); } } } int visited_count_; ZoneList<HBasicBlock*> stack_; BitVector reachable_; HBasicBlock* dont_visit_; }; void HGraph::Verify(bool do_full_verify) const { Heap::RelocationLock relocation_lock(isolate()->heap()); AllowHandleDereference allow_deref; AllowDeferredHandleDereference allow_deferred_deref; for (int i = 0; i < blocks_.length(); i++) { HBasicBlock* block = blocks_.at(i); block->Verify(); // Check that every block contains at least one node and that only the last // node is a control instruction. HInstruction* current = block->first(); ASSERT(current != NULL && current->IsBlockEntry()); while (current != NULL) { ASSERT((current->next() == NULL) == current->IsControlInstruction()); ASSERT(current->block() == block); current->Verify(); current = current->next(); } // Check that successors are correctly set. HBasicBlock* first = block->end()->FirstSuccessor(); HBasicBlock* second = block->end()->SecondSuccessor(); ASSERT(second == NULL || first != NULL); // Check that the predecessor array is correct. if (first != NULL) { ASSERT(first->predecessors()->Contains(block)); if (second != NULL) { ASSERT(second->predecessors()->Contains(block)); } } // Check that phis have correct arguments. for (int j = 0; j < block->phis()->length(); j++) { HPhi* phi = block->phis()->at(j); phi->Verify(); } // Check that all join blocks have predecessors that end with an // unconditional goto and agree on their environment node id. if (block->predecessors()->length() >= 2) { BailoutId id = block->predecessors()->first()->last_environment()->ast_id(); for (int k = 0; k < block->predecessors()->length(); k++) { HBasicBlock* predecessor = block->predecessors()->at(k); ASSERT(predecessor->end()->IsGoto() || predecessor->end()->IsDeoptimize()); ASSERT(predecessor->last_environment()->ast_id() == id); } } } // Check special property of first block to have no predecessors. ASSERT(blocks_.at(0)->predecessors()->is_empty()); if (do_full_verify) { // Check that the graph is fully connected. ReachabilityAnalyzer analyzer(entry_block_, blocks_.length(), NULL); ASSERT(analyzer.visited_count() == blocks_.length()); // Check that entry block dominator is NULL. ASSERT(entry_block_->dominator() == NULL); // Check dominators. for (int i = 0; i < blocks_.length(); ++i) { HBasicBlock* block = blocks_.at(i); if (block->dominator() == NULL) { // Only start block may have no dominator assigned to. ASSERT(i == 0); } else { // Assert that block is unreachable if dominator must not be visited. ReachabilityAnalyzer dominator_analyzer(entry_block_, blocks_.length(), block->dominator()); ASSERT(!dominator_analyzer.reachable()->Contains(block->block_id())); } } } } #endif HConstant* HGraph::GetConstant(SetOncePointer<HConstant>* pointer, int32_t value) { if (!pointer->is_set()) { // Can't pass GetInvalidContext() to HConstant::New, because that will // recursively call GetConstant HConstant* constant = HConstant::New(zone(), NULL, value); constant->InsertAfter(entry_block()->first()); pointer->set(constant); return constant; } return ReinsertConstantIfNecessary(pointer->get()); } HConstant* HGraph::ReinsertConstantIfNecessary(HConstant* constant) { if (!constant->IsLinked()) { // The constant was removed from the graph. Reinsert. constant->ClearFlag(HValue::kIsDead); constant->InsertAfter(entry_block()->first()); } return constant; } HConstant* HGraph::GetConstant0() { return GetConstant(&constant_0_, 0); } HConstant* HGraph::GetConstant1() { return GetConstant(&constant_1_, 1); } HConstant* HGraph::GetConstantMinus1() { return GetConstant(&constant_minus1_, -1); } #define DEFINE_GET_CONSTANT(Name, name, type, htype, boolean_value) \ HConstant* HGraph::GetConstant##Name() { \ if (!constant_##name##_.is_set()) { \ HConstant* constant = new(zone()) HConstant( \ Unique<Object>::CreateImmovable(isolate()->factory()->name##_value()), \ Unique<Map>::CreateImmovable(isolate()->factory()->type##_map()), \ false, \ Representation::Tagged(), \ htype, \ true, \ boolean_value, \ false, \ ODDBALL_TYPE); \ constant->InsertAfter(entry_block()->first()); \ constant_##name##_.set(constant); \ } \ return ReinsertConstantIfNecessary(constant_##name##_.get()); \ } DEFINE_GET_CONSTANT(Undefined, undefined, undefined, HType::Undefined(), false) DEFINE_GET_CONSTANT(True, true, boolean, HType::Boolean(), true) DEFINE_GET_CONSTANT(False, false, boolean, HType::Boolean(), false) DEFINE_GET_CONSTANT(Hole, the_hole, the_hole, HType::None(), false) DEFINE_GET_CONSTANT(Null, null, null, HType::Null(), false) #undef DEFINE_GET_CONSTANT #define DEFINE_IS_CONSTANT(Name, name) \ bool HGraph::IsConstant##Name(HConstant* constant) { \ return constant_##name##_.is_set() && constant == constant_##name##_.get(); \ } DEFINE_IS_CONSTANT(Undefined, undefined) DEFINE_IS_CONSTANT(0, 0) DEFINE_IS_CONSTANT(1, 1) DEFINE_IS_CONSTANT(Minus1, minus1) DEFINE_IS_CONSTANT(True, true) DEFINE_IS_CONSTANT(False, false) DEFINE_IS_CONSTANT(Hole, the_hole) DEFINE_IS_CONSTANT(Null, null) #undef DEFINE_IS_CONSTANT HConstant* HGraph::GetInvalidContext() { return GetConstant(&constant_invalid_context_, 0xFFFFC0C7); } bool HGraph::IsStandardConstant(HConstant* constant) { if (IsConstantUndefined(constant)) return true; if (IsConstant0(constant)) return true; if (IsConstant1(constant)) return true; if (IsConstantMinus1(constant)) return true; if (IsConstantTrue(constant)) return true; if (IsConstantFalse(constant)) return true; if (IsConstantHole(constant)) return true; if (IsConstantNull(constant)) return true; return false; } HGraphBuilder::IfBuilder::IfBuilder(HGraphBuilder* builder) : builder_(builder), finished_(false), did_then_(false), did_else_(false), did_else_if_(false), did_and_(false), did_or_(false), captured_(false), needs_compare_(true), pending_merge_block_(false), split_edge_merge_block_(NULL), merge_at_join_blocks_(NULL), normal_merge_at_join_block_count_(0), deopt_merge_at_join_block_count_(0) { HEnvironment* env = builder->environment(); first_true_block_ = builder->CreateBasicBlock(env->Copy()); first_false_block_ = builder->CreateBasicBlock(env->Copy()); } HGraphBuilder::IfBuilder::IfBuilder( HGraphBuilder* builder, HIfContinuation* continuation) : builder_(builder), finished_(false), did_then_(false), did_else_(false), did_else_if_(false), did_and_(false), did_or_(false), captured_(false), needs_compare_(false), pending_merge_block_(false), first_true_block_(NULL), first_false_block_(NULL), split_edge_merge_block_(NULL), merge_at_join_blocks_(NULL), normal_merge_at_join_block_count_(0), deopt_merge_at_join_block_count_(0) { continuation->Continue(&first_true_block_, &first_false_block_); } HControlInstruction* HGraphBuilder::IfBuilder::AddCompare( HControlInstruction* compare) { ASSERT(did_then_ == did_else_); if (did_else_) { // Handle if-then-elseif did_else_if_ = true; did_else_ = false; did_then_ = false; did_and_ = false; did_or_ = false; pending_merge_block_ = false; split_edge_merge_block_ = NULL; HEnvironment* env = builder_->environment(); first_true_block_ = builder_->CreateBasicBlock(env->Copy()); first_false_block_ = builder_->CreateBasicBlock(env->Copy()); } if (split_edge_merge_block_ != NULL) { HEnvironment* env = first_false_block_->last_environment(); HBasicBlock* split_edge = builder_->CreateBasicBlock(env->Copy()); if (did_or_) { compare->SetSuccessorAt(0, split_edge); compare->SetSuccessorAt(1, first_false_block_); } else { compare->SetSuccessorAt(0, first_true_block_); compare->SetSuccessorAt(1, split_edge); } builder_->GotoNoSimulate(split_edge, split_edge_merge_block_); } else { compare->SetSuccessorAt(0, first_true_block_); compare->SetSuccessorAt(1, first_false_block_); } builder_->FinishCurrentBlock(compare); needs_compare_ = false; return compare; } void HGraphBuilder::IfBuilder::Or() { ASSERT(!needs_compare_); ASSERT(!did_and_); did_or_ = true; HEnvironment* env = first_false_block_->last_environment(); if (split_edge_merge_block_ == NULL) { split_edge_merge_block_ = builder_->CreateBasicBlock(env->Copy()); builder_->GotoNoSimulate(first_true_block_, split_edge_merge_block_); first_true_block_ = split_edge_merge_block_; } builder_->set_current_block(first_false_block_); first_false_block_ = builder_->CreateBasicBlock(env->Copy()); } void HGraphBuilder::IfBuilder::And() { ASSERT(!needs_compare_); ASSERT(!did_or_); did_and_ = true; HEnvironment* env = first_false_block_->last_environment(); if (split_edge_merge_block_ == NULL) { split_edge_merge_block_ = builder_->CreateBasicBlock(env->Copy()); builder_->GotoNoSimulate(first_false_block_, split_edge_merge_block_); first_false_block_ = split_edge_merge_block_; } builder_->set_current_block(first_true_block_); first_true_block_ = builder_->CreateBasicBlock(env->Copy()); } void HGraphBuilder::IfBuilder::CaptureContinuation( HIfContinuation* continuation) { ASSERT(!did_else_if_); ASSERT(!finished_); ASSERT(!captured_); HBasicBlock* true_block = NULL; HBasicBlock* false_block = NULL; Finish(&true_block, &false_block); ASSERT(true_block != NULL); ASSERT(false_block != NULL); continuation->Capture(true_block, false_block); captured_ = true; builder_->set_current_block(NULL); End(); } void HGraphBuilder::IfBuilder::JoinContinuation(HIfContinuation* continuation) { ASSERT(!did_else_if_); ASSERT(!finished_); ASSERT(!captured_); HBasicBlock* true_block = NULL; HBasicBlock* false_block = NULL; Finish(&true_block, &false_block); merge_at_join_blocks_ = NULL; if (true_block != NULL && !true_block->IsFinished()) { ASSERT(continuation->IsTrueReachable()); builder_->GotoNoSimulate(true_block, continuation->true_branch()); } if (false_block != NULL && !false_block->IsFinished()) { ASSERT(continuation->IsFalseReachable()); builder_->GotoNoSimulate(false_block, continuation->false_branch()); } captured_ = true; End(); } void HGraphBuilder::IfBuilder::Then() { ASSERT(!captured_); ASSERT(!finished_); did_then_ = true; if (needs_compare_) { // Handle if's without any expressions, they jump directly to the "else" // branch. However, we must pretend that the "then" branch is reachable, // so that the graph builder visits it and sees any live range extending // constructs within it. HConstant* constant_false = builder_->graph()->GetConstantFalse(); ToBooleanStub::Types boolean_type = ToBooleanStub::Types(); boolean_type.Add(ToBooleanStub::BOOLEAN); HBranch* branch = builder()->New<HBranch>( constant_false, boolean_type, first_true_block_, first_false_block_); builder_->FinishCurrentBlock(branch); } builder_->set_current_block(first_true_block_); pending_merge_block_ = true; } void HGraphBuilder::IfBuilder::Else() { ASSERT(did_then_); ASSERT(!captured_); ASSERT(!finished_); AddMergeAtJoinBlock(false); builder_->set_current_block(first_false_block_); pending_merge_block_ = true; did_else_ = true; } void HGraphBuilder::IfBuilder::Deopt(const char* reason) { ASSERT(did_then_); builder_->Add<HDeoptimize>(reason, Deoptimizer::EAGER); AddMergeAtJoinBlock(true); } void HGraphBuilder::IfBuilder::Return(HValue* value) { HValue* parameter_count = builder_->graph()->GetConstantMinus1(); builder_->FinishExitCurrentBlock( builder_->New<HReturn>(value, parameter_count)); AddMergeAtJoinBlock(false); } void HGraphBuilder::IfBuilder::AddMergeAtJoinBlock(bool deopt) { if (!pending_merge_block_) return; HBasicBlock* block = builder_->current_block(); ASSERT(block == NULL || !block->IsFinished()); MergeAtJoinBlock* record = new(builder_->zone()) MergeAtJoinBlock(block, deopt, merge_at_join_blocks_); merge_at_join_blocks_ = record; if (block != NULL) { ASSERT(block->end() == NULL); if (deopt) { normal_merge_at_join_block_count_++; } else { deopt_merge_at_join_block_count_++; } } builder_->set_current_block(NULL); pending_merge_block_ = false; } void HGraphBuilder::IfBuilder::Finish() { ASSERT(!finished_); if (!did_then_) { Then(); } AddMergeAtJoinBlock(false); if (!did_else_) { Else(); AddMergeAtJoinBlock(false); } finished_ = true; } void HGraphBuilder::IfBuilder::Finish(HBasicBlock** then_continuation, HBasicBlock** else_continuation) { Finish(); MergeAtJoinBlock* else_record = merge_at_join_blocks_; if (else_continuation != NULL) { *else_continuation = else_record->block_; } MergeAtJoinBlock* then_record = else_record->next_; if (then_continuation != NULL) { *then_continuation = then_record->block_; } ASSERT(then_record->next_ == NULL); } void HGraphBuilder::IfBuilder::End() { if (captured_) return; Finish(); int total_merged_blocks = normal_merge_at_join_block_count_ + deopt_merge_at_join_block_count_; ASSERT(total_merged_blocks >= 1); HBasicBlock* merge_block = total_merged_blocks == 1 ? NULL : builder_->graph()->CreateBasicBlock(); // Merge non-deopt blocks first to ensure environment has right size for // padding. MergeAtJoinBlock* current = merge_at_join_blocks_; while (current != NULL) { if (!current->deopt_ && current->block_ != NULL) { // If there is only one block that makes it through to the end of the // if, then just set it as the current block and continue rather then // creating an unnecessary merge block. if (total_merged_blocks == 1) { builder_->set_current_block(current->block_); return; } builder_->GotoNoSimulate(current->block_, merge_block); } current = current->next_; } // Merge deopt blocks, padding when necessary. current = merge_at_join_blocks_; while (current != NULL) { if (current->deopt_ && current->block_ != NULL) { current->block_->FinishExit( HAbnormalExit::New(builder_->zone(), NULL), HSourcePosition::Unknown()); } current = current->next_; } builder_->set_current_block(merge_block); } HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder, HValue* context, LoopBuilder::Direction direction) : builder_(builder), context_(context), direction_(direction), finished_(false) { header_block_ = builder->CreateLoopHeaderBlock(); body_block_ = NULL; exit_block_ = NULL; exit_trampoline_block_ = NULL; increment_amount_ = builder_->graph()->GetConstant1(); } HGraphBuilder::LoopBuilder::LoopBuilder(HGraphBuilder* builder, HValue* context, LoopBuilder::Direction direction, HValue* increment_amount) : builder_(builder), context_(context), direction_(direction), finished_(false) { header_block_ = builder->CreateLoopHeaderBlock(); body_block_ = NULL; exit_block_ = NULL; exit_trampoline_block_ = NULL; increment_amount_ = increment_amount; } HValue* HGraphBuilder::LoopBuilder::BeginBody( HValue* initial, HValue* terminating, Token::Value token) { HEnvironment* env = builder_->environment(); phi_ = header_block_->AddNewPhi(env->values()->length()); phi_->AddInput(initial); env->Push(initial); builder_->GotoNoSimulate(header_block_); HEnvironment* body_env = env->Copy(); HEnvironment* exit_env = env->Copy(); // Remove the phi from the expression stack body_env->Pop(); exit_env->Pop(); body_block_ = builder_->CreateBasicBlock(body_env); exit_block_ = builder_->CreateBasicBlock(exit_env); builder_->set_current_block(header_block_); env->Pop(); builder_->FinishCurrentBlock(builder_->New<HCompareNumericAndBranch>( phi_, terminating, token, body_block_, exit_block_)); builder_->set_current_block(body_block_); if (direction_ == kPreIncrement || direction_ == kPreDecrement) { HValue* one = builder_->graph()->GetConstant1(); if (direction_ == kPreIncrement) { increment_ = HAdd::New(zone(), context_, phi_, one); } else { increment_ = HSub::New(zone(), context_, phi_, one); } increment_->ClearFlag(HValue::kCanOverflow); builder_->AddInstruction(increment_); return increment_; } else { return phi_; } } void HGraphBuilder::LoopBuilder::Break() { if (exit_trampoline_block_ == NULL) { // Its the first time we saw a break. HEnvironment* env = exit_block_->last_environment()->Copy(); exit_trampoline_block_ = builder_->CreateBasicBlock(env); builder_->GotoNoSimulate(exit_block_, exit_trampoline_block_); } builder_->GotoNoSimulate(exit_trampoline_block_); builder_->set_current_block(NULL); } void HGraphBuilder::LoopBuilder::EndBody() { ASSERT(!finished_); if (direction_ == kPostIncrement || direction_ == kPostDecrement) { if (direction_ == kPostIncrement) { increment_ = HAdd::New(zone(), context_, phi_, increment_amount_); } else { increment_ = HSub::New(zone(), context_, phi_, increment_amount_); } increment_->ClearFlag(HValue::kCanOverflow); builder_->AddInstruction(increment_); } // Push the new increment value on the expression stack to merge into the phi. builder_->environment()->Push(increment_); HBasicBlock* last_block = builder_->current_block(); builder_->GotoNoSimulate(last_block, header_block_); header_block_->loop_information()->RegisterBackEdge(last_block); if (exit_trampoline_block_ != NULL) { builder_->set_current_block(exit_trampoline_block_); } else { builder_->set_current_block(exit_block_); } finished_ = true; } HGraph* HGraphBuilder::CreateGraph() { graph_ = new(zone()) HGraph(info_); if (FLAG_hydrogen_stats) isolate()->GetHStatistics()->Initialize(info_); CompilationPhase phase("H_Block building", info_); set_current_block(graph()->entry_block()); if (!BuildGraph()) return NULL; graph()->FinalizeUniqueness(); return graph_; } HInstruction* HGraphBuilder::AddInstruction(HInstruction* instr) { ASSERT(current_block() != NULL); ASSERT(!FLAG_hydrogen_track_positions || !position_.IsUnknown() || !info_->IsOptimizing()); current_block()->AddInstruction(instr, source_position()); if (graph()->IsInsideNoSideEffectsScope()) { instr->SetFlag(HValue::kHasNoObservableSideEffects); } return instr; } void HGraphBuilder::FinishCurrentBlock(HControlInstruction* last) { ASSERT(!FLAG_hydrogen_track_positions || !info_->IsOptimizing() || !position_.IsUnknown()); current_block()->Finish(last, source_position()); if (last->IsReturn() || last->IsAbnormalExit()) { set_current_block(NULL); } } void HGraphBuilder::FinishExitCurrentBlock(HControlInstruction* instruction) { ASSERT(!FLAG_hydrogen_track_positions || !info_->IsOptimizing() || !position_.IsUnknown()); current_block()->FinishExit(instruction, source_position()); if (instruction->IsReturn() || instruction->IsAbnormalExit()) { set_current_block(NULL); } } void HGraphBuilder::AddIncrementCounter(StatsCounter* counter) { if (FLAG_native_code_counters && counter->Enabled()) { HValue* reference = Add<HConstant>(ExternalReference(counter)); HValue* old_value = Add<HLoadNamedField>( reference, static_cast<HValue*>(NULL), HObjectAccess::ForCounter()); HValue* new_value = AddUncasted<HAdd>(old_value, graph()->GetConstant1()); new_value->ClearFlag(HValue::kCanOverflow); // Ignore counter overflow Add<HStoreNamedField>(reference, HObjectAccess::ForCounter(), new_value, STORE_TO_INITIALIZED_ENTRY); } } void HGraphBuilder::AddSimulate(BailoutId id, RemovableSimulate removable) { ASSERT(current_block() != NULL); ASSERT(!graph()->IsInsideNoSideEffectsScope()); current_block()->AddNewSimulate(id, source_position(), removable); } HBasicBlock* HGraphBuilder::CreateBasicBlock(HEnvironment* env) { HBasicBlock* b = graph()->CreateBasicBlock(); b->SetInitialEnvironment(env); return b; } HBasicBlock* HGraphBuilder::CreateLoopHeaderBlock() { HBasicBlock* header = graph()->CreateBasicBlock(); HEnvironment* entry_env = environment()->CopyAsLoopHeader(header); header->SetInitialEnvironment(entry_env); header->AttachLoopInformation(); return header; } HValue* HGraphBuilder::BuildGetElementsKind(HValue* object) { HValue* map = Add<HLoadNamedField>(object, static_cast<HValue*>(NULL), HObjectAccess::ForMap()); HValue* bit_field2 = Add<HLoadNamedField>(map, static_cast<HValue*>(NULL), HObjectAccess::ForMapBitField2()); return BuildDecodeField<Map::ElementsKindBits>(bit_field2); } HValue* HGraphBuilder::BuildCheckHeapObject(HValue* obj) { if (obj->type().IsHeapObject()) return obj; return Add<HCheckHeapObject>(obj); } void HGraphBuilder::FinishExitWithHardDeoptimization(const char* reason) { Add<HDeoptimize>(reason, Deoptimizer::EAGER); FinishExitCurrentBlock(New<HAbnormalExit>()); } HValue* HGraphBuilder::BuildCheckString(HValue* string) { if (!string->type().IsString()) { ASSERT(!string->IsConstant() || !HConstant::cast(string)->HasStringValue()); BuildCheckHeapObject(string); return Add<HCheckInstanceType>(string, HCheckInstanceType::IS_STRING); } return string; } HValue* HGraphBuilder::BuildWrapReceiver(HValue* object, HValue* function) { if (object->type().IsJSObject()) return object; if (function->IsConstant() && HConstant::cast(function)->handle(isolate())->IsJSFunction()) { Handle<JSFunction> f = Handle<JSFunction>::cast( HConstant::cast(function)->handle(isolate())); SharedFunctionInfo* shared = f->shared(); if (shared->strict_mode() == STRICT || shared->native()) return object; } return Add<HWrapReceiver>(object, function); } HValue* HGraphBuilder::BuildCheckForCapacityGrow( HValue* object, HValue* elements, ElementsKind kind, HValue* length, HValue* key, bool is_js_array, PropertyAccessType access_type) { IfBuilder length_checker(this); Token::Value token = IsHoleyElementsKind(kind) ? Token::GTE : Token::EQ; length_checker.If<HCompareNumericAndBranch>(key, length, token); length_checker.Then(); HValue* current_capacity = AddLoadFixedArrayLength(elements); IfBuilder capacity_checker(this); capacity_checker.If<HCompareNumericAndBranch>(key, current_capacity, Token::GTE); capacity_checker.Then(); HValue* max_gap = Add<HConstant>(static_cast<int32_t>(JSObject::kMaxGap)); HValue* max_capacity = AddUncasted<HAdd>(current_capacity, max_gap); Add<HBoundsCheck>(key, max_capacity); HValue* new_capacity = BuildNewElementsCapacity(key); HValue* new_elements = BuildGrowElementsCapacity(object, elements, kind, kind, length, new_capacity); environment()->Push(new_elements); capacity_checker.Else(); environment()->Push(elements); capacity_checker.End(); if (is_js_array) { HValue* new_length = AddUncasted<HAdd>(key, graph_->GetConstant1()); new_length->ClearFlag(HValue::kCanOverflow); Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength(kind), new_length); } if (access_type == STORE && kind == FAST_SMI_ELEMENTS) { HValue* checked_elements = environment()->Top(); // Write zero to ensure that the new element is initialized with some smi. Add<HStoreKeyed>(checked_elements, key, graph()->GetConstant0(), kind); } length_checker.Else(); Add<HBoundsCheck>(key, length); environment()->Push(elements); length_checker.End(); return environment()->Pop(); } HValue* HGraphBuilder::BuildCopyElementsOnWrite(HValue* object, HValue* elements, ElementsKind kind, HValue* length) { Factory* factory = isolate()->factory(); IfBuilder cow_checker(this); cow_checker.If<HCompareMap>(elements, factory->fixed_cow_array_map()); cow_checker.Then(); HValue* capacity = AddLoadFixedArrayLength(elements); HValue* new_elements = BuildGrowElementsCapacity(object, elements, kind, kind, length, capacity); environment()->Push(new_elements); cow_checker.Else(); environment()->Push(elements); cow_checker.End(); return environment()->Pop(); } void HGraphBuilder::BuildTransitionElementsKind(HValue* object, HValue* map, ElementsKind from_kind, ElementsKind to_kind, bool is_jsarray) { ASSERT(!IsFastHoleyElementsKind(from_kind) || IsFastHoleyElementsKind(to_kind)); if (AllocationSite::GetMode(from_kind, to_kind) == TRACK_ALLOCATION_SITE) { Add<HTrapAllocationMemento>(object); } if (!IsSimpleMapChangeTransition(from_kind, to_kind)) { HInstruction* elements = AddLoadElements(object); HInstruction* empty_fixed_array = Add<HConstant>( isolate()->factory()->empty_fixed_array()); IfBuilder if_builder(this); if_builder.IfNot<HCompareObjectEqAndBranch>(elements, empty_fixed_array); if_builder.Then(); HInstruction* elements_length = AddLoadFixedArrayLength(elements); HInstruction* array_length = is_jsarray ? Add<HLoadNamedField>(object, static_cast<HValue*>(NULL), HObjectAccess::ForArrayLength(from_kind)) : elements_length; BuildGrowElementsCapacity(object, elements, from_kind, to_kind, array_length, elements_length); if_builder.End(); } Add<HStoreNamedField>(object, HObjectAccess::ForMap(), map); } void HGraphBuilder::BuildJSObjectCheck(HValue* receiver, int bit_field_mask) { // Check that the object isn't a smi. Add<HCheckHeapObject>(receiver); // Get the map of the receiver. HValue* map = Add<HLoadNamedField>(receiver, static_cast<HValue*>(NULL), HObjectAccess::ForMap()); // Check the instance type and if an access check is needed, this can be // done with a single load, since both bytes are adjacent in the map. HObjectAccess access(HObjectAccess::ForMapInstanceTypeAndBitField()); HValue* instance_type_and_bit_field = Add<HLoadNamedField>(map, static_cast<HValue*>(NULL), access); HValue* mask = Add<HConstant>(0x00FF | (bit_field_mask << 8)); HValue* and_result = AddUncasted<HBitwise>(Token::BIT_AND, instance_type_and_bit_field, mask); HValue* sub_result = AddUncasted<HSub>(and_result, Add<HConstant>(JS_OBJECT_TYPE)); Add<HBoundsCheck>(sub_result, Add<HConstant>(0x100 - JS_OBJECT_TYPE)); } void HGraphBuilder::BuildKeyedIndexCheck(HValue* key, HIfContinuation* join_continuation) { // The sometimes unintuitively backward ordering of the ifs below is // convoluted, but necessary. All of the paths must guarantee that the // if-true of the continuation returns a smi element index and the if-false of // the continuation returns either a symbol or a unique string key. All other // object types cause a deopt to fall back to the runtime. IfBuilder key_smi_if(this); key_smi_if.If<HIsSmiAndBranch>(key); key_smi_if.Then(); { Push(key); // Nothing to do, just continue to true of continuation. } key_smi_if.Else(); { HValue* map = Add<HLoadNamedField>(key, static_cast<HValue*>(NULL), HObjectAccess::ForMap()); HValue* instance_type = Add<HLoadNamedField>(map, static_cast<HValue*>(NULL), HObjectAccess::ForMapInstanceType()); // Non-unique string, check for a string with a hash code that is actually // an index. STATIC_ASSERT(LAST_UNIQUE_NAME_TYPE == FIRST_NONSTRING_TYPE); IfBuilder not_string_or_name_if(this); not_string_or_name_if.If<HCompareNumericAndBranch>( instance_type, Add<HConstant>(LAST_UNIQUE_NAME_TYPE), Token::GT); not_string_or_name_if.Then(); { // Non-smi, non-Name, non-String: Try to convert to smi in case of // HeapNumber. // TODO(danno): This could call some variant of ToString Push(AddUncasted<HForceRepresentation>(key, Representation::Smi())); } not_string_or_name_if.Else(); { // String or Name: check explicitly for Name, they can short-circuit // directly to unique non-index key path. IfBuilder not_symbol_if(this); not_symbol_if.If<HCompareNumericAndBranch>( instance_type, Add<HConstant>(SYMBOL_TYPE), Token::NE); not_symbol_if.Then(); { // String: check whether the String is a String of an index. If it is, // extract the index value from the hash. HValue* hash = Add<HLoadNamedField>(key, static_cast<HValue*>(NULL), HObjectAccess::ForNameHashField()); HValue* not_index_mask = Add<HConstant>(static_cast<int>( String::kContainsCachedArrayIndexMask)); HValue* not_index_test = AddUncasted<HBitwise>( Token::BIT_AND, hash, not_index_mask); IfBuilder string_index_if(this); string_index_if.If<HCompareNumericAndBranch>(not_index_test, graph()->GetConstant0(), Token::EQ); string_index_if.Then(); { // String with index in hash: extract string and merge to index path. Push(BuildDecodeField<String::ArrayIndexValueBits>(hash)); } string_index_if.Else(); { // Key is a non-index String, check for uniqueness/internalization. If // it's not, deopt. HValue* not_internalized_bit = AddUncasted<HBitwise>( Token::BIT_AND, instance_type, Add<HConstant>(static_cast<int>(kIsNotInternalizedMask))); DeoptimizeIf<HCompareNumericAndBranch>( not_internalized_bit, graph()->GetConstant0(), Token::NE, "BuildKeyedIndexCheck: string isn't internalized"); // Key guaranteed to be a unqiue string Push(key); } string_index_if.JoinContinuation(join_continuation); } not_symbol_if.Else(); { Push(key); // Key is symbol } not_symbol_if.JoinContinuation(join_continuation); } not_string_or_name_if.JoinContinuation(join_continuation); } key_smi_if.JoinContinuation(join_continuation); } void HGraphBuilder::BuildNonGlobalObjectCheck(HValue* receiver) { // Get the the instance type of the receiver, and make sure that it is // not one of the global object types. HValue* map = Add<HLoadNamedField>(receiver, static_cast<HValue*>(NULL), HObjectAccess::ForMap()); HValue* instance_type = Add<HLoadNamedField>(map, static_cast<HValue*>(NULL), HObjectAccess::ForMapInstanceType()); STATIC_ASSERT(JS_BUILTINS_OBJECT_TYPE == JS_GLOBAL_OBJECT_TYPE + 1); HValue* min_global_type = Add<HConstant>(JS_GLOBAL_OBJECT_TYPE); HValue* max_global_type = Add<HConstant>(JS_BUILTINS_OBJECT_TYPE); IfBuilder if_global_object(this); if_global_object.If<HCompareNumericAndBranch>(instance_type, max_global_type, Token::LTE); if_global_object.And(); if_global_object.If<HCompareNumericAndBranch>(instance_type, min_global_type, Token::GTE); if_global_object.ThenDeopt("receiver was a global object"); if_global_object.End(); } void HGraphBuilder::BuildTestForDictionaryProperties( HValue* object, HIfContinuation* continuation) { HValue* properties = Add<HLoadNamedField>( object, static_cast<HValue*>(NULL), HObjectAccess::ForPropertiesPointer()); HValue* properties_map = Add<HLoadNamedField>(properties, static_cast<HValue*>(NULL), HObjectAccess::ForMap()); HValue* hash_map = Add<HLoadRoot>(Heap::kHashTableMapRootIndex); IfBuilder builder(this); builder.If<HCompareObjectEqAndBranch>(properties_map, hash_map); builder.CaptureContinuation(continuation); } HValue* HGraphBuilder::BuildKeyedLookupCacheHash(HValue* object, HValue* key) { // Load the map of the receiver, compute the keyed lookup cache hash // based on 32 bits of the map pointer and the string hash. HValue* object_map = Add<HLoadNamedField>(object, static_cast<HValue*>(NULL), HObjectAccess::ForMapAsInteger32()); HValue* shifted_map = AddUncasted<HShr>( object_map, Add<HConstant>(KeyedLookupCache::kMapHashShift)); HValue* string_hash = Add<HLoadNamedField>(key, static_cast<HValue*>(NULL), HObjectAccess::ForStringHashField()); HValue* shifted_hash = AddUncasted<HShr>( string_hash, Add<HConstant>(String::kHashShift)); HValue* xor_result = AddUncasted<HBitwise>(Token::BIT_XOR, shifted_map, shifted_hash); int mask = (KeyedLookupCache::kCapacityMask & KeyedLookupCache::kHashMask); return AddUncasted<HBitwise>(Token::BIT_AND, xor_result, Add<HConstant>(mask)); } HValue* HGraphBuilder::BuildUncheckedDictionaryElementLoadHelper( HValue* elements, HValue* key, HValue* hash, HValue* mask, int current_probe) { if (current_probe == kNumberDictionaryProbes) { return NULL; } int32_t offset = SeededNumberDictionary::GetProbeOffset(current_probe); HValue* raw_index = (current_probe == 0) ? hash : AddUncasted<HAdd>(hash, Add<HConstant>(offset)); raw_index = AddUncasted<HBitwise>(Token::BIT_AND, raw_index, mask); int32_t entry_size = SeededNumberDictionary::kEntrySize; raw_index = AddUncasted<HMul>(raw_index, Add<HConstant>(entry_size)); raw_index->ClearFlag(HValue::kCanOverflow); int32_t base_offset = SeededNumberDictionary::kElementsStartIndex; HValue* key_index = AddUncasted<HAdd>(raw_index, Add<HConstant>(base_offset)); key_index->ClearFlag(HValue::kCanOverflow); HValue* candidate_key = Add<HLoadKeyed>(elements, key_index, static_cast<HValue*>(NULL), FAST_ELEMENTS); IfBuilder key_compare(this); key_compare.IfNot<HCompareObjectEqAndBranch>(key, candidate_key); key_compare.Then(); { // Key at the current probe doesn't match, try at the next probe. HValue* result = BuildUncheckedDictionaryElementLoadHelper( elements, key, hash, mask, current_probe + 1); if (result == NULL) { key_compare.Deopt("probes exhausted in keyed load dictionary lookup"); result = graph()->GetConstantUndefined(); } else { Push(result); } } key_compare.Else(); { // Key at current probe matches. Details must be zero, otherwise the // dictionary element requires special handling. HValue* details_index = AddUncasted<HAdd>( raw_index, Add<HConstant>(base_offset + 2)); details_index->ClearFlag(HValue::kCanOverflow); HValue* details = Add<HLoadKeyed>(elements, details_index, static_cast<HValue*>(NULL), FAST_ELEMENTS); IfBuilder details_compare(this); details_compare.If<HCompareNumericAndBranch>(details, graph()->GetConstant0(), Token::NE); details_compare.ThenDeopt("keyed load dictionary element not fast case"); details_compare.Else(); { // Key matches and details are zero --> fast case. Load and return the // value. HValue* result_index = AddUncasted<HAdd>( raw_index, Add<HConstant>(base_offset + 1)); result_index->ClearFlag(HValue::kCanOverflow); Push(Add<HLoadKeyed>(elements, result_index, static_cast<HValue*>(NULL), FAST_ELEMENTS)); } details_compare.End(); } key_compare.End(); return Pop(); } HValue* HGraphBuilder::BuildElementIndexHash(HValue* index) { int32_t seed_value = static_cast<uint32_t>(isolate()->heap()->HashSeed()); HValue* seed = Add<HConstant>(seed_value); HValue* hash = AddUncasted<HBitwise>(Token::BIT_XOR, index, seed); // hash = ~hash + (hash << 15); HValue* shifted_hash = AddUncasted<HShl>(hash, Add<HConstant>(15)); HValue* not_hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, graph()->GetConstantMinus1()); hash = AddUncasted<HAdd>(shifted_hash, not_hash); // hash = hash ^ (hash >> 12); shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(12)); hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash); // hash = hash + (hash << 2); shifted_hash = AddUncasted<HShl>(hash, Add<HConstant>(2)); hash = AddUncasted<HAdd>(hash, shifted_hash); // hash = hash ^ (hash >> 4); shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(4)); hash = AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash); // hash = hash * 2057; hash = AddUncasted<HMul>(hash, Add<HConstant>(2057)); hash->ClearFlag(HValue::kCanOverflow); // hash = hash ^ (hash >> 16); shifted_hash = AddUncasted<HShr>(hash, Add<HConstant>(16)); return AddUncasted<HBitwise>(Token::BIT_XOR, hash, shifted_hash); } HValue* HGraphBuilder::BuildUncheckedDictionaryElementLoad(HValue* receiver, HValue* elements, HValue* key, HValue* hash) { HValue* capacity = Add<HLoadKeyed>( elements, Add<HConstant>(NameDictionary::kCapacityIndex), static_cast<HValue*>(NULL), FAST_ELEMENTS); HValue* mask = AddUncasted<HSub>(capacity, graph()->GetConstant1()); mask->ChangeRepresentation(Representation::Integer32()); mask->ClearFlag(HValue::kCanOverflow); return BuildUncheckedDictionaryElementLoadHelper(elements, key, hash, mask, 0); } HValue* HGraphBuilder::BuildRegExpConstructResult(HValue* length, HValue* index, HValue* input) { NoObservableSideEffectsScope scope(this); HConstant* max_length = Add<HConstant>(JSObject::kInitialMaxFastElementArray); Add<HBoundsCheck>(length, max_length); // Generate size calculation code here in order to make it dominate // the JSRegExpResult allocation. ElementsKind elements_kind = FAST_ELEMENTS; HValue* size = BuildCalculateElementsSize(elements_kind, length); // Allocate the JSRegExpResult and the FixedArray in one step. HValue* result = Add<HAllocate>( Add<HConstant>(JSRegExpResult::kSize), HType::JSArray(), NOT_TENURED, JS_ARRAY_TYPE); // Initialize the JSRegExpResult header. HValue* global_object = Add<HLoadNamedField>( context(), static_cast<HValue*>(NULL), HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX)); HValue* native_context = Add<HLoadNamedField>( global_object, static_cast<HValue*>(NULL), HObjectAccess::ForGlobalObjectNativeContext()); Add<HStoreNamedField>( result, HObjectAccess::ForMap(), Add<HLoadNamedField>( native_context, static_cast<HValue*>(NULL), HObjectAccess::ForContextSlot(Context::REGEXP_RESULT_MAP_INDEX))); HConstant* empty_fixed_array = Add<HConstant>(isolate()->factory()->empty_fixed_array()); Add<HStoreNamedField>( result, HObjectAccess::ForJSArrayOffset(JSArray::kPropertiesOffset), empty_fixed_array); Add<HStoreNamedField>( result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset), empty_fixed_array); Add<HStoreNamedField>( result, HObjectAccess::ForJSArrayOffset(JSArray::kLengthOffset), length); // Initialize the additional fields. Add<HStoreNamedField>( result, HObjectAccess::ForJSArrayOffset(JSRegExpResult::kIndexOffset), index); Add<HStoreNamedField>( result, HObjectAccess::ForJSArrayOffset(JSRegExpResult::kInputOffset), input); // Allocate and initialize the elements header. HAllocate* elements = BuildAllocateElements(elements_kind, size); BuildInitializeElementsHeader(elements, elements_kind, length); HConstant* size_in_bytes_upper_bound = EstablishElementsAllocationSize( elements_kind, max_length->Integer32Value()); elements->set_size_upper_bound(size_in_bytes_upper_bound); Add<HStoreNamedField>( result, HObjectAccess::ForJSArrayOffset(JSArray::kElementsOffset), elements); // Initialize the elements contents with undefined. BuildFillElementsWithValue( elements, elements_kind, graph()->GetConstant0(), length, graph()->GetConstantUndefined()); return result; } HValue* HGraphBuilder::BuildNumberToString(HValue* object, Type* type) { NoObservableSideEffectsScope scope(this); // Convert constant numbers at compile time. if (object->IsConstant() && HConstant::cast(object)->HasNumberValue()) { Handle<Object> number = HConstant::cast(object)->handle(isolate()); Handle<String> result = isolate()->factory()->NumberToString(number); return Add<HConstant>(result); } // Create a joinable continuation. HIfContinuation found(graph()->CreateBasicBlock(), graph()->CreateBasicBlock()); // Load the number string cache. HValue* number_string_cache = Add<HLoadRoot>(Heap::kNumberStringCacheRootIndex); // Make the hash mask from the length of the number string cache. It // contains two elements (number and string) for each cache entry. HValue* mask = AddLoadFixedArrayLength(number_string_cache); mask->set_type(HType::Smi()); mask = AddUncasted<HSar>(mask, graph()->GetConstant1()); mask = AddUncasted<HSub>(mask, graph()->GetConstant1()); // Check whether object is a smi. IfBuilder if_objectissmi(this); if_objectissmi.If<HIsSmiAndBranch>(object); if_objectissmi.Then(); { // Compute hash for smi similar to smi_get_hash(). HValue* hash = AddUncasted<HBitwise>(Token::BIT_AND, object, mask); // Load the key. HValue* key_index = AddUncasted<HShl>(hash, graph()->GetConstant1()); HValue* key = Add<HLoadKeyed>(number_string_cache, key_index, static_cast<HValue*>(NULL), FAST_ELEMENTS, ALLOW_RETURN_HOLE); // Check if object == key. IfBuilder if_objectiskey(this); if_objectiskey.If<HCompareObjectEqAndBranch>(object, key); if_objectiskey.Then(); { // Make the key_index available. Push(key_index); } if_objectiskey.JoinContinuation(&found); } if_objectissmi.Else(); { if (type->Is(Type::SignedSmall())) { if_objectissmi.Deopt("Expected smi"); } else { // Check if the object is a heap number. IfBuilder if_objectisnumber(this); HValue* objectisnumber = if_objectisnumber.If<HCompareMap>( object, isolate()->factory()->heap_number_map()); if_objectisnumber.Then(); { // Compute hash for heap number similar to double_get_hash(). HValue* low = Add<HLoadNamedField>( object, objectisnumber, HObjectAccess::ForHeapNumberValueLowestBits()); HValue* high = Add<HLoadNamedField>( object, objectisnumber, HObjectAccess::ForHeapNumberValueHighestBits()); HValue* hash = AddUncasted<HBitwise>(Token::BIT_XOR, low, high); hash = AddUncasted<HBitwise>(Token::BIT_AND, hash, mask); // Load the key. HValue* key_index = AddUncasted<HShl>(hash, graph()->GetConstant1()); HValue* key = Add<HLoadKeyed>(number_string_cache, key_index, static_cast<HValue*>(NULL), FAST_ELEMENTS, ALLOW_RETURN_HOLE); // Check if the key is a heap number and compare it with the object. IfBuilder if_keyisnotsmi(this); HValue* keyisnotsmi = if_keyisnotsmi.IfNot<HIsSmiAndBranch>(key); if_keyisnotsmi.Then(); { IfBuilder if_keyisheapnumber(this); if_keyisheapnumber.If<HCompareMap>( key, isolate()->factory()->heap_number_map()); if_keyisheapnumber.Then(); { // Check if values of key and object match. IfBuilder if_keyeqobject(this); if_keyeqobject.If<HCompareNumericAndBranch>( Add<HLoadNamedField>(key, keyisnotsmi, HObjectAccess::ForHeapNumberValue()), Add<HLoadNamedField>(object, objectisnumber, HObjectAccess::ForHeapNumberValue()), Token::EQ); if_keyeqobject.Then(); { // Make the key_index available. Push(key_index); } if_keyeqobject.JoinContinuation(&found); } if_keyisheapnumber.JoinContinuation(&found); } if_keyisnotsmi.JoinContinuation(&found); } if_objectisnumber.Else(); { if (type->Is(Type::Number())) { if_objectisnumber.Deopt("Expected heap number"); } } if_objectisnumber.JoinContinuation(&found); } } if_objectissmi.JoinContinuation(&found); // Check for cache hit. IfBuilder if_found(this, &found); if_found.Then(); { // Count number to string operation in native code. AddIncrementCounter(isolate()->counters()->number_to_string_native()); // Load the value in case of cache hit. HValue* key_index = Pop(); HValue* value_index = AddUncasted<HAdd>(key_index, graph()->GetConstant1()); Push(Add<HLoadKeyed>(number_string_cache, value_index, static_cast<HValue*>(NULL), FAST_ELEMENTS, ALLOW_RETURN_HOLE)); } if_found.Else(); { // Cache miss, fallback to runtime. Add<HPushArguments>(object); Push(Add<HCallRuntime>( isolate()->factory()->empty_string(), Runtime::FunctionForId(Runtime::kHiddenNumberToStringSkipCache), 1)); } if_found.End(); return Pop(); } HAllocate* HGraphBuilder::BuildAllocate( HValue* object_size, HType type, InstanceType instance_type, HAllocationMode allocation_mode) { // Compute the effective allocation size. HValue* size = object_size; if (allocation_mode.CreateAllocationMementos()) { size = AddUncasted<HAdd>(size, Add<HConstant>(AllocationMemento::kSize)); size->ClearFlag(HValue::kCanOverflow); } // Perform the actual allocation. HAllocate* object = Add<HAllocate>( size, type, allocation_mode.GetPretenureMode(), instance_type, allocation_mode.feedback_site()); // Setup the allocation memento. if (allocation_mode.CreateAllocationMementos()) { BuildCreateAllocationMemento( object, object_size, allocation_mode.current_site()); } return object; } HValue* HGraphBuilder::BuildAddStringLengths(HValue* left_length, HValue* right_length) { // Compute the combined string length and check against max string length. HValue* length = AddUncasted<HAdd>(left_length, right_length); // Check that length <= kMaxLength <=> length < MaxLength + 1. HValue* max_length = Add<HConstant>(String::kMaxLength + 1); Add<HBoundsCheck>(length, max_length); return length; } HValue* HGraphBuilder::BuildCreateConsString( HValue* length, HValue* left, HValue* right, HAllocationMode allocation_mode) { // Determine the string instance types. HInstruction* left_instance_type = AddLoadStringInstanceType(left); HInstruction* right_instance_type = AddLoadStringInstanceType(right); // Allocate the cons string object. HAllocate does not care whether we // pass CONS_STRING_TYPE or CONS_ASCII_STRING_TYPE here, so we just use // CONS_STRING_TYPE here. Below we decide whether the cons string is // one-byte or two-byte and set the appropriate map. ASSERT(HAllocate::CompatibleInstanceTypes(CONS_STRING_TYPE, CONS_ASCII_STRING_TYPE)); HAllocate* result = BuildAllocate(Add<HConstant>(ConsString::kSize), HType::String(), CONS_STRING_TYPE, allocation_mode); // Compute intersection and difference of instance types. HValue* anded_instance_types = AddUncasted<HBitwise>( Token::BIT_AND, left_instance_type, right_instance_type); HValue* xored_instance_types = AddUncasted<HBitwise>( Token::BIT_XOR, left_instance_type, right_instance_type); // We create a one-byte cons string if // 1. both strings are one-byte, or // 2. at least one of the strings is two-byte, but happens to contain only // one-byte characters. // To do this, we check // 1. if both strings are one-byte, or if the one-byte data hint is set in // both strings, or // 2. if one of the strings has the one-byte data hint set and the other // string is one-byte. IfBuilder if_onebyte(this); STATIC_ASSERT(kOneByteStringTag != 0); STATIC_ASSERT(kOneByteDataHintMask != 0); if_onebyte.If<HCompareNumericAndBranch>( AddUncasted<HBitwise>( Token::BIT_AND, anded_instance_types, Add<HConstant>(static_cast<int32_t>( kStringEncodingMask | kOneByteDataHintMask))), graph()->GetConstant0(), Token::NE); if_onebyte.Or(); STATIC_ASSERT(kOneByteStringTag != 0 && kOneByteDataHintTag != 0 && kOneByteDataHintTag != kOneByteStringTag); if_onebyte.If<HCompareNumericAndBranch>( AddUncasted<HBitwise>( Token::BIT_AND, xored_instance_types, Add<HConstant>(static_cast<int32_t>( kOneByteStringTag | kOneByteDataHintTag))), Add<HConstant>(static_cast<int32_t>( kOneByteStringTag | kOneByteDataHintTag)), Token::EQ); if_onebyte.Then(); { // We can safely skip the write barrier for storing the map here. Add<HStoreNamedField>( result, HObjectAccess::ForMap(), Add<HConstant>(isolate()->factory()->cons_ascii_string_map())); } if_onebyte.Else(); { // We can safely skip the write barrier for storing the map here. Add<HStoreNamedField>( result, HObjectAccess::ForMap(), Add<HConstant>(isolate()->factory()->cons_string_map())); } if_onebyte.End(); // Initialize the cons string fields. Add<HStoreNamedField>(result, HObjectAccess::ForStringHashField(), Add<HConstant>(String::kEmptyHashField)); Add<HStoreNamedField>(result, HObjectAccess::ForStringLength(), length); Add<HStoreNamedField>(result, HObjectAccess::ForConsStringFirst(), left); Add<HStoreNamedField>(result, HObjectAccess::ForConsStringSecond(), right); // Count the native string addition. AddIncrementCounter(isolate()->counters()->string_add_native()); return result; } void HGraphBuilder::BuildCopySeqStringChars(HValue* src, HValue* src_offset, String::Encoding src_encoding, HValue* dst, HValue* dst_offset, String::Encoding dst_encoding, HValue* length) { ASSERT(dst_encoding != String::ONE_BYTE_ENCODING || src_encoding == String::ONE_BYTE_ENCODING); LoopBuilder loop(this, context(), LoopBuilder::kPostIncrement); HValue* index = loop.BeginBody(graph()->GetConstant0(), length, Token::LT); { HValue* src_index = AddUncasted<HAdd>(src_offset, index); HValue* value = AddUncasted<HSeqStringGetChar>(src_encoding, src, src_index); HValue* dst_index = AddUncasted<HAdd>(dst_offset, index); Add<HSeqStringSetChar>(dst_encoding, dst, dst_index, value); } loop.EndBody(); } HValue* HGraphBuilder::BuildObjectSizeAlignment( HValue* unaligned_size, int header_size) { ASSERT((header_size & kObjectAlignmentMask) == 0); HValue* size = AddUncasted<HAdd>( unaligned_size, Add<HConstant>(static_cast<int32_t>( header_size + kObjectAlignmentMask))); size->ClearFlag(HValue::kCanOverflow); return AddUncasted<HBitwise>( Token::BIT_AND, size, Add<HConstant>(static_cast<int32_t>( ~kObjectAlignmentMask))); } HValue* HGraphBuilder::BuildUncheckedStringAdd( HValue* left, HValue* right, HAllocationMode allocation_mode) { // Determine the string lengths. HValue* left_length = AddLoadStringLength(left); HValue* right_length = AddLoadStringLength(right); // Compute the combined string length. HValue* length = BuildAddStringLengths(left_length, right_length); // Do some manual constant folding here. if (left_length->IsConstant()) { HConstant* c_left_length = HConstant::cast(left_length); ASSERT_NE(0, c_left_length->Integer32Value()); if (c_left_length->Integer32Value() + 1 >= ConsString::kMinLength) { // The right string contains at least one character. return BuildCreateConsString(length, left, right, allocation_mode); } } else if (right_length->IsConstant()) { HConstant* c_right_length = HConstant::cast(right_length); ASSERT_NE(0, c_right_length->Integer32Value()); if (c_right_length->Integer32Value() + 1 >= ConsString::kMinLength) { // The left string contains at least one character. return BuildCreateConsString(length, left, right, allocation_mode); } } // Check if we should create a cons string. IfBuilder if_createcons(this); if_createcons.If<HCompareNumericAndBranch>( length, Add<HConstant>(ConsString::kMinLength), Token::GTE); if_createcons.Then(); { // Create a cons string. Push(BuildCreateConsString(length, left, right, allocation_mode)); } if_createcons.Else(); { // Determine the string instance types. HValue* left_instance_type = AddLoadStringInstanceType(left); HValue* right_instance_type = AddLoadStringInstanceType(right); // Compute union and difference of instance types. HValue* ored_instance_types = AddUncasted<HBitwise>( Token::BIT_OR, left_instance_type, right_instance_type); HValue* xored_instance_types = AddUncasted<HBitwise>( Token::BIT_XOR, left_instance_type, right_instance_type); // Check if both strings have the same encoding and both are // sequential. IfBuilder if_sameencodingandsequential(this); if_sameencodingandsequential.If<HCompareNumericAndBranch>( AddUncasted<HBitwise>( Token::BIT_AND, xored_instance_types, Add<HConstant>(static_cast<int32_t>(kStringEncodingMask))), graph()->GetConstant0(), Token::EQ); if_sameencodingandsequential.And(); STATIC_ASSERT(kSeqStringTag == 0); if_sameencodingandsequential.If<HCompareNumericAndBranch>( AddUncasted<HBitwise>( Token::BIT_AND, ored_instance_types, Add<HConstant>(static_cast<int32_t>(kStringRepresentationMask))), graph()->GetConstant0(), Token::EQ); if_sameencodingandsequential.Then(); { HConstant* string_map = Add<HConstant>(isolate()->factory()->string_map()); HConstant* ascii_string_map = Add<HConstant>(isolate()->factory()->ascii_string_map()); // Determine map and size depending on whether result is one-byte string. IfBuilder if_onebyte(this); STATIC_ASSERT(kOneByteStringTag != 0); if_onebyte.If<HCompareNumericAndBranch>( AddUncasted<HBitwise>( Token::BIT_AND, ored_instance_types, Add<HConstant>(static_cast<int32_t>(kStringEncodingMask))), graph()->GetConstant0(), Token::NE); if_onebyte.Then(); { // Allocate sequential one-byte string object. Push(length); Push(ascii_string_map); } if_onebyte.Else(); { // Allocate sequential two-byte string object. HValue* size = AddUncasted<HShl>(length, graph()->GetConstant1()); size->ClearFlag(HValue::kCanOverflow); size->SetFlag(HValue::kUint32); Push(size); Push(string_map); } if_onebyte.End(); HValue* map = Pop(); // Calculate the number of bytes needed for the characters in the // string while observing object alignment. STATIC_ASSERT((SeqString::kHeaderSize & kObjectAlignmentMask) == 0); HValue* size = BuildObjectSizeAlignment(Pop(), SeqString::kHeaderSize); // Allocate the string object. HAllocate does not care whether we pass // STRING_TYPE or ASCII_STRING_TYPE here, so we just use STRING_TYPE here. HAllocate* result = BuildAllocate( size, HType::String(), STRING_TYPE, allocation_mode); Add<HStoreNamedField>(result, HObjectAccess::ForMap(), map); // Initialize the string fields. Add<HStoreNamedField>(result, HObjectAccess::ForStringHashField(), Add<HConstant>(String::kEmptyHashField)); Add<HStoreNamedField>(result, HObjectAccess::ForStringLength(), length); // Copy characters to the result string. IfBuilder if_twobyte(this); if_twobyte.If<HCompareObjectEqAndBranch>(map, string_map); if_twobyte.Then(); { // Copy characters from the left string. BuildCopySeqStringChars( left, graph()->GetConstant0(), String::TWO_BYTE_ENCODING, result, graph()->GetConstant0(), String::TWO_BYTE_ENCODING, left_length); // Copy characters from the right string. BuildCopySeqStringChars( right, graph()->GetConstant0(), String::TWO_BYTE_ENCODING, result, left_length, String::TWO_BYTE_ENCODING, right_length); } if_twobyte.Else(); { // Copy characters from the left string. BuildCopySeqStringChars( left, graph()->GetConstant0(), String::ONE_BYTE_ENCODING, result, graph()->GetConstant0(), String::ONE_BYTE_ENCODING, left_length); // Copy characters from the right string. BuildCopySeqStringChars( right, graph()->GetConstant0(), String::ONE_BYTE_ENCODING, result, left_length, String::ONE_BYTE_ENCODING, right_length); } if_twobyte.End(); // Count the native string addition. AddIncrementCounter(isolate()->counters()->string_add_native()); // Return the sequential string. Push(result); } if_sameencodingandsequential.Else(); { // Fallback to the runtime to add the two strings. Add<HPushArguments>(left, right); Push(Add<HCallRuntime>( isolate()->factory()->empty_string(), Runtime::FunctionForId(Runtime::kHiddenStringAdd), 2)); } if_sameencodingandsequential.End(); } if_createcons.End(); return Pop(); } HValue* HGraphBuilder::BuildStringAdd( HValue* left, HValue* right, HAllocationMode allocation_mode) { NoObservableSideEffectsScope no_effects(this); // Determine string lengths. HValue* left_length = AddLoadStringLength(left); HValue* right_length = AddLoadStringLength(right); // Check if left string is empty. IfBuilder if_leftempty(this); if_leftempty.If<HCompareNumericAndBranch>( left_length, graph()->GetConstant0(), Token::EQ); if_leftempty.Then(); { // Count the native string addition. AddIncrementCounter(isolate()->counters()->string_add_native()); // Just return the right string. Push(right); } if_leftempty.Else(); { // Check if right string is empty. IfBuilder if_rightempty(this); if_rightempty.If<HCompareNumericAndBranch>( right_length, graph()->GetConstant0(), Token::EQ); if_rightempty.Then(); { // Count the native string addition. AddIncrementCounter(isolate()->counters()->string_add_native()); // Just return the left string. Push(left); } if_rightempty.Else(); { // Add the two non-empty strings. Push(BuildUncheckedStringAdd(left, right, allocation_mode)); } if_rightempty.End(); } if_leftempty.End(); return Pop(); } HInstruction* HGraphBuilder::BuildUncheckedMonomorphicElementAccess( HValue* checked_object, HValue* key, HValue* val, bool is_js_array, ElementsKind elements_kind, PropertyAccessType access_type, LoadKeyedHoleMode load_mode, KeyedAccessStoreMode store_mode) { ASSERT((!IsExternalArrayElementsKind(elements_kind) && !IsFixedTypedArrayElementsKind(elements_kind)) || !is_js_array); // No GVNFlag is necessary for ElementsKind if there is an explicit dependency // on a HElementsTransition instruction. The flag can also be removed if the // map to check has FAST_HOLEY_ELEMENTS, since there can be no further // ElementsKind transitions. Finally, the dependency can be removed for stores // for FAST_ELEMENTS, since a transition to HOLEY elements won't change the // generated store code. if ((elements_kind == FAST_HOLEY_ELEMENTS) || (elements_kind == FAST_ELEMENTS && access_type == STORE)) { checked_object->ClearDependsOnFlag(kElementsKind); } bool fast_smi_only_elements = IsFastSmiElementsKind(elements_kind); bool fast_elements = IsFastObjectElementsKind(elements_kind); HValue* elements = AddLoadElements(checked_object); if (access_type == STORE && (fast_elements || fast_smi_only_elements) && store_mode != STORE_NO_TRANSITION_HANDLE_COW) { HCheckMaps* check_cow_map = Add<HCheckMaps>( elements, isolate()->factory()->fixed_array_map()); check_cow_map->ClearDependsOnFlag(kElementsKind); } HInstruction* length = NULL; if (is_js_array) { length = Add<HLoadNamedField>( checked_object->ActualValue(), checked_object, HObjectAccess::ForArrayLength(elements_kind)); } else { length = AddLoadFixedArrayLength(elements); } length->set_type(HType::Smi()); HValue* checked_key = NULL; if (IsExternalArrayElementsKind(elements_kind) || IsFixedTypedArrayElementsKind(elements_kind)) { HValue* backing_store; if (IsExternalArrayElementsKind(elements_kind)) { backing_store = Add<HLoadNamedField>( elements, static_cast<HValue*>(NULL), HObjectAccess::ForExternalArrayExternalPointer()); } else { backing_store = elements; } if (store_mode == STORE_NO_TRANSITION_IGNORE_OUT_OF_BOUNDS) { NoObservableSideEffectsScope no_effects(this); IfBuilder length_checker(this); length_checker.If<HCompareNumericAndBranch>(key, length, Token::LT); length_checker.Then(); IfBuilder negative_checker(this); HValue* bounds_check = negative_checker.If<HCompareNumericAndBranch>( key, graph()->GetConstant0(), Token::GTE); negative_checker.Then(); HInstruction* result = AddElementAccess( backing_store, key, val, bounds_check, elements_kind, access_type); negative_checker.ElseDeopt("Negative key encountered"); negative_checker.End(); length_checker.End(); return result; } else { ASSERT(store_mode == STANDARD_STORE); checked_key = Add<HBoundsCheck>(key, length); return AddElementAccess( backing_store, checked_key, val, checked_object, elements_kind, access_type); } } ASSERT(fast_smi_only_elements || fast_elements || IsFastDoubleElementsKind(elements_kind)); // In case val is stored into a fast smi array, assure that the value is a smi // before manipulating the backing store. Otherwise the actual store may // deopt, leaving the backing store in an invalid state. if (access_type == STORE && IsFastSmiElementsKind(elements_kind) && !val->type().IsSmi()) { val = AddUncasted<HForceRepresentation>(val, Representation::Smi()); } if (IsGrowStoreMode(store_mode)) { NoObservableSideEffectsScope no_effects(this); elements = BuildCheckForCapacityGrow(checked_object, elements, elements_kind, length, key, is_js_array, access_type); checked_key = key; } else { checked_key = Add<HBoundsCheck>(key, length); if (access_type == STORE && (fast_elements || fast_smi_only_elements)) { if (store_mode == STORE_NO_TRANSITION_HANDLE_COW) { NoObservableSideEffectsScope no_effects(this); elements = BuildCopyElementsOnWrite(checked_object, elements, elements_kind, length); } else { HCheckMaps* check_cow_map = Add<HCheckMaps>( elements, isolate()->factory()->fixed_array_map()); check_cow_map->ClearDependsOnFlag(kElementsKind); } } } return AddElementAccess(elements, checked_key, val, checked_object, elements_kind, access_type, load_mode); } HValue* HGraphBuilder::BuildAllocateArrayFromLength( JSArrayBuilder* array_builder, HValue* length_argument) { if (length_argument->IsConstant() && HConstant::cast(length_argument)->HasSmiValue()) { int array_length = HConstant::cast(length_argument)->Integer32Value(); if (array_length == 0) { return array_builder->AllocateEmptyArray(); } else { return array_builder->AllocateArray(length_argument, array_length, length_argument); } } HValue* constant_zero = graph()->GetConstant0(); HConstant* max_alloc_length = Add<HConstant>(JSObject::kInitialMaxFastElementArray); HInstruction* checked_length = Add<HBoundsCheck>(length_argument, max_alloc_length); IfBuilder if_builder(this); if_builder.If<HCompareNumericAndBranch>(checked_length, constant_zero, Token::EQ); if_builder.Then(); const int initial_capacity = JSArray::kPreallocatedArrayElements; HConstant* initial_capacity_node = Add<HConstant>(initial_capacity); Push(initial_capacity_node); // capacity Push(constant_zero); // length if_builder.Else(); if (!(top_info()->IsStub()) && IsFastPackedElementsKind(array_builder->kind())) { // We'll come back later with better (holey) feedback. if_builder.Deopt("Holey array despite packed elements_kind feedback"); } else { Push(checked_length); // capacity Push(checked_length); // length } if_builder.End(); // Figure out total size HValue* length = Pop(); HValue* capacity = Pop(); return array_builder->AllocateArray(capacity, max_alloc_length, length); } HValue* HGraphBuilder::BuildCalculateElementsSize(ElementsKind kind, HValue* capacity) { int elements_size = IsFastDoubleElementsKind(kind) ? kDoubleSize : kPointerSize; HConstant* elements_size_value = Add<HConstant>(elements_size); HInstruction* mul = HMul::NewImul(zone(), context(), capacity->ActualValue(), elements_size_value); AddInstruction(mul); mul->ClearFlag(HValue::kCanOverflow); STATIC_ASSERT(FixedDoubleArray::kHeaderSize == FixedArray::kHeaderSize); HConstant* header_size = Add<HConstant>(FixedArray::kHeaderSize); HValue* total_size = AddUncasted<HAdd>(mul, header_size); total_size->ClearFlag(HValue::kCanOverflow); return total_size; } HAllocate* HGraphBuilder::AllocateJSArrayObject(AllocationSiteMode mode) { int base_size = JSArray::kSize; if (mode == TRACK_ALLOCATION_SITE) { base_size += AllocationMemento::kSize; } HConstant* size_in_bytes = Add<HConstant>(base_size); return Add<HAllocate>( size_in_bytes, HType::JSArray(), NOT_TENURED, JS_OBJECT_TYPE); } HConstant* HGraphBuilder::EstablishElementsAllocationSize( ElementsKind kind, int capacity) { int base_size = IsFastDoubleElementsKind(kind) ? FixedDoubleArray::SizeFor(capacity) : FixedArray::SizeFor(capacity); return Add<HConstant>(base_size); } HAllocate* HGraphBuilder::BuildAllocateElements(ElementsKind kind, HValue* size_in_bytes) { InstanceType instance_type = IsFastDoubleElementsKind(kind) ? FIXED_DOUBLE_ARRAY_TYPE : FIXED_ARRAY_TYPE; return Add<HAllocate>(size_in_bytes, HType::HeapObject(), NOT_TENURED, instance_type); } void HGraphBuilder::BuildInitializeElementsHeader(HValue* elements, ElementsKind kind, HValue* capacity) { Factory* factory = isolate()->factory(); Handle<Map> map = IsFastDoubleElementsKind(kind) ? factory->fixed_double_array_map() : factory->fixed_array_map(); Add<HStoreNamedField>(elements, HObjectAccess::ForMap(), Add<HConstant>(map)); Add<HStoreNamedField>(elements, HObjectAccess::ForFixedArrayLength(), capacity); } HValue* HGraphBuilder::BuildAllocateElementsAndInitializeElementsHeader( ElementsKind kind, HValue* capacity) { // The HForceRepresentation is to prevent possible deopt on int-smi // conversion after allocation but before the new object fields are set. capacity = AddUncasted<HForceRepresentation>(capacity, Representation::Smi()); HValue* size_in_bytes = BuildCalculateElementsSize(kind, capacity); HValue* new_elements = BuildAllocateElements(kind, size_in_bytes); BuildInitializeElementsHeader(new_elements, kind, capacity); return new_elements; } void HGraphBuilder::BuildJSArrayHeader(HValue* array, HValue* array_map, HValue* elements, AllocationSiteMode mode, ElementsKind elements_kind, HValue* allocation_site_payload, HValue* length_field) { Add<HStoreNamedField>(array, HObjectAccess::ForMap(), array_map); HConstant* empty_fixed_array = Add<HConstant>(isolate()->factory()->empty_fixed_array()); Add<HStoreNamedField>( array, HObjectAccess::ForPropertiesPointer(), empty_fixed_array); Add<HStoreNamedField>( array, HObjectAccess::ForElementsPointer(), elements != NULL ? elements : empty_fixed_array); Add<HStoreNamedField>( array, HObjectAccess::ForArrayLength(elements_kind), length_field); if (mode == TRACK_ALLOCATION_SITE) { BuildCreateAllocationMemento( array, Add<HConstant>(JSArray::kSize), allocation_site_payload); } } HInstruction* HGraphBuilder::AddElementAccess( HValue* elements, HValue* checked_key, HValue* val, HValue* dependency, ElementsKind elements_kind, PropertyAccessType access_type, LoadKeyedHoleMode load_mode) { if (access_type == STORE) { ASSERT(val != NULL); if (elements_kind == EXTERNAL_UINT8_CLAMPED_ELEMENTS || elements_kind == UINT8_CLAMPED_ELEMENTS) { val = Add<HClampToUint8>(val); } return Add<HStoreKeyed>(elements, checked_key, val, elements_kind, elements_kind == FAST_SMI_ELEMENTS ? STORE_TO_INITIALIZED_ENTRY : INITIALIZING_STORE); } ASSERT(access_type == LOAD); ASSERT(val == NULL); HLoadKeyed* load = Add<HLoadKeyed>( elements, checked_key, dependency, elements_kind, load_mode); if (FLAG_opt_safe_uint32_operations && (elements_kind == EXTERNAL_UINT32_ELEMENTS || elements_kind == UINT32_ELEMENTS)) { graph()->RecordUint32Instruction(load); } return load; } HLoadNamedField* HGraphBuilder::AddLoadMap(HValue* object, HValue* dependency) { return Add<HLoadNamedField>(object, dependency, HObjectAccess::ForMap()); } HLoadNamedField* HGraphBuilder::AddLoadElements(HValue* object, HValue* dependency) { return Add<HLoadNamedField>( object, dependency, HObjectAccess::ForElementsPointer()); } HLoadNamedField* HGraphBuilder::AddLoadFixedArrayLength( HValue* array, HValue* dependency) { return Add<HLoadNamedField>( array, dependency, HObjectAccess::ForFixedArrayLength()); } HLoadNamedField* HGraphBuilder::AddLoadArrayLength(HValue* array, ElementsKind kind, HValue* dependency) { return Add<HLoadNamedField>( array, dependency, HObjectAccess::ForArrayLength(kind)); } HValue* HGraphBuilder::BuildNewElementsCapacity(HValue* old_capacity) { HValue* half_old_capacity = AddUncasted<HShr>(old_capacity, graph_->GetConstant1()); HValue* new_capacity = AddUncasted<HAdd>(half_old_capacity, old_capacity); new_capacity->ClearFlag(HValue::kCanOverflow); HValue* min_growth = Add<HConstant>(16); new_capacity = AddUncasted<HAdd>(new_capacity, min_growth); new_capacity->ClearFlag(HValue::kCanOverflow); return new_capacity; } HValue* HGraphBuilder::BuildGrowElementsCapacity(HValue* object, HValue* elements, ElementsKind kind, ElementsKind new_kind, HValue* length, HValue* new_capacity) { Add<HBoundsCheck>(new_capacity, Add<HConstant>( (Page::kMaxRegularHeapObjectSize - FixedArray::kHeaderSize) >> ElementsKindToShiftSize(kind))); HValue* new_elements = BuildAllocateElementsAndInitializeElementsHeader( new_kind, new_capacity); BuildCopyElements(elements, kind, new_elements, new_kind, length, new_capacity); Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(), new_elements); return new_elements; } void HGraphBuilder::BuildFillElementsWithValue(HValue* elements, ElementsKind elements_kind, HValue* from, HValue* to, HValue* value) { if (to == NULL) { to = AddLoadFixedArrayLength(elements); } // Special loop unfolding case STATIC_ASSERT(JSArray::kPreallocatedArrayElements <= kElementLoopUnrollThreshold); int initial_capacity = -1; if (from->IsInteger32Constant() && to->IsInteger32Constant()) { int constant_from = from->GetInteger32Constant(); int constant_to = to->GetInteger32Constant(); if (constant_from == 0 && constant_to <= kElementLoopUnrollThreshold) { initial_capacity = constant_to; } } // Since we're about to store a hole value, the store instruction below must // assume an elements kind that supports heap object values. if (IsFastSmiOrObjectElementsKind(elements_kind)) { elements_kind = FAST_HOLEY_ELEMENTS; } if (initial_capacity >= 0) { for (int i = 0; i < initial_capacity; i++) { HInstruction* key = Add<HConstant>(i); Add<HStoreKeyed>(elements, key, value, elements_kind); } } else { // Carefully loop backwards so that the "from" remains live through the loop // rather than the to. This often corresponds to keeping length live rather // then capacity, which helps register allocation, since length is used more // other than capacity after filling with holes. LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement); HValue* key = builder.BeginBody(to, from, Token::GT); HValue* adjusted_key = AddUncasted<HSub>(key, graph()->GetConstant1()); adjusted_key->ClearFlag(HValue::kCanOverflow); Add<HStoreKeyed>(elements, adjusted_key, value, elements_kind); builder.EndBody(); } } void HGraphBuilder::BuildFillElementsWithHole(HValue* elements, ElementsKind elements_kind, HValue* from, HValue* to) { // Fast elements kinds need to be initialized in case statements below cause a // garbage collection. Factory* factory = isolate()->factory(); double nan_double = FixedDoubleArray::hole_nan_as_double(); HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind) ? Add<HConstant>(factory->the_hole_value()) : Add<HConstant>(nan_double); BuildFillElementsWithValue(elements, elements_kind, from, to, hole); } void HGraphBuilder::BuildCopyElements(HValue* from_elements, ElementsKind from_elements_kind, HValue* to_elements, ElementsKind to_elements_kind, HValue* length, HValue* capacity) { int constant_capacity = -1; if (capacity != NULL && capacity->IsConstant() && HConstant::cast(capacity)->HasInteger32Value()) { int constant_candidate = HConstant::cast(capacity)->Integer32Value(); if (constant_candidate <= kElementLoopUnrollThreshold) { constant_capacity = constant_candidate; } } bool pre_fill_with_holes = IsFastDoubleElementsKind(from_elements_kind) && IsFastObjectElementsKind(to_elements_kind); if (pre_fill_with_holes) { // If the copy might trigger a GC, make sure that the FixedArray is // pre-initialized with holes to make sure that it's always in a // consistent state. BuildFillElementsWithHole(to_elements, to_elements_kind, graph()->GetConstant0(), NULL); } if (constant_capacity != -1) { // Unroll the loop for small elements kinds. for (int i = 0; i < constant_capacity; i++) { HValue* key_constant = Add<HConstant>(i); HInstruction* value = Add<HLoadKeyed>(from_elements, key_constant, static_cast<HValue*>(NULL), from_elements_kind); Add<HStoreKeyed>(to_elements, key_constant, value, to_elements_kind); } } else { if (!pre_fill_with_holes && (capacity == NULL || !length->Equals(capacity))) { BuildFillElementsWithHole(to_elements, to_elements_kind, length, NULL); } if (capacity == NULL) { capacity = AddLoadFixedArrayLength(to_elements); } LoopBuilder builder(this, context(), LoopBuilder::kPostDecrement); HValue* key = builder.BeginBody(length, graph()->GetConstant0(), Token::GT); key = AddUncasted<HSub>(key, graph()->GetConstant1()); key->ClearFlag(HValue::kCanOverflow); HValue* element = Add<HLoadKeyed>(from_elements, key, static_cast<HValue*>(NULL), from_elements_kind, ALLOW_RETURN_HOLE); ElementsKind kind = (IsHoleyElementsKind(from_elements_kind) && IsFastSmiElementsKind(to_elements_kind)) ? FAST_HOLEY_ELEMENTS : to_elements_kind; if (IsHoleyElementsKind(from_elements_kind) && from_elements_kind != to_elements_kind) { IfBuilder if_hole(this); if_hole.If<HCompareHoleAndBranch>(element); if_hole.Then(); HConstant* hole_constant = IsFastDoubleElementsKind(to_elements_kind) ? Add<HConstant>(FixedDoubleArray::hole_nan_as_double()) : graph()->GetConstantHole(); Add<HStoreKeyed>(to_elements, key, hole_constant, kind); if_hole.Else(); HStoreKeyed* store = Add<HStoreKeyed>(to_elements, key, element, kind); store->SetFlag(HValue::kAllowUndefinedAsNaN); if_hole.End(); } else { HStoreKeyed* store = Add<HStoreKeyed>(to_elements, key, element, kind); store->SetFlag(HValue::kAllowUndefinedAsNaN); } builder.EndBody(); } Counters* counters = isolate()->counters(); AddIncrementCounter(counters->inlined_copied_elements()); } HValue* HGraphBuilder::BuildCloneShallowArrayCow(HValue* boilerplate, HValue* allocation_site, AllocationSiteMode mode, ElementsKind kind) { HAllocate* array = AllocateJSArrayObject(mode); HValue* map = AddLoadMap(boilerplate); HValue* elements = AddLoadElements(boilerplate); HValue* length = AddLoadArrayLength(boilerplate, kind); BuildJSArrayHeader(array, map, elements, mode, FAST_ELEMENTS, allocation_site, length); return array; } HValue* HGraphBuilder::BuildCloneShallowArrayEmpty(HValue* boilerplate, HValue* allocation_site, AllocationSiteMode mode) { HAllocate* array = AllocateJSArrayObject(mode); HValue* map = AddLoadMap(boilerplate); BuildJSArrayHeader(array, map, NULL, // set elements to empty fixed array mode, FAST_ELEMENTS, allocation_site, graph()->GetConstant0()); return array; } HValue* HGraphBuilder::BuildCloneShallowArrayNonEmpty(HValue* boilerplate, HValue* allocation_site, AllocationSiteMode mode, ElementsKind kind) { HValue* boilerplate_elements = AddLoadElements(boilerplate); HValue* capacity = AddLoadFixedArrayLength(boilerplate_elements); // Generate size calculation code here in order to make it dominate // the JSArray allocation. HValue* elements_size = BuildCalculateElementsSize(kind, capacity); // Create empty JSArray object for now, store elimination should remove // redundant initialization of elements and length fields and at the same // time the object will be fully prepared for GC if it happens during // elements allocation. HValue* result = BuildCloneShallowArrayEmpty( boilerplate, allocation_site, mode); HAllocate* elements = BuildAllocateElements(kind, elements_size); // This function implicitly relies on the fact that the // FastCloneShallowArrayStub is called only for literals shorter than // JSObject::kInitialMaxFastElementArray. // Can't add HBoundsCheck here because otherwise the stub will eager a frame. HConstant* size_upper_bound = EstablishElementsAllocationSize( kind, JSObject::kInitialMaxFastElementArray); elements->set_size_upper_bound(size_upper_bound); Add<HStoreNamedField>(result, HObjectAccess::ForElementsPointer(), elements); // The allocation for the cloned array above causes register pressure on // machines with low register counts. Force a reload of the boilerplate // elements here to free up a register for the allocation to avoid unnecessary // spillage. boilerplate_elements = AddLoadElements(boilerplate); boilerplate_elements->SetFlag(HValue::kCantBeReplaced); // Copy the elements array header. for (int i = 0; i < FixedArrayBase::kHeaderSize; i += kPointerSize) { HObjectAccess access = HObjectAccess::ForFixedArrayHeader(i); Add<HStoreNamedField>(elements, access, Add<HLoadNamedField>(boilerplate_elements, static_cast<HValue*>(NULL), access)); } // And the result of the length HValue* length = AddLoadArrayLength(boilerplate, kind); Add<HStoreNamedField>(result, HObjectAccess::ForArrayLength(kind), length); BuildCopyElements(boilerplate_elements, kind, elements, kind, length, NULL); return result; } void HGraphBuilder::BuildCompareNil( HValue* value, Type* type, HIfContinuation* continuation) { IfBuilder if_nil(this); bool some_case_handled = false; bool some_case_missing = false; if (type->Maybe(Type::Null())) { if (some_case_handled) if_nil.Or(); if_nil.If<HCompareObjectEqAndBranch>(value, graph()->GetConstantNull()); some_case_handled = true; } else { some_case_missing = true; } if (type->Maybe(Type::Undefined())) { if (some_case_handled) if_nil.Or(); if_nil.If<HCompareObjectEqAndBranch>(value, graph()->GetConstantUndefined()); some_case_handled = true; } else { some_case_missing = true; } if (type->Maybe(Type::Undetectable())) { if (some_case_handled) if_nil.Or(); if_nil.If<HIsUndetectableAndBranch>(value); some_case_handled = true; } else { some_case_missing = true; } if (some_case_missing) { if_nil.Then(); if_nil.Else(); if (type->NumClasses() == 1) { BuildCheckHeapObject(value); // For ICs, the map checked below is a sentinel map that gets replaced by // the monomorphic map when the code is used as a template to generate a // new IC. For optimized functions, there is no sentinel map, the map // emitted below is the actual monomorphic map. Add<HCheckMaps>(value, type->Classes().Current()); } else { if_nil.Deopt("Too many undetectable types"); } } if_nil.CaptureContinuation(continuation); } void HGraphBuilder::BuildCreateAllocationMemento( HValue* previous_object, HValue* previous_object_size, HValue* allocation_site) { ASSERT(allocation_site != NULL); HInnerAllocatedObject* allocation_memento = Add<HInnerAllocatedObject>( previous_object, previous_object_size, HType::HeapObject()); AddStoreMapConstant( allocation_memento, isolate()->factory()->allocation_memento_map()); Add<HStoreNamedField>( allocation_memento, HObjectAccess::ForAllocationMementoSite(), allocation_site); if (FLAG_allocation_site_pretenuring) { HValue* memento_create_count = Add<HLoadNamedField>( allocation_site, static_cast<HValue*>(NULL), HObjectAccess::ForAllocationSiteOffset( AllocationSite::kPretenureCreateCountOffset)); memento_create_count = AddUncasted<HAdd>( memento_create_count, graph()->GetConstant1()); // This smi value is reset to zero after every gc, overflow isn't a problem // since the counter is bounded by the new space size. memento_create_count->ClearFlag(HValue::kCanOverflow); Add<HStoreNamedField>( allocation_site, HObjectAccess::ForAllocationSiteOffset( AllocationSite::kPretenureCreateCountOffset), memento_create_count); } } HInstruction* HGraphBuilder::BuildGetNativeContext(HValue* closure) { // Get the global context, then the native context HInstruction* context = Add<HLoadNamedField>(closure, static_cast<HValue*>(NULL), HObjectAccess::ForFunctionContextPointer()); HInstruction* global_object = Add<HLoadNamedField>( context, static_cast<HValue*>(NULL), HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX)); HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset( GlobalObject::kNativeContextOffset); return Add<HLoadNamedField>( global_object, static_cast<HValue*>(NULL), access); } HInstruction* HGraphBuilder::BuildGetNativeContext() { // Get the global context, then the native context HValue* global_object = Add<HLoadNamedField>( context(), static_cast<HValue*>(NULL), HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX)); return Add<HLoadNamedField>( global_object, static_cast<HValue*>(NULL), HObjectAccess::ForObservableJSObjectOffset( GlobalObject::kNativeContextOffset)); } HInstruction* HGraphBuilder::BuildGetArrayFunction() { HInstruction* native_context = BuildGetNativeContext(); HInstruction* index = Add<HConstant>(static_cast<int32_t>(Context::ARRAY_FUNCTION_INDEX)); return Add<HLoadKeyed>( native_context, index, static_cast<HValue*>(NULL), FAST_ELEMENTS); } HGraphBuilder::JSArrayBuilder::JSArrayBuilder(HGraphBuilder* builder, ElementsKind kind, HValue* allocation_site_payload, HValue* constructor_function, AllocationSiteOverrideMode override_mode) : builder_(builder), kind_(kind), allocation_site_payload_(allocation_site_payload), constructor_function_(constructor_function) { ASSERT(!allocation_site_payload->IsConstant() || HConstant::cast(allocation_site_payload)->handle( builder_->isolate())->IsAllocationSite()); mode_ = override_mode == DISABLE_ALLOCATION_SITES ? DONT_TRACK_ALLOCATION_SITE : AllocationSite::GetMode(kind); } HGraphBuilder::JSArrayBuilder::JSArrayBuilder(HGraphBuilder* builder, ElementsKind kind, HValue* constructor_function) : builder_(builder), kind_(kind), mode_(DONT_TRACK_ALLOCATION_SITE), allocation_site_payload_(NULL), constructor_function_(constructor_function) { } HValue* HGraphBuilder::JSArrayBuilder::EmitMapCode() { if (!builder()->top_info()->IsStub()) { // A constant map is fine. Handle<Map> map(builder()->isolate()->get_initial_js_array_map(kind_), builder()->isolate()); return builder()->Add<HConstant>(map); } if (constructor_function_ != NULL && kind_ == GetInitialFastElementsKind()) { // No need for a context lookup if the kind_ matches the initial // map, because we can just load the map in that case. HObjectAccess access = HObjectAccess::ForPrototypeOrInitialMap(); return builder()->Add<HLoadNamedField>( constructor_function_, static_cast<HValue*>(NULL), access); } // TODO(mvstanton): we should always have a constructor function if we // are creating a stub. HInstruction* native_context = constructor_function_ != NULL ? builder()->BuildGetNativeContext(constructor_function_) : builder()->BuildGetNativeContext(); HInstruction* index = builder()->Add<HConstant>( static_cast<int32_t>(Context::JS_ARRAY_MAPS_INDEX)); HInstruction* map_array = builder()->Add<HLoadKeyed>( native_context, index, static_cast<HValue*>(NULL), FAST_ELEMENTS); HInstruction* kind_index = builder()->Add<HConstant>(kind_); return builder()->Add<HLoadKeyed>( map_array, kind_index, static_cast<HValue*>(NULL), FAST_ELEMENTS); } HValue* HGraphBuilder::JSArrayBuilder::EmitInternalMapCode() { // Find the map near the constructor function HObjectAccess access = HObjectAccess::ForPrototypeOrInitialMap(); return builder()->Add<HLoadNamedField>( constructor_function_, static_cast<HValue*>(NULL), access); } HAllocate* HGraphBuilder::JSArrayBuilder::AllocateEmptyArray() { HConstant* capacity = builder()->Add<HConstant>(initial_capacity()); return AllocateArray(capacity, capacity, builder()->graph()->GetConstant0()); } HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray( HValue* capacity, HConstant* capacity_upper_bound, HValue* length_field, FillMode fill_mode) { return AllocateArray(capacity, capacity_upper_bound->GetInteger32Constant(), length_field, fill_mode); } HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray( HValue* capacity, int capacity_upper_bound, HValue* length_field, FillMode fill_mode) { HConstant* elememts_size_upper_bound = capacity->IsInteger32Constant() ? HConstant::cast(capacity) : builder()->EstablishElementsAllocationSize(kind_, capacity_upper_bound); HAllocate* array = AllocateArray(capacity, length_field, fill_mode); if (!elements_location_->has_size_upper_bound()) { elements_location_->set_size_upper_bound(elememts_size_upper_bound); } return array; } HAllocate* HGraphBuilder::JSArrayBuilder::AllocateArray( HValue* capacity, HValue* length_field, FillMode fill_mode) { // These HForceRepresentations are because we store these as fields in the // objects we construct, and an int32-to-smi HChange could deopt. Accept // the deopt possibility now, before allocation occurs. capacity = builder()->AddUncasted<HForceRepresentation>(capacity, Representation::Smi()); length_field = builder()->AddUncasted<HForceRepresentation>(length_field, Representation::Smi()); // Generate size calculation code here in order to make it dominate // the JSArray allocation. HValue* elements_size = builder()->BuildCalculateElementsSize(kind_, capacity); // Allocate (dealing with failure appropriately) HAllocate* array_object = builder()->AllocateJSArrayObject(mode_); // Fill in the fields: map, properties, length HValue* map; if (allocation_site_payload_ == NULL) { map = EmitInternalMapCode(); } else { map = EmitMapCode(); } builder()->BuildJSArrayHeader(array_object, map, NULL, // set elements to empty fixed array mode_, kind_, allocation_site_payload_, length_field); // Allocate and initialize the elements elements_location_ = builder()->BuildAllocateElements(kind_, elements_size); builder()->BuildInitializeElementsHeader(elements_location_, kind_, capacity); // Set the elements builder()->Add<HStoreNamedField>( array_object, HObjectAccess::ForElementsPointer(), elements_location_); if (fill_mode == FILL_WITH_HOLE) { builder()->BuildFillElementsWithHole(elements_location_, kind_, graph()->GetConstant0(), capacity); } return array_object; } HValue* HGraphBuilder::AddLoadJSBuiltin(Builtins::JavaScript builtin) { HValue* global_object = Add<HLoadNamedField>( context(), static_cast<HValue*>(NULL), HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX)); HObjectAccess access = HObjectAccess::ForObservableJSObjectOffset( GlobalObject::kBuiltinsOffset); HValue* builtins = Add<HLoadNamedField>( global_object, static_cast<HValue*>(NULL), access); HObjectAccess function_access = HObjectAccess::ForObservableJSObjectOffset( JSBuiltinsObject::OffsetOfFunctionWithId(builtin)); return Add<HLoadNamedField>( builtins, static_cast<HValue*>(NULL), function_access); } HOptimizedGraphBuilder::HOptimizedGraphBuilder(CompilationInfo* info) : HGraphBuilder(info), function_state_(NULL), initial_function_state_(this, info, NORMAL_RETURN, 0), ast_context_(NULL), break_scope_(NULL), inlined_count_(0), globals_(10, info->zone()), inline_bailout_(false), osr_(new(info->zone()) HOsrBuilder(this)) { // This is not initialized in the initializer list because the // constructor for the initial state relies on function_state_ == NULL // to know it's the initial state. function_state_= &initial_function_state_; InitializeAstVisitor(info->zone()); if (FLAG_hydrogen_track_positions) { SetSourcePosition(info->shared_info()->start_position()); } } HBasicBlock* HOptimizedGraphBuilder::CreateJoin(HBasicBlock* first, HBasicBlock* second, BailoutId join_id) { if (first == NULL) { return second; } else if (second == NULL) { return first; } else { HBasicBlock* join_block = graph()->CreateBasicBlock(); Goto(first, join_block); Goto(second, join_block); join_block->SetJoinId(join_id); return join_block; } } HBasicBlock* HOptimizedGraphBuilder::JoinContinue(IterationStatement* statement, HBasicBlock* exit_block, HBasicBlock* continue_block) { if (continue_block != NULL) { if (exit_block != NULL) Goto(exit_block, continue_block); continue_block->SetJoinId(statement->ContinueId()); return continue_block; } return exit_block; } HBasicBlock* HOptimizedGraphBuilder::CreateLoop(IterationStatement* statement, HBasicBlock* loop_entry, HBasicBlock* body_exit, HBasicBlock* loop_successor, HBasicBlock* break_block) { if (body_exit != NULL) Goto(body_exit, loop_entry); loop_entry->PostProcessLoopHeader(statement); if (break_block != NULL) { if (loop_successor != NULL) Goto(loop_successor, break_block); break_block->SetJoinId(statement->ExitId()); return break_block; } return loop_successor; } // Build a new loop header block and set it as the current block. HBasicBlock* HOptimizedGraphBuilder::BuildLoopEntry() { HBasicBlock* loop_entry = CreateLoopHeaderBlock(); Goto(loop_entry); set_current_block(loop_entry); return loop_entry; } HBasicBlock* HOptimizedGraphBuilder::BuildLoopEntry( IterationStatement* statement) { HBasicBlock* loop_entry = osr()->HasOsrEntryAt(statement) ? osr()->BuildOsrLoopEntry(statement) : BuildLoopEntry(); return loop_entry; } void HBasicBlock::FinishExit(HControlInstruction* instruction, HSourcePosition position) { Finish(instruction, position); ClearEnvironment(); } HGraph::HGraph(CompilationInfo* info) : isolate_(info->isolate()), next_block_id_(0), entry_block_(NULL), blocks_(8, info->zone()), values_(16, info->zone()), phi_list_(NULL), uint32_instructions_(NULL), osr_(NULL), info_(info), zone_(info->zone()), is_recursive_(false), use_optimistic_licm_(false), depends_on_empty_array_proto_elements_(false), type_change_checksum_(0), maximum_environment_size_(0), no_side_effects_scope_count_(0), disallow_adding_new_values_(false), next_inline_id_(0), inlined_functions_(5, info->zone()) { if (info->IsStub()) { HydrogenCodeStub* stub = info->code_stub(); CodeStubInterfaceDescriptor* descriptor = stub->GetInterfaceDescriptor(); start_environment_ = new(zone_) HEnvironment(zone_, descriptor->environment_length()); } else { TraceInlinedFunction(info->shared_info(), HSourcePosition::Unknown()); start_environment_ = new(zone_) HEnvironment(NULL, info->scope(), info->closure(), zone_); } start_environment_->set_ast_id(BailoutId::FunctionEntry()); entry_block_ = CreateBasicBlock(); entry_block_->SetInitialEnvironment(start_environment_); } HBasicBlock* HGraph::CreateBasicBlock() { HBasicBlock* result = new(zone()) HBasicBlock(this); blocks_.Add(result, zone()); return result; } void HGraph::FinalizeUniqueness() { DisallowHeapAllocation no_gc; ASSERT(!OptimizingCompilerThread::IsOptimizerThread(isolate())); for (int i = 0; i < blocks()->length(); ++i) { for (HInstructionIterator it(blocks()->at(i)); !it.Done(); it.Advance()) { it.Current()->FinalizeUniqueness(); } } } int HGraph::TraceInlinedFunction( Handle<SharedFunctionInfo> shared, HSourcePosition position) { if (!FLAG_hydrogen_track_positions) { return 0; } int id = 0; for (; id < inlined_functions_.length(); id++) { if (inlined_functions_[id].shared().is_identical_to(shared)) { break; } } if (id == inlined_functions_.length()) { inlined_functions_.Add(InlinedFunctionInfo(shared), zone()); if (!shared->script()->IsUndefined()) { Handle<Script> script(Script::cast(shared->script())); if (!script->source()->IsUndefined()) { CodeTracer::Scope tracing_scope(isolate()->GetCodeTracer()); PrintF(tracing_scope.file(), "--- FUNCTION SOURCE (%s) id{%d,%d} ---\n", shared->DebugName()->ToCString().get(), info()->optimization_id(), id); { ConsStringIteratorOp op; StringCharacterStream stream(String::cast(script->source()), &op, shared->start_position()); // fun->end_position() points to the last character in the stream. We // need to compensate by adding one to calculate the length. int source_len = shared->end_position() - shared->start_position() + 1; for (int i = 0; i < source_len; i++) { if (stream.HasMore()) { PrintF(tracing_scope.file(), "%c", stream.GetNext()); } } } PrintF(tracing_scope.file(), "\n--- END ---\n"); } } } int inline_id = next_inline_id_++; if (inline_id != 0) { CodeTracer::Scope tracing_scope(isolate()->GetCodeTracer()); PrintF(tracing_scope.file(), "INLINE (%s) id{%d,%d} AS %d AT ", shared->DebugName()->ToCString().get(), info()->optimization_id(), id, inline_id); position.PrintTo(tracing_scope.file()); PrintF(tracing_scope.file(), "\n"); } return inline_id; } int HGraph::SourcePositionToScriptPosition(HSourcePosition pos) { if (!FLAG_hydrogen_track_positions || pos.IsUnknown()) { return pos.raw(); } return inlined_functions_[pos.inlining_id()].start_position() + pos.position(); } // Block ordering was implemented with two mutually recursive methods, // HGraph::Postorder and HGraph::PostorderLoopBlocks. // The recursion could lead to stack overflow so the algorithm has been // implemented iteratively. // At a high level the algorithm looks like this: // // Postorder(block, loop_header) : { // if (block has already been visited or is of another loop) return; // mark block as visited; // if (block is a loop header) { // VisitLoopMembers(block, loop_header); // VisitSuccessorsOfLoopHeader(block); // } else { // VisitSuccessors(block) // } // put block in result list; // } // // VisitLoopMembers(block, outer_loop_header) { // foreach (block b in block loop members) { // VisitSuccessorsOfLoopMember(b, outer_loop_header); // if (b is loop header) VisitLoopMembers(b); // } // } // // VisitSuccessorsOfLoopMember(block, outer_loop_header) { // foreach (block b in block successors) Postorder(b, outer_loop_header) // } // // VisitSuccessorsOfLoopHeader(block) { // foreach (block b in block successors) Postorder(b, block) // } // // VisitSuccessors(block, loop_header) { // foreach (block b in block successors) Postorder(b, loop_header) // } // // The ordering is started calling Postorder(entry, NULL). // // Each instance of PostorderProcessor represents the "stack frame" of the // recursion, and particularly keeps the state of the loop (iteration) of the // "Visit..." function it represents. // To recycle memory we keep all the frames in a double linked list but // this means that we cannot use constructors to initialize the frames. // class PostorderProcessor : public ZoneObject { public: // Back link (towards the stack bottom). PostorderProcessor* parent() {return father_; } // Forward link (towards the stack top). PostorderProcessor* child() {return child_; } HBasicBlock* block() { return block_; } HLoopInformation* loop() { return loop_; } HBasicBlock* loop_header() { return loop_header_; } static PostorderProcessor* CreateEntryProcessor(Zone* zone, HBasicBlock* block) { PostorderProcessor* result = new(zone) PostorderProcessor(NULL); return result->SetupSuccessors(zone, block, NULL); } PostorderProcessor* PerformStep(Zone* zone, ZoneList<HBasicBlock*>* order) { PostorderProcessor* next = PerformNonBacktrackingStep(zone, order); if (next != NULL) { return next; } else { return Backtrack(zone, order); } } private: explicit PostorderProcessor(PostorderProcessor* father) : father_(father), child_(NULL), successor_iterator(NULL) { } // Each enum value states the cycle whose state is kept by this instance. enum LoopKind { NONE, SUCCESSORS, SUCCESSORS_OF_LOOP_HEADER, LOOP_MEMBERS, SUCCESSORS_OF_LOOP_MEMBER }; // Each "Setup..." method is like a constructor for a cycle state. PostorderProcessor* SetupSuccessors(Zone* zone, HBasicBlock* block, HBasicBlock* loop_header) { if (block == NULL || block->IsOrdered() || block->parent_loop_header() != loop_header) { kind_ = NONE; block_ = NULL; loop_ = NULL; loop_header_ = NULL; return this; } else { block_ = block; loop_ = NULL; block->MarkAsOrdered(); if (block->IsLoopHeader()) { kind_ = SUCCESSORS_OF_LOOP_HEADER; loop_header_ = block; InitializeSuccessors(); PostorderProcessor* result = Push(zone); return result->SetupLoopMembers(zone, block, block->loop_information(), loop_header); } else { ASSERT(block->IsFinished()); kind_ = SUCCESSORS; loop_header_ = loop_header; InitializeSuccessors(); return this; } } } PostorderProcessor* SetupLoopMembers(Zone* zone, HBasicBlock* block, HLoopInformation* loop, HBasicBlock* loop_header) { kind_ = LOOP_MEMBERS; block_ = block; loop_ = loop; loop_header_ = loop_header; InitializeLoopMembers(); return this; } PostorderProcessor* SetupSuccessorsOfLoopMember( HBasicBlock* block, HLoopInformation* loop, HBasicBlock* loop_header) { kind_ = SUCCESSORS_OF_LOOP_MEMBER; block_ = block; loop_ = loop; loop_header_ = loop_header; InitializeSuccessors(); return this; } // This method "allocates" a new stack frame. PostorderProcessor* Push(Zone* zone) { if (child_ == NULL) { child_ = new(zone) PostorderProcessor(this); } return child_; } void ClosePostorder(ZoneList<HBasicBlock*>* order, Zone* zone) { ASSERT(block_->end()->FirstSuccessor() == NULL || order->Contains(block_->end()->FirstSuccessor()) || block_->end()->FirstSuccessor()->IsLoopHeader()); ASSERT(block_->end()->SecondSuccessor() == NULL || order->Contains(block_->end()->SecondSuccessor()) || block_->end()->SecondSuccessor()->IsLoopHeader()); order->Add(block_, zone); } // This method is the basic block to walk up the stack. PostorderProcessor* Pop(Zone* zone, ZoneList<HBasicBlock*>* order) { switch (kind_) { case SUCCESSORS: case SUCCESSORS_OF_LOOP_HEADER: ClosePostorder(order, zone); return father_; case LOOP_MEMBERS: return father_; case SUCCESSORS_OF_LOOP_MEMBER: if (block()->IsLoopHeader() && block() != loop_->loop_header()) { // In this case we need to perform a LOOP_MEMBERS cycle so we // initialize it and return this instead of father. return SetupLoopMembers(zone, block(), block()->loop_information(), loop_header_); } else { return father_; } case NONE: return father_; } UNREACHABLE(); return NULL; } // Walks up the stack. PostorderProcessor* Backtrack(Zone* zone, ZoneList<HBasicBlock*>* order) { PostorderProcessor* parent = Pop(zone, order); while (parent != NULL) { PostorderProcessor* next = parent->PerformNonBacktrackingStep(zone, order); if (next != NULL) { return next; } else { parent = parent->Pop(zone, order); } } return NULL; } PostorderProcessor* PerformNonBacktrackingStep( Zone* zone, ZoneList<HBasicBlock*>* order) { HBasicBlock* next_block; switch (kind_) { case SUCCESSORS: next_block = AdvanceSuccessors(); if (next_block != NULL) { PostorderProcessor* result = Push(zone); return result->SetupSuccessors(zone, next_block, loop_header_); } break; case SUCCESSORS_OF_LOOP_HEADER: next_block = AdvanceSuccessors(); if (next_block != NULL) { PostorderProcessor* result = Push(zone); return result->SetupSuccessors(zone, next_block, block()); } break; case LOOP_MEMBERS: next_block = AdvanceLoopMembers(); if (next_block != NULL) { PostorderProcessor* result = Push(zone); return result->SetupSuccessorsOfLoopMember(next_block, loop_, loop_header_); } break; case SUCCESSORS_OF_LOOP_MEMBER: next_block = AdvanceSuccessors(); if (next_block != NULL) { PostorderProcessor* result = Push(zone); return result->SetupSuccessors(zone, next_block, loop_header_); } break; case NONE: return NULL; } return NULL; } // The following two methods implement a "foreach b in successors" cycle. void InitializeSuccessors() { loop_index = 0; loop_length = 0; successor_iterator = HSuccessorIterator(block_->end()); } HBasicBlock* AdvanceSuccessors() { if (!successor_iterator.Done()) { HBasicBlock* result = successor_iterator.Current(); successor_iterator.Advance(); return result; } return NULL; } // The following two methods implement a "foreach b in loop members" cycle. void InitializeLoopMembers() { loop_index = 0; loop_length = loop_->blocks()->length(); } HBasicBlock* AdvanceLoopMembers() { if (loop_index < loop_length) { HBasicBlock* result = loop_->blocks()->at(loop_index); loop_index++; return result; } else { return NULL; } } LoopKind kind_; PostorderProcessor* father_; PostorderProcessor* child_; HLoopInformation* loop_; HBasicBlock* block_; HBasicBlock* loop_header_; int loop_index; int loop_length; HSuccessorIterator successor_iterator; }; void HGraph::OrderBlocks() { CompilationPhase phase("H_Block ordering", info()); #ifdef DEBUG // Initially the blocks must not be ordered. for (int i = 0; i < blocks_.length(); ++i) { ASSERT(!blocks_[i]->IsOrdered()); } #endif PostorderProcessor* postorder = PostorderProcessor::CreateEntryProcessor(zone(), blocks_[0]); blocks_.Rewind(0); while (postorder) { postorder = postorder->PerformStep(zone(), &blocks_); } #ifdef DEBUG // Now all blocks must be marked as ordered. for (int i = 0; i < blocks_.length(); ++i) { ASSERT(blocks_[i]->IsOrdered()); } #endif // Reverse block list and assign block IDs. for (int i = 0, j = blocks_.length(); --j >= i; ++i) { HBasicBlock* bi = blocks_[i]; HBasicBlock* bj = blocks_[j]; bi->set_block_id(j); bj->set_block_id(i); blocks_[i] = bj; blocks_[j] = bi; } } void HGraph::AssignDominators() { HPhase phase("H_Assign dominators", this); for (int i = 0; i < blocks_.length(); ++i) { HBasicBlock* block = blocks_[i]; if (block->IsLoopHeader()) { // Only the first predecessor of a loop header is from outside the loop. // All others are back edges, and thus cannot dominate the loop header. block->AssignCommonDominator(block->predecessors()->first()); block->AssignLoopSuccessorDominators(); } else { for (int j = blocks_[i]->predecessors()->length() - 1; j >= 0; --j) { blocks_[i]->AssignCommonDominator(blocks_[i]->predecessors()->at(j)); } } } } bool HGraph::CheckArgumentsPhiUses() { int block_count = blocks_.length(); for (int i = 0; i < block_count; ++i) { for (int j = 0; j < blocks_[i]->phis()->length(); ++j) { HPhi* phi = blocks_[i]->phis()->at(j); // We don't support phi uses of arguments for now. if (phi->CheckFlag(HValue::kIsArguments)) return false; } } return true; } bool HGraph::CheckConstPhiUses() { int block_count = blocks_.length(); for (int i = 0; i < block_count; ++i) { for (int j = 0; j < blocks_[i]->phis()->length(); ++j) { HPhi* phi = blocks_[i]->phis()->at(j); // Check for the hole value (from an uninitialized const). for (int k = 0; k < phi->OperandCount(); k++) { if (phi->OperandAt(k) == GetConstantHole()) return false; } } } return true; } void HGraph::CollectPhis() { int block_count = blocks_.length(); phi_list_ = new(zone()) ZoneList<HPhi*>(block_count, zone()); for (int i = 0; i < block_count; ++i) { for (int j = 0; j < blocks_[i]->phis()->length(); ++j) { HPhi* phi = blocks_[i]->phis()->at(j); phi_list_->Add(phi, zone()); } } } // Implementation of utility class to encapsulate the translation state for // a (possibly inlined) function. FunctionState::FunctionState(HOptimizedGraphBuilder* owner, CompilationInfo* info, InliningKind inlining_kind, int inlining_id) : owner_(owner), compilation_info_(info), call_context_(NULL), inlining_kind_(inlining_kind), function_return_(NULL), test_context_(NULL), entry_(NULL), arguments_object_(NULL), arguments_elements_(NULL), inlining_id_(inlining_id), outer_source_position_(HSourcePosition::Unknown()), outer_(owner->function_state()) { if (outer_ != NULL) { // State for an inline function. if (owner->ast_context()->IsTest()) { HBasicBlock* if_true = owner->graph()->CreateBasicBlock(); HBasicBlock* if_false = owner->graph()->CreateBasicBlock(); if_true->MarkAsInlineReturnTarget(owner->current_block()); if_false->MarkAsInlineReturnTarget(owner->current_block()); TestContext* outer_test_context = TestContext::cast(owner->ast_context()); Expression* cond = outer_test_context->condition(); // The AstContext constructor pushed on the context stack. This newed // instance is the reason that AstContext can't be BASE_EMBEDDED. test_context_ = new TestContext(owner, cond, if_true, if_false); } else { function_return_ = owner->graph()->CreateBasicBlock(); function_return()->MarkAsInlineReturnTarget(owner->current_block()); } // Set this after possibly allocating a new TestContext above. call_context_ = owner->ast_context(); } // Push on the state stack. owner->set_function_state(this); if (FLAG_hydrogen_track_positions) { outer_source_position_ = owner->source_position(); owner->EnterInlinedSource( info->shared_info()->start_position(), inlining_id); owner->SetSourcePosition(info->shared_info()->start_position()); } } FunctionState::~FunctionState() { delete test_context_; owner_->set_function_state(outer_); if (FLAG_hydrogen_track_positions) { owner_->set_source_position(outer_source_position_); owner_->EnterInlinedSource( outer_->compilation_info()->shared_info()->start_position(), outer_->inlining_id()); } } // Implementation of utility classes to represent an expression's context in // the AST. AstContext::AstContext(HOptimizedGraphBuilder* owner, Expression::Context kind) : owner_(owner), kind_(kind), outer_(owner->ast_context()), for_typeof_(false) { owner->set_ast_context(this); // Push. #ifdef DEBUG ASSERT(owner->environment()->frame_type() == JS_FUNCTION); original_length_ = owner->environment()->length(); #endif } AstContext::~AstContext() { owner_->set_ast_context(outer_); // Pop. } EffectContext::~EffectContext() { ASSERT(owner()->HasStackOverflow() || owner()->current_block() == NULL || (owner()->environment()->length() == original_length_ && owner()->environment()->frame_type() == JS_FUNCTION)); } ValueContext::~ValueContext() { ASSERT(owner()->HasStackOverflow() || owner()->current_block() == NULL || (owner()->environment()->length() == original_length_ + 1 && owner()->environment()->frame_type() == JS_FUNCTION)); } void EffectContext::ReturnValue(HValue* value) { // The value is simply ignored. } void ValueContext::ReturnValue(HValue* value) { // The value is tracked in the bailout environment, and communicated // through the environment as the result of the expression. if (!arguments_allowed() && value->CheckFlag(HValue::kIsArguments)) { owner()->Bailout(kBadValueContextForArgumentsValue); } owner()->Push(value); } void TestContext::ReturnValue(HValue* value) { BuildBranch(value); } void EffectContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) { ASSERT(!instr->IsControlInstruction()); owner()->AddInstruction(instr); if (instr->HasObservableSideEffects()) { owner()->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); } } void EffectContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) { ASSERT(!instr->HasObservableSideEffects()); HBasicBlock* empty_true = owner()->graph()->CreateBasicBlock(); HBasicBlock* empty_false = owner()->graph()->CreateBasicBlock(); instr->SetSuccessorAt(0, empty_true); instr->SetSuccessorAt(1, empty_false); owner()->FinishCurrentBlock(instr); HBasicBlock* join = owner()->CreateJoin(empty_true, empty_false, ast_id); owner()->set_current_block(join); } void EffectContext::ReturnContinuation(HIfContinuation* continuation, BailoutId ast_id) { HBasicBlock* true_branch = NULL; HBasicBlock* false_branch = NULL; continuation->Continue(&true_branch, &false_branch); if (!continuation->IsTrueReachable()) { owner()->set_current_block(false_branch); } else if (!continuation->IsFalseReachable()) { owner()->set_current_block(true_branch); } else { HBasicBlock* join = owner()->CreateJoin(true_branch, false_branch, ast_id); owner()->set_current_block(join); } } void ValueContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) { ASSERT(!instr->IsControlInstruction()); if (!arguments_allowed() && instr->CheckFlag(HValue::kIsArguments)) { return owner()->Bailout(kBadValueContextForArgumentsObjectValue); } owner()->AddInstruction(instr); owner()->Push(instr); if (instr->HasObservableSideEffects()) { owner()->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); } } void ValueContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) { ASSERT(!instr->HasObservableSideEffects()); if (!arguments_allowed() && instr->CheckFlag(HValue::kIsArguments)) { return owner()->Bailout(kBadValueContextForArgumentsObjectValue); } HBasicBlock* materialize_false = owner()->graph()->CreateBasicBlock(); HBasicBlock* materialize_true = owner()->graph()->CreateBasicBlock(); instr->SetSuccessorAt(0, materialize_true); instr->SetSuccessorAt(1, materialize_false); owner()->FinishCurrentBlock(instr); owner()->set_current_block(materialize_true); owner()->Push(owner()->graph()->GetConstantTrue()); owner()->set_current_block(materialize_false); owner()->Push(owner()->graph()->GetConstantFalse()); HBasicBlock* join = owner()->CreateJoin(materialize_true, materialize_false, ast_id); owner()->set_current_block(join); } void ValueContext::ReturnContinuation(HIfContinuation* continuation, BailoutId ast_id) { HBasicBlock* materialize_true = NULL; HBasicBlock* materialize_false = NULL; continuation->Continue(&materialize_true, &materialize_false); if (continuation->IsTrueReachable()) { owner()->set_current_block(materialize_true); owner()->Push(owner()->graph()->GetConstantTrue()); owner()->set_current_block(materialize_true); } if (continuation->IsFalseReachable()) { owner()->set_current_block(materialize_false); owner()->Push(owner()->graph()->GetConstantFalse()); owner()->set_current_block(materialize_false); } if (continuation->TrueAndFalseReachable()) { HBasicBlock* join = owner()->CreateJoin(materialize_true, materialize_false, ast_id); owner()->set_current_block(join); } } void TestContext::ReturnInstruction(HInstruction* instr, BailoutId ast_id) { ASSERT(!instr->IsControlInstruction()); HOptimizedGraphBuilder* builder = owner(); builder->AddInstruction(instr); // We expect a simulate after every expression with side effects, though // this one isn't actually needed (and wouldn't work if it were targeted). if (instr->HasObservableSideEffects()) { builder->Push(instr); builder->Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); builder->Pop(); } BuildBranch(instr); } void TestContext::ReturnControl(HControlInstruction* instr, BailoutId ast_id) { ASSERT(!instr->HasObservableSideEffects()); HBasicBlock* empty_true = owner()->graph()->CreateBasicBlock(); HBasicBlock* empty_false = owner()->graph()->CreateBasicBlock(); instr->SetSuccessorAt(0, empty_true); instr->SetSuccessorAt(1, empty_false); owner()->FinishCurrentBlock(instr); owner()->Goto(empty_true, if_true(), owner()->function_state()); owner()->Goto(empty_false, if_false(), owner()->function_state()); owner()->set_current_block(NULL); } void TestContext::ReturnContinuation(HIfContinuation* continuation, BailoutId ast_id) { HBasicBlock* true_branch = NULL; HBasicBlock* false_branch = NULL; continuation->Continue(&true_branch, &false_branch); if (continuation->IsTrueReachable()) { owner()->Goto(true_branch, if_true(), owner()->function_state()); } if (continuation->IsFalseReachable()) { owner()->Goto(false_branch, if_false(), owner()->function_state()); } owner()->set_current_block(NULL); } void TestContext::BuildBranch(HValue* value) { // We expect the graph to be in edge-split form: there is no edge that // connects a branch node to a join node. We conservatively ensure that // property by always adding an empty block on the outgoing edges of this // branch. HOptimizedGraphBuilder* builder = owner(); if (value != NULL && value->CheckFlag(HValue::kIsArguments)) { builder->Bailout(kArgumentsObjectValueInATestContext); } ToBooleanStub::Types expected(condition()->to_boolean_types()); ReturnControl(owner()->New<HBranch>(value, expected), BailoutId::None()); } // HOptimizedGraphBuilder infrastructure for bailing out and checking bailouts. #define CHECK_BAILOUT(call) \ do { \ call; \ if (HasStackOverflow()) return; \ } while (false) #define CHECK_ALIVE(call) \ do { \ call; \ if (HasStackOverflow() || current_block() == NULL) return; \ } while (false) #define CHECK_ALIVE_OR_RETURN(call, value) \ do { \ call; \ if (HasStackOverflow() || current_block() == NULL) return value; \ } while (false) void HOptimizedGraphBuilder::Bailout(BailoutReason reason) { current_info()->set_bailout_reason(reason); SetStackOverflow(); } void HOptimizedGraphBuilder::VisitForEffect(Expression* expr) { EffectContext for_effect(this); Visit(expr); } void HOptimizedGraphBuilder::VisitForValue(Expression* expr, ArgumentsAllowedFlag flag) { ValueContext for_value(this, flag); Visit(expr); } void HOptimizedGraphBuilder::VisitForTypeOf(Expression* expr) { ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED); for_value.set_for_typeof(true); Visit(expr); } void HOptimizedGraphBuilder::VisitForControl(Expression* expr, HBasicBlock* true_block, HBasicBlock* false_block) { TestContext for_test(this, expr, true_block, false_block); Visit(expr); } void HOptimizedGraphBuilder::VisitExpressions( ZoneList<Expression*>* exprs) { for (int i = 0; i < exprs->length(); ++i) { CHECK_ALIVE(VisitForValue(exprs->at(i))); } } bool HOptimizedGraphBuilder::BuildGraph() { if (current_info()->function()->is_generator()) { Bailout(kFunctionIsAGenerator); return false; } Scope* scope = current_info()->scope(); if (scope->HasIllegalRedeclaration()) { Bailout(kFunctionWithIllegalRedeclaration); return false; } if (scope->calls_eval()) { Bailout(kFunctionCallsEval); return false; } SetUpScope(scope); // Add an edge to the body entry. This is warty: the graph's start // environment will be used by the Lithium translation as the initial // environment on graph entry, but it has now been mutated by the // Hydrogen translation of the instructions in the start block. This // environment uses values which have not been defined yet. These // Hydrogen instructions will then be replayed by the Lithium // translation, so they cannot have an environment effect. The edge to // the body's entry block (along with some special logic for the start // block in HInstruction::InsertAfter) seals the start block from // getting unwanted instructions inserted. // // TODO(kmillikin): Fix this. Stop mutating the initial environment. // Make the Hydrogen instructions in the initial block into Hydrogen // values (but not instructions), present in the initial environment and // not replayed by the Lithium translation. HEnvironment* initial_env = environment()->CopyWithoutHistory(); HBasicBlock* body_entry = CreateBasicBlock(initial_env); Goto(body_entry); body_entry->SetJoinId(BailoutId::FunctionEntry()); set_current_block(body_entry); // Handle implicit declaration of the function name in named function // expressions before other declarations. if (scope->is_function_scope() && scope->function() != NULL) { VisitVariableDeclaration(scope->function()); } VisitDeclarations(scope->declarations()); Add<HSimulate>(BailoutId::Declarations()); Add<HStackCheck>(HStackCheck::kFunctionEntry); VisitStatements(current_info()->function()->body()); if (HasStackOverflow()) return false; if (current_block() != NULL) { Add<HReturn>(graph()->GetConstantUndefined()); set_current_block(NULL); } // If the checksum of the number of type info changes is the same as the // last time this function was compiled, then this recompile is likely not // due to missing/inadequate type feedback, but rather too aggressive // optimization. Disable optimistic LICM in that case. Handle<Code> unoptimized_code(current_info()->shared_info()->code()); ASSERT(unoptimized_code->kind() == Code::FUNCTION); Handle<TypeFeedbackInfo> type_info( TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info())); int checksum = type_info->own_type_change_checksum(); int composite_checksum = graph()->update_type_change_checksum(checksum); graph()->set_use_optimistic_licm( !type_info->matches_inlined_type_change_checksum(composite_checksum)); type_info->set_inlined_type_change_checksum(composite_checksum); // Perform any necessary OSR-specific cleanups or changes to the graph. osr()->FinishGraph(); return true; } bool HGraph::Optimize(BailoutReason* bailout_reason) { OrderBlocks(); AssignDominators(); // We need to create a HConstant "zero" now so that GVN will fold every // zero-valued constant in the graph together. // The constant is needed to make idef-based bounds check work: the pass // evaluates relations with "zero" and that zero cannot be created after GVN. GetConstant0(); #ifdef DEBUG // Do a full verify after building the graph and computing dominators. Verify(true); #endif if (FLAG_analyze_environment_liveness && maximum_environment_size() != 0) { Run<HEnvironmentLivenessAnalysisPhase>(); } if (!CheckConstPhiUses()) { *bailout_reason = kUnsupportedPhiUseOfConstVariable; return false; } Run<HRedundantPhiEliminationPhase>(); if (!CheckArgumentsPhiUses()) { *bailout_reason = kUnsupportedPhiUseOfArguments; return false; } // Find and mark unreachable code to simplify optimizations, especially gvn, // where unreachable code could unnecessarily defeat LICM. Run<HMarkUnreachableBlocksPhase>(); if (FLAG_dead_code_elimination) Run<HDeadCodeEliminationPhase>(); if (FLAG_use_escape_analysis) Run<HEscapeAnalysisPhase>(); if (FLAG_load_elimination) Run<HLoadEliminationPhase>(); CollectPhis(); if (has_osr()) osr()->FinishOsrValues(); Run<HInferRepresentationPhase>(); // Remove HSimulate instructions that have turned out not to be needed // after all by folding them into the following HSimulate. // This must happen after inferring representations. Run<HMergeRemovableSimulatesPhase>(); Run<HMarkDeoptimizeOnUndefinedPhase>(); Run<HRepresentationChangesPhase>(); Run<HInferTypesPhase>(); // Must be performed before canonicalization to ensure that Canonicalize // will not remove semantically meaningful ToInt32 operations e.g. BIT_OR with // zero. if (FLAG_opt_safe_uint32_operations) Run<HUint32AnalysisPhase>(); if (FLAG_use_canonicalizing) Run<HCanonicalizePhase>(); if (FLAG_use_gvn) Run<HGlobalValueNumberingPhase>(); if (FLAG_check_elimination) Run<HCheckEliminationPhase>(); if (FLAG_store_elimination) Run<HStoreEliminationPhase>(); Run<HRangeAnalysisPhase>(); Run<HComputeChangeUndefinedToNaN>(); // Eliminate redundant stack checks on backwards branches. Run<HStackCheckEliminationPhase>(); if (FLAG_array_bounds_checks_elimination) Run<HBoundsCheckEliminationPhase>(); if (FLAG_array_bounds_checks_hoisting) Run<HBoundsCheckHoistingPhase>(); if (FLAG_array_index_dehoisting) Run<HDehoistIndexComputationsPhase>(); if (FLAG_dead_code_elimination) Run<HDeadCodeEliminationPhase>(); RestoreActualValues(); // Find unreachable code a second time, GVN and other optimizations may have // made blocks unreachable that were previously reachable. Run<HMarkUnreachableBlocksPhase>(); return true; } void HGraph::RestoreActualValues() { HPhase phase("H_Restore actual values", this); for (int block_index = 0; block_index < blocks()->length(); block_index++) { HBasicBlock* block = blocks()->at(block_index); #ifdef DEBUG for (int i = 0; i < block->phis()->length(); i++) { HPhi* phi = block->phis()->at(i); ASSERT(phi->ActualValue() == phi); } #endif for (HInstructionIterator it(block); !it.Done(); it.Advance()) { HInstruction* instruction = it.Current(); if (instruction->ActualValue() == instruction) continue; if (instruction->CheckFlag(HValue::kIsDead)) { // The instruction was marked as deleted but left in the graph // as a control flow dependency point for subsequent // instructions. instruction->DeleteAndReplaceWith(instruction->ActualValue()); } else { ASSERT(instruction->IsInformativeDefinition()); if (instruction->IsPurelyInformativeDefinition()) { instruction->DeleteAndReplaceWith(instruction->RedefinedOperand()); } else { instruction->ReplaceAllUsesWith(instruction->ActualValue()); } } } } } void HOptimizedGraphBuilder::PushArgumentsFromEnvironment(int count) { ZoneList<HValue*> arguments(count, zone()); for (int i = 0; i < count; ++i) { arguments.Add(Pop(), zone()); } HPushArguments* push_args = New<HPushArguments>(); while (!arguments.is_empty()) { push_args->AddInput(arguments.RemoveLast()); } AddInstruction(push_args); } template <class Instruction> HInstruction* HOptimizedGraphBuilder::PreProcessCall(Instruction* call) { PushArgumentsFromEnvironment(call->argument_count()); return call; } void HOptimizedGraphBuilder::SetUpScope(Scope* scope) { // First special is HContext. HInstruction* context = Add<HContext>(); environment()->BindContext(context); // Create an arguments object containing the initial parameters. Set the // initial values of parameters including "this" having parameter index 0. ASSERT_EQ(scope->num_parameters() + 1, environment()->parameter_count()); HArgumentsObject* arguments_object = New<HArgumentsObject>(environment()->parameter_count()); for (int i = 0; i < environment()->parameter_count(); ++i) { HInstruction* parameter = Add<HParameter>(i); arguments_object->AddArgument(parameter, zone()); environment()->Bind(i, parameter); } AddInstruction(arguments_object); graph()->SetArgumentsObject(arguments_object); HConstant* undefined_constant = graph()->GetConstantUndefined(); // Initialize specials and locals to undefined. for (int i = environment()->parameter_count() + 1; i < environment()->length(); ++i) { environment()->Bind(i, undefined_constant); } // Handle the arguments and arguments shadow variables specially (they do // not have declarations). if (scope->arguments() != NULL) { if (!scope->arguments()->IsStackAllocated()) { return Bailout(kContextAllocatedArguments); } environment()->Bind(scope->arguments(), graph()->GetArgumentsObject()); } } void HOptimizedGraphBuilder::VisitStatements(ZoneList<Statement*>* statements) { for (int i = 0; i < statements->length(); i++) { Statement* stmt = statements->at(i); CHECK_ALIVE(Visit(stmt)); if (stmt->IsJump()) break; } } void HOptimizedGraphBuilder::VisitBlock(Block* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); Scope* outer_scope = scope(); Scope* scope = stmt->scope(); BreakAndContinueInfo break_info(stmt, outer_scope); { BreakAndContinueScope push(&break_info, this); if (scope != NULL) { // Load the function object. Scope* declaration_scope = scope->DeclarationScope(); HInstruction* function; HValue* outer_context = environment()->context(); if (declaration_scope->is_global_scope() || declaration_scope->is_eval_scope()) { function = new(zone()) HLoadContextSlot( outer_context, Context::CLOSURE_INDEX, HLoadContextSlot::kNoCheck); } else { function = New<HThisFunction>(); } AddInstruction(function); // Allocate a block context and store it to the stack frame. HInstruction* inner_context = Add<HAllocateBlockContext>( outer_context, function, scope->GetScopeInfo()); HInstruction* instr = Add<HStoreFrameContext>(inner_context); if (instr->HasObservableSideEffects()) { AddSimulate(stmt->EntryId(), REMOVABLE_SIMULATE); } set_scope(scope); environment()->BindContext(inner_context); VisitDeclarations(scope->declarations()); AddSimulate(stmt->DeclsId(), REMOVABLE_SIMULATE); } CHECK_BAILOUT(VisitStatements(stmt->statements())); } set_scope(outer_scope); if (scope != NULL && current_block() != NULL) { HValue* inner_context = environment()->context(); HValue* outer_context = Add<HLoadNamedField>( inner_context, static_cast<HValue*>(NULL), HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX)); HInstruction* instr = Add<HStoreFrameContext>(outer_context); if (instr->HasObservableSideEffects()) { AddSimulate(stmt->ExitId(), REMOVABLE_SIMULATE); } environment()->BindContext(outer_context); } HBasicBlock* break_block = break_info.break_block(); if (break_block != NULL) { if (current_block() != NULL) Goto(break_block); break_block->SetJoinId(stmt->ExitId()); set_current_block(break_block); } } void HOptimizedGraphBuilder::VisitExpressionStatement( ExpressionStatement* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); VisitForEffect(stmt->expression()); } void HOptimizedGraphBuilder::VisitEmptyStatement(EmptyStatement* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); } void HOptimizedGraphBuilder::VisitIfStatement(IfStatement* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); if (stmt->condition()->ToBooleanIsTrue()) { Add<HSimulate>(stmt->ThenId()); Visit(stmt->then_statement()); } else if (stmt->condition()->ToBooleanIsFalse()) { Add<HSimulate>(stmt->ElseId()); Visit(stmt->else_statement()); } else { HBasicBlock* cond_true = graph()->CreateBasicBlock(); HBasicBlock* cond_false = graph()->CreateBasicBlock(); CHECK_BAILOUT(VisitForControl(stmt->condition(), cond_true, cond_false)); if (cond_true->HasPredecessor()) { cond_true->SetJoinId(stmt->ThenId()); set_current_block(cond_true); CHECK_BAILOUT(Visit(stmt->then_statement())); cond_true = current_block(); } else { cond_true = NULL; } if (cond_false->HasPredecessor()) { cond_false->SetJoinId(stmt->ElseId()); set_current_block(cond_false); CHECK_BAILOUT(Visit(stmt->else_statement())); cond_false = current_block(); } else { cond_false = NULL; } HBasicBlock* join = CreateJoin(cond_true, cond_false, stmt->IfId()); set_current_block(join); } } HBasicBlock* HOptimizedGraphBuilder::BreakAndContinueScope::Get( BreakableStatement* stmt, BreakType type, Scope** scope, int* drop_extra) { *drop_extra = 0; BreakAndContinueScope* current = this; while (current != NULL && current->info()->target() != stmt) { *drop_extra += current->info()->drop_extra(); current = current->next(); } ASSERT(current != NULL); // Always found (unless stack is malformed). *scope = current->info()->scope(); if (type == BREAK) { *drop_extra += current->info()->drop_extra(); } HBasicBlock* block = NULL; switch (type) { case BREAK: block = current->info()->break_block(); if (block == NULL) { block = current->owner()->graph()->CreateBasicBlock(); current->info()->set_break_block(block); } break; case CONTINUE: block = current->info()->continue_block(); if (block == NULL) { block = current->owner()->graph()->CreateBasicBlock(); current->info()->set_continue_block(block); } break; } return block; } void HOptimizedGraphBuilder::VisitContinueStatement( ContinueStatement* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); Scope* outer_scope = NULL; Scope* inner_scope = scope(); int drop_extra = 0; HBasicBlock* continue_block = break_scope()->Get( stmt->target(), BreakAndContinueScope::CONTINUE, &outer_scope, &drop_extra); HValue* context = environment()->context(); Drop(drop_extra); int context_pop_count = inner_scope->ContextChainLength(outer_scope); if (context_pop_count > 0) { while (context_pop_count-- > 0) { HInstruction* context_instruction = Add<HLoadNamedField>( context, static_cast<HValue*>(NULL), HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX)); context = context_instruction; } HInstruction* instr = Add<HStoreFrameContext>(context); if (instr->HasObservableSideEffects()) { AddSimulate(stmt->target()->EntryId(), REMOVABLE_SIMULATE); } environment()->BindContext(context); } Goto(continue_block); set_current_block(NULL); } void HOptimizedGraphBuilder::VisitBreakStatement(BreakStatement* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); Scope* outer_scope = NULL; Scope* inner_scope = scope(); int drop_extra = 0; HBasicBlock* break_block = break_scope()->Get( stmt->target(), BreakAndContinueScope::BREAK, &outer_scope, &drop_extra); HValue* context = environment()->context(); Drop(drop_extra); int context_pop_count = inner_scope->ContextChainLength(outer_scope); if (context_pop_count > 0) { while (context_pop_count-- > 0) { HInstruction* context_instruction = Add<HLoadNamedField>( context, static_cast<HValue*>(NULL), HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX)); context = context_instruction; } HInstruction* instr = Add<HStoreFrameContext>(context); if (instr->HasObservableSideEffects()) { AddSimulate(stmt->target()->ExitId(), REMOVABLE_SIMULATE); } environment()->BindContext(context); } Goto(break_block); set_current_block(NULL); } void HOptimizedGraphBuilder::VisitReturnStatement(ReturnStatement* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); FunctionState* state = function_state(); AstContext* context = call_context(); if (context == NULL) { // Not an inlined return, so an actual one. CHECK_ALIVE(VisitForValue(stmt->expression())); HValue* result = environment()->Pop(); Add<HReturn>(result); } else if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) { // Return from an inlined construct call. In a test context the return value // will always evaluate to true, in a value context the return value needs // to be a JSObject. if (context->IsTest()) { TestContext* test = TestContext::cast(context); CHECK_ALIVE(VisitForEffect(stmt->expression())); Goto(test->if_true(), state); } else if (context->IsEffect()) { CHECK_ALIVE(VisitForEffect(stmt->expression())); Goto(function_return(), state); } else { ASSERT(context->IsValue()); CHECK_ALIVE(VisitForValue(stmt->expression())); HValue* return_value = Pop(); HValue* receiver = environment()->arguments_environment()->Lookup(0); HHasInstanceTypeAndBranch* typecheck = New<HHasInstanceTypeAndBranch>(return_value, FIRST_SPEC_OBJECT_TYPE, LAST_SPEC_OBJECT_TYPE); HBasicBlock* if_spec_object = graph()->CreateBasicBlock(); HBasicBlock* not_spec_object = graph()->CreateBasicBlock(); typecheck->SetSuccessorAt(0, if_spec_object); typecheck->SetSuccessorAt(1, not_spec_object); FinishCurrentBlock(typecheck); AddLeaveInlined(if_spec_object, return_value, state); AddLeaveInlined(not_spec_object, receiver, state); } } else if (state->inlining_kind() == SETTER_CALL_RETURN) { // Return from an inlined setter call. The returned value is never used, the // value of an assignment is always the value of the RHS of the assignment. CHECK_ALIVE(VisitForEffect(stmt->expression())); if (context->IsTest()) { HValue* rhs = environment()->arguments_environment()->Lookup(1); context->ReturnValue(rhs); } else if (context->IsEffect()) { Goto(function_return(), state); } else { ASSERT(context->IsValue()); HValue* rhs = environment()->arguments_environment()->Lookup(1); AddLeaveInlined(rhs, state); } } else { // Return from a normal inlined function. Visit the subexpression in the // expression context of the call. if (context->IsTest()) { TestContext* test = TestContext::cast(context); VisitForControl(stmt->expression(), test->if_true(), test->if_false()); } else if (context->IsEffect()) { // Visit in value context and ignore the result. This is needed to keep // environment in sync with full-codegen since some visitors (e.g. // VisitCountOperation) use the operand stack differently depending on // context. CHECK_ALIVE(VisitForValue(stmt->expression())); Pop(); Goto(function_return(), state); } else { ASSERT(context->IsValue()); CHECK_ALIVE(VisitForValue(stmt->expression())); AddLeaveInlined(Pop(), state); } } set_current_block(NULL); } void HOptimizedGraphBuilder::VisitWithStatement(WithStatement* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); return Bailout(kWithStatement); } void HOptimizedGraphBuilder::VisitSwitchStatement(SwitchStatement* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); // We only optimize switch statements with a bounded number of clauses. const int kCaseClauseLimit = 128; ZoneList<CaseClause*>* clauses = stmt->cases(); int clause_count = clauses->length(); ZoneList<HBasicBlock*> body_blocks(clause_count, zone()); if (clause_count > kCaseClauseLimit) { return Bailout(kSwitchStatementTooManyClauses); } CHECK_ALIVE(VisitForValue(stmt->tag())); Add<HSimulate>(stmt->EntryId()); HValue* tag_value = Top(); Type* tag_type = stmt->tag()->bounds().lower; // 1. Build all the tests, with dangling true branches BailoutId default_id = BailoutId::None(); for (int i = 0; i < clause_count; ++i) { CaseClause* clause = clauses->at(i); if (clause->is_default()) { body_blocks.Add(NULL, zone()); if (default_id.IsNone()) default_id = clause->EntryId(); continue; } // Generate a compare and branch. CHECK_ALIVE(VisitForValue(clause->label())); HValue* label_value = Pop(); Type* label_type = clause->label()->bounds().lower; Type* combined_type = clause->compare_type(); HControlInstruction* compare = BuildCompareInstruction( Token::EQ_STRICT, tag_value, label_value, tag_type, label_type, combined_type, ScriptPositionToSourcePosition(stmt->tag()->position()), ScriptPositionToSourcePosition(clause->label()->position()), PUSH_BEFORE_SIMULATE, clause->id()); HBasicBlock* next_test_block = graph()->CreateBasicBlock(); HBasicBlock* body_block = graph()->CreateBasicBlock(); body_blocks.Add(body_block, zone()); compare->SetSuccessorAt(0, body_block); compare->SetSuccessorAt(1, next_test_block); FinishCurrentBlock(compare); set_current_block(body_block); Drop(1); // tag_value set_current_block(next_test_block); } // Save the current block to use for the default or to join with the // exit. HBasicBlock* last_block = current_block(); Drop(1); // tag_value // 2. Loop over the clauses and the linked list of tests in lockstep, // translating the clause bodies. HBasicBlock* fall_through_block = NULL; BreakAndContinueInfo break_info(stmt, scope()); { BreakAndContinueScope push(&break_info, this); for (int i = 0; i < clause_count; ++i) { CaseClause* clause = clauses->at(i); // Identify the block where normal (non-fall-through) control flow // goes to. HBasicBlock* normal_block = NULL; if (clause->is_default()) { if (last_block == NULL) continue; normal_block = last_block; last_block = NULL; // Cleared to indicate we've handled it. } else { normal_block = body_blocks[i]; } if (fall_through_block == NULL) { set_current_block(normal_block); } else { HBasicBlock* join = CreateJoin(fall_through_block, normal_block, clause->EntryId()); set_current_block(join); } CHECK_BAILOUT(VisitStatements(clause->statements())); fall_through_block = current_block(); } } // Create an up-to-3-way join. Use the break block if it exists since // it's already a join block. HBasicBlock* break_block = break_info.break_block(); if (break_block == NULL) { set_current_block(CreateJoin(fall_through_block, last_block, stmt->ExitId())); } else { if (fall_through_block != NULL) Goto(fall_through_block, break_block); if (last_block != NULL) Goto(last_block, break_block); break_block->SetJoinId(stmt->ExitId()); set_current_block(break_block); } } void HOptimizedGraphBuilder::VisitLoopBody(IterationStatement* stmt, HBasicBlock* loop_entry) { Add<HSimulate>(stmt->StackCheckId()); HStackCheck* stack_check = HStackCheck::cast(Add<HStackCheck>(HStackCheck::kBackwardsBranch)); ASSERT(loop_entry->IsLoopHeader()); loop_entry->loop_information()->set_stack_check(stack_check); CHECK_BAILOUT(Visit(stmt->body())); } void HOptimizedGraphBuilder::VisitDoWhileStatement(DoWhileStatement* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); ASSERT(current_block() != NULL); HBasicBlock* loop_entry = BuildLoopEntry(stmt); BreakAndContinueInfo break_info(stmt, scope()); { BreakAndContinueScope push(&break_info, this); CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry)); } HBasicBlock* body_exit = JoinContinue(stmt, current_block(), break_info.continue_block()); HBasicBlock* loop_successor = NULL; if (body_exit != NULL && !stmt->cond()->ToBooleanIsTrue()) { set_current_block(body_exit); loop_successor = graph()->CreateBasicBlock(); if (stmt->cond()->ToBooleanIsFalse()) { loop_entry->loop_information()->stack_check()->Eliminate(); Goto(loop_successor); body_exit = NULL; } else { // The block for a true condition, the actual predecessor block of the // back edge. body_exit = graph()->CreateBasicBlock(); CHECK_BAILOUT(VisitForControl(stmt->cond(), body_exit, loop_successor)); } if (body_exit != NULL && body_exit->HasPredecessor()) { body_exit->SetJoinId(stmt->BackEdgeId()); } else { body_exit = NULL; } if (loop_successor->HasPredecessor()) { loop_successor->SetJoinId(stmt->ExitId()); } else { loop_successor = NULL; } } HBasicBlock* loop_exit = CreateLoop(stmt, loop_entry, body_exit, loop_successor, break_info.break_block()); set_current_block(loop_exit); } void HOptimizedGraphBuilder::VisitWhileStatement(WhileStatement* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); ASSERT(current_block() != NULL); HBasicBlock* loop_entry = BuildLoopEntry(stmt); // If the condition is constant true, do not generate a branch. HBasicBlock* loop_successor = NULL; if (!stmt->cond()->ToBooleanIsTrue()) { HBasicBlock* body_entry = graph()->CreateBasicBlock(); loop_successor = graph()->CreateBasicBlock(); CHECK_BAILOUT(VisitForControl(stmt->cond(), body_entry, loop_successor)); if (body_entry->HasPredecessor()) { body_entry->SetJoinId(stmt->BodyId()); set_current_block(body_entry); } if (loop_successor->HasPredecessor()) { loop_successor->SetJoinId(stmt->ExitId()); } else { loop_successor = NULL; } } BreakAndContinueInfo break_info(stmt, scope()); if (current_block() != NULL) { BreakAndContinueScope push(&break_info, this); CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry)); } HBasicBlock* body_exit = JoinContinue(stmt, current_block(), break_info.continue_block()); HBasicBlock* loop_exit = CreateLoop(stmt, loop_entry, body_exit, loop_successor, break_info.break_block()); set_current_block(loop_exit); } void HOptimizedGraphBuilder::VisitForStatement(ForStatement* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); if (stmt->init() != NULL) { CHECK_ALIVE(Visit(stmt->init())); } ASSERT(current_block() != NULL); HBasicBlock* loop_entry = BuildLoopEntry(stmt); HBasicBlock* loop_successor = NULL; if (stmt->cond() != NULL) { HBasicBlock* body_entry = graph()->CreateBasicBlock(); loop_successor = graph()->CreateBasicBlock(); CHECK_BAILOUT(VisitForControl(stmt->cond(), body_entry, loop_successor)); if (body_entry->HasPredecessor()) { body_entry->SetJoinId(stmt->BodyId()); set_current_block(body_entry); } if (loop_successor->HasPredecessor()) { loop_successor->SetJoinId(stmt->ExitId()); } else { loop_successor = NULL; } } BreakAndContinueInfo break_info(stmt, scope()); if (current_block() != NULL) { BreakAndContinueScope push(&break_info, this); CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry)); } HBasicBlock* body_exit = JoinContinue(stmt, current_block(), break_info.continue_block()); if (stmt->next() != NULL && body_exit != NULL) { set_current_block(body_exit); CHECK_BAILOUT(Visit(stmt->next())); body_exit = current_block(); } HBasicBlock* loop_exit = CreateLoop(stmt, loop_entry, body_exit, loop_successor, break_info.break_block()); set_current_block(loop_exit); } void HOptimizedGraphBuilder::VisitForInStatement(ForInStatement* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); if (!FLAG_optimize_for_in) { return Bailout(kForInStatementOptimizationIsDisabled); } if (stmt->for_in_type() != ForInStatement::FAST_FOR_IN) { return Bailout(kForInStatementIsNotFastCase); } if (!stmt->each()->IsVariableProxy() || !stmt->each()->AsVariableProxy()->var()->IsStackLocal()) { return Bailout(kForInStatementWithNonLocalEachVariable); } Variable* each_var = stmt->each()->AsVariableProxy()->var(); CHECK_ALIVE(VisitForValue(stmt->enumerable())); HValue* enumerable = Top(); // Leave enumerable at the top. HInstruction* map = Add<HForInPrepareMap>(enumerable); Add<HSimulate>(stmt->PrepareId()); HInstruction* array = Add<HForInCacheArray>( enumerable, map, DescriptorArray::kEnumCacheBridgeCacheIndex); HInstruction* enum_length = Add<HMapEnumLength>(map); HInstruction* start_index = Add<HConstant>(0); Push(map); Push(array); Push(enum_length); Push(start_index); HInstruction* index_cache = Add<HForInCacheArray>( enumerable, map, DescriptorArray::kEnumCacheBridgeIndicesCacheIndex); HForInCacheArray::cast(array)->set_index_cache( HForInCacheArray::cast(index_cache)); HBasicBlock* loop_entry = BuildLoopEntry(stmt); HValue* index = environment()->ExpressionStackAt(0); HValue* limit = environment()->ExpressionStackAt(1); // Check that we still have more keys. HCompareNumericAndBranch* compare_index = New<HCompareNumericAndBranch>(index, limit, Token::LT); compare_index->set_observed_input_representation( Representation::Smi(), Representation::Smi()); HBasicBlock* loop_body = graph()->CreateBasicBlock(); HBasicBlock* loop_successor = graph()->CreateBasicBlock(); compare_index->SetSuccessorAt(0, loop_body); compare_index->SetSuccessorAt(1, loop_successor); FinishCurrentBlock(compare_index); set_current_block(loop_successor); Drop(5); set_current_block(loop_body); HValue* key = Add<HLoadKeyed>( environment()->ExpressionStackAt(2), // Enum cache. environment()->ExpressionStackAt(0), // Iteration index. environment()->ExpressionStackAt(0), FAST_ELEMENTS); // Check if the expected map still matches that of the enumerable. // If not just deoptimize. Add<HCheckMapValue>(environment()->ExpressionStackAt(4), environment()->ExpressionStackAt(3)); Bind(each_var, key); BreakAndContinueInfo break_info(stmt, scope(), 5); { BreakAndContinueScope push(&break_info, this); CHECK_BAILOUT(VisitLoopBody(stmt, loop_entry)); } HBasicBlock* body_exit = JoinContinue(stmt, current_block(), break_info.continue_block()); if (body_exit != NULL) { set_current_block(body_exit); HValue* current_index = Pop(); Push(AddUncasted<HAdd>(current_index, graph()->GetConstant1())); body_exit = current_block(); } HBasicBlock* loop_exit = CreateLoop(stmt, loop_entry, body_exit, loop_successor, break_info.break_block()); set_current_block(loop_exit); } void HOptimizedGraphBuilder::VisitForOfStatement(ForOfStatement* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); return Bailout(kForOfStatement); } void HOptimizedGraphBuilder::VisitTryCatchStatement(TryCatchStatement* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); return Bailout(kTryCatchStatement); } void HOptimizedGraphBuilder::VisitTryFinallyStatement( TryFinallyStatement* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); return Bailout(kTryFinallyStatement); } void HOptimizedGraphBuilder::VisitDebuggerStatement(DebuggerStatement* stmt) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); return Bailout(kDebuggerStatement); } void HOptimizedGraphBuilder::VisitCaseClause(CaseClause* clause) { UNREACHABLE(); } void HOptimizedGraphBuilder::VisitFunctionLiteral(FunctionLiteral* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); Handle<SharedFunctionInfo> shared_info = expr->shared_info(); if (shared_info.is_null()) { shared_info = Compiler::BuildFunctionInfo(expr, current_info()->script()); } // We also have a stack overflow if the recursive compilation did. if (HasStackOverflow()) return; HFunctionLiteral* instr = New<HFunctionLiteral>(shared_info, expr->pretenure()); return ast_context()->ReturnInstruction(instr, expr->id()); } void HOptimizedGraphBuilder::VisitNativeFunctionLiteral( NativeFunctionLiteral* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); return Bailout(kNativeFunctionLiteral); } void HOptimizedGraphBuilder::VisitConditional(Conditional* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); HBasicBlock* cond_true = graph()->CreateBasicBlock(); HBasicBlock* cond_false = graph()->CreateBasicBlock(); CHECK_BAILOUT(VisitForControl(expr->condition(), cond_true, cond_false)); // Visit the true and false subexpressions in the same AST context as the // whole expression. if (cond_true->HasPredecessor()) { cond_true->SetJoinId(expr->ThenId()); set_current_block(cond_true); CHECK_BAILOUT(Visit(expr->then_expression())); cond_true = current_block(); } else { cond_true = NULL; } if (cond_false->HasPredecessor()) { cond_false->SetJoinId(expr->ElseId()); set_current_block(cond_false); CHECK_BAILOUT(Visit(expr->else_expression())); cond_false = current_block(); } else { cond_false = NULL; } if (!ast_context()->IsTest()) { HBasicBlock* join = CreateJoin(cond_true, cond_false, expr->id()); set_current_block(join); if (join != NULL && !ast_context()->IsEffect()) { return ast_context()->ReturnValue(Pop()); } } } HOptimizedGraphBuilder::GlobalPropertyAccess HOptimizedGraphBuilder::LookupGlobalProperty( Variable* var, LookupResult* lookup, PropertyAccessType access_type) { if (var->is_this() || !current_info()->has_global_object()) { return kUseGeneric; } Handle<GlobalObject> global(current_info()->global_object()); global->Lookup(var->name(), lookup); if (!lookup->IsNormal() || (access_type == STORE && lookup->IsReadOnly()) || lookup->holder() != *global) { return kUseGeneric; } return kUseCell; } HValue* HOptimizedGraphBuilder::BuildContextChainWalk(Variable* var) { ASSERT(var->IsContextSlot()); HValue* context = environment()->context(); int length = scope()->ContextChainLength(var->scope()); while (length-- > 0) { context = Add<HLoadNamedField>( context, static_cast<HValue*>(NULL), HObjectAccess::ForContextSlot(Context::PREVIOUS_INDEX)); } return context; } void HOptimizedGraphBuilder::VisitVariableProxy(VariableProxy* expr) { if (expr->is_this()) { current_info()->set_this_has_uses(true); } ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); Variable* variable = expr->var(); switch (variable->location()) { case Variable::UNALLOCATED: { if (IsLexicalVariableMode(variable->mode())) { // TODO(rossberg): should this be an ASSERT? return Bailout(kReferenceToGlobalLexicalVariable); } // Handle known global constants like 'undefined' specially to avoid a // load from a global cell for them. Handle<Object> constant_value = isolate()->factory()->GlobalConstantFor(variable->name()); if (!constant_value.is_null()) { HConstant* instr = New<HConstant>(constant_value); return ast_context()->ReturnInstruction(instr, expr->id()); } LookupResult lookup(isolate()); GlobalPropertyAccess type = LookupGlobalProperty(variable, &lookup, LOAD); if (type == kUseCell && current_info()->global_object()->IsAccessCheckNeeded()) { type = kUseGeneric; } if (type == kUseCell) { Handle<GlobalObject> global(current_info()->global_object()); Handle<PropertyCell> cell(global->GetPropertyCell(&lookup)); if (cell->type()->IsConstant()) { PropertyCell::AddDependentCompilationInfo(cell, top_info()); Handle<Object> constant_object = cell->type()->AsConstant()->Value(); if (constant_object->IsConsString()) { constant_object = String::Flatten(Handle<String>::cast(constant_object)); } HConstant* constant = New<HConstant>(constant_object); return ast_context()->ReturnInstruction(constant, expr->id()); } else { HLoadGlobalCell* instr = New<HLoadGlobalCell>(cell, lookup.GetPropertyDetails()); return ast_context()->ReturnInstruction(instr, expr->id()); } } else { HValue* global_object = Add<HLoadNamedField>( context(), static_cast<HValue*>(NULL), HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX)); HLoadGlobalGeneric* instr = New<HLoadGlobalGeneric>(global_object, variable->name(), ast_context()->is_for_typeof()); return ast_context()->ReturnInstruction(instr, expr->id()); } } case Variable::PARAMETER: case Variable::LOCAL: { HValue* value = LookupAndMakeLive(variable); if (value == graph()->GetConstantHole()) { ASSERT(IsDeclaredVariableMode(variable->mode()) && variable->mode() != VAR); return Bailout(kReferenceToUninitializedVariable); } return ast_context()->ReturnValue(value); } case Variable::CONTEXT: { HValue* context = BuildContextChainWalk(variable); HLoadContextSlot::Mode mode; switch (variable->mode()) { case LET: case CONST: mode = HLoadContextSlot::kCheckDeoptimize; break; case CONST_LEGACY: mode = HLoadContextSlot::kCheckReturnUndefined; break; default: mode = HLoadContextSlot::kNoCheck; break; } HLoadContextSlot* instr = new(zone()) HLoadContextSlot(context, variable->index(), mode); return ast_context()->ReturnInstruction(instr, expr->id()); } case Variable::LOOKUP: return Bailout(kReferenceToAVariableWhichRequiresDynamicLookup); } } void HOptimizedGraphBuilder::VisitLiteral(Literal* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); HConstant* instr = New<HConstant>(expr->value()); return ast_context()->ReturnInstruction(instr, expr->id()); } void HOptimizedGraphBuilder::VisitRegExpLiteral(RegExpLiteral* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); Handle<JSFunction> closure = function_state()->compilation_info()->closure(); Handle<FixedArray> literals(closure->literals()); HRegExpLiteral* instr = New<HRegExpLiteral>(literals, expr->pattern(), expr->flags(), expr->literal_index()); return ast_context()->ReturnInstruction(instr, expr->id()); } static bool CanInlinePropertyAccess(Type* type) { if (type->Is(Type::NumberOrString())) return true; if (!type->IsClass()) return false; Handle<Map> map = type->AsClass()->Map(); return map->IsJSObjectMap() && !map->is_dictionary_map() && !map->has_named_interceptor(); } // Determines whether the given array or object literal boilerplate satisfies // all limits to be considered for fast deep-copying and computes the total // size of all objects that are part of the graph. static bool IsFastLiteral(Handle<JSObject> boilerplate, int max_depth, int* max_properties) { if (boilerplate->map()->is_deprecated() && !JSObject::TryMigrateInstance(boilerplate)) { return false; } ASSERT(max_depth >= 0 && *max_properties >= 0); if (max_depth == 0) return false; Isolate* isolate = boilerplate->GetIsolate(); Handle<FixedArrayBase> elements(boilerplate->elements()); if (elements->length() > 0 && elements->map() != isolate->heap()->fixed_cow_array_map()) { if (boilerplate->HasFastObjectElements()) { Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements); int length = elements->length(); for (int i = 0; i < length; i++) { if ((*max_properties)-- == 0) return false; Handle<Object> value(fast_elements->get(i), isolate); if (value->IsJSObject()) { Handle<JSObject> value_object = Handle<JSObject>::cast(value); if (!IsFastLiteral(value_object, max_depth - 1, max_properties)) { return false; } } } } else if (!boilerplate->HasFastDoubleElements()) { return false; } } Handle<FixedArray> properties(boilerplate->properties()); if (properties->length() > 0) { return false; } else { Handle<DescriptorArray> descriptors( boilerplate->map()->instance_descriptors()); int limit = boilerplate->map()->NumberOfOwnDescriptors(); for (int i = 0; i < limit; i++) { PropertyDetails details = descriptors->GetDetails(i); if (details.type() != FIELD) continue; int index = descriptors->GetFieldIndex(i); if ((*max_properties)-- == 0) return false; Handle<Object> value(boilerplate->InObjectPropertyAt(index), isolate); if (value->IsJSObject()) { Handle<JSObject> value_object = Handle<JSObject>::cast(value); if (!IsFastLiteral(value_object, max_depth - 1, max_properties)) { return false; } } } } return true; } void HOptimizedGraphBuilder::VisitObjectLiteral(ObjectLiteral* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); expr->BuildConstantProperties(isolate()); Handle<JSFunction> closure = function_state()->compilation_info()->closure(); HInstruction* literal; // Check whether to use fast or slow deep-copying for boilerplate. int max_properties = kMaxFastLiteralProperties; Handle<Object> literals_cell(closure->literals()->get(expr->literal_index()), isolate()); Handle<AllocationSite> site; Handle<JSObject> boilerplate; if (!literals_cell->IsUndefined()) { // Retrieve the boilerplate site = Handle<AllocationSite>::cast(literals_cell); boilerplate = Handle<JSObject>(JSObject::cast(site->transition_info()), isolate()); } if (!boilerplate.is_null() && IsFastLiteral(boilerplate, kMaxFastLiteralDepth, &max_properties)) { AllocationSiteUsageContext usage_context(isolate(), site, false); usage_context.EnterNewScope(); literal = BuildFastLiteral(boilerplate, &usage_context); usage_context.ExitScope(site, boilerplate); } else { NoObservableSideEffectsScope no_effects(this); Handle<FixedArray> closure_literals(closure->literals(), isolate()); Handle<FixedArray> constant_properties = expr->constant_properties(); int literal_index = expr->literal_index(); int flags = expr->fast_elements() ? ObjectLiteral::kFastElements : ObjectLiteral::kNoFlags; flags |= expr->has_function() ? ObjectLiteral::kHasFunction : ObjectLiteral::kNoFlags; Add<HPushArguments>(Add<HConstant>(closure_literals), Add<HConstant>(literal_index), Add<HConstant>(constant_properties), Add<HConstant>(flags)); // TODO(mvstanton): Add a flag to turn off creation of any // AllocationMementos for this call: we are in crankshaft and should have // learned enough about transition behavior to stop emitting mementos. Runtime::FunctionId function_id = Runtime::kHiddenCreateObjectLiteral; literal = Add<HCallRuntime>(isolate()->factory()->empty_string(), Runtime::FunctionForId(function_id), 4); } // The object is expected in the bailout environment during computation // of the property values and is the value of the entire expression. Push(literal); expr->CalculateEmitStore(zone()); for (int i = 0; i < expr->properties()->length(); i++) { ObjectLiteral::Property* property = expr->properties()->at(i); if (property->IsCompileTimeValue()) continue; Literal* key = property->key(); Expression* value = property->value(); switch (property->kind()) { case ObjectLiteral::Property::MATERIALIZED_LITERAL: ASSERT(!CompileTimeValue::IsCompileTimeValue(value)); // Fall through. case ObjectLiteral::Property::COMPUTED: if (key->value()->IsInternalizedString()) { if (property->emit_store()) { CHECK_ALIVE(VisitForValue(value)); HValue* value = Pop(); Handle<Map> map = property->GetReceiverType(); Handle<String> name = property->key()->AsPropertyName(); HInstruction* store; if (map.is_null()) { // If we don't know the monomorphic type, do a generic store. CHECK_ALIVE(store = BuildNamedGeneric( STORE, literal, name, value)); } else { PropertyAccessInfo info(this, STORE, ToType(map), name); if (info.CanAccessMonomorphic()) { HValue* checked_literal = Add<HCheckMaps>(literal, map); ASSERT(!info.lookup()->IsPropertyCallbacks()); store = BuildMonomorphicAccess( &info, literal, checked_literal, value, BailoutId::None(), BailoutId::None()); } else { CHECK_ALIVE(store = BuildNamedGeneric( STORE, literal, name, value)); } } AddInstruction(store); if (store->HasObservableSideEffects()) { Add<HSimulate>(key->id(), REMOVABLE_SIMULATE); } } else { CHECK_ALIVE(VisitForEffect(value)); } break; } // Fall through. case ObjectLiteral::Property::PROTOTYPE: case ObjectLiteral::Property::SETTER: case ObjectLiteral::Property::GETTER: return Bailout(kObjectLiteralWithComplexProperty); default: UNREACHABLE(); } } if (expr->has_function()) { // Return the result of the transformation to fast properties // instead of the original since this operation changes the map // of the object. This makes sure that the original object won't // be used by other optimized code before it is transformed // (e.g. because of code motion). HToFastProperties* result = Add<HToFastProperties>(Pop()); return ast_context()->ReturnValue(result); } else { return ast_context()->ReturnValue(Pop()); } } void HOptimizedGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); expr->BuildConstantElements(isolate()); ZoneList<Expression*>* subexprs = expr->values(); int length = subexprs->length(); HInstruction* literal; Handle<AllocationSite> site; Handle<FixedArray> literals(environment()->closure()->literals(), isolate()); bool uninitialized = false; Handle<Object> literals_cell(literals->get(expr->literal_index()), isolate()); Handle<JSObject> boilerplate_object; if (literals_cell->IsUndefined()) { uninitialized = true; Handle<Object> raw_boilerplate; ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate(), raw_boilerplate, Runtime::CreateArrayLiteralBoilerplate( isolate(), literals, expr->constant_elements()), Bailout(kArrayBoilerplateCreationFailed)); boilerplate_object = Handle<JSObject>::cast(raw_boilerplate); AllocationSiteCreationContext creation_context(isolate()); site = creation_context.EnterNewScope(); if (JSObject::DeepWalk(boilerplate_object, &creation_context).is_null()) { return Bailout(kArrayBoilerplateCreationFailed); } creation_context.ExitScope(site, boilerplate_object); literals->set(expr->literal_index(), *site); if (boilerplate_object->elements()->map() == isolate()->heap()->fixed_cow_array_map()) { isolate()->counters()->cow_arrays_created_runtime()->Increment(); } } else { ASSERT(literals_cell->IsAllocationSite()); site = Handle<AllocationSite>::cast(literals_cell); boilerplate_object = Handle<JSObject>( JSObject::cast(site->transition_info()), isolate()); } ASSERT(!boilerplate_object.is_null()); ASSERT(site->SitePointsToLiteral()); ElementsKind boilerplate_elements_kind = boilerplate_object->GetElementsKind(); // Check whether to use fast or slow deep-copying for boilerplate. int max_properties = kMaxFastLiteralProperties; if (IsFastLiteral(boilerplate_object, kMaxFastLiteralDepth, &max_properties)) { AllocationSiteUsageContext usage_context(isolate(), site, false); usage_context.EnterNewScope(); literal = BuildFastLiteral(boilerplate_object, &usage_context); usage_context.ExitScope(site, boilerplate_object); } else { NoObservableSideEffectsScope no_effects(this); // Boilerplate already exists and constant elements are never accessed, // pass an empty fixed array to the runtime function instead. Handle<FixedArray> constants = isolate()->factory()->empty_fixed_array(); int literal_index = expr->literal_index(); int flags = expr->depth() == 1 ? ArrayLiteral::kShallowElements : ArrayLiteral::kNoFlags; flags |= ArrayLiteral::kDisableMementos; Add<HPushArguments>(Add<HConstant>(literals), Add<HConstant>(literal_index), Add<HConstant>(constants), Add<HConstant>(flags)); // TODO(mvstanton): Consider a flag to turn off creation of any // AllocationMementos for this call: we are in crankshaft and should have // learned enough about transition behavior to stop emitting mementos. Runtime::FunctionId function_id = Runtime::kHiddenCreateArrayLiteral; literal = Add<HCallRuntime>(isolate()->factory()->empty_string(), Runtime::FunctionForId(function_id), 4); // De-opt if elements kind changed from boilerplate_elements_kind. Handle<Map> map = Handle<Map>(boilerplate_object->map(), isolate()); literal = Add<HCheckMaps>(literal, map); } // The array is expected in the bailout environment during computation // of the property values and is the value of the entire expression. Push(literal); // The literal index is on the stack, too. Push(Add<HConstant>(expr->literal_index())); HInstruction* elements = NULL; for (int i = 0; i < length; i++) { Expression* subexpr = subexprs->at(i); // If the subexpression is a literal or a simple materialized literal it // is already set in the cloned array. if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue; CHECK_ALIVE(VisitForValue(subexpr)); HValue* value = Pop(); if (!Smi::IsValid(i)) return Bailout(kNonSmiKeyInArrayLiteral); elements = AddLoadElements(literal); HValue* key = Add<HConstant>(i); switch (boilerplate_elements_kind) { case FAST_SMI_ELEMENTS: case FAST_HOLEY_SMI_ELEMENTS: case FAST_ELEMENTS: case FAST_HOLEY_ELEMENTS: case FAST_DOUBLE_ELEMENTS: case FAST_HOLEY_DOUBLE_ELEMENTS: { HStoreKeyed* instr = Add<HStoreKeyed>(elements, key, value, boilerplate_elements_kind); instr->SetUninitialized(uninitialized); break; } default: UNREACHABLE(); break; } Add<HSimulate>(expr->GetIdForElement(i)); } Drop(1); // array literal index return ast_context()->ReturnValue(Pop()); } HCheckMaps* HOptimizedGraphBuilder::AddCheckMap(HValue* object, Handle<Map> map) { BuildCheckHeapObject(object); return Add<HCheckMaps>(object, map); } HInstruction* HOptimizedGraphBuilder::BuildLoadNamedField( PropertyAccessInfo* info, HValue* checked_object) { // See if this is a load for an immutable property if (checked_object->ActualValue()->IsConstant() && info->lookup()->IsCacheable() && info->lookup()->IsReadOnly() && info->lookup()->IsDontDelete()) { Handle<Object> object( HConstant::cast(checked_object->ActualValue())->handle(isolate())); if (object->IsJSObject()) { LookupResult lookup(isolate()); Handle<JSObject>::cast(object)->Lookup(info->name(), &lookup); Handle<Object> value(lookup.GetLazyValue(), isolate()); if (!value->IsTheHole()) { return New<HConstant>(value); } } } HObjectAccess access = info->access(); if (access.representation().IsDouble()) { // Load the heap number. checked_object = Add<HLoadNamedField>( checked_object, static_cast<HValue*>(NULL), access.WithRepresentation(Representation::Tagged())); // Load the double value from it. access = HObjectAccess::ForHeapNumberValue(); } SmallMapList* map_list = info->field_maps(); if (map_list->length() == 0) { return New<HLoadNamedField>(checked_object, checked_object, access); } UniqueSet<Map>* maps = new(zone()) UniqueSet<Map>(map_list->length(), zone()); for (int i = 0; i < map_list->length(); ++i) { maps->Add(Unique<Map>::CreateImmovable(map_list->at(i)), zone()); } return New<HLoadNamedField>( checked_object, checked_object, access, maps, info->field_type()); } HInstruction* HOptimizedGraphBuilder::BuildStoreNamedField( PropertyAccessInfo* info, HValue* checked_object, HValue* value) { bool transition_to_field = info->lookup()->IsTransition(); // TODO(verwaest): Move this logic into PropertyAccessInfo. HObjectAccess field_access = info->access(); HStoreNamedField *instr; if (field_access.representation().IsDouble()) { HObjectAccess heap_number_access = field_access.WithRepresentation(Representation::Tagged()); if (transition_to_field) { // The store requires a mutable HeapNumber to be allocated. NoObservableSideEffectsScope no_side_effects(this); HInstruction* heap_number_size = Add<HConstant>(HeapNumber::kSize); // TODO(hpayer): Allocation site pretenuring support. HInstruction* heap_number = Add<HAllocate>(heap_number_size, HType::HeapObject(), NOT_TENURED, HEAP_NUMBER_TYPE); AddStoreMapConstant(heap_number, isolate()->factory()->heap_number_map()); Add<HStoreNamedField>(heap_number, HObjectAccess::ForHeapNumberValue(), value); instr = New<HStoreNamedField>(checked_object->ActualValue(), heap_number_access, heap_number); } else { // Already holds a HeapNumber; load the box and write its value field. HInstruction* heap_number = Add<HLoadNamedField>( checked_object, static_cast<HValue*>(NULL), heap_number_access); instr = New<HStoreNamedField>(heap_number, HObjectAccess::ForHeapNumberValue(), value, STORE_TO_INITIALIZED_ENTRY); } } else { if (field_access.representation().IsHeapObject()) { BuildCheckHeapObject(value); } if (!info->field_maps()->is_empty()) { ASSERT(field_access.representation().IsHeapObject()); value = Add<HCheckMaps>(value, info->field_maps()); } // This is a normal store. instr = New<HStoreNamedField>( checked_object->ActualValue(), field_access, value, transition_to_field ? INITIALIZING_STORE : STORE_TO_INITIALIZED_ENTRY); } if (transition_to_field) { Handle<Map> transition(info->transition()); ASSERT(!transition->is_deprecated()); instr->SetTransition(Add<HConstant>(transition)); } return instr; } bool HOptimizedGraphBuilder::PropertyAccessInfo::IsCompatible( PropertyAccessInfo* info) { if (!CanInlinePropertyAccess(type_)) return false; // Currently only handle Type::Number as a polymorphic case. // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber // instruction. if (type_->Is(Type::Number())) return false; // Values are only compatible for monomorphic load if they all behave the same // regarding value wrappers. if (type_->Is(Type::NumberOrString())) { if (!info->type_->Is(Type::NumberOrString())) return false; } else { if (info->type_->Is(Type::NumberOrString())) return false; } if (!LookupDescriptor()) return false; if (!lookup_.IsFound()) { return (!info->lookup_.IsFound() || info->has_holder()) && map()->prototype() == info->map()->prototype(); } // Mismatch if the other access info found the property in the prototype // chain. if (info->has_holder()) return false; if (lookup_.IsPropertyCallbacks()) { return accessor_.is_identical_to(info->accessor_) && api_holder_.is_identical_to(info->api_holder_); } if (lookup_.IsConstant()) { return constant_.is_identical_to(info->constant_); } ASSERT(lookup_.IsField()); if (!info->lookup_.IsField()) return false; Representation r = access_.representation(); if (IsLoad()) { if (!info->access_.representation().IsCompatibleForLoad(r)) return false; } else { if (!info->access_.representation().IsCompatibleForStore(r)) return false; } if (info->access_.offset() != access_.offset()) return false; if (info->access_.IsInobject() != access_.IsInobject()) return false; if (IsLoad()) { if (field_maps_.is_empty()) { info->field_maps_.Clear(); } else if (!info->field_maps_.is_empty()) { for (int i = 0; i < field_maps_.length(); ++i) { info->field_maps_.AddMapIfMissing(field_maps_.at(i), info->zone()); } info->field_maps_.Sort(); } } else { // We can only merge stores that agree on their field maps. The comparison // below is safe, since we keep the field maps sorted. if (field_maps_.length() != info->field_maps_.length()) return false; for (int i = 0; i < field_maps_.length(); ++i) { if (!field_maps_.at(i).is_identical_to(info->field_maps_.at(i))) { return false; } } } info->GeneralizeRepresentation(r); info->field_type_ = info->field_type_.Combine(field_type_); return true; } bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupDescriptor() { if (!type_->IsClass()) return true; map()->LookupDescriptor(NULL, *name_, &lookup_); return LoadResult(map()); } bool HOptimizedGraphBuilder::PropertyAccessInfo::LoadResult(Handle<Map> map) { if (!IsLoad() && lookup_.IsProperty() && (lookup_.IsReadOnly() || !lookup_.IsCacheable())) { return false; } if (lookup_.IsField()) { // Construct the object field access. access_ = HObjectAccess::ForField(map, &lookup_, name_); // Load field map for heap objects. LoadFieldMaps(map); } else if (lookup_.IsPropertyCallbacks()) { Handle<Object> callback(lookup_.GetValueFromMap(*map), isolate()); if (!callback->IsAccessorPair()) return false; Object* raw_accessor = IsLoad() ? Handle<AccessorPair>::cast(callback)->getter() : Handle<AccessorPair>::cast(callback)->setter(); if (!raw_accessor->IsJSFunction()) return false; Handle<JSFunction> accessor = handle(JSFunction::cast(raw_accessor)); if (accessor->shared()->IsApiFunction()) { CallOptimization call_optimization(accessor); if (call_optimization.is_simple_api_call()) { CallOptimization::HolderLookup holder_lookup; Handle<Map> receiver_map = this->map(); api_holder_ = call_optimization.LookupHolderOfExpectedType( receiver_map, &holder_lookup); } } accessor_ = accessor; } else if (lookup_.IsConstant()) { constant_ = handle(lookup_.GetConstantFromMap(*map), isolate()); } return true; } void HOptimizedGraphBuilder::PropertyAccessInfo::LoadFieldMaps( Handle<Map> map) { // Clear any previously collected field maps/type. field_maps_.Clear(); field_type_ = HType::Tagged(); // Figure out the field type from the accessor map. Handle<HeapType> field_type(lookup_.GetFieldTypeFromMap(*map), isolate()); // Collect the (stable) maps from the field type. int num_field_maps = field_type->NumClasses(); if (num_field_maps == 0) return; ASSERT(access_.representation().IsHeapObject()); field_maps_.Reserve(num_field_maps, zone()); HeapType::Iterator<Map> it = field_type->Classes(); while (!it.Done()) { Handle<Map> field_map = it.Current(); if (!field_map->is_stable()) { field_maps_.Clear(); return; } field_maps_.Add(field_map, zone()); it.Advance(); } field_maps_.Sort(); ASSERT_EQ(num_field_maps, field_maps_.length()); // Determine field HType from field HeapType. field_type_ = HType::FromType<HeapType>(field_type); ASSERT(field_type_.IsHeapObject()); // Add dependency on the map that introduced the field. Map::AddDependentCompilationInfo( handle(lookup_.GetFieldOwnerFromMap(*map), isolate()), DependentCode::kFieldTypeGroup, top_info()); } bool HOptimizedGraphBuilder::PropertyAccessInfo::LookupInPrototypes() { Handle<Map> map = this->map(); while (map->prototype()->IsJSObject()) { holder_ = handle(JSObject::cast(map->prototype())); if (holder_->map()->is_deprecated()) { JSObject::TryMigrateInstance(holder_); } map = Handle<Map>(holder_->map()); if (!CanInlinePropertyAccess(ToType(map))) { lookup_.NotFound(); return false; } map->LookupDescriptor(*holder_, *name_, &lookup_); if (lookup_.IsFound()) return LoadResult(map); } lookup_.NotFound(); return true; } bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessMonomorphic() { if (!CanInlinePropertyAccess(type_)) return false; if (IsJSObjectFieldAccessor()) return IsLoad(); if (!LookupDescriptor()) return false; if (lookup_.IsFound()) { if (IsLoad()) return true; return !lookup_.IsReadOnly() && lookup_.IsCacheable(); } if (!LookupInPrototypes()) return false; if (IsLoad()) return true; if (lookup_.IsPropertyCallbacks()) return true; Handle<Map> map = this->map(); map->LookupTransition(NULL, *name_, &lookup_); if (lookup_.IsTransitionToField() && map->unused_property_fields() > 0) { // Construct the object field access. access_ = HObjectAccess::ForField(map, &lookup_, name_); // Load field map for heap objects. LoadFieldMaps(transition()); return true; } return false; } bool HOptimizedGraphBuilder::PropertyAccessInfo::CanAccessAsMonomorphic( SmallMapList* types) { ASSERT(type_->Is(ToType(types->first()))); if (!CanAccessMonomorphic()) return false; STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism); if (types->length() > kMaxLoadPolymorphism) return false; HObjectAccess access = HObjectAccess::ForMap(); // bogus default if (GetJSObjectFieldAccess(&access)) { for (int i = 1; i < types->length(); ++i) { PropertyAccessInfo test_info( builder_, access_type_, ToType(types->at(i)), name_); HObjectAccess test_access = HObjectAccess::ForMap(); // bogus default if (!test_info.GetJSObjectFieldAccess(&test_access)) return false; if (!access.Equals(test_access)) return false; } return true; } // Currently only handle Type::Number as a polymorphic case. // TODO(verwaest): Support monomorphic handling of numbers with a HCheckNumber // instruction. if (type_->Is(Type::Number())) return false; // Multiple maps cannot transition to the same target map. ASSERT(!IsLoad() || !lookup_.IsTransition()); if (lookup_.IsTransition() && types->length() > 1) return false; for (int i = 1; i < types->length(); ++i) { PropertyAccessInfo test_info( builder_, access_type_, ToType(types->at(i)), name_); if (!test_info.IsCompatible(this)) return false; } return true; } static bool NeedsWrappingFor(Type* type, Handle<JSFunction> target) { return type->Is(Type::NumberOrString()) && target->shared()->strict_mode() == SLOPPY && !target->shared()->native(); } HInstruction* HOptimizedGraphBuilder::BuildMonomorphicAccess( PropertyAccessInfo* info, HValue* object, HValue* checked_object, HValue* value, BailoutId ast_id, BailoutId return_id, bool can_inline_accessor) { HObjectAccess access = HObjectAccess::ForMap(); // bogus default if (info->GetJSObjectFieldAccess(&access)) { ASSERT(info->IsLoad()); return New<HLoadNamedField>(object, checked_object, access); } HValue* checked_holder = checked_object; if (info->has_holder()) { Handle<JSObject> prototype(JSObject::cast(info->map()->prototype())); checked_holder = BuildCheckPrototypeMaps(prototype, info->holder()); } if (!info->lookup()->IsFound()) { ASSERT(info->IsLoad()); return graph()->GetConstantUndefined(); } if (info->lookup()->IsField()) { if (info->IsLoad()) { return BuildLoadNamedField(info, checked_holder); } else { return BuildStoreNamedField(info, checked_object, value); } } if (info->lookup()->IsTransition()) { ASSERT(!info->IsLoad()); return BuildStoreNamedField(info, checked_object, value); } if (info->lookup()->IsPropertyCallbacks()) { Push(checked_object); int argument_count = 1; if (!info->IsLoad()) { argument_count = 2; Push(value); } if (NeedsWrappingFor(info->type(), info->accessor())) { HValue* function = Add<HConstant>(info->accessor()); PushArgumentsFromEnvironment(argument_count); return New<HCallFunction>(function, argument_count, WRAP_AND_CALL); } else if (FLAG_inline_accessors && can_inline_accessor) { bool success = info->IsLoad() ? TryInlineGetter(info->accessor(), info->map(), ast_id, return_id) : TryInlineSetter( info->accessor(), info->map(), ast_id, return_id, value); if (success || HasStackOverflow()) return NULL; } PushArgumentsFromEnvironment(argument_count); return BuildCallConstantFunction(info->accessor(), argument_count); } ASSERT(info->lookup()->IsConstant()); if (info->IsLoad()) { return New<HConstant>(info->constant()); } else { return New<HCheckValue>(value, Handle<JSFunction>::cast(info->constant())); } } void HOptimizedGraphBuilder::HandlePolymorphicNamedFieldAccess( PropertyAccessType access_type, BailoutId ast_id, BailoutId return_id, HValue* object, HValue* value, SmallMapList* types, Handle<String> name) { // Something did not match; must use a polymorphic load. int count = 0; HBasicBlock* join = NULL; HBasicBlock* number_block = NULL; bool handled_string = false; bool handle_smi = false; STATIC_ASSERT(kMaxLoadPolymorphism == kMaxStorePolymorphism); for (int i = 0; i < types->length() && count < kMaxLoadPolymorphism; ++i) { PropertyAccessInfo info(this, access_type, ToType(types->at(i)), name); if (info.type()->Is(Type::String())) { if (handled_string) continue; handled_string = true; } if (info.CanAccessMonomorphic()) { count++; if (info.type()->Is(Type::Number())) { handle_smi = true; break; } } } count = 0; HControlInstruction* smi_check = NULL; handled_string = false; for (int i = 0; i < types->length() && count < kMaxLoadPolymorphism; ++i) { PropertyAccessInfo info(this, access_type, ToType(types->at(i)), name); if (info.type()->Is(Type::String())) { if (handled_string) continue; handled_string = true; } if (!info.CanAccessMonomorphic()) continue; if (count == 0) { join = graph()->CreateBasicBlock(); if (handle_smi) { HBasicBlock* empty_smi_block = graph()->CreateBasicBlock(); HBasicBlock* not_smi_block = graph()->CreateBasicBlock(); number_block = graph()->CreateBasicBlock(); smi_check = New<HIsSmiAndBranch>( object, empty_smi_block, not_smi_block); FinishCurrentBlock(smi_check); GotoNoSimulate(empty_smi_block, number_block); set_current_block(not_smi_block); } else { BuildCheckHeapObject(object); } } ++count; HBasicBlock* if_true = graph()->CreateBasicBlock(); HBasicBlock* if_false = graph()->CreateBasicBlock(); HUnaryControlInstruction* compare; HValue* dependency; if (info.type()->Is(Type::Number())) { Handle<Map> heap_number_map = isolate()->factory()->heap_number_map(); compare = New<HCompareMap>(object, heap_number_map, if_true, if_false); dependency = smi_check; } else if (info.type()->Is(Type::String())) { compare = New<HIsStringAndBranch>(object, if_true, if_false); dependency = compare; } else { compare = New<HCompareMap>(object, info.map(), if_true, if_false); dependency = compare; } FinishCurrentBlock(compare); if (info.type()->Is(Type::Number())) { GotoNoSimulate(if_true, number_block); if_true = number_block; } set_current_block(if_true); HInstruction* access = BuildMonomorphicAccess( &info, object, dependency, value, ast_id, return_id, FLAG_polymorphic_inlining); HValue* result = NULL; switch (access_type) { case LOAD: result = access; break; case STORE: result = value; break; } if (access == NULL) { if (HasStackOverflow()) return; } else { if (!access->IsLinked()) AddInstruction(access); if (!ast_context()->IsEffect()) Push(result); } if (current_block() != NULL) Goto(join); set_current_block(if_false); } // Finish up. Unconditionally deoptimize if we've handled all the maps we // know about and do not want to handle ones we've never seen. Otherwise // use a generic IC. if (count == types->length() && FLAG_deoptimize_uncommon_cases) { FinishExitWithHardDeoptimization("Uknown map in polymorphic access"); } else { HInstruction* instr = BuildNamedGeneric(access_type, object, name, value); AddInstruction(instr); if (!ast_context()->IsEffect()) Push(access_type == LOAD ? instr : value); if (join != NULL) { Goto(join); } else { Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop()); return; } } ASSERT(join != NULL); if (join->HasPredecessor()) { join->SetJoinId(ast_id); set_current_block(join); if (!ast_context()->IsEffect()) ast_context()->ReturnValue(Pop()); } else { set_current_block(NULL); } } static bool ComputeReceiverTypes(Expression* expr, HValue* receiver, SmallMapList** t, Zone* zone) { SmallMapList* types = expr->GetReceiverTypes(); *t = types; bool monomorphic = expr->IsMonomorphic(); if (types != NULL && receiver->HasMonomorphicJSObjectType()) { Map* root_map = receiver->GetMonomorphicJSObjectMap()->FindRootMap(); types->FilterForPossibleTransitions(root_map); monomorphic = types->length() == 1; } return monomorphic && CanInlinePropertyAccess( IC::MapToType<Type>(types->first(), zone)); } static bool AreStringTypes(SmallMapList* types) { for (int i = 0; i < types->length(); i++) { if (types->at(i)->instance_type() >= FIRST_NONSTRING_TYPE) return false; } return true; } void HOptimizedGraphBuilder::BuildStore(Expression* expr, Property* prop, BailoutId ast_id, BailoutId return_id, bool is_uninitialized) { if (!prop->key()->IsPropertyName()) { // Keyed store. HValue* value = environment()->ExpressionStackAt(0); HValue* key = environment()->ExpressionStackAt(1); HValue* object = environment()->ExpressionStackAt(2); bool has_side_effects = false; HandleKeyedElementAccess(object, key, value, expr, STORE, &has_side_effects); Drop(3); Push(value); Add<HSimulate>(return_id, REMOVABLE_SIMULATE); return ast_context()->ReturnValue(Pop()); } // Named store. HValue* value = Pop(); HValue* object = Pop(); Literal* key = prop->key()->AsLiteral(); Handle<String> name = Handle<String>::cast(key->value()); ASSERT(!name.is_null()); HInstruction* instr = BuildNamedAccess(STORE, ast_id, return_id, expr, object, name, value, is_uninitialized); if (instr == NULL) return; if (!ast_context()->IsEffect()) Push(value); AddInstruction(instr); if (instr->HasObservableSideEffects()) { Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); } if (!ast_context()->IsEffect()) Drop(1); return ast_context()->ReturnValue(value); } void HOptimizedGraphBuilder::HandlePropertyAssignment(Assignment* expr) { Property* prop = expr->target()->AsProperty(); ASSERT(prop != NULL); CHECK_ALIVE(VisitForValue(prop->obj())); if (!prop->key()->IsPropertyName()) { CHECK_ALIVE(VisitForValue(prop->key())); } CHECK_ALIVE(VisitForValue(expr->value())); BuildStore(expr, prop, expr->id(), expr->AssignmentId(), expr->IsUninitialized()); } // Because not every expression has a position and there is not common // superclass of Assignment and CountOperation, we cannot just pass the // owning expression instead of position and ast_id separately. void HOptimizedGraphBuilder::HandleGlobalVariableAssignment( Variable* var, HValue* value, BailoutId ast_id) { LookupResult lookup(isolate()); GlobalPropertyAccess type = LookupGlobalProperty(var, &lookup, STORE); if (type == kUseCell) { Handle<GlobalObject> global(current_info()->global_object()); Handle<PropertyCell> cell(global->GetPropertyCell(&lookup)); if (cell->type()->IsConstant()) { Handle<Object> constant = cell->type()->AsConstant()->Value(); if (value->IsConstant()) { HConstant* c_value = HConstant::cast(value); if (!constant.is_identical_to(c_value->handle(isolate()))) { Add<HDeoptimize>("Constant global variable assignment", Deoptimizer::EAGER); } } else { HValue* c_constant = Add<HConstant>(constant); IfBuilder builder(this); if (constant->IsNumber()) { builder.If<HCompareNumericAndBranch>(value, c_constant, Token::EQ); } else { builder.If<HCompareObjectEqAndBranch>(value, c_constant); } builder.Then(); builder.Else(); Add<HDeoptimize>("Constant global variable assignment", Deoptimizer::EAGER); builder.End(); } } HInstruction* instr = Add<HStoreGlobalCell>(value, cell, lookup.GetPropertyDetails()); if (instr->HasObservableSideEffects()) { Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); } } else { HValue* global_object = Add<HLoadNamedField>( context(), static_cast<HValue*>(NULL), HObjectAccess::ForContextSlot(Context::GLOBAL_OBJECT_INDEX)); HStoreNamedGeneric* instr = Add<HStoreNamedGeneric>(global_object, var->name(), value, function_strict_mode()); USE(instr); ASSERT(instr->HasObservableSideEffects()); Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); } } void HOptimizedGraphBuilder::HandleCompoundAssignment(Assignment* expr) { Expression* target = expr->target(); VariableProxy* proxy = target->AsVariableProxy(); Property* prop = target->AsProperty(); ASSERT(proxy == NULL || prop == NULL); // We have a second position recorded in the FullCodeGenerator to have // type feedback for the binary operation. BinaryOperation* operation = expr->binary_operation(); if (proxy != NULL) { Variable* var = proxy->var(); if (var->mode() == LET) { return Bailout(kUnsupportedLetCompoundAssignment); } CHECK_ALIVE(VisitForValue(operation)); switch (var->location()) { case Variable::UNALLOCATED: HandleGlobalVariableAssignment(var, Top(), expr->AssignmentId()); break; case Variable::PARAMETER: case Variable::LOCAL: if (var->mode() == CONST_LEGACY) { return Bailout(kUnsupportedConstCompoundAssignment); } BindIfLive(var, Top()); break; case Variable::CONTEXT: { // Bail out if we try to mutate a parameter value in a function // using the arguments object. We do not (yet) correctly handle the // arguments property of the function. if (current_info()->scope()->arguments() != NULL) { // Parameters will be allocated to context slots. We have no // direct way to detect that the variable is a parameter so we do // a linear search of the parameter variables. int count = current_info()->scope()->num_parameters(); for (int i = 0; i < count; ++i) { if (var == current_info()->scope()->parameter(i)) { Bailout(kAssignmentToParameterFunctionUsesArgumentsObject); } } } HStoreContextSlot::Mode mode; switch (var->mode()) { case LET: mode = HStoreContextSlot::kCheckDeoptimize; break; case CONST: // This case is checked statically so no need to // perform checks here UNREACHABLE(); case CONST_LEGACY: return ast_context()->ReturnValue(Pop()); default: mode = HStoreContextSlot::kNoCheck; } HValue* context = BuildContextChainWalk(var); HStoreContextSlot* instr = Add<HStoreContextSlot>( context, var->index(), mode, Top()); if (instr->HasObservableSideEffects()) { Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE); } break; } case Variable::LOOKUP: return Bailout(kCompoundAssignmentToLookupSlot); } return ast_context()->ReturnValue(Pop()); } else if (prop != NULL) { CHECK_ALIVE(VisitForValue(prop->obj())); HValue* object = Top(); HValue* key = NULL; if ((!prop->IsFunctionPrototype() && !prop->key()->IsPropertyName()) || prop->IsStringAccess()) { CHECK_ALIVE(VisitForValue(prop->key())); key = Top(); } CHECK_ALIVE(PushLoad(prop, object, key)); CHECK_ALIVE(VisitForValue(expr->value())); HValue* right = Pop(); HValue* left = Pop(); Push(BuildBinaryOperation(operation, left, right, PUSH_BEFORE_SIMULATE)); BuildStore(expr, prop, expr->id(), expr->AssignmentId(), expr->IsUninitialized()); } else { return Bailout(kInvalidLhsInCompoundAssignment); } } void HOptimizedGraphBuilder::VisitAssignment(Assignment* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); VariableProxy* proxy = expr->target()->AsVariableProxy(); Property* prop = expr->target()->AsProperty(); ASSERT(proxy == NULL || prop == NULL); if (expr->is_compound()) { HandleCompoundAssignment(expr); return; } if (prop != NULL) { HandlePropertyAssignment(expr); } else if (proxy != NULL) { Variable* var = proxy->var(); if (var->mode() == CONST) { if (expr->op() != Token::INIT_CONST) { return Bailout(kNonInitializerAssignmentToConst); } } else if (var->mode() == CONST_LEGACY) { if (expr->op() != Token::INIT_CONST_LEGACY) { CHECK_ALIVE(VisitForValue(expr->value())); return ast_context()->ReturnValue(Pop()); } if (var->IsStackAllocated()) { // We insert a use of the old value to detect unsupported uses of const // variables (e.g. initialization inside a loop). HValue* old_value = environment()->Lookup(var); Add<HUseConst>(old_value); } } if (proxy->IsArguments()) return Bailout(kAssignmentToArguments); // Handle the assignment. switch (var->location()) { case Variable::UNALLOCATED: CHECK_ALIVE(VisitForValue(expr->value())); HandleGlobalVariableAssignment(var, Top(), expr->AssignmentId()); return ast_context()->ReturnValue(Pop()); case Variable::PARAMETER: case Variable::LOCAL: { // Perform an initialization check for let declared variables // or parameters. if (var->mode() == LET && expr->op() == Token::ASSIGN) { HValue* env_value = environment()->Lookup(var); if (env_value == graph()->GetConstantHole()) { return Bailout(kAssignmentToLetVariableBeforeInitialization); } } // We do not allow the arguments object to occur in a context where it // may escape, but assignments to stack-allocated locals are // permitted. CHECK_ALIVE(VisitForValue(expr->value(), ARGUMENTS_ALLOWED)); HValue* value = Pop(); BindIfLive(var, value); return ast_context()->ReturnValue(value); } case Variable::CONTEXT: { // Bail out if we try to mutate a parameter value in a function using // the arguments object. We do not (yet) correctly handle the // arguments property of the function. if (current_info()->scope()->arguments() != NULL) { // Parameters will rewrite to context slots. We have no direct way // to detect that the variable is a parameter. int count = current_info()->scope()->num_parameters(); for (int i = 0; i < count; ++i) { if (var == current_info()->scope()->parameter(i)) { return Bailout(kAssignmentToParameterInArgumentsObject); } } } CHECK_ALIVE(VisitForValue(expr->value())); HStoreContextSlot::Mode mode; if (expr->op() == Token::ASSIGN) { switch (var->mode()) { case LET: mode = HStoreContextSlot::kCheckDeoptimize; break; case CONST: // This case is checked statically so no need to // perform checks here UNREACHABLE(); case CONST_LEGACY: return ast_context()->ReturnValue(Pop()); default: mode = HStoreContextSlot::kNoCheck; } } else if (expr->op() == Token::INIT_VAR || expr->op() == Token::INIT_LET || expr->op() == Token::INIT_CONST) { mode = HStoreContextSlot::kNoCheck; } else { ASSERT(expr->op() == Token::INIT_CONST_LEGACY); mode = HStoreContextSlot::kCheckIgnoreAssignment; } HValue* context = BuildContextChainWalk(var); HStoreContextSlot* instr = Add<HStoreContextSlot>( context, var->index(), mode, Top()); if (instr->HasObservableSideEffects()) { Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE); } return ast_context()->ReturnValue(Pop()); } case Variable::LOOKUP: return Bailout(kAssignmentToLOOKUPVariable); } } else { return Bailout(kInvalidLeftHandSideInAssignment); } } void HOptimizedGraphBuilder::VisitYield(Yield* expr) { // Generators are not optimized, so we should never get here. UNREACHABLE(); } void HOptimizedGraphBuilder::VisitThrow(Throw* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); // We don't optimize functions with invalid left-hand sides in // assignments, count operations, or for-in. Consequently throw can // currently only occur in an effect context. ASSERT(ast_context()->IsEffect()); CHECK_ALIVE(VisitForValue(expr->exception())); HValue* value = environment()->Pop(); if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position()); Add<HPushArguments>(value); Add<HCallRuntime>(isolate()->factory()->empty_string(), Runtime::FunctionForId(Runtime::kHiddenThrow), 1); Add<HSimulate>(expr->id()); // If the throw definitely exits the function, we can finish with a dummy // control flow at this point. This is not the case if the throw is inside // an inlined function which may be replaced. if (call_context() == NULL) { FinishExitCurrentBlock(New<HAbnormalExit>()); } } HInstruction* HGraphBuilder::AddLoadStringInstanceType(HValue* string) { if (string->IsConstant()) { HConstant* c_string = HConstant::cast(string); if (c_string->HasStringValue()) { return Add<HConstant>(c_string->StringValue()->map()->instance_type()); } } return Add<HLoadNamedField>( Add<HLoadNamedField>(string, static_cast<HValue*>(NULL), HObjectAccess::ForMap()), static_cast<HValue*>(NULL), HObjectAccess::ForMapInstanceType()); } HInstruction* HGraphBuilder::AddLoadStringLength(HValue* string) { if (string->IsConstant()) { HConstant* c_string = HConstant::cast(string); if (c_string->HasStringValue()) { return Add<HConstant>(c_string->StringValue()->length()); } } return Add<HLoadNamedField>(string, static_cast<HValue*>(NULL), HObjectAccess::ForStringLength()); } HInstruction* HOptimizedGraphBuilder::BuildNamedGeneric( PropertyAccessType access_type, HValue* object, Handle<String> name, HValue* value, bool is_uninitialized) { if (is_uninitialized) { Add<HDeoptimize>("Insufficient type feedback for generic named access", Deoptimizer::SOFT); } if (access_type == LOAD) { return New<HLoadNamedGeneric>(object, name); } else { return New<HStoreNamedGeneric>(object, name, value, function_strict_mode()); } } HInstruction* HOptimizedGraphBuilder::BuildKeyedGeneric( PropertyAccessType access_type, HValue* object, HValue* key, HValue* value) { if (access_type == LOAD) { return New<HLoadKeyedGeneric>(object, key); } else { return New<HStoreKeyedGeneric>(object, key, value, function_strict_mode()); } } LoadKeyedHoleMode HOptimizedGraphBuilder::BuildKeyedHoleMode(Handle<Map> map) { // Loads from a "stock" fast holey double arrays can elide the hole check. LoadKeyedHoleMode load_mode = NEVER_RETURN_HOLE; if (*map == isolate()->get_initial_js_array_map(FAST_HOLEY_DOUBLE_ELEMENTS) && isolate()->IsFastArrayConstructorPrototypeChainIntact()) { Handle<JSObject> prototype(JSObject::cast(map->prototype()), isolate()); Handle<JSObject> object_prototype = isolate()->initial_object_prototype(); BuildCheckPrototypeMaps(prototype, object_prototype); load_mode = ALLOW_RETURN_HOLE; graph()->MarkDependsOnEmptyArrayProtoElements(); } return load_mode; } HInstruction* HOptimizedGraphBuilder::BuildMonomorphicElementAccess( HValue* object, HValue* key, HValue* val, HValue* dependency, Handle<Map> map, PropertyAccessType access_type, KeyedAccessStoreMode store_mode) { HCheckMaps* checked_object = Add<HCheckMaps>(object, map, dependency); if (dependency) { checked_object->ClearDependsOnFlag(kElementsKind); } if (access_type == STORE && map->prototype()->IsJSObject()) { // monomorphic stores need a prototype chain check because shape // changes could allow callbacks on elements in the chain that // aren't compatible with monomorphic keyed stores. Handle<JSObject> prototype(JSObject::cast(map->prototype())); JSObject* holder = JSObject::cast(map->prototype()); while (!holder->GetPrototype()->IsNull()) { holder = JSObject::cast(holder->GetPrototype()); } BuildCheckPrototypeMaps(prototype, Handle<JSObject>(JSObject::cast(holder))); } LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map); return BuildUncheckedMonomorphicElementAccess( checked_object, key, val, map->instance_type() == JS_ARRAY_TYPE, map->elements_kind(), access_type, load_mode, store_mode); } HInstruction* HOptimizedGraphBuilder::TryBuildConsolidatedElementLoad( HValue* object, HValue* key, HValue* val, SmallMapList* maps) { // For polymorphic loads of similar elements kinds (i.e. all tagged or all // double), always use the "worst case" code without a transition. This is // much faster than transitioning the elements to the worst case, trading a // HTransitionElements for a HCheckMaps, and avoiding mutation of the array. bool has_double_maps = false; bool has_smi_or_object_maps = false; bool has_js_array_access = false; bool has_non_js_array_access = false; bool has_seen_holey_elements = false; Handle<Map> most_general_consolidated_map; for (int i = 0; i < maps->length(); ++i) { Handle<Map> map = maps->at(i); if (!map->IsJSObjectMap()) return NULL; // Don't allow mixing of JSArrays with JSObjects. if (map->instance_type() == JS_ARRAY_TYPE) { if (has_non_js_array_access) return NULL; has_js_array_access = true; } else if (has_js_array_access) { return NULL; } else { has_non_js_array_access = true; } // Don't allow mixed, incompatible elements kinds. if (map->has_fast_double_elements()) { if (has_smi_or_object_maps) return NULL; has_double_maps = true; } else if (map->has_fast_smi_or_object_elements()) { if (has_double_maps) return NULL; has_smi_or_object_maps = true; } else { return NULL; } // Remember if we've ever seen holey elements. if (IsHoleyElementsKind(map->elements_kind())) { has_seen_holey_elements = true; } // Remember the most general elements kind, the code for its load will // properly handle all of the more specific cases. if ((i == 0) || IsMoreGeneralElementsKindTransition( most_general_consolidated_map->elements_kind(), map->elements_kind())) { most_general_consolidated_map = map; } } if (!has_double_maps && !has_smi_or_object_maps) return NULL; HCheckMaps* checked_object = Add<HCheckMaps>(object, maps); // FAST_ELEMENTS is considered more general than FAST_HOLEY_SMI_ELEMENTS. // If we've seen both, the consolidated load must use FAST_HOLEY_ELEMENTS. ElementsKind consolidated_elements_kind = has_seen_holey_elements ? GetHoleyElementsKind(most_general_consolidated_map->elements_kind()) : most_general_consolidated_map->elements_kind(); HInstruction* instr = BuildUncheckedMonomorphicElementAccess( checked_object, key, val, most_general_consolidated_map->instance_type() == JS_ARRAY_TYPE, consolidated_elements_kind, LOAD, NEVER_RETURN_HOLE, STANDARD_STORE); return instr; } HValue* HOptimizedGraphBuilder::HandlePolymorphicElementAccess( HValue* object, HValue* key, HValue* val, SmallMapList* maps, PropertyAccessType access_type, KeyedAccessStoreMode store_mode, bool* has_side_effects) { *has_side_effects = false; BuildCheckHeapObject(object); if (access_type == LOAD) { HInstruction* consolidated_load = TryBuildConsolidatedElementLoad(object, key, val, maps); if (consolidated_load != NULL) { *has_side_effects |= consolidated_load->HasObservableSideEffects(); return consolidated_load; } } // Elements_kind transition support. MapHandleList transition_target(maps->length()); // Collect possible transition targets. MapHandleList possible_transitioned_maps(maps->length()); for (int i = 0; i < maps->length(); ++i) { Handle<Map> map = maps->at(i); ElementsKind elements_kind = map->elements_kind(); if (IsFastElementsKind(elements_kind) && elements_kind != GetInitialFastElementsKind()) { possible_transitioned_maps.Add(map); } if (elements_kind == SLOPPY_ARGUMENTS_ELEMENTS) { HInstruction* result = BuildKeyedGeneric(access_type, object, key, val); *has_side_effects = result->HasObservableSideEffects(); return AddInstruction(result); } } // Get transition target for each map (NULL == no transition). for (int i = 0; i < maps->length(); ++i) { Handle<Map> map = maps->at(i); Handle<Map> transitioned_map = map->FindTransitionedMap(&possible_transitioned_maps); transition_target.Add(transitioned_map); } MapHandleList untransitionable_maps(maps->length()); HTransitionElementsKind* transition = NULL; for (int i = 0; i < maps->length(); ++i) { Handle<Map> map = maps->at(i); ASSERT(map->IsMap()); if (!transition_target.at(i).is_null()) { ASSERT(Map::IsValidElementsTransition( map->elements_kind(), transition_target.at(i)->elements_kind())); transition = Add<HTransitionElementsKind>(object, map, transition_target.at(i)); } else { untransitionable_maps.Add(map); } } // If only one map is left after transitioning, handle this case // monomorphically. ASSERT(untransitionable_maps.length() >= 1); if (untransitionable_maps.length() == 1) { Handle<Map> untransitionable_map = untransitionable_maps[0]; HInstruction* instr = NULL; if (untransitionable_map->has_slow_elements_kind() || !untransitionable_map->IsJSObjectMap()) { instr = AddInstruction(BuildKeyedGeneric(access_type, object, key, val)); } else { instr = BuildMonomorphicElementAccess( object, key, val, transition, untransitionable_map, access_type, store_mode); } *has_side_effects |= instr->HasObservableSideEffects(); return access_type == STORE ? NULL : instr; } HBasicBlock* join = graph()->CreateBasicBlock(); for (int i = 0; i < untransitionable_maps.length(); ++i) { Handle<Map> map = untransitionable_maps[i]; if (!map->IsJSObjectMap()) continue; ElementsKind elements_kind = map->elements_kind(); HBasicBlock* this_map = graph()->CreateBasicBlock(); HBasicBlock* other_map = graph()->CreateBasicBlock(); HCompareMap* mapcompare = New<HCompareMap>(object, map, this_map, other_map); FinishCurrentBlock(mapcompare); set_current_block(this_map); HInstruction* access = NULL; if (IsDictionaryElementsKind(elements_kind)) { access = AddInstruction(BuildKeyedGeneric(access_type, object, key, val)); } else { ASSERT(IsFastElementsKind(elements_kind) || IsExternalArrayElementsKind(elements_kind) || IsFixedTypedArrayElementsKind(elements_kind)); LoadKeyedHoleMode load_mode = BuildKeyedHoleMode(map); // Happily, mapcompare is a checked object. access = BuildUncheckedMonomorphicElementAccess( mapcompare, key, val, map->instance_type() == JS_ARRAY_TYPE, elements_kind, access_type, load_mode, store_mode); } *has_side_effects |= access->HasObservableSideEffects(); // The caller will use has_side_effects and add a correct Simulate. access->SetFlag(HValue::kHasNoObservableSideEffects); if (access_type == LOAD) { Push(access); } NoObservableSideEffectsScope scope(this); GotoNoSimulate(join); set_current_block(other_map); } // Ensure that we visited at least one map above that goes to join. This is // necessary because FinishExitWithHardDeoptimization does an AbnormalExit // rather than joining the join block. If this becomes an issue, insert a // generic access in the case length() == 0. ASSERT(join->predecessors()->length() > 0); // Deopt if none of the cases matched. NoObservableSideEffectsScope scope(this); FinishExitWithHardDeoptimization("Unknown map in polymorphic element access"); set_current_block(join); return access_type == STORE ? NULL : Pop(); } HValue* HOptimizedGraphBuilder::HandleKeyedElementAccess( HValue* obj, HValue* key, HValue* val, Expression* expr, PropertyAccessType access_type, bool* has_side_effects) { ASSERT(!expr->IsPropertyName()); HInstruction* instr = NULL; SmallMapList* types; bool monomorphic = ComputeReceiverTypes(expr, obj, &types, zone()); bool force_generic = false; if (access_type == STORE && (monomorphic || (types != NULL && !types->is_empty()))) { // Stores can't be mono/polymorphic if their prototype chain has dictionary // elements. However a receiver map that has dictionary elements itself // should be left to normal mono/poly behavior (the other maps may benefit // from highly optimized stores). for (int i = 0; i < types->length(); i++) { Handle<Map> current_map = types->at(i); if (current_map->DictionaryElementsInPrototypeChainOnly()) { force_generic = true; monomorphic = false; break; } } } if (monomorphic) { Handle<Map> map = types->first(); if (map->has_slow_elements_kind() || !map->IsJSObjectMap()) { instr = AddInstruction(BuildKeyedGeneric(access_type, obj, key, val)); } else { BuildCheckHeapObject(obj); instr = BuildMonomorphicElementAccess( obj, key, val, NULL, map, access_type, expr->GetStoreMode()); } } else if (!force_generic && (types != NULL && !types->is_empty())) { return HandlePolymorphicElementAccess( obj, key, val, types, access_type, expr->GetStoreMode(), has_side_effects); } else { if (access_type == STORE) { if (expr->IsAssignment() && expr->AsAssignment()->HasNoTypeInformation()) { Add<HDeoptimize>("Insufficient type feedback for keyed store", Deoptimizer::SOFT); } } else { if (expr->AsProperty()->HasNoTypeInformation()) { Add<HDeoptimize>("Insufficient type feedback for keyed load", Deoptimizer::SOFT); } } instr = AddInstruction(BuildKeyedGeneric(access_type, obj, key, val)); } *has_side_effects = instr->HasObservableSideEffects(); return instr; } void HOptimizedGraphBuilder::EnsureArgumentsArePushedForAccess() { // Outermost function already has arguments on the stack. if (function_state()->outer() == NULL) return; if (function_state()->arguments_pushed()) return; // Push arguments when entering inlined function. HEnterInlined* entry = function_state()->entry(); entry->set_arguments_pushed(); HArgumentsObject* arguments = entry->arguments_object(); const ZoneList<HValue*>* arguments_values = arguments->arguments_values(); HInstruction* insert_after = entry; for (int i = 0; i < arguments_values->length(); i++) { HValue* argument = arguments_values->at(i); HInstruction* push_argument = New<HPushArguments>(argument); push_argument->InsertAfter(insert_after); insert_after = push_argument; } HArgumentsElements* arguments_elements = New<HArgumentsElements>(true); arguments_elements->ClearFlag(HValue::kUseGVN); arguments_elements->InsertAfter(insert_after); function_state()->set_arguments_elements(arguments_elements); } bool HOptimizedGraphBuilder::TryArgumentsAccess(Property* expr) { VariableProxy* proxy = expr->obj()->AsVariableProxy(); if (proxy == NULL) return false; if (!proxy->var()->IsStackAllocated()) return false; if (!environment()->Lookup(proxy->var())->CheckFlag(HValue::kIsArguments)) { return false; } HInstruction* result = NULL; if (expr->key()->IsPropertyName()) { Handle<String> name = expr->key()->AsLiteral()->AsPropertyName(); if (!name->IsOneByteEqualTo(STATIC_ASCII_VECTOR("length"))) return false; if (function_state()->outer() == NULL) { HInstruction* elements = Add<HArgumentsElements>(false); result = New<HArgumentsLength>(elements); } else { // Number of arguments without receiver. int argument_count = environment()-> arguments_environment()->parameter_count() - 1; result = New<HConstant>(argument_count); } } else { Push(graph()->GetArgumentsObject()); CHECK_ALIVE_OR_RETURN(VisitForValue(expr->key()), true); HValue* key = Pop(); Drop(1); // Arguments object. if (function_state()->outer() == NULL) { HInstruction* elements = Add<HArgumentsElements>(false); HInstruction* length = Add<HArgumentsLength>(elements); HInstruction* checked_key = Add<HBoundsCheck>(key, length); result = New<HAccessArgumentsAt>(elements, length, checked_key); } else { EnsureArgumentsArePushedForAccess(); // Number of arguments without receiver. HInstruction* elements = function_state()->arguments_elements(); int argument_count = environment()-> arguments_environment()->parameter_count() - 1; HInstruction* length = Add<HConstant>(argument_count); HInstruction* checked_key = Add<HBoundsCheck>(key, length); result = New<HAccessArgumentsAt>(elements, length, checked_key); } } ast_context()->ReturnInstruction(result, expr->id()); return true; } HInstruction* HOptimizedGraphBuilder::BuildNamedAccess( PropertyAccessType access, BailoutId ast_id, BailoutId return_id, Expression* expr, HValue* object, Handle<String> name, HValue* value, bool is_uninitialized) { SmallMapList* types; ComputeReceiverTypes(expr, object, &types, zone()); ASSERT(types != NULL); if (types->length() > 0) { PropertyAccessInfo info(this, access, ToType(types->first()), name); if (!info.CanAccessAsMonomorphic(types)) { HandlePolymorphicNamedFieldAccess( access, ast_id, return_id, object, value, types, name); return NULL; } HValue* checked_object; // Type::Number() is only supported by polymorphic load/call handling. ASSERT(!info.type()->Is(Type::Number())); BuildCheckHeapObject(object); if (AreStringTypes(types)) { checked_object = Add<HCheckInstanceType>(object, HCheckInstanceType::IS_STRING); } else { checked_object = Add<HCheckMaps>(object, types); } return BuildMonomorphicAccess( &info, object, checked_object, value, ast_id, return_id); } return BuildNamedGeneric(access, object, name, value, is_uninitialized); } void HOptimizedGraphBuilder::PushLoad(Property* expr, HValue* object, HValue* key) { ValueContext for_value(this, ARGUMENTS_NOT_ALLOWED); Push(object); if (key != NULL) Push(key); BuildLoad(expr, expr->LoadId()); } void HOptimizedGraphBuilder::BuildLoad(Property* expr, BailoutId ast_id) { HInstruction* instr = NULL; if (expr->IsStringAccess()) { HValue* index = Pop(); HValue* string = Pop(); HInstruction* char_code = BuildStringCharCodeAt(string, index); AddInstruction(char_code); instr = NewUncasted<HStringCharFromCode>(char_code); } else if (expr->IsFunctionPrototype()) { HValue* function = Pop(); BuildCheckHeapObject(function); instr = New<HLoadFunctionPrototype>(function); } else if (expr->key()->IsPropertyName()) { Handle<String> name = expr->key()->AsLiteral()->AsPropertyName(); HValue* object = Pop(); instr = BuildNamedAccess(LOAD, ast_id, expr->LoadId(), expr, object, name, NULL, expr->IsUninitialized()); if (instr == NULL) return; if (instr->IsLinked()) return ast_context()->ReturnValue(instr); } else { HValue* key = Pop(); HValue* obj = Pop(); bool has_side_effects = false; HValue* load = HandleKeyedElementAccess( obj, key, NULL, expr, LOAD, &has_side_effects); if (has_side_effects) { if (ast_context()->IsEffect()) { Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); } else { Push(load); Add<HSimulate>(ast_id, REMOVABLE_SIMULATE); Drop(1); } } return ast_context()->ReturnValue(load); } return ast_context()->ReturnInstruction(instr, ast_id); } void HOptimizedGraphBuilder::VisitProperty(Property* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); if (TryArgumentsAccess(expr)) return; CHECK_ALIVE(VisitForValue(expr->obj())); if ((!expr->IsFunctionPrototype() && !expr->key()->IsPropertyName()) || expr->IsStringAccess()) { CHECK_ALIVE(VisitForValue(expr->key())); } BuildLoad(expr, expr->id()); } HInstruction* HGraphBuilder::BuildConstantMapCheck(Handle<JSObject> constant) { HCheckMaps* check = Add<HCheckMaps>( Add<HConstant>(constant), handle(constant->map())); check->ClearDependsOnFlag(kElementsKind); return check; } HInstruction* HGraphBuilder::BuildCheckPrototypeMaps(Handle<JSObject> prototype, Handle<JSObject> holder) { while (holder.is_null() || !prototype.is_identical_to(holder)) { BuildConstantMapCheck(prototype); Object* next_prototype = prototype->GetPrototype(); if (next_prototype->IsNull()) return NULL; CHECK(next_prototype->IsJSObject()); prototype = handle(JSObject::cast(next_prototype)); } return BuildConstantMapCheck(prototype); } void HOptimizedGraphBuilder::AddCheckPrototypeMaps(Handle<JSObject> holder, Handle<Map> receiver_map) { if (!holder.is_null()) { Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype())); BuildCheckPrototypeMaps(prototype, holder); } } HInstruction* HOptimizedGraphBuilder::NewPlainFunctionCall( HValue* fun, int argument_count, bool pass_argument_count) { return New<HCallJSFunction>( fun, argument_count, pass_argument_count); } HInstruction* HOptimizedGraphBuilder::NewArgumentAdaptorCall( HValue* fun, HValue* context, int argument_count, HValue* expected_param_count) { CallInterfaceDescriptor* descriptor = isolate()->call_descriptor(Isolate::ArgumentAdaptorCall); HValue* arity = Add<HConstant>(argument_count - 1); HValue* op_vals[] = { fun, context, arity, expected_param_count }; Handle<Code> adaptor = isolate()->builtins()->ArgumentsAdaptorTrampoline(); HConstant* adaptor_value = Add<HConstant>(adaptor); return New<HCallWithDescriptor>( adaptor_value, argument_count, descriptor, Vector<HValue*>(op_vals, descriptor->environment_length())); } HInstruction* HOptimizedGraphBuilder::BuildCallConstantFunction( Handle<JSFunction> jsfun, int argument_count) { HValue* target = Add<HConstant>(jsfun); // For constant functions, we try to avoid calling the // argument adaptor and instead call the function directly int formal_parameter_count = jsfun->shared()->formal_parameter_count(); bool dont_adapt_arguments = (formal_parameter_count == SharedFunctionInfo::kDontAdaptArgumentsSentinel); int arity = argument_count - 1; bool can_invoke_directly = dont_adapt_arguments || formal_parameter_count == arity; if (can_invoke_directly) { if (jsfun.is_identical_to(current_info()->closure())) { graph()->MarkRecursive(); } return NewPlainFunctionCall(target, argument_count, dont_adapt_arguments); } else { HValue* param_count_value = Add<HConstant>(formal_parameter_count); HValue* context = Add<HLoadNamedField>( target, static_cast<HValue*>(NULL), HObjectAccess::ForFunctionContextPointer()); return NewArgumentAdaptorCall(target, context, argument_count, param_count_value); } UNREACHABLE(); return NULL; } class FunctionSorter { public: FunctionSorter(int index = 0, int ticks = 0, int size = 0) : index_(index), ticks_(ticks), size_(size) { } int index() const { return index_; } int ticks() const { return ticks_; } int size() const { return size_; } private: int index_; int ticks_; int size_; }; inline bool operator<(const FunctionSorter& lhs, const FunctionSorter& rhs) { int diff = lhs.ticks() - rhs.ticks(); if (diff != 0) return diff > 0; return lhs.size() < rhs.size(); } void HOptimizedGraphBuilder::HandlePolymorphicCallNamed( Call* expr, HValue* receiver, SmallMapList* types, Handle<String> name) { int argument_count = expr->arguments()->length() + 1; // Includes receiver. FunctionSorter order[kMaxCallPolymorphism]; bool handle_smi = false; bool handled_string = false; int ordered_functions = 0; for (int i = 0; i < types->length() && ordered_functions < kMaxCallPolymorphism; ++i) { PropertyAccessInfo info(this, LOAD, ToType(types->at(i)), name); if (info.CanAccessMonomorphic() && info.lookup()->IsConstant() && info.constant()->IsJSFunction()) { if (info.type()->Is(Type::String())) { if (handled_string) continue; handled_string = true; } Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant()); if (info.type()->Is(Type::Number())) { handle_smi = true; } expr->set_target(target); order[ordered_functions++] = FunctionSorter( i, target->shared()->profiler_ticks(), InliningAstSize(target)); } } std::sort(order, order + ordered_functions); HBasicBlock* number_block = NULL; HBasicBlock* join = NULL; handled_string = false; int count = 0; for (int fn = 0; fn < ordered_functions; ++fn) { int i = order[fn].index(); PropertyAccessInfo info(this, LOAD, ToType(types->at(i)), name); if (info.type()->Is(Type::String())) { if (handled_string) continue; handled_string = true; } // Reloads the target. info.CanAccessMonomorphic(); Handle<JSFunction> target = Handle<JSFunction>::cast(info.constant()); expr->set_target(target); if (count == 0) { // Only needed once. join = graph()->CreateBasicBlock(); if (handle_smi) { HBasicBlock* empty_smi_block = graph()->CreateBasicBlock(); HBasicBlock* not_smi_block = graph()->CreateBasicBlock(); number_block = graph()->CreateBasicBlock(); FinishCurrentBlock(New<HIsSmiAndBranch>( receiver, empty_smi_block, not_smi_block)); GotoNoSimulate(empty_smi_block, number_block); set_current_block(not_smi_block); } else { BuildCheckHeapObject(receiver); } } ++count; HBasicBlock* if_true = graph()->CreateBasicBlock(); HBasicBlock* if_false = graph()->CreateBasicBlock(); HUnaryControlInstruction* compare; Handle<Map> map = info.map(); if (info.type()->Is(Type::Number())) { Handle<Map> heap_number_map = isolate()->factory()->heap_number_map(); compare = New<HCompareMap>(receiver, heap_number_map, if_true, if_false); } else if (info.type()->Is(Type::String())) { compare = New<HIsStringAndBranch>(receiver, if_true, if_false); } else { compare = New<HCompareMap>(receiver, map, if_true, if_false); } FinishCurrentBlock(compare); if (info.type()->Is(Type::Number())) { GotoNoSimulate(if_true, number_block); if_true = number_block; } set_current_block(if_true); AddCheckPrototypeMaps(info.holder(), map); HValue* function = Add<HConstant>(expr->target()); environment()->SetExpressionStackAt(0, function); Push(receiver); CHECK_ALIVE(VisitExpressions(expr->arguments())); bool needs_wrapping = NeedsWrappingFor(info.type(), target); bool try_inline = FLAG_polymorphic_inlining && !needs_wrapping; if (FLAG_trace_inlining && try_inline) { Handle<JSFunction> caller = current_info()->closure(); SmartArrayPointer<char> caller_name = caller->shared()->DebugName()->ToCString(); PrintF("Trying to inline the polymorphic call to %s from %s\n", name->ToCString().get(), caller_name.get()); } if (try_inline && TryInlineCall(expr)) { // Trying to inline will signal that we should bailout from the // entire compilation by setting stack overflow on the visitor. if (HasStackOverflow()) return; } else { // Since HWrapReceiver currently cannot actually wrap numbers and strings, // use the regular CallFunctionStub for method calls to wrap the receiver. // TODO(verwaest): Support creation of value wrappers directly in // HWrapReceiver. HInstruction* call = needs_wrapping ? NewUncasted<HCallFunction>( function, argument_count, WRAP_AND_CALL) : BuildCallConstantFunction(target, argument_count); PushArgumentsFromEnvironment(argument_count); AddInstruction(call); Drop(1); // Drop the function. if (!ast_context()->IsEffect()) Push(call); } if (current_block() != NULL) Goto(join); set_current_block(if_false); } // Finish up. Unconditionally deoptimize if we've handled all the maps we // know about and do not want to handle ones we've never seen. Otherwise // use a generic IC. if (ordered_functions == types->length() && FLAG_deoptimize_uncommon_cases) { FinishExitWithHardDeoptimization("Unknown map in polymorphic call"); } else { Property* prop = expr->expression()->AsProperty(); HInstruction* function = BuildNamedGeneric( LOAD, receiver, name, NULL, prop->IsUninitialized()); AddInstruction(function); Push(function); AddSimulate(prop->LoadId(), REMOVABLE_SIMULATE); environment()->SetExpressionStackAt(1, function); environment()->SetExpressionStackAt(0, receiver); CHECK_ALIVE(VisitExpressions(expr->arguments())); CallFunctionFlags flags = receiver->type().IsJSObject() ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD; HInstruction* call = New<HCallFunction>( function, argument_count, flags); PushArgumentsFromEnvironment(argument_count); Drop(1); // Function. if (join != NULL) { AddInstruction(call); if (!ast_context()->IsEffect()) Push(call); Goto(join); } else { return ast_context()->ReturnInstruction(call, expr->id()); } } // We assume that control flow is always live after an expression. So // even without predecessors to the join block, we set it as the exit // block and continue by adding instructions there. ASSERT(join != NULL); if (join->HasPredecessor()) { set_current_block(join); join->SetJoinId(expr->id()); if (!ast_context()->IsEffect()) return ast_context()->ReturnValue(Pop()); } else { set_current_block(NULL); } } void HOptimizedGraphBuilder::TraceInline(Handle<JSFunction> target, Handle<JSFunction> caller, const char* reason) { if (FLAG_trace_inlining) { SmartArrayPointer<char> target_name = target->shared()->DebugName()->ToCString(); SmartArrayPointer<char> caller_name = caller->shared()->DebugName()->ToCString(); if (reason == NULL) { PrintF("Inlined %s called from %s.\n", target_name.get(), caller_name.get()); } else { PrintF("Did not inline %s called from %s (%s).\n", target_name.get(), caller_name.get(), reason); } } } static const int kNotInlinable = 1000000000; int HOptimizedGraphBuilder::InliningAstSize(Handle<JSFunction> target) { if (!FLAG_use_inlining) return kNotInlinable; // Precondition: call is monomorphic and we have found a target with the // appropriate arity. Handle<JSFunction> caller = current_info()->closure(); Handle<SharedFunctionInfo> target_shared(target->shared()); // Always inline builtins marked for inlining. if (target->IsBuiltin()) { return target_shared->inline_builtin() ? 0 : kNotInlinable; } if (target_shared->IsApiFunction()) { TraceInline(target, caller, "target is api function"); return kNotInlinable; } // Do a quick check on source code length to avoid parsing large // inlining candidates. if (target_shared->SourceSize() > Min(FLAG_max_inlined_source_size, kUnlimitedMaxInlinedSourceSize)) { TraceInline(target, caller, "target text too big"); return kNotInlinable; } // Target must be inlineable. if (!target_shared->IsInlineable()) { TraceInline(target, caller, "target not inlineable"); return kNotInlinable; } if (target_shared->dont_inline() || target_shared->dont_optimize()) { TraceInline(target, caller, "target contains unsupported syntax [early]"); return kNotInlinable; } int nodes_added = target_shared->ast_node_count(); return nodes_added; } bool HOptimizedGraphBuilder::TryInline(Handle<JSFunction> target, int arguments_count, HValue* implicit_return_value, BailoutId ast_id, BailoutId return_id, InliningKind inlining_kind, HSourcePosition position) { int nodes_added = InliningAstSize(target); if (nodes_added == kNotInlinable) return false; Handle<JSFunction> caller = current_info()->closure(); if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) { TraceInline(target, caller, "target AST is too large [early]"); return false; } // Don't inline deeper than the maximum number of inlining levels. HEnvironment* env = environment(); int current_level = 1; while (env->outer() != NULL) { if (current_level == FLAG_max_inlining_levels) { TraceInline(target, caller, "inline depth limit reached"); return false; } if (env->outer()->frame_type() == JS_FUNCTION) { current_level++; } env = env->outer(); } // Don't inline recursive functions. for (FunctionState* state = function_state(); state != NULL; state = state->outer()) { if (*state->compilation_info()->closure() == *target) { TraceInline(target, caller, "target is recursive"); return false; } } // We don't want to add more than a certain number of nodes from inlining. if (inlined_count_ > Min(FLAG_max_inlined_nodes_cumulative, kUnlimitedMaxInlinedNodesCumulative)) { TraceInline(target, caller, "cumulative AST node limit reached"); return false; } // Parse and allocate variables. CompilationInfo target_info(target, zone()); // Use the same AstValueFactory for creating strings in the sub-compilation // step, but don't transfer ownership to target_info. target_info.SetAstValueFactory(top_info()->ast_value_factory(), false); Handle<SharedFunctionInfo> target_shared(target->shared()); if (!Parser::Parse(&target_info) || !Scope::Analyze(&target_info)) { if (target_info.isolate()->has_pending_exception()) { // Parse or scope error, never optimize this function. SetStackOverflow(); target_shared->DisableOptimization(kParseScopeError); } TraceInline(target, caller, "parse failure"); return false; } if (target_info.scope()->num_heap_slots() > 0) { TraceInline(target, caller, "target has context-allocated variables"); return false; } FunctionLiteral* function = target_info.function(); // The following conditions must be checked again after re-parsing, because // earlier the information might not have been complete due to lazy parsing. nodes_added = function->ast_node_count(); if (nodes_added > Min(FLAG_max_inlined_nodes, kUnlimitedMaxInlinedNodes)) { TraceInline(target, caller, "target AST is too large [late]"); return false; } AstProperties::Flags* flags(function->flags()); if (flags->Contains(kDontInline) || function->dont_optimize()) { TraceInline(target, caller, "target contains unsupported syntax [late]"); return false; } // If the function uses the arguments object check that inlining of functions // with arguments object is enabled and the arguments-variable is // stack allocated. if (function->scope()->arguments() != NULL) { if (!FLAG_inline_arguments) { TraceInline(target, caller, "target uses arguments object"); return false; } if (!function->scope()->arguments()->IsStackAllocated()) { TraceInline(target, caller, "target uses non-stackallocated arguments object"); return false; } } // All declarations must be inlineable. ZoneList<Declaration*>* decls = target_info.scope()->declarations(); int decl_count = decls->length(); for (int i = 0; i < decl_count; ++i) { if (!decls->at(i)->IsInlineable()) { TraceInline(target, caller, "target has non-trivial declaration"); return false; } } // Generate the deoptimization data for the unoptimized version of // the target function if we don't already have it. if (!target_shared->has_deoptimization_support()) { // Note that we compile here using the same AST that we will use for // generating the optimized inline code. target_info.EnableDeoptimizationSupport(); if (!FullCodeGenerator::MakeCode(&target_info)) { TraceInline(target, caller, "could not generate deoptimization info"); return false; } if (target_shared->scope_info() == ScopeInfo::Empty(isolate())) { // The scope info might not have been set if a lazily compiled // function is inlined before being called for the first time. Handle<ScopeInfo> target_scope_info = ScopeInfo::Create(target_info.scope(), zone()); target_shared->set_scope_info(*target_scope_info); } target_shared->EnableDeoptimizationSupport(*target_info.code()); target_shared->set_feedback_vector(*target_info.feedback_vector()); Compiler::RecordFunctionCompilation(Logger::FUNCTION_TAG, &target_info, target_shared); } // ---------------------------------------------------------------- // After this point, we've made a decision to inline this function (so // TryInline should always return true). // Type-check the inlined function. ASSERT(target_shared->has_deoptimization_support()); AstTyper::Run(&target_info); int function_id = graph()->TraceInlinedFunction(target_shared, position); // Save the pending call context. Set up new one for the inlined function. // The function state is new-allocated because we need to delete it // in two different places. FunctionState* target_state = new FunctionState( this, &target_info, inlining_kind, function_id); HConstant* undefined = graph()->GetConstantUndefined(); HEnvironment* inner_env = environment()->CopyForInlining(target, arguments_count, function, undefined, function_state()->inlining_kind()); HConstant* context = Add<HConstant>(Handle<Context>(target->context())); inner_env->BindContext(context); HArgumentsObject* arguments_object = NULL; // If the function uses arguments object create and bind one, also copy // current arguments values to use them for materialization. if (function->scope()->arguments() != NULL) { ASSERT(function->scope()->arguments()->IsStackAllocated()); HEnvironment* arguments_env = inner_env->arguments_environment(); int arguments_count = arguments_env->parameter_count(); arguments_object = Add<HArgumentsObject>(arguments_count); inner_env->Bind(function->scope()->arguments(), arguments_object); for (int i = 0; i < arguments_count; i++) { arguments_object->AddArgument(arguments_env->Lookup(i), zone()); } } // Capture the state before invoking the inlined function for deopt in the // inlined function. This simulate has no bailout-id since it's not directly // reachable for deopt, and is only used to capture the state. If the simulate // becomes reachable by merging, the ast id of the simulate merged into it is // adopted. Add<HSimulate>(BailoutId::None()); current_block()->UpdateEnvironment(inner_env); Scope* saved_scope = scope(); set_scope(target_info.scope()); HEnterInlined* enter_inlined = Add<HEnterInlined>(return_id, target, arguments_count, function, function_state()->inlining_kind(), function->scope()->arguments(), arguments_object); function_state()->set_entry(enter_inlined); VisitDeclarations(target_info.scope()->declarations()); VisitStatements(function->body()); set_scope(saved_scope); if (HasStackOverflow()) { // Bail out if the inline function did, as we cannot residualize a call // instead. TraceInline(target, caller, "inline graph construction failed"); target_shared->DisableOptimization(kInliningBailedOut); inline_bailout_ = true; delete target_state; return true; } // Update inlined nodes count. inlined_count_ += nodes_added; Handle<Code> unoptimized_code(target_shared->code()); ASSERT(unoptimized_code->kind() == Code::FUNCTION); Handle<TypeFeedbackInfo> type_info( TypeFeedbackInfo::cast(unoptimized_code->type_feedback_info())); graph()->update_type_change_checksum(type_info->own_type_change_checksum()); TraceInline(target, caller, NULL); if (current_block() != NULL) { FunctionState* state = function_state(); if (state->inlining_kind() == CONSTRUCT_CALL_RETURN) { // Falling off the end of an inlined construct call. In a test context the // return value will always evaluate to true, in a value context the // return value is the newly allocated receiver. if (call_context()->IsTest()) { Goto(inlined_test_context()->if_true(), state); } else if (call_context()->IsEffect()) { Goto(function_return(), state); } else { ASSERT(call_context()->IsValue()); AddLeaveInlined(implicit_return_value, state); } } else if (state->inlining_kind() == SETTER_CALL_RETURN) { // Falling off the end of an inlined setter call. The returned value is // never used, the value of an assignment is always the value of the RHS // of the assignment. if (call_context()->IsTest()) { inlined_test_context()->ReturnValue(implicit_return_value); } else if (call_context()->IsEffect()) { Goto(function_return(), state); } else { ASSERT(call_context()->IsValue()); AddLeaveInlined(implicit_return_value, state); } } else { // Falling off the end of a normal inlined function. This basically means // returning undefined. if (call_context()->IsTest()) { Goto(inlined_test_context()->if_false(), state); } else if (call_context()->IsEffect()) { Goto(function_return(), state); } else { ASSERT(call_context()->IsValue()); AddLeaveInlined(undefined, state); } } } // Fix up the function exits. if (inlined_test_context() != NULL) { HBasicBlock* if_true = inlined_test_context()->if_true(); HBasicBlock* if_false = inlined_test_context()->if_false(); HEnterInlined* entry = function_state()->entry(); // Pop the return test context from the expression context stack. ASSERT(ast_context() == inlined_test_context()); ClearInlinedTestContext(); delete target_state; // Forward to the real test context. if (if_true->HasPredecessor()) { entry->RegisterReturnTarget(if_true, zone()); if_true->SetJoinId(ast_id); HBasicBlock* true_target = TestContext::cast(ast_context())->if_true(); Goto(if_true, true_target, function_state()); } if (if_false->HasPredecessor()) { entry->RegisterReturnTarget(if_false, zone()); if_false->SetJoinId(ast_id); HBasicBlock* false_target = TestContext::cast(ast_context())->if_false(); Goto(if_false, false_target, function_state()); } set_current_block(NULL); return true; } else if (function_return()->HasPredecessor()) { function_state()->entry()->RegisterReturnTarget(function_return(), zone()); function_return()->SetJoinId(ast_id); set_current_block(function_return()); } else { set_current_block(NULL); } delete target_state; return true; } bool HOptimizedGraphBuilder::TryInlineCall(Call* expr) { return TryInline(expr->target(), expr->arguments()->length(), NULL, expr->id(), expr->ReturnId(), NORMAL_RETURN, ScriptPositionToSourcePosition(expr->position())); } bool HOptimizedGraphBuilder::TryInlineConstruct(CallNew* expr, HValue* implicit_return_value) { return TryInline(expr->target(), expr->arguments()->length(), implicit_return_value, expr->id(), expr->ReturnId(), CONSTRUCT_CALL_RETURN, ScriptPositionToSourcePosition(expr->position())); } bool HOptimizedGraphBuilder::TryInlineGetter(Handle<JSFunction> getter, Handle<Map> receiver_map, BailoutId ast_id, BailoutId return_id) { if (TryInlineApiGetter(getter, receiver_map, ast_id)) return true; return TryInline(getter, 0, NULL, ast_id, return_id, GETTER_CALL_RETURN, source_position()); } bool HOptimizedGraphBuilder::TryInlineSetter(Handle<JSFunction> setter, Handle<Map> receiver_map, BailoutId id, BailoutId assignment_id, HValue* implicit_return_value) { if (TryInlineApiSetter(setter, receiver_map, id)) return true; return TryInline(setter, 1, implicit_return_value, id, assignment_id, SETTER_CALL_RETURN, source_position()); } bool HOptimizedGraphBuilder::TryInlineApply(Handle<JSFunction> function, Call* expr, int arguments_count) { return TryInline(function, arguments_count, NULL, expr->id(), expr->ReturnId(), NORMAL_RETURN, ScriptPositionToSourcePosition(expr->position())); } bool HOptimizedGraphBuilder::TryInlineBuiltinFunctionCall(Call* expr) { if (!expr->target()->shared()->HasBuiltinFunctionId()) return false; BuiltinFunctionId id = expr->target()->shared()->builtin_function_id(); switch (id) { case kMathExp: if (!FLAG_fast_math) break; // Fall through if FLAG_fast_math. case kMathRound: case kMathFloor: case kMathAbs: case kMathSqrt: case kMathLog: case kMathClz32: if (expr->arguments()->length() == 1) { HValue* argument = Pop(); Drop(2); // Receiver and function. HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id); ast_context()->ReturnInstruction(op, expr->id()); return true; } break; case kMathImul: if (expr->arguments()->length() == 2) { HValue* right = Pop(); HValue* left = Pop(); Drop(2); // Receiver and function. HInstruction* op = HMul::NewImul(zone(), context(), left, right); ast_context()->ReturnInstruction(op, expr->id()); return true; } break; default: // Not supported for inlining yet. break; } return false; } bool HOptimizedGraphBuilder::TryInlineBuiltinMethodCall( Call* expr, HValue* receiver, Handle<Map> receiver_map) { // Try to inline calls like Math.* as operations in the calling function. if (!expr->target()->shared()->HasBuiltinFunctionId()) return false; BuiltinFunctionId id = expr->target()->shared()->builtin_function_id(); int argument_count = expr->arguments()->length() + 1; // Plus receiver. switch (id) { case kStringCharCodeAt: case kStringCharAt: if (argument_count == 2) { HValue* index = Pop(); HValue* string = Pop(); Drop(1); // Function. HInstruction* char_code = BuildStringCharCodeAt(string, index); if (id == kStringCharCodeAt) { ast_context()->ReturnInstruction(char_code, expr->id()); return true; } AddInstruction(char_code); HInstruction* result = NewUncasted<HStringCharFromCode>(char_code); ast_context()->ReturnInstruction(result, expr->id()); return true; } break; case kStringFromCharCode: if (argument_count == 2) { HValue* argument = Pop(); Drop(2); // Receiver and function. HInstruction* result = NewUncasted<HStringCharFromCode>(argument); ast_context()->ReturnInstruction(result, expr->id()); return true; } break; case kMathExp: if (!FLAG_fast_math) break; // Fall through if FLAG_fast_math. case kMathRound: case kMathFloor: case kMathAbs: case kMathSqrt: case kMathLog: case kMathClz32: if (argument_count == 2) { HValue* argument = Pop(); Drop(2); // Receiver and function. HInstruction* op = NewUncasted<HUnaryMathOperation>(argument, id); ast_context()->ReturnInstruction(op, expr->id()); return true; } break; case kMathPow: if (argument_count == 3) { HValue* right = Pop(); HValue* left = Pop(); Drop(2); // Receiver and function. HInstruction* result = NULL; // Use sqrt() if exponent is 0.5 or -0.5. if (right->IsConstant() && HConstant::cast(right)->HasDoubleValue()) { double exponent = HConstant::cast(right)->DoubleValue(); if (exponent == 0.5) { result = NewUncasted<HUnaryMathOperation>(left, kMathPowHalf); } else if (exponent == -0.5) { HValue* one = graph()->GetConstant1(); HInstruction* sqrt = AddUncasted<HUnaryMathOperation>( left, kMathPowHalf); // MathPowHalf doesn't have side effects so there's no need for // an environment simulation here. ASSERT(!sqrt->HasObservableSideEffects()); result = NewUncasted<HDiv>(one, sqrt); } else if (exponent == 2.0) { result = NewUncasted<HMul>(left, left); } } if (result == NULL) { result = NewUncasted<HPower>(left, right); } ast_context()->ReturnInstruction(result, expr->id()); return true; } break; case kMathMax: case kMathMin: if (argument_count == 3) { HValue* right = Pop(); HValue* left = Pop(); Drop(2); // Receiver and function. HMathMinMax::Operation op = (id == kMathMin) ? HMathMinMax::kMathMin : HMathMinMax::kMathMax; HInstruction* result = NewUncasted<HMathMinMax>(left, right, op); ast_context()->ReturnInstruction(result, expr->id()); return true; } break; case kMathImul: if (argument_count == 3) { HValue* right = Pop(); HValue* left = Pop(); Drop(2); // Receiver and function. HInstruction* result = HMul::NewImul(zone(), context(), left, right); ast_context()->ReturnInstruction(result, expr->id()); return true; } break; case kArrayPop: { if (receiver_map.is_null()) return false; if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false; ElementsKind elements_kind = receiver_map->elements_kind(); if (!IsFastElementsKind(elements_kind)) return false; if (receiver_map->is_observed()) return false; ASSERT(receiver_map->is_extensible()); Drop(expr->arguments()->length()); HValue* result; HValue* reduced_length; HValue* receiver = Pop(); HValue* checked_object = AddCheckMap(receiver, receiver_map); HValue* length = Add<HLoadNamedField>( checked_object, static_cast<HValue*>(NULL), HObjectAccess::ForArrayLength(elements_kind)); Drop(1); // Function. { NoObservableSideEffectsScope scope(this); IfBuilder length_checker(this); HValue* bounds_check = length_checker.If<HCompareNumericAndBranch>( length, graph()->GetConstant0(), Token::EQ); length_checker.Then(); if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined()); length_checker.Else(); HValue* elements = AddLoadElements(checked_object); // Ensure that we aren't popping from a copy-on-write array. if (IsFastSmiOrObjectElementsKind(elements_kind)) { elements = BuildCopyElementsOnWrite(checked_object, elements, elements_kind, length); } reduced_length = AddUncasted<HSub>(length, graph()->GetConstant1()); result = AddElementAccess(elements, reduced_length, NULL, bounds_check, elements_kind, LOAD); Factory* factory = isolate()->factory(); double nan_double = FixedDoubleArray::hole_nan_as_double(); HValue* hole = IsFastSmiOrObjectElementsKind(elements_kind) ? Add<HConstant>(factory->the_hole_value()) : Add<HConstant>(nan_double); if (IsFastSmiOrObjectElementsKind(elements_kind)) { elements_kind = FAST_HOLEY_ELEMENTS; } AddElementAccess( elements, reduced_length, hole, bounds_check, elements_kind, STORE); Add<HStoreNamedField>( checked_object, HObjectAccess::ForArrayLength(elements_kind), reduced_length, STORE_TO_INITIALIZED_ENTRY); if (!ast_context()->IsEffect()) Push(result); length_checker.End(); } result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top(); Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE); if (!ast_context()->IsEffect()) Drop(1); ast_context()->ReturnValue(result); return true; } case kArrayPush: { if (receiver_map.is_null()) return false; if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false; ElementsKind elements_kind = receiver_map->elements_kind(); if (!IsFastElementsKind(elements_kind)) return false; if (receiver_map->is_observed()) return false; if (JSArray::IsReadOnlyLengthDescriptor(receiver_map)) return false; ASSERT(receiver_map->is_extensible()); // If there may be elements accessors in the prototype chain, the fast // inlined version can't be used. if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false; // If there currently can be no elements accessors on the prototype chain, // it doesn't mean that there won't be any later. Install a full prototype // chain check to trap element accessors being installed on the prototype // chain, which would cause elements to go to dictionary mode and result // in a map change. Handle<JSObject> prototype(JSObject::cast(receiver_map->prototype())); BuildCheckPrototypeMaps(prototype, Handle<JSObject>()); const int argc = expr->arguments()->length(); if (argc != 1) return false; HValue* value_to_push = Pop(); HValue* array = Pop(); Drop(1); // Drop function. HInstruction* new_size = NULL; HValue* length = NULL; { NoObservableSideEffectsScope scope(this); length = Add<HLoadNamedField>(array, static_cast<HValue*>(NULL), HObjectAccess::ForArrayLength(elements_kind)); new_size = AddUncasted<HAdd>(length, graph()->GetConstant1()); bool is_array = receiver_map->instance_type() == JS_ARRAY_TYPE; BuildUncheckedMonomorphicElementAccess(array, length, value_to_push, is_array, elements_kind, STORE, NEVER_RETURN_HOLE, STORE_AND_GROW_NO_TRANSITION); if (!ast_context()->IsEffect()) Push(new_size); Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE); if (!ast_context()->IsEffect()) Drop(1); } ast_context()->ReturnValue(new_size); return true; } case kArrayShift: { if (receiver_map.is_null()) return false; if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false; ElementsKind kind = receiver_map->elements_kind(); if (!IsFastElementsKind(kind)) return false; if (receiver_map->is_observed()) return false; ASSERT(receiver_map->is_extensible()); // If there may be elements accessors in the prototype chain, the fast // inlined version can't be used. if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false; // If there currently can be no elements accessors on the prototype chain, // it doesn't mean that there won't be any later. Install a full prototype // chain check to trap element accessors being installed on the prototype // chain, which would cause elements to go to dictionary mode and result // in a map change. BuildCheckPrototypeMaps( handle(JSObject::cast(receiver_map->prototype()), isolate()), Handle<JSObject>::null()); // Threshold for fast inlined Array.shift(). HConstant* inline_threshold = Add<HConstant>(static_cast<int32_t>(16)); Drop(expr->arguments()->length()); HValue* receiver = Pop(); HValue* function = Pop(); HValue* result; { NoObservableSideEffectsScope scope(this); HValue* length = Add<HLoadNamedField>( receiver, static_cast<HValue*>(NULL), HObjectAccess::ForArrayLength(kind)); IfBuilder if_lengthiszero(this); HValue* lengthiszero = if_lengthiszero.If<HCompareNumericAndBranch>( length, graph()->GetConstant0(), Token::EQ); if_lengthiszero.Then(); { if (!ast_context()->IsEffect()) Push(graph()->GetConstantUndefined()); } if_lengthiszero.Else(); { HValue* elements = AddLoadElements(receiver); // Check if we can use the fast inlined Array.shift(). IfBuilder if_inline(this); if_inline.If<HCompareNumericAndBranch>( length, inline_threshold, Token::LTE); if (IsFastSmiOrObjectElementsKind(kind)) { // We cannot handle copy-on-write backing stores here. if_inline.AndIf<HCompareMap>( elements, isolate()->factory()->fixed_array_map()); } if_inline.Then(); { // Remember the result. if (!ast_context()->IsEffect()) { Push(AddElementAccess(elements, graph()->GetConstant0(), NULL, lengthiszero, kind, LOAD)); } // Compute the new length. HValue* new_length = AddUncasted<HSub>( length, graph()->GetConstant1()); new_length->ClearFlag(HValue::kCanOverflow); // Copy the remaining elements. LoopBuilder loop(this, context(), LoopBuilder::kPostIncrement); { HValue* new_key = loop.BeginBody( graph()->GetConstant0(), new_length, Token::LT); HValue* key = AddUncasted<HAdd>(new_key, graph()->GetConstant1()); key->ClearFlag(HValue::kCanOverflow); HValue* element = AddUncasted<HLoadKeyed>( elements, key, lengthiszero, kind, ALLOW_RETURN_HOLE); HStoreKeyed* store = Add<HStoreKeyed>( elements, new_key, element, kind); store->SetFlag(HValue::kAllowUndefinedAsNaN); } loop.EndBody(); // Put a hole at the end. HValue* hole = IsFastSmiOrObjectElementsKind(kind) ? Add<HConstant>(isolate()->factory()->the_hole_value()) : Add<HConstant>(FixedDoubleArray::hole_nan_as_double()); if (IsFastSmiOrObjectElementsKind(kind)) kind = FAST_HOLEY_ELEMENTS; Add<HStoreKeyed>( elements, new_length, hole, kind, INITIALIZING_STORE); // Remember new length. Add<HStoreNamedField>( receiver, HObjectAccess::ForArrayLength(kind), new_length, STORE_TO_INITIALIZED_ENTRY); } if_inline.Else(); { Add<HPushArguments>(receiver); result = Add<HCallJSFunction>(function, 1, true); if (!ast_context()->IsEffect()) Push(result); } if_inline.End(); } if_lengthiszero.End(); } result = ast_context()->IsEffect() ? graph()->GetConstant0() : Top(); Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE); if (!ast_context()->IsEffect()) Drop(1); ast_context()->ReturnValue(result); return true; } case kArrayIndexOf: case kArrayLastIndexOf: { if (receiver_map.is_null()) return false; if (receiver_map->instance_type() != JS_ARRAY_TYPE) return false; ElementsKind kind = receiver_map->elements_kind(); if (!IsFastElementsKind(kind)) return false; if (receiver_map->is_observed()) return false; if (argument_count != 2) return false; ASSERT(receiver_map->is_extensible()); // If there may be elements accessors in the prototype chain, the fast // inlined version can't be used. if (receiver_map->DictionaryElementsInPrototypeChainOnly()) return false; // If there currently can be no elements accessors on the prototype chain, // it doesn't mean that there won't be any later. Install a full prototype // chain check to trap element accessors being installed on the prototype // chain, which would cause elements to go to dictionary mode and result // in a map change. BuildCheckPrototypeMaps( handle(JSObject::cast(receiver_map->prototype()), isolate()), Handle<JSObject>::null()); HValue* search_element = Pop(); HValue* receiver = Pop(); Drop(1); // Drop function. ArrayIndexOfMode mode = (id == kArrayIndexOf) ? kFirstIndexOf : kLastIndexOf; HValue* index = BuildArrayIndexOf(receiver, search_element, kind, mode); if (!ast_context()->IsEffect()) Push(index); Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE); if (!ast_context()->IsEffect()) Drop(1); ast_context()->ReturnValue(index); return true; } default: // Not yet supported for inlining. break; } return false; } bool HOptimizedGraphBuilder::TryInlineApiFunctionCall(Call* expr, HValue* receiver) { Handle<JSFunction> function = expr->target(); int argc = expr->arguments()->length(); SmallMapList receiver_maps; return TryInlineApiCall(function, receiver, &receiver_maps, argc, expr->id(), kCallApiFunction); } bool HOptimizedGraphBuilder::TryInlineApiMethodCall( Call* expr, HValue* receiver, SmallMapList* receiver_maps) { Handle<JSFunction> function = expr->target(); int argc = expr->arguments()->length(); return TryInlineApiCall(function, receiver, receiver_maps, argc, expr->id(), kCallApiMethod); } bool HOptimizedGraphBuilder::TryInlineApiGetter(Handle<JSFunction> function, Handle<Map> receiver_map, BailoutId ast_id) { SmallMapList receiver_maps(1, zone()); receiver_maps.Add(receiver_map, zone()); return TryInlineApiCall(function, NULL, // Receiver is on expression stack. &receiver_maps, 0, ast_id, kCallApiGetter); } bool HOptimizedGraphBuilder::TryInlineApiSetter(Handle<JSFunction> function, Handle<Map> receiver_map, BailoutId ast_id) { SmallMapList receiver_maps(1, zone()); receiver_maps.Add(receiver_map, zone()); return TryInlineApiCall(function, NULL, // Receiver is on expression stack. &receiver_maps, 1, ast_id, kCallApiSetter); } bool HOptimizedGraphBuilder::TryInlineApiCall(Handle<JSFunction> function, HValue* receiver, SmallMapList* receiver_maps, int argc, BailoutId ast_id, ApiCallType call_type) { CallOptimization optimization(function); if (!optimization.is_simple_api_call()) return false; Handle<Map> holder_map; if (call_type == kCallApiFunction) { // Cannot embed a direct reference to the global proxy map // as it maybe dropped on deserialization. CHECK(!isolate()->serializer_enabled()); ASSERT_EQ(0, receiver_maps->length()); receiver_maps->Add(handle( function->context()->global_object()->global_receiver()->map()), zone()); } CallOptimization::HolderLookup holder_lookup = CallOptimization::kHolderNotFound; Handle<JSObject> api_holder = optimization.LookupHolderOfExpectedType( receiver_maps->first(), &holder_lookup); if (holder_lookup == CallOptimization::kHolderNotFound) return false; if (FLAG_trace_inlining) { PrintF("Inlining api function "); function->ShortPrint(); PrintF("\n"); } bool drop_extra = false; bool is_store = false; switch (call_type) { case kCallApiFunction: case kCallApiMethod: // Need to check that none of the receiver maps could have changed. Add<HCheckMaps>(receiver, receiver_maps); // Need to ensure the chain between receiver and api_holder is intact. if (holder_lookup == CallOptimization::kHolderFound) { AddCheckPrototypeMaps(api_holder, receiver_maps->first()); } else { ASSERT_EQ(holder_lookup, CallOptimization::kHolderIsReceiver); } // Includes receiver. PushArgumentsFromEnvironment(argc + 1); // Drop function after call. drop_extra = true; break; case kCallApiGetter: // Receiver and prototype chain cannot have changed. ASSERT_EQ(0, argc); ASSERT_EQ(NULL, receiver); // Receiver is on expression stack. receiver = Pop(); Add<HPushArguments>(receiver); break; case kCallApiSetter: { is_store = true; // Receiver and prototype chain cannot have changed. ASSERT_EQ(1, argc); ASSERT_EQ(NULL, receiver); // Receiver and value are on expression stack. HValue* value = Pop(); receiver = Pop(); Add<HPushArguments>(receiver, value); break; } } HValue* holder = NULL; switch (holder_lookup) { case CallOptimization::kHolderFound: holder = Add<HConstant>(api_holder); break; case CallOptimization::kHolderIsReceiver: holder = receiver; break; case CallOptimization::kHolderNotFound: UNREACHABLE(); break; } Handle<CallHandlerInfo> api_call_info = optimization.api_call_info(); Handle<Object> call_data_obj(api_call_info->data(), isolate()); bool call_data_is_undefined = call_data_obj->IsUndefined(); HValue* call_data = Add<HConstant>(call_data_obj); ApiFunction fun(v8::ToCData<Address>(api_call_info->callback())); ExternalReference ref = ExternalReference(&fun, ExternalReference::DIRECT_API_CALL, isolate()); HValue* api_function_address = Add<HConstant>(ExternalReference(ref)); HValue* op_vals[] = { Add<HConstant>(function), call_data, holder, api_function_address, context() }; CallInterfaceDescriptor* descriptor = isolate()->call_descriptor(Isolate::ApiFunctionCall); CallApiFunctionStub stub(isolate(), is_store, call_data_is_undefined, argc); Handle<Code> code = stub.GetCode(); HConstant* code_value = Add<HConstant>(code); ASSERT((sizeof(op_vals) / kPointerSize) == descriptor->environment_length()); HInstruction* call = New<HCallWithDescriptor>( code_value, argc + 1, descriptor, Vector<HValue*>(op_vals, descriptor->environment_length())); if (drop_extra) Drop(1); // Drop function. ast_context()->ReturnInstruction(call, ast_id); return true; } bool HOptimizedGraphBuilder::TryCallApply(Call* expr) { ASSERT(expr->expression()->IsProperty()); if (!expr->IsMonomorphic()) { return false; } Handle<Map> function_map = expr->GetReceiverTypes()->first(); if (function_map->instance_type() != JS_FUNCTION_TYPE || !expr->target()->shared()->HasBuiltinFunctionId() || expr->target()->shared()->builtin_function_id() != kFunctionApply) { return false; } if (current_info()->scope()->arguments() == NULL) return false; ZoneList<Expression*>* args = expr->arguments(); if (args->length() != 2) return false; VariableProxy* arg_two = args->at(1)->AsVariableProxy(); if (arg_two == NULL || !arg_two->var()->IsStackAllocated()) return false; HValue* arg_two_value = LookupAndMakeLive(arg_two->var()); if (!arg_two_value->CheckFlag(HValue::kIsArguments)) return false; // Found pattern f.apply(receiver, arguments). CHECK_ALIVE_OR_RETURN(VisitForValue(args->at(0)), true); HValue* receiver = Pop(); // receiver HValue* function = Pop(); // f Drop(1); // apply HValue* checked_function = AddCheckMap(function, function_map); if (function_state()->outer() == NULL) { HInstruction* elements = Add<HArgumentsElements>(false); HInstruction* length = Add<HArgumentsLength>(elements); HValue* wrapped_receiver = BuildWrapReceiver(receiver, checked_function); HInstruction* result = New<HApplyArguments>(function, wrapped_receiver, length, elements); ast_context()->ReturnInstruction(result, expr->id()); return true; } else { // We are inside inlined function and we know exactly what is inside // arguments object. But we need to be able to materialize at deopt. ASSERT_EQ(environment()->arguments_environment()->parameter_count(), function_state()->entry()->arguments_object()->arguments_count()); HArgumentsObject* args = function_state()->entry()->arguments_object(); const ZoneList<HValue*>* arguments_values = args->arguments_values(); int arguments_count = arguments_values->length(); Push(function); Push(BuildWrapReceiver(receiver, checked_function)); for (int i = 1; i < arguments_count; i++) { Push(arguments_values->at(i)); } Handle<JSFunction> known_function; if (function->IsConstant() && HConstant::cast(function)->handle(isolate())->IsJSFunction()) { known_function = Handle<JSFunction>::cast( HConstant::cast(function)->handle(isolate())); int args_count = arguments_count - 1; // Excluding receiver. if (TryInlineApply(known_function, expr, args_count)) return true; } PushArgumentsFromEnvironment(arguments_count); HInvokeFunction* call = New<HInvokeFunction>( function, known_function, arguments_count); Drop(1); // Function. ast_context()->ReturnInstruction(call, expr->id()); return true; } } HValue* HOptimizedGraphBuilder::ImplicitReceiverFor(HValue* function, Handle<JSFunction> target) { SharedFunctionInfo* shared = target->shared(); if (shared->strict_mode() == SLOPPY && !shared->native()) { // Cannot embed a direct reference to the global proxy // as is it dropped on deserialization. CHECK(!isolate()->serializer_enabled()); Handle<JSObject> global_receiver( target->context()->global_object()->global_receiver()); return Add<HConstant>(global_receiver); } return graph()->GetConstantUndefined(); } void HOptimizedGraphBuilder::BuildArrayCall(Expression* expression, int arguments_count, HValue* function, Handle<AllocationSite> site) { Add<HCheckValue>(function, array_function()); if (IsCallArrayInlineable(arguments_count, site)) { BuildInlinedCallArray(expression, arguments_count, site); return; } HInstruction* call = PreProcessCall(New<HCallNewArray>( function, arguments_count + 1, site->GetElementsKind())); if (expression->IsCall()) { Drop(1); } ast_context()->ReturnInstruction(call, expression->id()); } HValue* HOptimizedGraphBuilder::BuildArrayIndexOf(HValue* receiver, HValue* search_element, ElementsKind kind, ArrayIndexOfMode mode) { ASSERT(IsFastElementsKind(kind)); NoObservableSideEffectsScope no_effects(this); HValue* elements = AddLoadElements(receiver); HValue* length = AddLoadArrayLength(receiver, kind); HValue* initial; HValue* terminating; Token::Value token; LoopBuilder::Direction direction; if (mode == kFirstIndexOf) { initial = graph()->GetConstant0(); terminating = length; token = Token::LT; direction = LoopBuilder::kPostIncrement; } else { ASSERT_EQ(kLastIndexOf, mode); initial = length; terminating = graph()->GetConstant0(); token = Token::GT; direction = LoopBuilder::kPreDecrement; } Push(graph()->GetConstantMinus1()); if (IsFastDoubleElementsKind(kind) || IsFastSmiElementsKind(kind)) { LoopBuilder loop(this, context(), direction); { HValue* index = loop.BeginBody(initial, terminating, token); HValue* element = AddUncasted<HLoadKeyed>( elements, index, static_cast<HValue*>(NULL), kind, ALLOW_RETURN_HOLE); IfBuilder if_issame(this); if (IsFastDoubleElementsKind(kind)) { if_issame.If<HCompareNumericAndBranch>( element, search_element, Token::EQ_STRICT); } else { if_issame.If<HCompareObjectEqAndBranch>(element, search_element); } if_issame.Then(); { Drop(1); Push(index); loop.Break(); } if_issame.End(); } loop.EndBody(); } else { IfBuilder if_isstring(this); if_isstring.If<HIsStringAndBranch>(search_element); if_isstring.Then(); { LoopBuilder loop(this, context(), direction); { HValue* index = loop.BeginBody(initial, terminating, token); HValue* element = AddUncasted<HLoadKeyed>( elements, index, static_cast<HValue*>(NULL), kind, ALLOW_RETURN_HOLE); IfBuilder if_issame(this); if_issame.If<HIsStringAndBranch>(element); if_issame.AndIf<HStringCompareAndBranch>( element, search_element, Token::EQ_STRICT); if_issame.Then(); { Drop(1); Push(index); loop.Break(); } if_issame.End(); } loop.EndBody(); } if_isstring.Else(); { IfBuilder if_isnumber(this); if_isnumber.If<HIsSmiAndBranch>(search_element); if_isnumber.OrIf<HCompareMap>( search_element, isolate()->factory()->heap_number_map()); if_isnumber.Then(); { HValue* search_number = AddUncasted<HForceRepresentation>(search_element, Representation::Double()); LoopBuilder loop(this, context(), direction); { HValue* index = loop.BeginBody(initial, terminating, token); HValue* element = AddUncasted<HLoadKeyed>( elements, index, static_cast<HValue*>(NULL), kind, ALLOW_RETURN_HOLE); IfBuilder if_element_isnumber(this); if_element_isnumber.If<HIsSmiAndBranch>(element); if_element_isnumber.OrIf<HCompareMap>( element, isolate()->factory()->heap_number_map()); if_element_isnumber.Then(); { HValue* number = AddUncasted<HForceRepresentation>(element, Representation::Double()); IfBuilder if_issame(this); if_issame.If<HCompareNumericAndBranch>( number, search_number, Token::EQ_STRICT); if_issame.Then(); { Drop(1); Push(index); loop.Break(); } if_issame.End(); } if_element_isnumber.End(); } loop.EndBody(); } if_isnumber.Else(); { LoopBuilder loop(this, context(), direction); { HValue* index = loop.BeginBody(initial, terminating, token); HValue* element = AddUncasted<HLoadKeyed>( elements, index, static_cast<HValue*>(NULL), kind, ALLOW_RETURN_HOLE); IfBuilder if_issame(this); if_issame.If<HCompareObjectEqAndBranch>( element, search_element); if_issame.Then(); { Drop(1); Push(index); loop.Break(); } if_issame.End(); } loop.EndBody(); } if_isnumber.End(); } if_isstring.End(); } return Pop(); } bool HOptimizedGraphBuilder::TryHandleArrayCall(Call* expr, HValue* function) { if (!array_function().is_identical_to(expr->target())) { return false; } Handle<AllocationSite> site = expr->allocation_site(); if (site.is_null()) return false; BuildArrayCall(expr, expr->arguments()->length(), function, site); return true; } bool HOptimizedGraphBuilder::TryHandleArrayCallNew(CallNew* expr, HValue* function) { if (!array_function().is_identical_to(expr->target())) { return false; } BuildArrayCall(expr, expr->arguments()->length(), function, expr->allocation_site()); return true; } void HOptimizedGraphBuilder::VisitCall(Call* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); Expression* callee = expr->expression(); int argument_count = expr->arguments()->length() + 1; // Plus receiver. HInstruction* call = NULL; Property* prop = callee->AsProperty(); if (prop != NULL) { CHECK_ALIVE(VisitForValue(prop->obj())); HValue* receiver = Top(); SmallMapList* types; ComputeReceiverTypes(expr, receiver, &types, zone()); if (prop->key()->IsPropertyName() && types->length() > 0) { Handle<String> name = prop->key()->AsLiteral()->AsPropertyName(); PropertyAccessInfo info(this, LOAD, ToType(types->first()), name); if (!info.CanAccessAsMonomorphic(types)) { HandlePolymorphicCallNamed(expr, receiver, types, name); return; } } HValue* key = NULL; if (!prop->key()->IsPropertyName()) { CHECK_ALIVE(VisitForValue(prop->key())); key = Pop(); } CHECK_ALIVE(PushLoad(prop, receiver, key)); HValue* function = Pop(); if (FLAG_hydrogen_track_positions) SetSourcePosition(expr->position()); // Push the function under the receiver. environment()->SetExpressionStackAt(0, function); Push(receiver); if (function->IsConstant() && HConstant::cast(function)->handle(isolate())->IsJSFunction()) { Handle<JSFunction> known_function = Handle<JSFunction>::cast( HConstant::cast(function)->handle(isolate())); expr->set_target(known_function); if (TryCallApply(expr)) return; CHECK_ALIVE(VisitExpressions(expr->arguments())); Handle<Map> map = types->length() == 1 ? types->first() : Handle<Map>(); if (TryInlineBuiltinMethodCall(expr, receiver, map)) { if (FLAG_trace_inlining) { PrintF("Inlining builtin "); known_function->ShortPrint(); PrintF("\n"); } return; } if (TryInlineApiMethodCall(expr, receiver, types)) return; // Wrap the receiver if necessary. if (NeedsWrappingFor(ToType(types->first()), known_function)) { // Since HWrapReceiver currently cannot actually wrap numbers and // strings, use the regular CallFunctionStub for method calls to wrap // the receiver. // TODO(verwaest): Support creation of value wrappers directly in // HWrapReceiver. call = New<HCallFunction>( function, argument_count, WRAP_AND_CALL); } else if (TryInlineCall(expr)) { return; } else { call = BuildCallConstantFunction(known_function, argument_count); } } else { CHECK_ALIVE(VisitExpressions(expr->arguments())); CallFunctionFlags flags = receiver->type().IsJSObject() ? NO_CALL_FUNCTION_FLAGS : CALL_AS_METHOD; call = New<HCallFunction>(function, argument_count, flags); } PushArgumentsFromEnvironment(argument_count); } else { VariableProxy* proxy = expr->expression()->AsVariableProxy(); if (proxy != NULL && proxy->var()->is_possibly_eval(isolate())) { return Bailout(kPossibleDirectCallToEval); } // The function is on the stack in the unoptimized code during // evaluation of the arguments. CHECK_ALIVE(VisitForValue(expr->expression())); HValue* function = Top(); if (expr->global_call()) { Variable* var = proxy->var(); bool known_global_function = false; // If there is a global property cell for the name at compile time and // access check is not enabled we assume that the function will not change // and generate optimized code for calling the function. LookupResult lookup(isolate()); GlobalPropertyAccess type = LookupGlobalProperty(var, &lookup, LOAD); if (type == kUseCell && !current_info()->global_object()->IsAccessCheckNeeded()) { Handle<GlobalObject> global(current_info()->global_object()); known_global_function = expr->ComputeGlobalTarget(global, &lookup); } if (known_global_function) { Add<HCheckValue>(function, expr->target()); // Placeholder for the receiver. Push(graph()->GetConstantUndefined()); CHECK_ALIVE(VisitExpressions(expr->arguments())); // Patch the global object on the stack by the expected receiver. HValue* receiver = ImplicitReceiverFor(function, expr->target()); const int receiver_index = argument_count - 1; environment()->SetExpressionStackAt(receiver_index, receiver); if (TryInlineBuiltinFunctionCall(expr)) { if (FLAG_trace_inlining) { PrintF("Inlining builtin "); expr->target()->ShortPrint(); PrintF("\n"); } return; } if (TryInlineApiFunctionCall(expr, receiver)) return; if (TryHandleArrayCall(expr, function)) return; if (TryInlineCall(expr)) return; PushArgumentsFromEnvironment(argument_count); call = BuildCallConstantFunction(expr->target(), argument_count); } else { Push(graph()->GetConstantUndefined()); CHECK_ALIVE(VisitExpressions(expr->arguments())); PushArgumentsFromEnvironment(argument_count); call = New<HCallFunction>(function, argument_count); } } else if (expr->IsMonomorphic()) { Add<HCheckValue>(function, expr->target()); Push(graph()->GetConstantUndefined()); CHECK_ALIVE(VisitExpressions(expr->arguments())); HValue* receiver = ImplicitReceiverFor(function, expr->target()); const int receiver_index = argument_count - 1; environment()->SetExpressionStackAt(receiver_index, receiver); if (TryInlineBuiltinFunctionCall(expr)) { if (FLAG_trace_inlining) { PrintF("Inlining builtin "); expr->target()->ShortPrint(); PrintF("\n"); } return; } if (TryInlineApiFunctionCall(expr, receiver)) return; if (TryInlineCall(expr)) return; call = PreProcessCall(New<HInvokeFunction>( function, expr->target(), argument_count)); } else { Push(graph()->GetConstantUndefined()); CHECK_ALIVE(VisitExpressions(expr->arguments())); PushArgumentsFromEnvironment(argument_count); call = New<HCallFunction>(function, argument_count); } } Drop(1); // Drop the function. return ast_context()->ReturnInstruction(call, expr->id()); } void HOptimizedGraphBuilder::BuildInlinedCallArray( Expression* expression, int argument_count, Handle<AllocationSite> site) { ASSERT(!site.is_null()); ASSERT(argument_count >= 0 && argument_count <= 1); NoObservableSideEffectsScope no_effects(this); // We should at least have the constructor on the expression stack. HValue* constructor = environment()->ExpressionStackAt(argument_count); // Register on the site for deoptimization if the transition feedback changes. AllocationSite::AddDependentCompilationInfo( site, AllocationSite::TRANSITIONS, top_info()); ElementsKind kind = site->GetElementsKind(); HInstruction* site_instruction = Add<HConstant>(site); // In the single constant argument case, we may have to adjust elements kind // to avoid creating a packed non-empty array. if (argument_count == 1 && !IsHoleyElementsKind(kind)) { HValue* argument = environment()->Top(); if (argument->IsConstant()) { HConstant* constant_argument = HConstant::cast(argument); ASSERT(constant_argument->HasSmiValue()); int constant_array_size = constant_argument->Integer32Value(); if (constant_array_size != 0) { kind = GetHoleyElementsKind(kind); } } } // Build the array. JSArrayBuilder array_builder(this, kind, site_instruction, constructor, DISABLE_ALLOCATION_SITES); HValue* new_object = argument_count == 0 ? array_builder.AllocateEmptyArray() : BuildAllocateArrayFromLength(&array_builder, Top()); int args_to_drop = argument_count + (expression->IsCall() ? 2 : 1); Drop(args_to_drop); ast_context()->ReturnValue(new_object); } // Checks whether allocation using the given constructor can be inlined. static bool IsAllocationInlineable(Handle<JSFunction> constructor) { return constructor->has_initial_map() && constructor->initial_map()->instance_type() == JS_OBJECT_TYPE && constructor->initial_map()->instance_size() < HAllocate::kMaxInlineSize && constructor->initial_map()->InitialPropertiesLength() == 0; } bool HOptimizedGraphBuilder::IsCallArrayInlineable( int argument_count, Handle<AllocationSite> site) { Handle<JSFunction> caller = current_info()->closure(); Handle<JSFunction> target = array_function(); // We should have the function plus array arguments on the environment stack. ASSERT(environment()->length() >= (argument_count + 1)); ASSERT(!site.is_null()); bool inline_ok = false; if (site->CanInlineCall()) { // We also want to avoid inlining in certain 1 argument scenarios. if (argument_count == 1) { HValue* argument = Top(); if (argument->IsConstant()) { // Do not inline if the constant length argument is not a smi or // outside the valid range for unrolled loop initialization. HConstant* constant_argument = HConstant::cast(argument); if (constant_argument->HasSmiValue()) { int value = constant_argument->Integer32Value(); inline_ok = value >= 0 && value <= kElementLoopUnrollThreshold; if (!inline_ok) { TraceInline(target, caller, "Constant length outside of valid inlining range."); } } } else { TraceInline(target, caller, "Dont inline [new] Array(n) where n isn't constant."); } } else if (argument_count == 0) { inline_ok = true; } else { TraceInline(target, caller, "Too many arguments to inline."); } } else { TraceInline(target, caller, "AllocationSite requested no inlining."); } if (inline_ok) { TraceInline(target, caller, NULL); } return inline_ok; } void HOptimizedGraphBuilder::VisitCallNew(CallNew* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position()); int argument_count = expr->arguments()->length() + 1; // Plus constructor. Factory* factory = isolate()->factory(); // The constructor function is on the stack in the unoptimized code // during evaluation of the arguments. CHECK_ALIVE(VisitForValue(expr->expression())); HValue* function = Top(); CHECK_ALIVE(VisitExpressions(expr->arguments())); if (FLAG_inline_construct && expr->IsMonomorphic() && IsAllocationInlineable(expr->target())) { Handle<JSFunction> constructor = expr->target(); HValue* check = Add<HCheckValue>(function, constructor); // Force completion of inobject slack tracking before generating // allocation code to finalize instance size. if (constructor->IsInobjectSlackTrackingInProgress()) { constructor->CompleteInobjectSlackTracking(); } // Calculate instance size from initial map of constructor. ASSERT(constructor->has_initial_map()); Handle<Map> initial_map(constructor->initial_map()); int instance_size = initial_map->instance_size(); ASSERT(initial_map->InitialPropertiesLength() == 0); // Allocate an instance of the implicit receiver object. HValue* size_in_bytes = Add<HConstant>(instance_size); HAllocationMode allocation_mode; if (FLAG_pretenuring_call_new) { if (FLAG_allocation_site_pretenuring) { // Try to use pretenuring feedback. Handle<AllocationSite> allocation_site = expr->allocation_site(); allocation_mode = HAllocationMode(allocation_site); // Take a dependency on allocation site. AllocationSite::AddDependentCompilationInfo(allocation_site, AllocationSite::TENURING, top_info()); } } HAllocate* receiver = BuildAllocate( size_in_bytes, HType::JSObject(), JS_OBJECT_TYPE, allocation_mode); receiver->set_known_initial_map(initial_map); // Initialize map and fields of the newly allocated object. { NoObservableSideEffectsScope no_effects(this); ASSERT(initial_map->instance_type() == JS_OBJECT_TYPE); Add<HStoreNamedField>(receiver, HObjectAccess::ForMapAndOffset(initial_map, JSObject::kMapOffset), Add<HConstant>(initial_map)); HValue* empty_fixed_array = Add<HConstant>(factory->empty_fixed_array()); Add<HStoreNamedField>(receiver, HObjectAccess::ForMapAndOffset(initial_map, JSObject::kPropertiesOffset), empty_fixed_array); Add<HStoreNamedField>(receiver, HObjectAccess::ForMapAndOffset(initial_map, JSObject::kElementsOffset), empty_fixed_array); if (initial_map->inobject_properties() != 0) { HConstant* undefined = graph()->GetConstantUndefined(); for (int i = 0; i < initial_map->inobject_properties(); i++) { int property_offset = initial_map->GetInObjectPropertyOffset(i); Add<HStoreNamedField>(receiver, HObjectAccess::ForMapAndOffset(initial_map, property_offset), undefined); } } } // Replace the constructor function with a newly allocated receiver using // the index of the receiver from the top of the expression stack. const int receiver_index = argument_count - 1; ASSERT(environment()->ExpressionStackAt(receiver_index) == function); environment()->SetExpressionStackAt(receiver_index, receiver); if (TryInlineConstruct(expr, receiver)) { // Inlining worked, add a dependency on the initial map to make sure that // this code is deoptimized whenever the initial map of the constructor // changes. Map::AddDependentCompilationInfo( initial_map, DependentCode::kInitialMapChangedGroup, top_info()); return; } // TODO(mstarzinger): For now we remove the previous HAllocate and all // corresponding instructions and instead add HPushArguments for the // arguments in case inlining failed. What we actually should do is for // inlining to try to build a subgraph without mutating the parent graph. HInstruction* instr = current_block()->last(); do { HInstruction* prev_instr = instr->previous(); instr->DeleteAndReplaceWith(NULL); instr = prev_instr; } while (instr != check); environment()->SetExpressionStackAt(receiver_index, function); HInstruction* call = PreProcessCall(New<HCallNew>(function, argument_count)); return ast_context()->ReturnInstruction(call, expr->id()); } else { // The constructor function is both an operand to the instruction and an // argument to the construct call. if (TryHandleArrayCallNew(expr, function)) return; HInstruction* call = PreProcessCall(New<HCallNew>(function, argument_count)); return ast_context()->ReturnInstruction(call, expr->id()); } } // Support for generating inlined runtime functions. // Lookup table for generators for runtime calls that are generated inline. // Elements of the table are member pointers to functions of // HOptimizedGraphBuilder. #define INLINE_FUNCTION_GENERATOR_ADDRESS(Name, argc, ressize) \ &HOptimizedGraphBuilder::Generate##Name, const HOptimizedGraphBuilder::InlineFunctionGenerator HOptimizedGraphBuilder::kInlineFunctionGenerators[] = { INLINE_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS) INLINE_OPTIMIZED_FUNCTION_LIST(INLINE_FUNCTION_GENERATOR_ADDRESS) }; #undef INLINE_FUNCTION_GENERATOR_ADDRESS template <class ViewClass> void HGraphBuilder::BuildArrayBufferViewInitialization( HValue* obj, HValue* buffer, HValue* byte_offset, HValue* byte_length) { for (int offset = ViewClass::kSize; offset < ViewClass::kSizeWithInternalFields; offset += kPointerSize) { Add<HStoreNamedField>(obj, HObjectAccess::ForObservableJSObjectOffset(offset), graph()->GetConstant0()); } Add<HStoreNamedField>( obj, HObjectAccess::ForJSArrayBufferViewByteOffset(), byte_offset); Add<HStoreNamedField>( obj, HObjectAccess::ForJSArrayBufferViewByteLength(), byte_length); if (buffer != NULL) { Add<HStoreNamedField>( obj, HObjectAccess::ForJSArrayBufferViewBuffer(), buffer); HObjectAccess weak_first_view_access = HObjectAccess::ForJSArrayBufferWeakFirstView(); Add<HStoreNamedField>(obj, HObjectAccess::ForJSArrayBufferViewWeakNext(), Add<HLoadNamedField>(buffer, static_cast<HValue*>(NULL), weak_first_view_access)); Add<HStoreNamedField>(buffer, weak_first_view_access, obj); } else { Add<HStoreNamedField>( obj, HObjectAccess::ForJSArrayBufferViewBuffer(), Add<HConstant>(static_cast<int32_t>(0))); Add<HStoreNamedField>(obj, HObjectAccess::ForJSArrayBufferViewWeakNext(), graph()->GetConstantUndefined()); } } void HOptimizedGraphBuilder::GenerateDataViewInitialize( CallRuntime* expr) { ZoneList<Expression*>* arguments = expr->arguments(); ASSERT(arguments->length()== 4); CHECK_ALIVE(VisitForValue(arguments->at(0))); HValue* obj = Pop(); CHECK_ALIVE(VisitForValue(arguments->at(1))); HValue* buffer = Pop(); CHECK_ALIVE(VisitForValue(arguments->at(2))); HValue* byte_offset = Pop(); CHECK_ALIVE(VisitForValue(arguments->at(3))); HValue* byte_length = Pop(); { NoObservableSideEffectsScope scope(this); BuildArrayBufferViewInitialization<JSDataView>( obj, buffer, byte_offset, byte_length); } } static Handle<Map> TypedArrayMap(Isolate* isolate, ExternalArrayType array_type, ElementsKind target_kind) { Handle<Context> native_context = isolate->native_context(); Handle<JSFunction> fun; switch (array_type) { #define TYPED_ARRAY_CASE(Type, type, TYPE, ctype, size) \ case kExternal##Type##Array: \ fun = Handle<JSFunction>(native_context->type##_array_fun()); \ break; TYPED_ARRAYS(TYPED_ARRAY_CASE) #undef TYPED_ARRAY_CASE } Handle<Map> map(fun->initial_map()); return Map::AsElementsKind(map, target_kind); } HValue* HOptimizedGraphBuilder::BuildAllocateExternalElements( ExternalArrayType array_type, bool is_zero_byte_offset, HValue* buffer, HValue* byte_offset, HValue* length) { Handle<Map> external_array_map( isolate()->heap()->MapForExternalArrayType(array_type)); // The HForceRepresentation is to prevent possible deopt on int-smi // conversion after allocation but before the new object fields are set. length = AddUncasted<HForceRepresentation>(length, Representation::Smi()); HValue* elements = Add<HAllocate>( Add<HConstant>(ExternalArray::kAlignedSize), HType::HeapObject(), NOT_TENURED, external_array_map->instance_type()); AddStoreMapConstant(elements, external_array_map); Add<HStoreNamedField>(elements, HObjectAccess::ForFixedArrayLength(), length); HValue* backing_store = Add<HLoadNamedField>( buffer, static_cast<HValue*>(NULL), HObjectAccess::ForJSArrayBufferBackingStore()); HValue* typed_array_start; if (is_zero_byte_offset) { typed_array_start = backing_store; } else { HInstruction* external_pointer = AddUncasted<HAdd>(backing_store, byte_offset); // Arguments are checked prior to call to TypedArrayInitialize, // including byte_offset. external_pointer->ClearFlag(HValue::kCanOverflow); typed_array_start = external_pointer; } Add<HStoreNamedField>(elements, HObjectAccess::ForExternalArrayExternalPointer(), typed_array_start); return elements; } HValue* HOptimizedGraphBuilder::BuildAllocateFixedTypedArray( ExternalArrayType array_type, size_t element_size, ElementsKind fixed_elements_kind, HValue* byte_length, HValue* length) { STATIC_ASSERT( (FixedTypedArrayBase::kHeaderSize & kObjectAlignmentMask) == 0); HValue* total_size; // if fixed array's elements are not aligned to object's alignment, // we need to align the whole array to object alignment. if (element_size % kObjectAlignment != 0) { total_size = BuildObjectSizeAlignment( byte_length, FixedTypedArrayBase::kHeaderSize); } else { total_size = AddUncasted<HAdd>(byte_length, Add<HConstant>(FixedTypedArrayBase::kHeaderSize)); total_size->ClearFlag(HValue::kCanOverflow); } // The HForceRepresentation is to prevent possible deopt on int-smi // conversion after allocation but before the new object fields are set. length = AddUncasted<HForceRepresentation>(length, Representation::Smi()); Handle<Map> fixed_typed_array_map( isolate()->heap()->MapForFixedTypedArray(array_type)); HValue* elements = Add<HAllocate>(total_size, HType::HeapObject(), NOT_TENURED, fixed_typed_array_map->instance_type()); AddStoreMapConstant(elements, fixed_typed_array_map); Add<HStoreNamedField>(elements, HObjectAccess::ForFixedArrayLength(), length); HValue* filler = Add<HConstant>(static_cast<int32_t>(0)); { LoopBuilder builder(this, context(), LoopBuilder::kPostIncrement); HValue* key = builder.BeginBody( Add<HConstant>(static_cast<int32_t>(0)), length, Token::LT); Add<HStoreKeyed>(elements, key, filler, fixed_elements_kind); builder.EndBody(); } return elements; } void HOptimizedGraphBuilder::GenerateTypedArrayInitialize( CallRuntime* expr) { ZoneList<Expression*>* arguments = expr->arguments(); static const int kObjectArg = 0; static const int kArrayIdArg = 1; static const int kBufferArg = 2; static const int kByteOffsetArg = 3; static const int kByteLengthArg = 4; static const int kArgsLength = 5; ASSERT(arguments->length() == kArgsLength); CHECK_ALIVE(VisitForValue(arguments->at(kObjectArg))); HValue* obj = Pop(); if (arguments->at(kArrayIdArg)->IsLiteral()) { // This should never happen in real use, but can happen when fuzzing. // Just bail out. Bailout(kNeedSmiLiteral); return; } Handle<Object> value = static_cast<Literal*>(arguments->at(kArrayIdArg))->value(); if (!value->IsSmi()) { // This should never happen in real use, but can happen when fuzzing. // Just bail out. Bailout(kNeedSmiLiteral); return; } int array_id = Smi::cast(*value)->value(); HValue* buffer; if (!arguments->at(kBufferArg)->IsNullLiteral()) { CHECK_ALIVE(VisitForValue(arguments->at(kBufferArg))); buffer = Pop(); } else { buffer = NULL; } HValue* byte_offset; bool is_zero_byte_offset; if (arguments->at(kByteOffsetArg)->IsLiteral() && Smi::FromInt(0) == *static_cast<Literal*>(arguments->at(kByteOffsetArg))->value()) { byte_offset = Add<HConstant>(static_cast<int32_t>(0)); is_zero_byte_offset = true; } else { CHECK_ALIVE(VisitForValue(arguments->at(kByteOffsetArg))); byte_offset = Pop(); is_zero_byte_offset = false; ASSERT(buffer != NULL); } CHECK_ALIVE(VisitForValue(arguments->at(kByteLengthArg))); HValue* byte_length = Pop(); NoObservableSideEffectsScope scope(this); IfBuilder byte_offset_smi(this); if (!is_zero_byte_offset) { byte_offset_smi.If<HIsSmiAndBranch>(byte_offset); byte_offset_smi.Then(); } ExternalArrayType array_type = kExternalInt8Array; // Bogus initialization. size_t element_size = 1; // Bogus initialization. ElementsKind external_elements_kind = // Bogus initialization. EXTERNAL_INT8_ELEMENTS; ElementsKind fixed_elements_kind = // Bogus initialization. INT8_ELEMENTS; Runtime::ArrayIdToTypeAndSize(array_id, &array_type, &external_elements_kind, &fixed_elements_kind, &element_size); { // byte_offset is Smi. BuildArrayBufferViewInitialization<JSTypedArray>( obj, buffer, byte_offset, byte_length); HInstruction* length = AddUncasted<HDiv>(byte_length, Add<HConstant>(static_cast<int32_t>(element_size))); Add<HStoreNamedField>(obj, HObjectAccess::ForJSTypedArrayLength(), length); HValue* elements; if (buffer != NULL) { elements = BuildAllocateExternalElements( array_type, is_zero_byte_offset, buffer, byte_offset, length); Handle<Map> obj_map = TypedArrayMap( isolate(), array_type, external_elements_kind); AddStoreMapConstant(obj, obj_map); } else { ASSERT(is_zero_byte_offset); elements = BuildAllocateFixedTypedArray( array_type, element_size, fixed_elements_kind, byte_length, length); } Add<HStoreNamedField>( obj, HObjectAccess::ForElementsPointer(), elements); } if (!is_zero_byte_offset) { byte_offset_smi.Else(); { // byte_offset is not Smi. Push(obj); CHECK_ALIVE(VisitForValue(arguments->at(kArrayIdArg))); Push(buffer); Push(byte_offset); Push(byte_length); PushArgumentsFromEnvironment(kArgsLength); Add<HCallRuntime>(expr->name(), expr->function(), kArgsLength); } } byte_offset_smi.End(); } void HOptimizedGraphBuilder::GenerateMaxSmi(CallRuntime* expr) { ASSERT(expr->arguments()->length() == 0); HConstant* max_smi = New<HConstant>(static_cast<int32_t>(Smi::kMaxValue)); return ast_context()->ReturnInstruction(max_smi, expr->id()); } void HOptimizedGraphBuilder::GenerateTypedArrayMaxSizeInHeap( CallRuntime* expr) { ASSERT(expr->arguments()->length() == 0); HConstant* result = New<HConstant>(static_cast<int32_t>( FLAG_typed_array_max_size_in_heap)); return ast_context()->ReturnInstruction(result, expr->id()); } void HOptimizedGraphBuilder::GenerateArrayBufferGetByteLength( CallRuntime* expr) { ASSERT(expr->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(expr->arguments()->at(0))); HValue* buffer = Pop(); HInstruction* result = New<HLoadNamedField>( buffer, static_cast<HValue*>(NULL), HObjectAccess::ForJSArrayBufferByteLength()); return ast_context()->ReturnInstruction(result, expr->id()); } void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteLength( CallRuntime* expr) { ASSERT(expr->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(expr->arguments()->at(0))); HValue* buffer = Pop(); HInstruction* result = New<HLoadNamedField>( buffer, static_cast<HValue*>(NULL), HObjectAccess::ForJSArrayBufferViewByteLength()); return ast_context()->ReturnInstruction(result, expr->id()); } void HOptimizedGraphBuilder::GenerateArrayBufferViewGetByteOffset( CallRuntime* expr) { ASSERT(expr->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(expr->arguments()->at(0))); HValue* buffer = Pop(); HInstruction* result = New<HLoadNamedField>( buffer, static_cast<HValue*>(NULL), HObjectAccess::ForJSArrayBufferViewByteOffset()); return ast_context()->ReturnInstruction(result, expr->id()); } void HOptimizedGraphBuilder::GenerateTypedArrayGetLength( CallRuntime* expr) { ASSERT(expr->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(expr->arguments()->at(0))); HValue* buffer = Pop(); HInstruction* result = New<HLoadNamedField>( buffer, static_cast<HValue*>(NULL), HObjectAccess::ForJSTypedArrayLength()); return ast_context()->ReturnInstruction(result, expr->id()); } void HOptimizedGraphBuilder::VisitCallRuntime(CallRuntime* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); if (expr->is_jsruntime()) { return Bailout(kCallToAJavaScriptRuntimeFunction); } const Runtime::Function* function = expr->function(); ASSERT(function != NULL); if (function->intrinsic_type == Runtime::INLINE || function->intrinsic_type == Runtime::INLINE_OPTIMIZED) { ASSERT(expr->name()->length() > 0); ASSERT(expr->name()->Get(0) == '_'); // Call to an inline function. int lookup_index = static_cast<int>(function->function_id) - static_cast<int>(Runtime::kFirstInlineFunction); ASSERT(lookup_index >= 0); ASSERT(static_cast<size_t>(lookup_index) < ARRAY_SIZE(kInlineFunctionGenerators)); InlineFunctionGenerator generator = kInlineFunctionGenerators[lookup_index]; // Call the inline code generator using the pointer-to-member. (this->*generator)(expr); } else { ASSERT(function->intrinsic_type == Runtime::RUNTIME); Handle<String> name = expr->name(); int argument_count = expr->arguments()->length(); CHECK_ALIVE(VisitExpressions(expr->arguments())); PushArgumentsFromEnvironment(argument_count); HCallRuntime* call = New<HCallRuntime>(name, function, argument_count); return ast_context()->ReturnInstruction(call, expr->id()); } } void HOptimizedGraphBuilder::VisitUnaryOperation(UnaryOperation* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); switch (expr->op()) { case Token::DELETE: return VisitDelete(expr); case Token::VOID: return VisitVoid(expr); case Token::TYPEOF: return VisitTypeof(expr); case Token::NOT: return VisitNot(expr); default: UNREACHABLE(); } } void HOptimizedGraphBuilder::VisitDelete(UnaryOperation* expr) { Property* prop = expr->expression()->AsProperty(); VariableProxy* proxy = expr->expression()->AsVariableProxy(); if (prop != NULL) { CHECK_ALIVE(VisitForValue(prop->obj())); CHECK_ALIVE(VisitForValue(prop->key())); HValue* key = Pop(); HValue* obj = Pop(); HValue* function = AddLoadJSBuiltin(Builtins::DELETE); Add<HPushArguments>(obj, key, Add<HConstant>(function_strict_mode())); // TODO(olivf) InvokeFunction produces a check for the parameter count, // even though we are certain to pass the correct number of arguments here. HInstruction* instr = New<HInvokeFunction>(function, 3); return ast_context()->ReturnInstruction(instr, expr->id()); } else if (proxy != NULL) { Variable* var = proxy->var(); if (var->IsUnallocated()) { Bailout(kDeleteWithGlobalVariable); } else if (var->IsStackAllocated() || var->IsContextSlot()) { // Result of deleting non-global variables is false. 'this' is not // really a variable, though we implement it as one. The // subexpression does not have side effects. HValue* value = var->is_this() ? graph()->GetConstantTrue() : graph()->GetConstantFalse(); return ast_context()->ReturnValue(value); } else { Bailout(kDeleteWithNonGlobalVariable); } } else { // Result of deleting non-property, non-variable reference is true. // Evaluate the subexpression for side effects. CHECK_ALIVE(VisitForEffect(expr->expression())); return ast_context()->ReturnValue(graph()->GetConstantTrue()); } } void HOptimizedGraphBuilder::VisitVoid(UnaryOperation* expr) { CHECK_ALIVE(VisitForEffect(expr->expression())); return ast_context()->ReturnValue(graph()->GetConstantUndefined()); } void HOptimizedGraphBuilder::VisitTypeof(UnaryOperation* expr) { CHECK_ALIVE(VisitForTypeOf(expr->expression())); HValue* value = Pop(); HInstruction* instr = New<HTypeof>(value); return ast_context()->ReturnInstruction(instr, expr->id()); } void HOptimizedGraphBuilder::VisitNot(UnaryOperation* expr) { if (ast_context()->IsTest()) { TestContext* context = TestContext::cast(ast_context()); VisitForControl(expr->expression(), context->if_false(), context->if_true()); return; } if (ast_context()->IsEffect()) { VisitForEffect(expr->expression()); return; } ASSERT(ast_context()->IsValue()); HBasicBlock* materialize_false = graph()->CreateBasicBlock(); HBasicBlock* materialize_true = graph()->CreateBasicBlock(); CHECK_BAILOUT(VisitForControl(expr->expression(), materialize_false, materialize_true)); if (materialize_false->HasPredecessor()) { materialize_false->SetJoinId(expr->MaterializeFalseId()); set_current_block(materialize_false); Push(graph()->GetConstantFalse()); } else { materialize_false = NULL; } if (materialize_true->HasPredecessor()) { materialize_true->SetJoinId(expr->MaterializeTrueId()); set_current_block(materialize_true); Push(graph()->GetConstantTrue()); } else { materialize_true = NULL; } HBasicBlock* join = CreateJoin(materialize_false, materialize_true, expr->id()); set_current_block(join); if (join != NULL) return ast_context()->ReturnValue(Pop()); } HInstruction* HOptimizedGraphBuilder::BuildIncrement( bool returns_original_input, CountOperation* expr) { // The input to the count operation is on top of the expression stack. Representation rep = Representation::FromType(expr->type()); if (rep.IsNone() || rep.IsTagged()) { rep = Representation::Smi(); } if (returns_original_input) { // We need an explicit HValue representing ToNumber(input). The // actual HChange instruction we need is (sometimes) added in a later // phase, so it is not available now to be used as an input to HAdd and // as the return value. HInstruction* number_input = AddUncasted<HForceRepresentation>(Pop(), rep); if (!rep.IsDouble()) { number_input->SetFlag(HInstruction::kFlexibleRepresentation); number_input->SetFlag(HInstruction::kCannotBeTagged); } Push(number_input); } // The addition has no side effects, so we do not need // to simulate the expression stack after this instruction. // Any later failures deopt to the load of the input or earlier. HConstant* delta = (expr->op() == Token::INC) ? graph()->GetConstant1() : graph()->GetConstantMinus1(); HInstruction* instr = AddUncasted<HAdd>(Top(), delta); if (instr->IsAdd()) { HAdd* add = HAdd::cast(instr); add->set_observed_input_representation(1, rep); add->set_observed_input_representation(2, Representation::Smi()); } instr->SetFlag(HInstruction::kCannotBeTagged); instr->ClearAllSideEffects(); return instr; } void HOptimizedGraphBuilder::BuildStoreForEffect(Expression* expr, Property* prop, BailoutId ast_id, BailoutId return_id, HValue* object, HValue* key, HValue* value) { EffectContext for_effect(this); Push(object); if (key != NULL) Push(key); Push(value); BuildStore(expr, prop, ast_id, return_id); } void HOptimizedGraphBuilder::VisitCountOperation(CountOperation* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position()); Expression* target = expr->expression(); VariableProxy* proxy = target->AsVariableProxy(); Property* prop = target->AsProperty(); if (proxy == NULL && prop == NULL) { return Bailout(kInvalidLhsInCountOperation); } // Match the full code generator stack by simulating an extra stack // element for postfix operations in a non-effect context. The return // value is ToNumber(input). bool returns_original_input = expr->is_postfix() && !ast_context()->IsEffect(); HValue* input = NULL; // ToNumber(original_input). HValue* after = NULL; // The result after incrementing or decrementing. if (proxy != NULL) { Variable* var = proxy->var(); if (var->mode() == CONST_LEGACY) { return Bailout(kUnsupportedCountOperationWithConst); } // Argument of the count operation is a variable, not a property. ASSERT(prop == NULL); CHECK_ALIVE(VisitForValue(target)); after = BuildIncrement(returns_original_input, expr); input = returns_original_input ? Top() : Pop(); Push(after); switch (var->location()) { case Variable::UNALLOCATED: HandleGlobalVariableAssignment(var, after, expr->AssignmentId()); break; case Variable::PARAMETER: case Variable::LOCAL: BindIfLive(var, after); break; case Variable::CONTEXT: { // Bail out if we try to mutate a parameter value in a function // using the arguments object. We do not (yet) correctly handle the // arguments property of the function. if (current_info()->scope()->arguments() != NULL) { // Parameters will rewrite to context slots. We have no direct // way to detect that the variable is a parameter so we use a // linear search of the parameter list. int count = current_info()->scope()->num_parameters(); for (int i = 0; i < count; ++i) { if (var == current_info()->scope()->parameter(i)) { return Bailout(kAssignmentToParameterInArgumentsObject); } } } HValue* context = BuildContextChainWalk(var); HStoreContextSlot::Mode mode = IsLexicalVariableMode(var->mode()) ? HStoreContextSlot::kCheckDeoptimize : HStoreContextSlot::kNoCheck; HStoreContextSlot* instr = Add<HStoreContextSlot>(context, var->index(), mode, after); if (instr->HasObservableSideEffects()) { Add<HSimulate>(expr->AssignmentId(), REMOVABLE_SIMULATE); } break; } case Variable::LOOKUP: return Bailout(kLookupVariableInCountOperation); } Drop(returns_original_input ? 2 : 1); return ast_context()->ReturnValue(expr->is_postfix() ? input : after); } // Argument of the count operation is a property. ASSERT(prop != NULL); if (returns_original_input) Push(graph()->GetConstantUndefined()); CHECK_ALIVE(VisitForValue(prop->obj())); HValue* object = Top(); HValue* key = NULL; if ((!prop->IsFunctionPrototype() && !prop->key()->IsPropertyName()) || prop->IsStringAccess()) { CHECK_ALIVE(VisitForValue(prop->key())); key = Top(); } CHECK_ALIVE(PushLoad(prop, object, key)); after = BuildIncrement(returns_original_input, expr); if (returns_original_input) { input = Pop(); // Drop object and key to push it again in the effect context below. Drop(key == NULL ? 1 : 2); environment()->SetExpressionStackAt(0, input); CHECK_ALIVE(BuildStoreForEffect( expr, prop, expr->id(), expr->AssignmentId(), object, key, after)); return ast_context()->ReturnValue(Pop()); } environment()->SetExpressionStackAt(0, after); return BuildStore(expr, prop, expr->id(), expr->AssignmentId()); } HInstruction* HOptimizedGraphBuilder::BuildStringCharCodeAt( HValue* string, HValue* index) { if (string->IsConstant() && index->IsConstant()) { HConstant* c_string = HConstant::cast(string); HConstant* c_index = HConstant::cast(index); if (c_string->HasStringValue() && c_index->HasNumberValue()) { int32_t i = c_index->NumberValueAsInteger32(); Handle<String> s = c_string->StringValue(); if (i < 0 || i >= s->length()) { return New<HConstant>(OS::nan_value()); } return New<HConstant>(s->Get(i)); } } string = BuildCheckString(string); index = Add<HBoundsCheck>(index, AddLoadStringLength(string)); return New<HStringCharCodeAt>(string, index); } // Checks if the given shift amounts have following forms: // (N1) and (N2) with N1 + N2 = 32; (sa) and (32 - sa). static bool ShiftAmountsAllowReplaceByRotate(HValue* sa, HValue* const32_minus_sa) { if (sa->IsConstant() && const32_minus_sa->IsConstant()) { const HConstant* c1 = HConstant::cast(sa); const HConstant* c2 = HConstant::cast(const32_minus_sa); return c1->HasInteger32Value() && c2->HasInteger32Value() && (c1->Integer32Value() + c2->Integer32Value() == 32); } if (!const32_minus_sa->IsSub()) return false; HSub* sub = HSub::cast(const32_minus_sa); return sub->left()->EqualsInteger32Constant(32) && sub->right() == sa; } // Checks if the left and the right are shift instructions with the oposite // directions that can be replaced by one rotate right instruction or not. // Returns the operand and the shift amount for the rotate instruction in the // former case. bool HGraphBuilder::MatchRotateRight(HValue* left, HValue* right, HValue** operand, HValue** shift_amount) { HShl* shl; HShr* shr; if (left->IsShl() && right->IsShr()) { shl = HShl::cast(left); shr = HShr::cast(right); } else if (left->IsShr() && right->IsShl()) { shl = HShl::cast(right); shr = HShr::cast(left); } else { return false; } if (shl->left() != shr->left()) return false; if (!ShiftAmountsAllowReplaceByRotate(shl->right(), shr->right()) && !ShiftAmountsAllowReplaceByRotate(shr->right(), shl->right())) { return false; } *operand= shr->left(); *shift_amount = shr->right(); return true; } bool CanBeZero(HValue* right) { if (right->IsConstant()) { HConstant* right_const = HConstant::cast(right); if (right_const->HasInteger32Value() && (right_const->Integer32Value() & 0x1f) != 0) { return false; } } return true; } HValue* HGraphBuilder::EnforceNumberType(HValue* number, Type* expected) { if (expected->Is(Type::SignedSmall())) { return AddUncasted<HForceRepresentation>(number, Representation::Smi()); } if (expected->Is(Type::Signed32())) { return AddUncasted<HForceRepresentation>(number, Representation::Integer32()); } return number; } HValue* HGraphBuilder::TruncateToNumber(HValue* value, Type** expected) { if (value->IsConstant()) { HConstant* constant = HConstant::cast(value); Maybe<HConstant*> number = constant->CopyToTruncatedNumber(zone()); if (number.has_value) { *expected = Type::Number(zone()); return AddInstruction(number.value); } } // We put temporary values on the stack, which don't correspond to anything // in baseline code. Since nothing is observable we avoid recording those // pushes with a NoObservableSideEffectsScope. NoObservableSideEffectsScope no_effects(this); Type* expected_type = *expected; // Separate the number type from the rest. Type* expected_obj = Type::Intersect(expected_type, Type::NonNumber(zone()), zone()); Type* expected_number = Type::Intersect(expected_type, Type::Number(zone()), zone()); // We expect to get a number. // (We need to check first, since Type::None->Is(Type::Any()) == true. if (expected_obj->Is(Type::None())) { ASSERT(!expected_number->Is(Type::None(zone()))); return value; } if (expected_obj->Is(Type::Undefined(zone()))) { // This is already done by HChange. *expected = Type::Union(expected_number, Type::Number(zone()), zone()); return value; } return value; } HValue* HOptimizedGraphBuilder::BuildBinaryOperation( BinaryOperation* expr, HValue* left, HValue* right, PushBeforeSimulateBehavior push_sim_result) { Type* left_type = expr->left()->bounds().lower; Type* right_type = expr->right()->bounds().lower; Type* result_type = expr->bounds().lower; Maybe<int> fixed_right_arg = expr->fixed_right_arg(); Handle<AllocationSite> allocation_site = expr->allocation_site(); HAllocationMode allocation_mode; if (FLAG_allocation_site_pretenuring && !allocation_site.is_null()) { allocation_mode = HAllocationMode(allocation_site); } HValue* result = HGraphBuilder::BuildBinaryOperation( expr->op(), left, right, left_type, right_type, result_type, fixed_right_arg, allocation_mode); // Add a simulate after instructions with observable side effects, and // after phis, which are the result of BuildBinaryOperation when we // inlined some complex subgraph. if (result->HasObservableSideEffects() || result->IsPhi()) { if (push_sim_result == PUSH_BEFORE_SIMULATE) { Push(result); Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE); Drop(1); } else { Add<HSimulate>(expr->id(), REMOVABLE_SIMULATE); } } return result; } HValue* HGraphBuilder::BuildBinaryOperation( Token::Value op, HValue* left, HValue* right, Type* left_type, Type* right_type, Type* result_type, Maybe<int> fixed_right_arg, HAllocationMode allocation_mode) { Representation left_rep = Representation::FromType(left_type); Representation right_rep = Representation::FromType(right_type); bool maybe_string_add = op == Token::ADD && (left_type->Maybe(Type::String()) || right_type->Maybe(Type::String())); if (left_type->Is(Type::None())) { Add<HDeoptimize>("Insufficient type feedback for LHS of binary operation", Deoptimizer::SOFT); // TODO(rossberg): we should be able to get rid of non-continuous // defaults. left_type = Type::Any(zone()); } else { if (!maybe_string_add) left = TruncateToNumber(left, &left_type); left_rep = Representation::FromType(left_type); } if (right_type->Is(Type::None())) { Add<HDeoptimize>("Insufficient type feedback for RHS of binary operation", Deoptimizer::SOFT); right_type = Type::Any(zone()); } else { if (!maybe_string_add) right = TruncateToNumber(right, &right_type); right_rep = Representation::FromType(right_type); } // Special case for string addition here. if (op == Token::ADD && (left_type->Is(Type::String()) || right_type->Is(Type::String()))) { // Validate type feedback for left argument. if (left_type->Is(Type::String())) { left = BuildCheckString(left); } // Validate type feedback for right argument. if (right_type->Is(Type::String())) { right = BuildCheckString(right); } // Convert left argument as necessary. if (left_type->Is(Type::Number())) { ASSERT(right_type->Is(Type::String())); left = BuildNumberToString(left, left_type); } else if (!left_type->Is(Type::String())) { ASSERT(right_type->Is(Type::String())); HValue* function = AddLoadJSBuiltin(Builtins::STRING_ADD_RIGHT); Add<HPushArguments>(left, right); return AddUncasted<HInvokeFunction>(function, 2); } // Convert right argument as necessary. if (right_type->Is(Type::Number())) { ASSERT(left_type->Is(Type::String())); right = BuildNumberToString(right, right_type); } else if (!right_type->Is(Type::String())) { ASSERT(left_type->Is(Type::String())); HValue* function = AddLoadJSBuiltin(Builtins::STRING_ADD_LEFT); Add<HPushArguments>(left, right); return AddUncasted<HInvokeFunction>(function, 2); } // Fast path for empty constant strings. if (left->IsConstant() && HConstant::cast(left)->HasStringValue() && HConstant::cast(left)->StringValue()->length() == 0) { return right; } if (right->IsConstant() && HConstant::cast(right)->HasStringValue() && HConstant::cast(right)->StringValue()->length() == 0) { return left; } // Register the dependent code with the allocation site. if (!allocation_mode.feedback_site().is_null()) { ASSERT(!graph()->info()->IsStub()); Handle<AllocationSite> site(allocation_mode.feedback_site()); AllocationSite::AddDependentCompilationInfo( site, AllocationSite::TENURING, top_info()); } // Inline the string addition into the stub when creating allocation // mementos to gather allocation site feedback, or if we can statically // infer that we're going to create a cons string. if ((graph()->info()->IsStub() && allocation_mode.CreateAllocationMementos()) || (left->IsConstant() && HConstant::cast(left)->HasStringValue() && HConstant::cast(left)->StringValue()->length() + 1 >= ConsString::kMinLength) || (right->IsConstant() && HConstant::cast(right)->HasStringValue() && HConstant::cast(right)->StringValue()->length() + 1 >= ConsString::kMinLength)) { return BuildStringAdd(left, right, allocation_mode); } // Fallback to using the string add stub. return AddUncasted<HStringAdd>( left, right, allocation_mode.GetPretenureMode(), STRING_ADD_CHECK_NONE, allocation_mode.feedback_site()); } if (graph()->info()->IsStub()) { left = EnforceNumberType(left, left_type); right = EnforceNumberType(right, right_type); } Representation result_rep = Representation::FromType(result_type); bool is_non_primitive = (left_rep.IsTagged() && !left_rep.IsSmi()) || (right_rep.IsTagged() && !right_rep.IsSmi()); HInstruction* instr = NULL; // Only the stub is allowed to call into the runtime, since otherwise we would // inline several instructions (including the two pushes) for every tagged // operation in optimized code, which is more expensive, than a stub call. if (graph()->info()->IsStub() && is_non_primitive) { HValue* function = AddLoadJSBuiltin(BinaryOpIC::TokenToJSBuiltin(op)); Add<HPushArguments>(left, right); instr = AddUncasted<HInvokeFunction>(function, 2); } else { switch (op) { case Token::ADD: instr = AddUncasted<HAdd>(left, right); break; case Token::SUB: instr = AddUncasted<HSub>(left, right); break; case Token::MUL: instr = AddUncasted<HMul>(left, right); break; case Token::MOD: { if (fixed_right_arg.has_value && !right->EqualsInteger32Constant(fixed_right_arg.value)) { HConstant* fixed_right = Add<HConstant>( static_cast<int>(fixed_right_arg.value)); IfBuilder if_same(this); if_same.If<HCompareNumericAndBranch>(right, fixed_right, Token::EQ); if_same.Then(); if_same.ElseDeopt("Unexpected RHS of binary operation"); right = fixed_right; } instr = AddUncasted<HMod>(left, right); break; } case Token::DIV: instr = AddUncasted<HDiv>(left, right); break; case Token::BIT_XOR: case Token::BIT_AND: instr = AddUncasted<HBitwise>(op, left, right); break; case Token::BIT_OR: { HValue* operand, *shift_amount; if (left_type->Is(Type::Signed32()) && right_type->Is(Type::Signed32()) && MatchRotateRight(left, right, &operand, &shift_amount)) { instr = AddUncasted<HRor>(operand, shift_amount); } else { instr = AddUncasted<HBitwise>(op, left, right); } break; } case Token::SAR: instr = AddUncasted<HSar>(left, right); break; case Token::SHR: instr = AddUncasted<HShr>(left, right); if (FLAG_opt_safe_uint32_operations && instr->IsShr() && CanBeZero(right)) { graph()->RecordUint32Instruction(instr); } break; case Token::SHL: instr = AddUncasted<HShl>(left, right); break; default: UNREACHABLE(); } } if (instr->IsBinaryOperation()) { HBinaryOperation* binop = HBinaryOperation::cast(instr); binop->set_observed_input_representation(1, left_rep); binop->set_observed_input_representation(2, right_rep); binop->initialize_output_representation(result_rep); if (graph()->info()->IsStub()) { // Stub should not call into stub. instr->SetFlag(HValue::kCannotBeTagged); // And should truncate on HForceRepresentation already. if (left->IsForceRepresentation()) { left->CopyFlag(HValue::kTruncatingToSmi, instr); left->CopyFlag(HValue::kTruncatingToInt32, instr); } if (right->IsForceRepresentation()) { right->CopyFlag(HValue::kTruncatingToSmi, instr); right->CopyFlag(HValue::kTruncatingToInt32, instr); } } } return instr; } // Check for the form (%_ClassOf(foo) === 'BarClass'). static bool IsClassOfTest(CompareOperation* expr) { if (expr->op() != Token::EQ_STRICT) return false; CallRuntime* call = expr->left()->AsCallRuntime(); if (call == NULL) return false; Literal* literal = expr->right()->AsLiteral(); if (literal == NULL) return false; if (!literal->value()->IsString()) return false; if (!call->name()->IsOneByteEqualTo(STATIC_ASCII_VECTOR("_ClassOf"))) { return false; } ASSERT(call->arguments()->length() == 1); return true; } void HOptimizedGraphBuilder::VisitBinaryOperation(BinaryOperation* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); switch (expr->op()) { case Token::COMMA: return VisitComma(expr); case Token::OR: case Token::AND: return VisitLogicalExpression(expr); default: return VisitArithmeticExpression(expr); } } void HOptimizedGraphBuilder::VisitComma(BinaryOperation* expr) { CHECK_ALIVE(VisitForEffect(expr->left())); // Visit the right subexpression in the same AST context as the entire // expression. Visit(expr->right()); } void HOptimizedGraphBuilder::VisitLogicalExpression(BinaryOperation* expr) { bool is_logical_and = expr->op() == Token::AND; if (ast_context()->IsTest()) { TestContext* context = TestContext::cast(ast_context()); // Translate left subexpression. HBasicBlock* eval_right = graph()->CreateBasicBlock(); if (is_logical_and) { CHECK_BAILOUT(VisitForControl(expr->left(), eval_right, context->if_false())); } else { CHECK_BAILOUT(VisitForControl(expr->left(), context->if_true(), eval_right)); } // Translate right subexpression by visiting it in the same AST // context as the entire expression. if (eval_right->HasPredecessor()) { eval_right->SetJoinId(expr->RightId()); set_current_block(eval_right); Visit(expr->right()); } } else if (ast_context()->IsValue()) { CHECK_ALIVE(VisitForValue(expr->left())); ASSERT(current_block() != NULL); HValue* left_value = Top(); // Short-circuit left values that always evaluate to the same boolean value. if (expr->left()->ToBooleanIsTrue() || expr->left()->ToBooleanIsFalse()) { // l (evals true) && r -> r // l (evals true) || r -> l // l (evals false) && r -> l // l (evals false) || r -> r if (is_logical_and == expr->left()->ToBooleanIsTrue()) { Drop(1); CHECK_ALIVE(VisitForValue(expr->right())); } return ast_context()->ReturnValue(Pop()); } // We need an extra block to maintain edge-split form. HBasicBlock* empty_block = graph()->CreateBasicBlock(); HBasicBlock* eval_right = graph()->CreateBasicBlock(); ToBooleanStub::Types expected(expr->left()->to_boolean_types()); HBranch* test = is_logical_and ? New<HBranch>(left_value, expected, eval_right, empty_block) : New<HBranch>(left_value, expected, empty_block, eval_right); FinishCurrentBlock(test); set_current_block(eval_right); Drop(1); // Value of the left subexpression. CHECK_BAILOUT(VisitForValue(expr->right())); HBasicBlock* join_block = CreateJoin(empty_block, current_block(), expr->id()); set_current_block(join_block); return ast_context()->ReturnValue(Pop()); } else { ASSERT(ast_context()->IsEffect()); // In an effect context, we don't need the value of the left subexpression, // only its control flow and side effects. We need an extra block to // maintain edge-split form. HBasicBlock* empty_block = graph()->CreateBasicBlock(); HBasicBlock* right_block = graph()->CreateBasicBlock(); if (is_logical_and) { CHECK_BAILOUT(VisitForControl(expr->left(), right_block, empty_block)); } else { CHECK_BAILOUT(VisitForControl(expr->left(), empty_block, right_block)); } // TODO(kmillikin): Find a way to fix this. It's ugly that there are // actually two empty blocks (one here and one inserted by // TestContext::BuildBranch, and that they both have an HSimulate though the // second one is not a merge node, and that we really have no good AST ID to // put on that first HSimulate. if (empty_block->HasPredecessor()) { empty_block->SetJoinId(expr->id()); } else { empty_block = NULL; } if (right_block->HasPredecessor()) { right_block->SetJoinId(expr->RightId()); set_current_block(right_block); CHECK_BAILOUT(VisitForEffect(expr->right())); right_block = current_block(); } else { right_block = NULL; } HBasicBlock* join_block = CreateJoin(empty_block, right_block, expr->id()); set_current_block(join_block); // We did not materialize any value in the predecessor environments, // so there is no need to handle it here. } } void HOptimizedGraphBuilder::VisitArithmeticExpression(BinaryOperation* expr) { CHECK_ALIVE(VisitForValue(expr->left())); CHECK_ALIVE(VisitForValue(expr->right())); SetSourcePosition(expr->position()); HValue* right = Pop(); HValue* left = Pop(); HValue* result = BuildBinaryOperation(expr, left, right, ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE : PUSH_BEFORE_SIMULATE); if (FLAG_hydrogen_track_positions && result->IsBinaryOperation()) { HBinaryOperation::cast(result)->SetOperandPositions( zone(), ScriptPositionToSourcePosition(expr->left()->position()), ScriptPositionToSourcePosition(expr->right()->position())); } return ast_context()->ReturnValue(result); } void HOptimizedGraphBuilder::HandleLiteralCompareTypeof(CompareOperation* expr, Expression* sub_expr, Handle<String> check) { CHECK_ALIVE(VisitForTypeOf(sub_expr)); SetSourcePosition(expr->position()); HValue* value = Pop(); HTypeofIsAndBranch* instr = New<HTypeofIsAndBranch>(value, check); return ast_context()->ReturnControl(instr, expr->id()); } static bool IsLiteralCompareBool(Isolate* isolate, HValue* left, Token::Value op, HValue* right) { return op == Token::EQ_STRICT && ((left->IsConstant() && HConstant::cast(left)->handle(isolate)->IsBoolean()) || (right->IsConstant() && HConstant::cast(right)->handle(isolate)->IsBoolean())); } void HOptimizedGraphBuilder::VisitCompareOperation(CompareOperation* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position()); // Check for a few fast cases. The AST visiting behavior must be in sync // with the full codegen: We don't push both left and right values onto // the expression stack when one side is a special-case literal. Expression* sub_expr = NULL; Handle<String> check; if (expr->IsLiteralCompareTypeof(&sub_expr, &check)) { return HandleLiteralCompareTypeof(expr, sub_expr, check); } if (expr->IsLiteralCompareUndefined(&sub_expr, isolate())) { return HandleLiteralCompareNil(expr, sub_expr, kUndefinedValue); } if (expr->IsLiteralCompareNull(&sub_expr)) { return HandleLiteralCompareNil(expr, sub_expr, kNullValue); } if (IsClassOfTest(expr)) { CallRuntime* call = expr->left()->AsCallRuntime(); ASSERT(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); Literal* literal = expr->right()->AsLiteral(); Handle<String> rhs = Handle<String>::cast(literal->value()); HClassOfTestAndBranch* instr = New<HClassOfTestAndBranch>(value, rhs); return ast_context()->ReturnControl(instr, expr->id()); } Type* left_type = expr->left()->bounds().lower; Type* right_type = expr->right()->bounds().lower; Type* combined_type = expr->combined_type(); CHECK_ALIVE(VisitForValue(expr->left())); CHECK_ALIVE(VisitForValue(expr->right())); if (FLAG_hydrogen_track_positions) SetSourcePosition(expr->position()); HValue* right = Pop(); HValue* left = Pop(); Token::Value op = expr->op(); if (IsLiteralCompareBool(isolate(), left, op, right)) { HCompareObjectEqAndBranch* result = New<HCompareObjectEqAndBranch>(left, right); return ast_context()->ReturnControl(result, expr->id()); } if (op == Token::INSTANCEOF) { // Check to see if the rhs of the instanceof is a global function not // residing in new space. If it is we assume that the function will stay the // same. Handle<JSFunction> target = Handle<JSFunction>::null(); VariableProxy* proxy = expr->right()->AsVariableProxy(); bool global_function = (proxy != NULL) && proxy->var()->IsUnallocated(); if (global_function && current_info()->has_global_object() && !current_info()->global_object()->IsAccessCheckNeeded()) { Handle<String> name = proxy->name(); Handle<GlobalObject> global(current_info()->global_object()); LookupResult lookup(isolate()); global->Lookup(name, &lookup); if (lookup.IsNormal() && lookup.GetValue()->IsJSFunction()) { Handle<JSFunction> candidate(JSFunction::cast(lookup.GetValue())); // If the function is in new space we assume it's more likely to // change and thus prefer the general IC code. if (!isolate()->heap()->InNewSpace(*candidate)) { target = candidate; } } } // If the target is not null we have found a known global function that is // assumed to stay the same for this instanceof. if (target.is_null()) { HInstanceOf* result = New<HInstanceOf>(left, right); return ast_context()->ReturnInstruction(result, expr->id()); } else { Add<HCheckValue>(right, target); HInstanceOfKnownGlobal* result = New<HInstanceOfKnownGlobal>(left, target); return ast_context()->ReturnInstruction(result, expr->id()); } // Code below assumes that we don't fall through. UNREACHABLE(); } else if (op == Token::IN) { HValue* function = AddLoadJSBuiltin(Builtins::IN); Add<HPushArguments>(left, right); // TODO(olivf) InvokeFunction produces a check for the parameter count, // even though we are certain to pass the correct number of arguments here. HInstruction* result = New<HInvokeFunction>(function, 2); return ast_context()->ReturnInstruction(result, expr->id()); } PushBeforeSimulateBehavior push_behavior = ast_context()->IsEffect() ? NO_PUSH_BEFORE_SIMULATE : PUSH_BEFORE_SIMULATE; HControlInstruction* compare = BuildCompareInstruction( op, left, right, left_type, right_type, combined_type, ScriptPositionToSourcePosition(expr->left()->position()), ScriptPositionToSourcePosition(expr->right()->position()), push_behavior, expr->id()); if (compare == NULL) return; // Bailed out. return ast_context()->ReturnControl(compare, expr->id()); } HControlInstruction* HOptimizedGraphBuilder::BuildCompareInstruction( Token::Value op, HValue* left, HValue* right, Type* left_type, Type* right_type, Type* combined_type, HSourcePosition left_position, HSourcePosition right_position, PushBeforeSimulateBehavior push_sim_result, BailoutId bailout_id) { // Cases handled below depend on collected type feedback. They should // soft deoptimize when there is no type feedback. if (combined_type->Is(Type::None())) { Add<HDeoptimize>("Insufficient type feedback for combined type " "of binary operation", Deoptimizer::SOFT); combined_type = left_type = right_type = Type::Any(zone()); } Representation left_rep = Representation::FromType(left_type); Representation right_rep = Representation::FromType(right_type); Representation combined_rep = Representation::FromType(combined_type); if (combined_type->Is(Type::Receiver())) { if (Token::IsEqualityOp(op)) { // HCompareObjectEqAndBranch can only deal with object, so // exclude numbers. if ((left->IsConstant() && HConstant::cast(left)->HasNumberValue()) || (right->IsConstant() && HConstant::cast(right)->HasNumberValue())) { Add<HDeoptimize>("Type mismatch between feedback and constant", Deoptimizer::SOFT); // The caller expects a branch instruction, so make it happy. return New<HBranch>(graph()->GetConstantTrue()); } // Can we get away with map check and not instance type check? HValue* operand_to_check = left->block()->block_id() < right->block()->block_id() ? left : right; if (combined_type->IsClass()) { Handle<Map> map = combined_type->AsClass()->Map(); AddCheckMap(operand_to_check, map); HCompareObjectEqAndBranch* result = New<HCompareObjectEqAndBranch>(left, right); if (FLAG_hydrogen_track_positions) { result->set_operand_position(zone(), 0, left_position); result->set_operand_position(zone(), 1, right_position); } return result; } else { BuildCheckHeapObject(operand_to_check); Add<HCheckInstanceType>(operand_to_check, HCheckInstanceType::IS_SPEC_OBJECT); HCompareObjectEqAndBranch* result = New<HCompareObjectEqAndBranch>(left, right); return result; } } else { Bailout(kUnsupportedNonPrimitiveCompare); return NULL; } } else if (combined_type->Is(Type::InternalizedString()) && Token::IsEqualityOp(op)) { // If we have a constant argument, it should be consistent with the type // feedback (otherwise we fail assertions in HCompareObjectEqAndBranch). if ((left->IsConstant() && !HConstant::cast(left)->HasInternalizedStringValue()) || (right->IsConstant() && !HConstant::cast(right)->HasInternalizedStringValue())) { Add<HDeoptimize>("Type mismatch between feedback and constant", Deoptimizer::SOFT); // The caller expects a branch instruction, so make it happy. return New<HBranch>(graph()->GetConstantTrue()); } BuildCheckHeapObject(left); Add<HCheckInstanceType>(left, HCheckInstanceType::IS_INTERNALIZED_STRING); BuildCheckHeapObject(right); Add<HCheckInstanceType>(right, HCheckInstanceType::IS_INTERNALIZED_STRING); HCompareObjectEqAndBranch* result = New<HCompareObjectEqAndBranch>(left, right); return result; } else if (combined_type->Is(Type::String())) { BuildCheckHeapObject(left); Add<HCheckInstanceType>(left, HCheckInstanceType::IS_STRING); BuildCheckHeapObject(right); Add<HCheckInstanceType>(right, HCheckInstanceType::IS_STRING); HStringCompareAndBranch* result = New<HStringCompareAndBranch>(left, right, op); return result; } else { if (combined_rep.IsTagged() || combined_rep.IsNone()) { HCompareGeneric* result = Add<HCompareGeneric>(left, right, op); result->set_observed_input_representation(1, left_rep); result->set_observed_input_representation(2, right_rep); if (result->HasObservableSideEffects()) { if (push_sim_result == PUSH_BEFORE_SIMULATE) { Push(result); AddSimulate(bailout_id, REMOVABLE_SIMULATE); Drop(1); } else { AddSimulate(bailout_id, REMOVABLE_SIMULATE); } } // TODO(jkummerow): Can we make this more efficient? HBranch* branch = New<HBranch>(result); return branch; } else { HCompareNumericAndBranch* result = New<HCompareNumericAndBranch>(left, right, op); result->set_observed_input_representation(left_rep, right_rep); if (FLAG_hydrogen_track_positions) { result->SetOperandPositions(zone(), left_position, right_position); } return result; } } } void HOptimizedGraphBuilder::HandleLiteralCompareNil(CompareOperation* expr, Expression* sub_expr, NilValue nil) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); ASSERT(expr->op() == Token::EQ || expr->op() == Token::EQ_STRICT); if (!FLAG_hydrogen_track_positions) SetSourcePosition(expr->position()); CHECK_ALIVE(VisitForValue(sub_expr)); HValue* value = Pop(); if (expr->op() == Token::EQ_STRICT) { HConstant* nil_constant = nil == kNullValue ? graph()->GetConstantNull() : graph()->GetConstantUndefined(); HCompareObjectEqAndBranch* instr = New<HCompareObjectEqAndBranch>(value, nil_constant); return ast_context()->ReturnControl(instr, expr->id()); } else { ASSERT_EQ(Token::EQ, expr->op()); Type* type = expr->combined_type()->Is(Type::None()) ? Type::Any(zone()) : expr->combined_type(); HIfContinuation continuation; BuildCompareNil(value, type, &continuation); return ast_context()->ReturnContinuation(&continuation, expr->id()); } } HInstruction* HOptimizedGraphBuilder::BuildThisFunction() { // If we share optimized code between different closures, the // this-function is not a constant, except inside an inlined body. if (function_state()->outer() != NULL) { return New<HConstant>( function_state()->compilation_info()->closure()); } else { return New<HThisFunction>(); } } HInstruction* HOptimizedGraphBuilder::BuildFastLiteral( Handle<JSObject> boilerplate_object, AllocationSiteUsageContext* site_context) { NoObservableSideEffectsScope no_effects(this); InstanceType instance_type = boilerplate_object->map()->instance_type(); ASSERT(instance_type == JS_ARRAY_TYPE || instance_type == JS_OBJECT_TYPE); HType type = instance_type == JS_ARRAY_TYPE ? HType::JSArray() : HType::JSObject(); HValue* object_size_constant = Add<HConstant>( boilerplate_object->map()->instance_size()); PretenureFlag pretenure_flag = NOT_TENURED; if (FLAG_allocation_site_pretenuring) { pretenure_flag = site_context->current()->GetPretenureMode(); Handle<AllocationSite> site(site_context->current()); AllocationSite::AddDependentCompilationInfo( site, AllocationSite::TENURING, top_info()); } HInstruction* object = Add<HAllocate>(object_size_constant, type, pretenure_flag, instance_type, site_context->current()); // If allocation folding reaches Page::kMaxRegularHeapObjectSize the // elements array may not get folded into the object. Hence, we set the // elements pointer to empty fixed array and let store elimination remove // this store in the folding case. HConstant* empty_fixed_array = Add<HConstant>( isolate()->factory()->empty_fixed_array()); Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(), empty_fixed_array); BuildEmitObjectHeader(boilerplate_object, object); Handle<FixedArrayBase> elements(boilerplate_object->elements()); int elements_size = (elements->length() > 0 && elements->map() != isolate()->heap()->fixed_cow_array_map()) ? elements->Size() : 0; if (pretenure_flag == TENURED && elements->map() == isolate()->heap()->fixed_cow_array_map() && isolate()->heap()->InNewSpace(*elements)) { // If we would like to pretenure a fixed cow array, we must ensure that the // array is already in old space, otherwise we'll create too many old-to- // new-space pointers (overflowing the store buffer). elements = Handle<FixedArrayBase>( isolate()->factory()->CopyAndTenureFixedCOWArray( Handle<FixedArray>::cast(elements))); boilerplate_object->set_elements(*elements); } HInstruction* object_elements = NULL; if (elements_size > 0) { HValue* object_elements_size = Add<HConstant>(elements_size); InstanceType instance_type = boilerplate_object->HasFastDoubleElements() ? FIXED_DOUBLE_ARRAY_TYPE : FIXED_ARRAY_TYPE; object_elements = Add<HAllocate>( object_elements_size, HType::HeapObject(), pretenure_flag, instance_type, site_context->current()); } BuildInitElementsInObjectHeader(boilerplate_object, object, object_elements); // Copy object elements if non-COW. if (object_elements != NULL) { BuildEmitElements(boilerplate_object, elements, object_elements, site_context); } // Copy in-object properties. if (boilerplate_object->map()->NumberOfFields() != 0) { BuildEmitInObjectProperties(boilerplate_object, object, site_context, pretenure_flag); } return object; } void HOptimizedGraphBuilder::BuildEmitObjectHeader( Handle<JSObject> boilerplate_object, HInstruction* object) { ASSERT(boilerplate_object->properties()->length() == 0); Handle<Map> boilerplate_object_map(boilerplate_object->map()); AddStoreMapConstant(object, boilerplate_object_map); Handle<Object> properties_field = Handle<Object>(boilerplate_object->properties(), isolate()); ASSERT(*properties_field == isolate()->heap()->empty_fixed_array()); HInstruction* properties = Add<HConstant>(properties_field); HObjectAccess access = HObjectAccess::ForPropertiesPointer(); Add<HStoreNamedField>(object, access, properties); if (boilerplate_object->IsJSArray()) { Handle<JSArray> boilerplate_array = Handle<JSArray>::cast(boilerplate_object); Handle<Object> length_field = Handle<Object>(boilerplate_array->length(), isolate()); HInstruction* length = Add<HConstant>(length_field); ASSERT(boilerplate_array->length()->IsSmi()); Add<HStoreNamedField>(object, HObjectAccess::ForArrayLength( boilerplate_array->GetElementsKind()), length); } } void HOptimizedGraphBuilder::BuildInitElementsInObjectHeader( Handle<JSObject> boilerplate_object, HInstruction* object, HInstruction* object_elements) { ASSERT(boilerplate_object->properties()->length() == 0); if (object_elements == NULL) { Handle<Object> elements_field = Handle<Object>(boilerplate_object->elements(), isolate()); object_elements = Add<HConstant>(elements_field); } Add<HStoreNamedField>(object, HObjectAccess::ForElementsPointer(), object_elements); } void HOptimizedGraphBuilder::BuildEmitInObjectProperties( Handle<JSObject> boilerplate_object, HInstruction* object, AllocationSiteUsageContext* site_context, PretenureFlag pretenure_flag) { Handle<Map> boilerplate_map(boilerplate_object->map()); Handle<DescriptorArray> descriptors(boilerplate_map->instance_descriptors()); int limit = boilerplate_map->NumberOfOwnDescriptors(); int copied_fields = 0; for (int i = 0; i < limit; i++) { PropertyDetails details = descriptors->GetDetails(i); if (details.type() != FIELD) continue; copied_fields++; int index = descriptors->GetFieldIndex(i); int property_offset = boilerplate_object->GetInObjectPropertyOffset(index); Handle<Name> name(descriptors->GetKey(i)); Handle<Object> value = Handle<Object>(boilerplate_object->InObjectPropertyAt(index), isolate()); // The access for the store depends on the type of the boilerplate. HObjectAccess access = boilerplate_object->IsJSArray() ? HObjectAccess::ForJSArrayOffset(property_offset) : HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset); if (value->IsJSObject()) { Handle<JSObject> value_object = Handle<JSObject>::cast(value); Handle<AllocationSite> current_site = site_context->EnterNewScope(); HInstruction* result = BuildFastLiteral(value_object, site_context); site_context->ExitScope(current_site, value_object); Add<HStoreNamedField>(object, access, result); } else { Representation representation = details.representation(); HInstruction* value_instruction; if (representation.IsDouble()) { // Allocate a HeapNumber box and store the value into it. HValue* heap_number_constant = Add<HConstant>(HeapNumber::kSize); // This heap number alloc does not have a corresponding // AllocationSite. That is okay because // 1) it's a child object of another object with a valid allocation site // 2) we can just use the mode of the parent object for pretenuring HInstruction* double_box = Add<HAllocate>(heap_number_constant, HType::HeapObject(), pretenure_flag, HEAP_NUMBER_TYPE); AddStoreMapConstant(double_box, isolate()->factory()->heap_number_map()); Add<HStoreNamedField>(double_box, HObjectAccess::ForHeapNumberValue(), Add<HConstant>(value)); value_instruction = double_box; } else if (representation.IsSmi()) { value_instruction = value->IsUninitialized() ? graph()->GetConstant0() : Add<HConstant>(value); // Ensure that value is stored as smi. access = access.WithRepresentation(representation); } else { value_instruction = Add<HConstant>(value); } Add<HStoreNamedField>(object, access, value_instruction); } } int inobject_properties = boilerplate_object->map()->inobject_properties(); HInstruction* value_instruction = Add<HConstant>(isolate()->factory()->one_pointer_filler_map()); for (int i = copied_fields; i < inobject_properties; i++) { ASSERT(boilerplate_object->IsJSObject()); int property_offset = boilerplate_object->GetInObjectPropertyOffset(i); HObjectAccess access = HObjectAccess::ForMapAndOffset(boilerplate_map, property_offset); Add<HStoreNamedField>(object, access, value_instruction); } } void HOptimizedGraphBuilder::BuildEmitElements( Handle<JSObject> boilerplate_object, Handle<FixedArrayBase> elements, HValue* object_elements, AllocationSiteUsageContext* site_context) { ElementsKind kind = boilerplate_object->map()->elements_kind(); int elements_length = elements->length(); HValue* object_elements_length = Add<HConstant>(elements_length); BuildInitializeElementsHeader(object_elements, kind, object_elements_length); // Copy elements backing store content. if (elements->IsFixedDoubleArray()) { BuildEmitFixedDoubleArray(elements, kind, object_elements); } else if (elements->IsFixedArray()) { BuildEmitFixedArray(elements, kind, object_elements, site_context); } else { UNREACHABLE(); } } void HOptimizedGraphBuilder::BuildEmitFixedDoubleArray( Handle<FixedArrayBase> elements, ElementsKind kind, HValue* object_elements) { HInstruction* boilerplate_elements = Add<HConstant>(elements); int elements_length = elements->length(); for (int i = 0; i < elements_length; i++) { HValue* key_constant = Add<HConstant>(i); HInstruction* value_instruction = Add<HLoadKeyed>(boilerplate_elements, key_constant, static_cast<HValue*>(NULL), kind, ALLOW_RETURN_HOLE); HInstruction* store = Add<HStoreKeyed>(object_elements, key_constant, value_instruction, kind); store->SetFlag(HValue::kAllowUndefinedAsNaN); } } void HOptimizedGraphBuilder::BuildEmitFixedArray( Handle<FixedArrayBase> elements, ElementsKind kind, HValue* object_elements, AllocationSiteUsageContext* site_context) { HInstruction* boilerplate_elements = Add<HConstant>(elements); int elements_length = elements->length(); Handle<FixedArray> fast_elements = Handle<FixedArray>::cast(elements); for (int i = 0; i < elements_length; i++) { Handle<Object> value(fast_elements->get(i), isolate()); HValue* key_constant = Add<HConstant>(i); if (value->IsJSObject()) { Handle<JSObject> value_object = Handle<JSObject>::cast(value); Handle<AllocationSite> current_site = site_context->EnterNewScope(); HInstruction* result = BuildFastLiteral(value_object, site_context); site_context->ExitScope(current_site, value_object); Add<HStoreKeyed>(object_elements, key_constant, result, kind); } else { HInstruction* value_instruction = Add<HLoadKeyed>(boilerplate_elements, key_constant, static_cast<HValue*>(NULL), kind, ALLOW_RETURN_HOLE); Add<HStoreKeyed>(object_elements, key_constant, value_instruction, kind); } } } void HOptimizedGraphBuilder::VisitThisFunction(ThisFunction* expr) { ASSERT(!HasStackOverflow()); ASSERT(current_block() != NULL); ASSERT(current_block()->HasPredecessor()); HInstruction* instr = BuildThisFunction(); return ast_context()->ReturnInstruction(instr, expr->id()); } void HOptimizedGraphBuilder::VisitDeclarations( ZoneList<Declaration*>* declarations) { ASSERT(globals_.is_empty()); AstVisitor::VisitDeclarations(declarations); if (!globals_.is_empty()) { Handle<FixedArray> array = isolate()->factory()->NewFixedArray(globals_.length(), TENURED); for (int i = 0; i < globals_.length(); ++i) array->set(i, *globals_.at(i)); int flags = DeclareGlobalsEvalFlag::encode(current_info()->is_eval()) | DeclareGlobalsNativeFlag::encode(current_info()->is_native()) | DeclareGlobalsStrictMode::encode(current_info()->strict_mode()); Add<HDeclareGlobals>(array, flags); globals_.Rewind(0); } } void HOptimizedGraphBuilder::VisitVariableDeclaration( VariableDeclaration* declaration) { VariableProxy* proxy = declaration->proxy(); VariableMode mode = declaration->mode(); Variable* variable = proxy->var(); bool hole_init = mode == LET || mode == CONST || mode == CONST_LEGACY; switch (variable->location()) { case Variable::UNALLOCATED: globals_.Add(variable->name(), zone()); globals_.Add(variable->binding_needs_init() ? isolate()->factory()->the_hole_value() : isolate()->factory()->undefined_value(), zone()); return; case Variable::PARAMETER: case Variable::LOCAL: if (hole_init) { HValue* value = graph()->GetConstantHole(); environment()->Bind(variable, value); } break; case Variable::CONTEXT: if (hole_init) { HValue* value = graph()->GetConstantHole(); HValue* context = environment()->context(); HStoreContextSlot* store = Add<HStoreContextSlot>( context, variable->index(), HStoreContextSlot::kNoCheck, value); if (store->HasObservableSideEffects()) { Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE); } } break; case Variable::LOOKUP: return Bailout(kUnsupportedLookupSlotInDeclaration); } } void HOptimizedGraphBuilder::VisitFunctionDeclaration( FunctionDeclaration* declaration) { VariableProxy* proxy = declaration->proxy(); Variable* variable = proxy->var(); switch (variable->location()) { case Variable::UNALLOCATED: { globals_.Add(variable->name(), zone()); Handle<SharedFunctionInfo> function = Compiler::BuildFunctionInfo( declaration->fun(), current_info()->script()); // Check for stack-overflow exception. if (function.is_null()) return SetStackOverflow(); globals_.Add(function, zone()); return; } case Variable::PARAMETER: case Variable::LOCAL: { CHECK_ALIVE(VisitForValue(declaration->fun())); HValue* value = Pop(); BindIfLive(variable, value); break; } case Variable::CONTEXT: { CHECK_ALIVE(VisitForValue(declaration->fun())); HValue* value = Pop(); HValue* context = environment()->context(); HStoreContextSlot* store = Add<HStoreContextSlot>( context, variable->index(), HStoreContextSlot::kNoCheck, value); if (store->HasObservableSideEffects()) { Add<HSimulate>(proxy->id(), REMOVABLE_SIMULATE); } break; } case Variable::LOOKUP: return Bailout(kUnsupportedLookupSlotInDeclaration); } } void HOptimizedGraphBuilder::VisitModuleDeclaration( ModuleDeclaration* declaration) { UNREACHABLE(); } void HOptimizedGraphBuilder::VisitImportDeclaration( ImportDeclaration* declaration) { UNREACHABLE(); } void HOptimizedGraphBuilder::VisitExportDeclaration( ExportDeclaration* declaration) { UNREACHABLE(); } void HOptimizedGraphBuilder::VisitModuleLiteral(ModuleLiteral* module) { UNREACHABLE(); } void HOptimizedGraphBuilder::VisitModuleVariable(ModuleVariable* module) { UNREACHABLE(); } void HOptimizedGraphBuilder::VisitModulePath(ModulePath* module) { UNREACHABLE(); } void HOptimizedGraphBuilder::VisitModuleUrl(ModuleUrl* module) { UNREACHABLE(); } void HOptimizedGraphBuilder::VisitModuleStatement(ModuleStatement* stmt) { UNREACHABLE(); } // Generators for inline runtime functions. // Support for types. void HOptimizedGraphBuilder::GenerateIsSmi(CallRuntime* call) { ASSERT(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HIsSmiAndBranch* result = New<HIsSmiAndBranch>(value); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateIsSpecObject(CallRuntime* call) { ASSERT(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HHasInstanceTypeAndBranch* result = New<HHasInstanceTypeAndBranch>(value, FIRST_SPEC_OBJECT_TYPE, LAST_SPEC_OBJECT_TYPE); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateIsFunction(CallRuntime* call) { ASSERT(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HHasInstanceTypeAndBranch* result = New<HHasInstanceTypeAndBranch>(value, JS_FUNCTION_TYPE); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateIsMinusZero(CallRuntime* call) { ASSERT(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HCompareMinusZeroAndBranch* result = New<HCompareMinusZeroAndBranch>(value); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateHasCachedArrayIndex(CallRuntime* call) { ASSERT(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HHasCachedArrayIndexAndBranch* result = New<HHasCachedArrayIndexAndBranch>(value); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateIsArray(CallRuntime* call) { ASSERT(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HHasInstanceTypeAndBranch* result = New<HHasInstanceTypeAndBranch>(value, JS_ARRAY_TYPE); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateIsRegExp(CallRuntime* call) { ASSERT(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HHasInstanceTypeAndBranch* result = New<HHasInstanceTypeAndBranch>(value, JS_REGEXP_TYPE); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateIsObject(CallRuntime* call) { ASSERT(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HIsObjectAndBranch* result = New<HIsObjectAndBranch>(value); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateIsNonNegativeSmi(CallRuntime* call) { return Bailout(kInlinedRuntimeFunctionIsNonNegativeSmi); } void HOptimizedGraphBuilder::GenerateIsUndetectableObject(CallRuntime* call) { ASSERT(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HIsUndetectableAndBranch* result = New<HIsUndetectableAndBranch>(value); return ast_context()->ReturnControl(result, call->id()); } void HOptimizedGraphBuilder::GenerateIsStringWrapperSafeForDefaultValueOf( CallRuntime* call) { return Bailout(kInlinedRuntimeFunctionIsStringWrapperSafeForDefaultValueOf); } // Support for construct call checks. void HOptimizedGraphBuilder::GenerateIsConstructCall(CallRuntime* call) { ASSERT(call->arguments()->length() == 0); if (function_state()->outer() != NULL) { // We are generating graph for inlined function. HValue* value = function_state()->inlining_kind() == CONSTRUCT_CALL_RETURN ? graph()->GetConstantTrue() : graph()->GetConstantFalse(); return ast_context()->ReturnValue(value); } else { return ast_context()->ReturnControl(New<HIsConstructCallAndBranch>(), call->id()); } } // Support for arguments.length and arguments[?]. void HOptimizedGraphBuilder::GenerateArgumentsLength(CallRuntime* call) { // Our implementation of arguments (based on this stack frame or an // adapter below it) does not work for inlined functions. This runtime // function is blacklisted by AstNode::IsInlineable. ASSERT(function_state()->outer() == NULL); ASSERT(call->arguments()->length() == 0); HInstruction* elements = Add<HArgumentsElements>(false); HArgumentsLength* result = New<HArgumentsLength>(elements); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateArguments(CallRuntime* call) { // Our implementation of arguments (based on this stack frame or an // adapter below it) does not work for inlined functions. This runtime // function is blacklisted by AstNode::IsInlineable. ASSERT(function_state()->outer() == NULL); ASSERT(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* index = Pop(); HInstruction* elements = Add<HArgumentsElements>(false); HInstruction* length = Add<HArgumentsLength>(elements); HInstruction* checked_index = Add<HBoundsCheck>(index, length); HAccessArgumentsAt* result = New<HAccessArgumentsAt>( elements, length, checked_index); return ast_context()->ReturnInstruction(result, call->id()); } // Support for accessing the class and value fields of an object. void HOptimizedGraphBuilder::GenerateClassOf(CallRuntime* call) { // The special form detected by IsClassOfTest is detected before we get here // and does not cause a bailout. return Bailout(kInlinedRuntimeFunctionClassOf); } void HOptimizedGraphBuilder::GenerateValueOf(CallRuntime* call) { ASSERT(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* object = Pop(); IfBuilder if_objectisvalue(this); HValue* objectisvalue = if_objectisvalue.If<HHasInstanceTypeAndBranch>( object, JS_VALUE_TYPE); if_objectisvalue.Then(); { // Return the actual value. Push(Add<HLoadNamedField>( object, objectisvalue, HObjectAccess::ForObservableJSObjectOffset( JSValue::kValueOffset))); Add<HSimulate>(call->id(), FIXED_SIMULATE); } if_objectisvalue.Else(); { // If the object is not a value return the object. Push(object); Add<HSimulate>(call->id(), FIXED_SIMULATE); } if_objectisvalue.End(); return ast_context()->ReturnValue(Pop()); } void HOptimizedGraphBuilder::GenerateDateField(CallRuntime* call) { ASSERT(call->arguments()->length() == 2); ASSERT_NE(NULL, call->arguments()->at(1)->AsLiteral()); Smi* index = Smi::cast(*(call->arguments()->at(1)->AsLiteral()->value())); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* date = Pop(); HDateField* result = New<HDateField>(date, index); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateOneByteSeqStringSetChar( CallRuntime* call) { ASSERT(call->arguments()->length() == 3); // We need to follow the evaluation order of full codegen. CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); CHECK_ALIVE(VisitForValue(call->arguments()->at(2))); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* string = Pop(); HValue* value = Pop(); HValue* index = Pop(); Add<HSeqStringSetChar>(String::ONE_BYTE_ENCODING, string, index, value); Add<HSimulate>(call->id(), FIXED_SIMULATE); return ast_context()->ReturnValue(graph()->GetConstantUndefined()); } void HOptimizedGraphBuilder::GenerateTwoByteSeqStringSetChar( CallRuntime* call) { ASSERT(call->arguments()->length() == 3); // We need to follow the evaluation order of full codegen. CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); CHECK_ALIVE(VisitForValue(call->arguments()->at(2))); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* string = Pop(); HValue* value = Pop(); HValue* index = Pop(); Add<HSeqStringSetChar>(String::TWO_BYTE_ENCODING, string, index, value); Add<HSimulate>(call->id(), FIXED_SIMULATE); return ast_context()->ReturnValue(graph()->GetConstantUndefined()); } void HOptimizedGraphBuilder::GenerateSetValueOf(CallRuntime* call) { ASSERT(call->arguments()->length() == 2); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* value = Pop(); HValue* object = Pop(); // Check if object is a JSValue. IfBuilder if_objectisvalue(this); if_objectisvalue.If<HHasInstanceTypeAndBranch>(object, JS_VALUE_TYPE); if_objectisvalue.Then(); { // Create in-object property store to kValueOffset. Add<HStoreNamedField>(object, HObjectAccess::ForObservableJSObjectOffset(JSValue::kValueOffset), value); if (!ast_context()->IsEffect()) { Push(value); } Add<HSimulate>(call->id(), FIXED_SIMULATE); } if_objectisvalue.Else(); { // Nothing to do in this case. if (!ast_context()->IsEffect()) { Push(value); } Add<HSimulate>(call->id(), FIXED_SIMULATE); } if_objectisvalue.End(); if (!ast_context()->IsEffect()) { Drop(1); } return ast_context()->ReturnValue(value); } // Fast support for charCodeAt(n). void HOptimizedGraphBuilder::GenerateStringCharCodeAt(CallRuntime* call) { ASSERT(call->arguments()->length() == 2); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* index = Pop(); HValue* string = Pop(); HInstruction* result = BuildStringCharCodeAt(string, index); return ast_context()->ReturnInstruction(result, call->id()); } // Fast support for string.charAt(n) and string[n]. void HOptimizedGraphBuilder::GenerateStringCharFromCode(CallRuntime* call) { ASSERT(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* char_code = Pop(); HInstruction* result = NewUncasted<HStringCharFromCode>(char_code); return ast_context()->ReturnInstruction(result, call->id()); } // Fast support for string.charAt(n) and string[n]. void HOptimizedGraphBuilder::GenerateStringCharAt(CallRuntime* call) { ASSERT(call->arguments()->length() == 2); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* index = Pop(); HValue* string = Pop(); HInstruction* char_code = BuildStringCharCodeAt(string, index); AddInstruction(char_code); HInstruction* result = NewUncasted<HStringCharFromCode>(char_code); return ast_context()->ReturnInstruction(result, call->id()); } // Fast support for object equality testing. void HOptimizedGraphBuilder::GenerateObjectEquals(CallRuntime* call) { ASSERT(call->arguments()->length() == 2); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* right = Pop(); HValue* left = Pop(); HCompareObjectEqAndBranch* result = New<HCompareObjectEqAndBranch>(left, right); return ast_context()->ReturnControl(result, call->id()); } // Fast support for StringAdd. void HOptimizedGraphBuilder::GenerateStringAdd(CallRuntime* call) { ASSERT_EQ(2, call->arguments()->length()); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* right = Pop(); HValue* left = Pop(); HInstruction* result = NewUncasted<HStringAdd>(left, right); return ast_context()->ReturnInstruction(result, call->id()); } // Fast support for SubString. void HOptimizedGraphBuilder::GenerateSubString(CallRuntime* call) { ASSERT_EQ(3, call->arguments()->length()); CHECK_ALIVE(VisitExpressions(call->arguments())); PushArgumentsFromEnvironment(call->arguments()->length()); HCallStub* result = New<HCallStub>(CodeStub::SubString, 3); return ast_context()->ReturnInstruction(result, call->id()); } // Fast support for StringCompare. void HOptimizedGraphBuilder::GenerateStringCompare(CallRuntime* call) { ASSERT_EQ(2, call->arguments()->length()); CHECK_ALIVE(VisitExpressions(call->arguments())); PushArgumentsFromEnvironment(call->arguments()->length()); HCallStub* result = New<HCallStub>(CodeStub::StringCompare, 2); return ast_context()->ReturnInstruction(result, call->id()); } // Support for direct calls from JavaScript to native RegExp code. void HOptimizedGraphBuilder::GenerateRegExpExec(CallRuntime* call) { ASSERT_EQ(4, call->arguments()->length()); CHECK_ALIVE(VisitExpressions(call->arguments())); PushArgumentsFromEnvironment(call->arguments()->length()); HCallStub* result = New<HCallStub>(CodeStub::RegExpExec, 4); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateDoubleLo(CallRuntime* call) { ASSERT_EQ(1, call->arguments()->length()); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::LOW); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateDoubleHi(CallRuntime* call) { ASSERT_EQ(1, call->arguments()->length()); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HInstruction* result = NewUncasted<HDoubleBits>(value, HDoubleBits::HIGH); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateConstructDouble(CallRuntime* call) { ASSERT_EQ(2, call->arguments()->length()); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* lo = Pop(); HValue* hi = Pop(); HInstruction* result = NewUncasted<HConstructDouble>(hi, lo); return ast_context()->ReturnInstruction(result, call->id()); } // Construct a RegExp exec result with two in-object properties. void HOptimizedGraphBuilder::GenerateRegExpConstructResult(CallRuntime* call) { ASSERT_EQ(3, call->arguments()->length()); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); CHECK_ALIVE(VisitForValue(call->arguments()->at(2))); HValue* input = Pop(); HValue* index = Pop(); HValue* length = Pop(); HValue* result = BuildRegExpConstructResult(length, index, input); return ast_context()->ReturnValue(result); } // Support for fast native caches. void HOptimizedGraphBuilder::GenerateGetFromCache(CallRuntime* call) { return Bailout(kInlinedRuntimeFunctionGetFromCache); } // Fast support for number to string. void HOptimizedGraphBuilder::GenerateNumberToString(CallRuntime* call) { ASSERT_EQ(1, call->arguments()->length()); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* number = Pop(); HValue* result = BuildNumberToString(number, Type::Any(zone())); return ast_context()->ReturnValue(result); } // Fast call for custom callbacks. void HOptimizedGraphBuilder::GenerateCallFunction(CallRuntime* call) { // 1 ~ The function to call is not itself an argument to the call. int arg_count = call->arguments()->length() - 1; ASSERT(arg_count >= 1); // There's always at least a receiver. CHECK_ALIVE(VisitExpressions(call->arguments())); // The function is the last argument HValue* function = Pop(); // Push the arguments to the stack PushArgumentsFromEnvironment(arg_count); IfBuilder if_is_jsfunction(this); if_is_jsfunction.If<HHasInstanceTypeAndBranch>(function, JS_FUNCTION_TYPE); if_is_jsfunction.Then(); { HInstruction* invoke_result = Add<HInvokeFunction>(function, arg_count); if (!ast_context()->IsEffect()) { Push(invoke_result); } Add<HSimulate>(call->id(), FIXED_SIMULATE); } if_is_jsfunction.Else(); { HInstruction* call_result = Add<HCallFunction>(function, arg_count); if (!ast_context()->IsEffect()) { Push(call_result); } Add<HSimulate>(call->id(), FIXED_SIMULATE); } if_is_jsfunction.End(); if (ast_context()->IsEffect()) { // EffectContext::ReturnValue ignores the value, so we can just pass // 'undefined' (as we do not have the call result anymore). return ast_context()->ReturnValue(graph()->GetConstantUndefined()); } else { return ast_context()->ReturnValue(Pop()); } } // Fast call to math functions. void HOptimizedGraphBuilder::GenerateMathPow(CallRuntime* call) { ASSERT_EQ(2, call->arguments()->length()); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); CHECK_ALIVE(VisitForValue(call->arguments()->at(1))); HValue* right = Pop(); HValue* left = Pop(); HInstruction* result = NewUncasted<HPower>(left, right); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateMathLogRT(CallRuntime* call) { ASSERT(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathLog); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateMathSqrtRT(CallRuntime* call) { ASSERT(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HInstruction* result = NewUncasted<HUnaryMathOperation>(value, kMathSqrt); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateGetCachedArrayIndex(CallRuntime* call) { ASSERT(call->arguments()->length() == 1); CHECK_ALIVE(VisitForValue(call->arguments()->at(0))); HValue* value = Pop(); HGetCachedArrayIndex* result = New<HGetCachedArrayIndex>(value); return ast_context()->ReturnInstruction(result, call->id()); } void HOptimizedGraphBuilder::GenerateFastAsciiArrayJoin(CallRuntime* call) { return Bailout(kInlinedRuntimeFunctionFastAsciiArrayJoin); } // Support for generators. void HOptimizedGraphBuilder::GenerateGeneratorNext(CallRuntime* call) { return Bailout(kInlinedRuntimeFunctionGeneratorNext); } void HOptimizedGraphBuilder::GenerateGeneratorThrow(CallRuntime* call) { return Bailout(kInlinedRuntimeFunctionGeneratorThrow); } void HOptimizedGraphBuilder::GenerateDebugBreakInOptimizedCode( CallRuntime* call) { Add<HDebugBreak>(); return ast_context()->ReturnValue(graph()->GetConstant0()); } void HOptimizedGraphBuilder::GenerateDebugIsActive(CallRuntime* call) { ASSERT(call->arguments()->length() == 0); HValue* ref = Add<HConstant>(ExternalReference::debug_is_active_address(isolate())); HValue* value = Add<HLoadNamedField>( ref, static_cast<HValue*>(NULL), HObjectAccess::ForExternalUInteger8()); return ast_context()->ReturnValue(value); } #undef CHECK_BAILOUT #undef CHECK_ALIVE HEnvironment::HEnvironment(HEnvironment* outer, Scope* scope, Handle<JSFunction> closure, Zone* zone) : closure_(closure), values_(0, zone), frame_type_(JS_FUNCTION), parameter_count_(0), specials_count_(1), local_count_(0), outer_(outer), entry_(NULL), pop_count_(0), push_count_(0), ast_id_(BailoutId::None()), zone_(zone) { Scope* declaration_scope = scope->DeclarationScope(); Initialize(declaration_scope->num_parameters() + 1, declaration_scope->num_stack_slots(), 0); } HEnvironment::HEnvironment(Zone* zone, int parameter_count) : values_(0, zone), frame_type_(STUB), parameter_count_(parameter_count), specials_count_(1), local_count_(0), outer_(NULL), entry_(NULL), pop_count_(0), push_count_(0), ast_id_(BailoutId::None()), zone_(zone) { Initialize(parameter_count, 0, 0); } HEnvironment::HEnvironment(const HEnvironment* other, Zone* zone) : values_(0, zone), frame_type_(JS_FUNCTION), parameter_count_(0), specials_count_(0), local_count_(0), outer_(NULL), entry_(NULL), pop_count_(0), push_count_(0), ast_id_(other->ast_id()), zone_(zone) { Initialize(other); } HEnvironment::HEnvironment(HEnvironment* outer, Handle<JSFunction> closure, FrameType frame_type, int arguments, Zone* zone) : closure_(closure), values_(arguments, zone), frame_type_(frame_type), parameter_count_(arguments), specials_count_(0), local_count_(0), outer_(outer), entry_(NULL), pop_count_(0), push_count_(0), ast_id_(BailoutId::None()), zone_(zone) { } void HEnvironment::Initialize(int parameter_count, int local_count, int stack_height) { parameter_count_ = parameter_count; local_count_ = local_count; // Avoid reallocating the temporaries' backing store on the first Push. int total = parameter_count + specials_count_ + local_count + stack_height; values_.Initialize(total + 4, zone()); for (int i = 0; i < total; ++i) values_.Add(NULL, zone()); } void HEnvironment::Initialize(const HEnvironment* other) { closure_ = other->closure(); values_.AddAll(other->values_, zone()); assigned_variables_.Union(other->assigned_variables_, zone()); frame_type_ = other->frame_type_; parameter_count_ = other->parameter_count_; local_count_ = other->local_count_; if (other->outer_ != NULL) outer_ = other->outer_->Copy(); // Deep copy. entry_ = other->entry_; pop_count_ = other->pop_count_; push_count_ = other->push_count_; specials_count_ = other->specials_count_; ast_id_ = other->ast_id_; } void HEnvironment::AddIncomingEdge(HBasicBlock* block, HEnvironment* other) { ASSERT(!block->IsLoopHeader()); ASSERT(values_.length() == other->values_.length()); int length = values_.length(); for (int i = 0; i < length; ++i) { HValue* value = values_[i]; if (value != NULL && value->IsPhi() && value->block() == block) { // There is already a phi for the i'th value. HPhi* phi = HPhi::cast(value); // Assert index is correct and that we haven't missed an incoming edge. ASSERT(phi->merged_index() == i || !phi->HasMergedIndex()); ASSERT(phi->OperandCount() == block->predecessors()->length()); phi->AddInput(other->values_[i]); } else if (values_[i] != other->values_[i]) { // There is a fresh value on the incoming edge, a phi is needed. ASSERT(values_[i] != NULL && other->values_[i] != NULL); HPhi* phi = block->AddNewPhi(i); HValue* old_value = values_[i]; for (int j = 0; j < block->predecessors()->length(); j++) { phi->AddInput(old_value); } phi->AddInput(other->values_[i]); this->values_[i] = phi; } } } void HEnvironment::Bind(int index, HValue* value) { ASSERT(value != NULL); assigned_variables_.Add(index, zone()); values_[index] = value; } bool HEnvironment::HasExpressionAt(int index) const { return index >= parameter_count_ + specials_count_ + local_count_; } bool HEnvironment::ExpressionStackIsEmpty() const { ASSERT(length() >= first_expression_index()); return length() == first_expression_index(); } void HEnvironment::SetExpressionStackAt(int index_from_top, HValue* value) { int count = index_from_top + 1; int index = values_.length() - count; ASSERT(HasExpressionAt(index)); // The push count must include at least the element in question or else // the new value will not be included in this environment's history. if (push_count_ < count) { // This is the same effect as popping then re-pushing 'count' elements. pop_count_ += (count - push_count_); push_count_ = count; } values_[index] = value; } void HEnvironment::Drop(int count) { for (int i = 0; i < count; ++i) { Pop(); } } HEnvironment* HEnvironment::Copy() const { return new(zone()) HEnvironment(this, zone()); } HEnvironment* HEnvironment::CopyWithoutHistory() const { HEnvironment* result = Copy(); result->ClearHistory(); return result; } HEnvironment* HEnvironment::CopyAsLoopHeader(HBasicBlock* loop_header) const { HEnvironment* new_env = Copy(); for (int i = 0; i < values_.length(); ++i) { HPhi* phi = loop_header->AddNewPhi(i); phi->AddInput(values_[i]); new_env->values_[i] = phi; } new_env->ClearHistory(); return new_env; } HEnvironment* HEnvironment::CreateStubEnvironment(HEnvironment* outer, Handle<JSFunction> target, FrameType frame_type, int arguments) const { HEnvironment* new_env = new(zone()) HEnvironment(outer, target, frame_type, arguments + 1, zone()); for (int i = 0; i <= arguments; ++i) { // Include receiver. new_env->Push(ExpressionStackAt(arguments - i)); } new_env->ClearHistory(); return new_env; } HEnvironment* HEnvironment::CopyForInlining( Handle<JSFunction> target, int arguments, FunctionLiteral* function, HConstant* undefined, InliningKind inlining_kind) const { ASSERT(frame_type() == JS_FUNCTION); // Outer environment is a copy of this one without the arguments. int arity = function->scope()->num_parameters(); HEnvironment* outer = Copy(); outer->Drop(arguments + 1); // Including receiver. outer->ClearHistory(); if (inlining_kind == CONSTRUCT_CALL_RETURN) { // Create artificial constructor stub environment. The receiver should // actually be the constructor function, but we pass the newly allocated // object instead, DoComputeConstructStubFrame() relies on that. outer = CreateStubEnvironment(outer, target, JS_CONSTRUCT, arguments); } else if (inlining_kind == GETTER_CALL_RETURN) { // We need an additional StackFrame::INTERNAL frame for restoring the // correct context. outer = CreateStubEnvironment(outer, target, JS_GETTER, arguments); } else if (inlining_kind == SETTER_CALL_RETURN) { // We need an additional StackFrame::INTERNAL frame for temporarily saving // the argument of the setter, see StoreStubCompiler::CompileStoreViaSetter. outer = CreateStubEnvironment(outer, target, JS_SETTER, arguments); } if (arity != arguments) { // Create artificial arguments adaptation environment. outer = CreateStubEnvironment(outer, target, ARGUMENTS_ADAPTOR, arguments); } HEnvironment* inner = new(zone()) HEnvironment(outer, function->scope(), target, zone()); // Get the argument values from the original environment. for (int i = 0; i <= arity; ++i) { // Include receiver. HValue* push = (i <= arguments) ? ExpressionStackAt(arguments - i) : undefined; inner->SetValueAt(i, push); } inner->SetValueAt(arity + 1, context()); for (int i = arity + 2; i < inner->length(); ++i) { inner->SetValueAt(i, undefined); } inner->set_ast_id(BailoutId::FunctionEntry()); return inner; } void HEnvironment::PrintTo(StringStream* stream) { for (int i = 0; i < length(); i++) { if (i == 0) stream->Add("parameters\n"); if (i == parameter_count()) stream->Add("specials\n"); if (i == parameter_count() + specials_count()) stream->Add("locals\n"); if (i == parameter_count() + specials_count() + local_count()) { stream->Add("expressions\n"); } HValue* val = values_.at(i); stream->Add("%d: ", i); if (val != NULL) { val->PrintNameTo(stream); } else { stream->Add("NULL"); } stream->Add("\n"); } PrintF("\n"); } void HEnvironment::PrintToStd() { HeapStringAllocator string_allocator; StringStream trace(&string_allocator); PrintTo(&trace); PrintF("%s", trace.ToCString().get()); } void HTracer::TraceCompilation(CompilationInfo* info) { Tag tag(this, "compilation"); if (info->IsOptimizing()) { Handle<String> name = info->function()->debug_name(); PrintStringProperty("name", name->ToCString().get()); PrintIndent(); trace_.Add("method \"%s:%d\"\n", name->ToCString().get(), info->optimization_id()); } else { CodeStub::Major major_key = info->code_stub()->MajorKey(); PrintStringProperty("name", CodeStub::MajorName(major_key, false)); PrintStringProperty("method", "stub"); } PrintLongProperty("date", static_cast<int64_t>(OS::TimeCurrentMillis())); } void HTracer::TraceLithium(const char* name, LChunk* chunk) { ASSERT(!chunk->isolate()->concurrent_recompilation_enabled()); AllowHandleDereference allow_deref; AllowDeferredHandleDereference allow_deferred_deref; Trace(name, chunk->graph(), chunk); } void HTracer::TraceHydrogen(const char* name, HGraph* graph) { ASSERT(!graph->isolate()->concurrent_recompilation_enabled()); AllowHandleDereference allow_deref; AllowDeferredHandleDereference allow_deferred_deref; Trace(name, graph, NULL); } void HTracer::Trace(const char* name, HGraph* graph, LChunk* chunk) { Tag tag(this, "cfg"); PrintStringProperty("name", name); const ZoneList<HBasicBlock*>* blocks = graph->blocks(); for (int i = 0; i < blocks->length(); i++) { HBasicBlock* current = blocks->at(i); Tag block_tag(this, "block"); PrintBlockProperty("name", current->block_id()); PrintIntProperty("from_bci", -1); PrintIntProperty("to_bci", -1); if (!current->predecessors()->is_empty()) { PrintIndent(); trace_.Add("predecessors"); for (int j = 0; j < current->predecessors()->length(); ++j) { trace_.Add(" \"B%d\"", current->predecessors()->at(j)->block_id()); } trace_.Add("\n"); } else { PrintEmptyProperty("predecessors"); } if (current->end()->SuccessorCount() == 0) { PrintEmptyProperty("successors"); } else { PrintIndent(); trace_.Add("successors"); for (HSuccessorIterator it(current->end()); !it.Done(); it.Advance()) { trace_.Add(" \"B%d\"", it.Current()->block_id()); } trace_.Add("\n"); } PrintEmptyProperty("xhandlers"); { PrintIndent(); trace_.Add("flags"); if (current->IsLoopSuccessorDominator()) { trace_.Add(" \"dom-loop-succ\""); } if (current->IsUnreachable()) { trace_.Add(" \"dead\""); } if (current->is_osr_entry()) { trace_.Add(" \"osr\""); } trace_.Add("\n"); } if (current->dominator() != NULL) { PrintBlockProperty("dominator", current->dominator()->block_id()); } PrintIntProperty("loop_depth", current->LoopNestingDepth()); if (chunk != NULL) { int first_index = current->first_instruction_index(); int last_index = current->last_instruction_index(); PrintIntProperty( "first_lir_id", LifetimePosition::FromInstructionIndex(first_index).Value()); PrintIntProperty( "last_lir_id", LifetimePosition::FromInstructionIndex(last_index).Value()); } { Tag states_tag(this, "states"); Tag locals_tag(this, "locals"); int total = current->phis()->length(); PrintIntProperty("size", current->phis()->length()); PrintStringProperty("method", "None"); for (int j = 0; j < total; ++j) { HPhi* phi = current->phis()->at(j); PrintIndent(); trace_.Add("%d ", phi->merged_index()); phi->PrintNameTo(&trace_); trace_.Add(" "); phi->PrintTo(&trace_); trace_.Add("\n"); } } { Tag HIR_tag(this, "HIR"); for (HInstructionIterator it(current); !it.Done(); it.Advance()) { HInstruction* instruction = it.Current(); int uses = instruction->UseCount(); PrintIndent(); trace_.Add("0 %d ", uses); instruction->PrintNameTo(&trace_); trace_.Add(" "); instruction->PrintTo(&trace_); if (FLAG_hydrogen_track_positions && instruction->has_position() && instruction->position().raw() != 0) { const HSourcePosition pos = instruction->position(); trace_.Add(" pos:"); if (pos.inlining_id() != 0) { trace_.Add("%d_", pos.inlining_id()); } trace_.Add("%d", pos.position()); } trace_.Add(" <|@\n"); } } if (chunk != NULL) { Tag LIR_tag(this, "LIR"); int first_index = current->first_instruction_index(); int last_index = current->last_instruction_index(); if (first_index != -1 && last_index != -1) { const ZoneList<LInstruction*>* instructions = chunk->instructions(); for (int i = first_index; i <= last_index; ++i) { LInstruction* linstr = instructions->at(i); if (linstr != NULL) { PrintIndent(); trace_.Add("%d ", LifetimePosition::FromInstructionIndex(i).Value()); linstr->PrintTo(&trace_); trace_.Add(" [hir:"); linstr->hydrogen_value()->PrintNameTo(&trace_); trace_.Add("]"); trace_.Add(" <|@\n"); } } } } } } void HTracer::TraceLiveRanges(const char* name, LAllocator* allocator) { Tag tag(this, "intervals"); PrintStringProperty("name", name); const Vector<LiveRange*>* fixed_d = allocator->fixed_double_live_ranges(); for (int i = 0; i < fixed_d->length(); ++i) { TraceLiveRange(fixed_d->at(i), "fixed", allocator->zone()); } const Vector<LiveRange*>* fixed = allocator->fixed_live_ranges(); for (int i = 0; i < fixed->length(); ++i) { TraceLiveRange(fixed->at(i), "fixed", allocator->zone()); } const ZoneList<LiveRange*>* live_ranges = allocator->live_ranges(); for (int i = 0; i < live_ranges->length(); ++i) { TraceLiveRange(live_ranges->at(i), "object", allocator->zone()); } } void HTracer::TraceLiveRange(LiveRange* range, const char* type, Zone* zone) { if (range != NULL && !range->IsEmpty()) { PrintIndent(); trace_.Add("%d %s", range->id(), type); if (range->HasRegisterAssigned()) { LOperand* op = range->CreateAssignedOperand(zone); int assigned_reg = op->index(); if (op->IsDoubleRegister()) { trace_.Add(" \"%s\"", DoubleRegister::AllocationIndexToString(assigned_reg)); } else { ASSERT(op->IsRegister()); trace_.Add(" \"%s\"", Register::AllocationIndexToString(assigned_reg)); } } else if (range->IsSpilled()) { LOperand* op = range->TopLevel()->GetSpillOperand(); if (op->IsDoubleStackSlot()) { trace_.Add(" \"double_stack:%d\"", op->index()); } else { ASSERT(op->IsStackSlot()); trace_.Add(" \"stack:%d\"", op->index()); } } int parent_index = -1; if (range->IsChild()) { parent_index = range->parent()->id(); } else { parent_index = range->id(); } LOperand* op = range->FirstHint(); int hint_index = -1; if (op != NULL && op->IsUnallocated()) { hint_index = LUnallocated::cast(op)->virtual_register(); } trace_.Add(" %d %d", parent_index, hint_index); UseInterval* cur_interval = range->first_interval(); while (cur_interval != NULL && range->Covers(cur_interval->start())) { trace_.Add(" [%d, %d[", cur_interval->start().Value(), cur_interval->end().Value()); cur_interval = cur_interval->next(); } UsePosition* current_pos = range->first_pos(); while (current_pos != NULL) { if (current_pos->RegisterIsBeneficial() || FLAG_trace_all_uses) { trace_.Add(" %d M", current_pos->pos().Value()); } current_pos = current_pos->next(); } trace_.Add(" \"\"\n"); } } void HTracer::FlushToFile() { AppendChars(filename_.start(), trace_.ToCString().get(), trace_.length(), false); trace_.Reset(); } void HStatistics::Initialize(CompilationInfo* info) { if (info->shared_info().is_null()) return; source_size_ += info->shared_info()->SourceSize(); } void HStatistics::Print() { PrintF("Timing results:\n"); TimeDelta sum; for (int i = 0; i < times_.length(); ++i) { sum += times_[i]; } for (int i = 0; i < names_.length(); ++i) { PrintF("%32s", names_[i]); double ms = times_[i].InMillisecondsF(); double percent = times_[i].PercentOf(sum); PrintF(" %8.3f ms / %4.1f %% ", ms, percent); unsigned size = sizes_[i]; double size_percent = static_cast<double>(size) * 100 / total_size_; PrintF(" %9u bytes / %4.1f %%\n", size, size_percent); } PrintF("----------------------------------------" "---------------------------------------\n"); TimeDelta total = create_graph_ + optimize_graph_ + generate_code_; PrintF("%32s %8.3f ms / %4.1f %% \n", "Create graph", create_graph_.InMillisecondsF(), create_graph_.PercentOf(total)); PrintF("%32s %8.3f ms / %4.1f %% \n", "Optimize graph", optimize_graph_.InMillisecondsF(), optimize_graph_.PercentOf(total)); PrintF("%32s %8.3f ms / %4.1f %% \n", "Generate and install code", generate_code_.InMillisecondsF(), generate_code_.PercentOf(total)); PrintF("----------------------------------------" "---------------------------------------\n"); PrintF("%32s %8.3f ms (%.1f times slower than full code gen)\n", "Total", total.InMillisecondsF(), total.TimesOf(full_code_gen_)); double source_size_in_kb = static_cast<double>(source_size_) / 1024; double normalized_time = source_size_in_kb > 0 ? total.InMillisecondsF() / source_size_in_kb : 0; double normalized_size_in_kb = source_size_in_kb > 0 ? total_size_ / 1024 / source_size_in_kb : 0; PrintF("%32s %8.3f ms %7.3f kB allocated\n", "Average per kB source", normalized_time, normalized_size_in_kb); } void HStatistics::SaveTiming(const char* name, TimeDelta time, unsigned size) { total_size_ += size; for (int i = 0; i < names_.length(); ++i) { if (strcmp(names_[i], name) == 0) { times_[i] += time; sizes_[i] += size; return; } } names_.Add(name); times_.Add(time); sizes_.Add(size); } HPhase::~HPhase() { if (ShouldProduceTraceOutput()) { isolate()->GetHTracer()->TraceHydrogen(name(), graph_); } #ifdef DEBUG graph_->Verify(false); // No full verify. #endif } } } // namespace v8::internal
438,399
134,313
#include "../../headers/data/Face.h" Face::Face() {} Face::~Face() { vertices.clear(); vertices.shrink_to_fit(); normais.clear(); normais.shrink_to_fit(); textures.clear(); textures.shrink_to_fit(); } void Face::addVerticeId(int idVertice) { this->vertices.push_back(idVertice); } void Face::addNormalId(int idNormal) { this->normais.push_back(idNormal); } void Face::addTextureId(int idTexture) { this->textures.push_back(idTexture); }
470
188
#include "StdAfx.h" #include "ThirdStandardDataModel.h" CThirdStandardDataModel::CThirdStandardDataModel(void) { } CThirdStandardDataModel::~CThirdStandardDataModel(void) { }
177
69
// Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.Completed_B697D9B445CA2BFDB1328D93C33FBCF3 // (HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // struct FGameplayAbilityTargetDataHandle TargetData (ConstParm, Parm, OutParm, ReferenceParm) // struct FGameplayTag ApplicationTag (Parm) void UGA_DefaultPlayer_InteractSearch_C::Completed_B697D9B445CA2BFDB1328D93C33FBCF3(const struct FGameplayAbilityTargetDataHandle& TargetData, const struct FGameplayTag& ApplicationTag) { static auto fn = UObject::FindObject<UFunction>("Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.Completed_B697D9B445CA2BFDB1328D93C33FBCF3"); UGA_DefaultPlayer_InteractSearch_C_Completed_B697D9B445CA2BFDB1328D93C33FBCF3_Params params; params.TargetData = TargetData; params.ApplicationTag = ApplicationTag; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.Cancelled_B697D9B445CA2BFDB1328D93C33FBCF3 // (HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // struct FGameplayAbilityTargetDataHandle TargetData (ConstParm, Parm, OutParm, ReferenceParm) // struct FGameplayTag ApplicationTag (Parm) void UGA_DefaultPlayer_InteractSearch_C::Cancelled_B697D9B445CA2BFDB1328D93C33FBCF3(const struct FGameplayAbilityTargetDataHandle& TargetData, const struct FGameplayTag& ApplicationTag) { static auto fn = UObject::FindObject<UFunction>("Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.Cancelled_B697D9B445CA2BFDB1328D93C33FBCF3"); UGA_DefaultPlayer_InteractSearch_C_Cancelled_B697D9B445CA2BFDB1328D93C33FBCF3_Params params; params.TargetData = TargetData; params.ApplicationTag = ApplicationTag; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.Triggered_B697D9B445CA2BFDB1328D93C33FBCF3 // (HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // struct FGameplayAbilityTargetDataHandle TargetData (ConstParm, Parm, OutParm, ReferenceParm) // struct FGameplayTag ApplicationTag (Parm) void UGA_DefaultPlayer_InteractSearch_C::Triggered_B697D9B445CA2BFDB1328D93C33FBCF3(const struct FGameplayAbilityTargetDataHandle& TargetData, const struct FGameplayTag& ApplicationTag) { static auto fn = UObject::FindObject<UFunction>("Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.Triggered_B697D9B445CA2BFDB1328D93C33FBCF3"); UGA_DefaultPlayer_InteractSearch_C_Triggered_B697D9B445CA2BFDB1328D93C33FBCF3_Params params; params.TargetData = TargetData; params.ApplicationTag = ApplicationTag; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.K2_ActivateAbility // (Event, Protected, BlueprintEvent) void UGA_DefaultPlayer_InteractSearch_C::K2_ActivateAbility() { static auto fn = UObject::FindObject<UFunction>("Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.K2_ActivateAbility"); UGA_DefaultPlayer_InteractSearch_C_K2_ActivateAbility_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.ExecuteUbergraph_GA_DefaultPlayer_InteractSearch // (HasDefaults) // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UGA_DefaultPlayer_InteractSearch_C::ExecuteUbergraph_GA_DefaultPlayer_InteractSearch(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function GA_DefaultPlayer_InteractSearch.GA_DefaultPlayer_InteractSearch_C.ExecuteUbergraph_GA_DefaultPlayer_InteractSearch"); UGA_DefaultPlayer_InteractSearch_C_ExecuteUbergraph_GA_DefaultPlayer_InteractSearch_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
4,667
1,636
// Fill out your copyright notice in the Description page of Project Settings. #include "Drone_Simulator.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, Drone_Simulator, "Drone_Simulator" );
208
71
/* Copyright 2017 - 2021 R. Thomas * Copyright 2017 - 2021 Quarkslab * * 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 "LIEF/PE/Structures.hpp" #include "LIEF/PE/EnumToString.hpp" #include "frozen.hpp" namespace LIEF { namespace PE { const char* to_string(PE_TYPE e) { CONST_MAP(PE_TYPE, const char*, 2) enumStrings { { PE_TYPE::PE32, "PE32" }, { PE_TYPE::PE32_PLUS,"PE32_PLUS" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(DATA_DIRECTORY e) { CONST_MAP(DATA_DIRECTORY, const char*, 15) enumStrings { { DATA_DIRECTORY::EXPORT_TABLE, "EXPORT_TABLE" }, { DATA_DIRECTORY::IMPORT_TABLE, "IMPORT_TABLE" }, { DATA_DIRECTORY::RESOURCE_TABLE, "RESOURCE_TABLE" }, { DATA_DIRECTORY::EXCEPTION_TABLE, "EXCEPTION_TABLE" }, { DATA_DIRECTORY::CERTIFICATE_TABLE, "CERTIFICATE_TABLE" }, { DATA_DIRECTORY::BASE_RELOCATION_TABLE, "BASE_RELOCATION_TABLE" }, { DATA_DIRECTORY::DEBUG, "DEBUG" }, { DATA_DIRECTORY::ARCHITECTURE, "ARCHITECTURE" }, { DATA_DIRECTORY::GLOBAL_PTR, "GLOBAL_PTR" }, { DATA_DIRECTORY::TLS_TABLE, "TLS_TABLE" }, { DATA_DIRECTORY::LOAD_CONFIG_TABLE, "LOAD_CONFIG_TABLE" }, { DATA_DIRECTORY::BOUND_IMPORT, "BOUND_IMPORT" }, { DATA_DIRECTORY::IAT, "IAT" }, { DATA_DIRECTORY::DELAY_IMPORT_DESCRIPTOR, "DELAY_IMPORT_DESCRIPTOR" }, { DATA_DIRECTORY::CLR_RUNTIME_HEADER, "CLR_RUNTIME_HEADER" } }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(MACHINE_TYPES e) { CONST_MAP(MACHINE_TYPES, const char*, 26) enumStrings { { MACHINE_TYPES::MT_Invalid, "INVALID" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_UNKNOWN, "UNKNOWN" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_AM33, "AM33" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_AMD64, "AMD64" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_ARM, "ARM" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_ARMNT, "ARMNT" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_ARM64, "ARM64" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_EBC, "EBC" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_I386, "I386" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_IA64, "IA64" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_M32R, "M32R" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_MIPS16, "MIPS16" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_MIPSFPU, "MIPSFPU" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_MIPSFPU16, "MIPSFPU16" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_POWERPC, "POWERPC" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_POWERPCFP, "POWERPCFP" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_R4000, "R4000" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_RISCV32, "RISCV32" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_RISCV64, "RISCV64" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_RISCV128, "RISCV128" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_SH3, "SH3" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_SH3DSP, "SH3DSP" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_SH4, "SH4" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_SH5, "SH5" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_THUMB, "THUMB" }, { MACHINE_TYPES::IMAGE_FILE_MACHINE_WCEMIPSV2, "WCEMIPSV2" } }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(HEADER_CHARACTERISTICS e) { CONST_MAP(HEADER_CHARACTERISTICS, const char*, 15) enumStrings { { HEADER_CHARACTERISTICS::IMAGE_FILE_RELOCS_STRIPPED, "RELOCS_STRIPPED" }, { HEADER_CHARACTERISTICS::IMAGE_FILE_EXECUTABLE_IMAGE, "EXECUTABLE_IMAGE" }, { HEADER_CHARACTERISTICS::IMAGE_FILE_LINE_NUMS_STRIPPED, "LINE_NUMS_STRIPPED" }, { HEADER_CHARACTERISTICS::IMAGE_FILE_LOCAL_SYMS_STRIPPED, "LOCAL_SYMS_STRIPPED" }, { HEADER_CHARACTERISTICS::IMAGE_FILE_AGGRESSIVE_WS_TRIM, "AGGRESSIVE_WS_TRIM" }, { HEADER_CHARACTERISTICS::IMAGE_FILE_LARGE_ADDRESS_AWARE, "LARGE_ADDRESS_AWARE" }, { HEADER_CHARACTERISTICS::IMAGE_FILE_BYTES_REVERSED_LO, "BYTES_REVERSED_LO" }, { HEADER_CHARACTERISTICS::IMAGE_FILE_32BIT_MACHINE, "CHARA_32BIT_MACHINE" }, { HEADER_CHARACTERISTICS::IMAGE_FILE_DEBUG_STRIPPED, "DEBUG_STRIPPED" }, { HEADER_CHARACTERISTICS::IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP, "REMOVABLE_RUN_FROM_SWAP" }, { HEADER_CHARACTERISTICS::IMAGE_FILE_NET_RUN_FROM_SWAP, "NET_RUN_FROM_SWAP" }, { HEADER_CHARACTERISTICS::IMAGE_FILE_SYSTEM, "SYSTEM" }, { HEADER_CHARACTERISTICS::IMAGE_FILE_DLL, "DLL" }, { HEADER_CHARACTERISTICS::IMAGE_FILE_UP_SYSTEM_ONLY, "UP_SYSTEM_ONLY" }, { HEADER_CHARACTERISTICS::IMAGE_FILE_BYTES_REVERSED_HI, "BYTES_REVERSED_HI" } }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(SUBSYSTEM e) { CONST_MAP(SUBSYSTEM, const char*, 14) enumStrings { { SUBSYSTEM::IMAGE_SUBSYSTEM_UNKNOWN, "UNKNOWN" }, { SUBSYSTEM::IMAGE_SUBSYSTEM_NATIVE, "NATIVE" }, { SUBSYSTEM::IMAGE_SUBSYSTEM_WINDOWS_GUI, "WINDOWS_GUI" }, { SUBSYSTEM::IMAGE_SUBSYSTEM_WINDOWS_CUI, "WINDOWS_CUI" }, { SUBSYSTEM::IMAGE_SUBSYSTEM_OS2_CUI, "OS2_CUI" }, { SUBSYSTEM::IMAGE_SUBSYSTEM_POSIX_CUI, "POSIX_CUI" }, { SUBSYSTEM::IMAGE_SUBSYSTEM_NATIVE_WINDOWS, "NATIVE_WINDOWS" }, { SUBSYSTEM::IMAGE_SUBSYSTEM_WINDOWS_CE_GUI, "WINDOWS_CE_GUI" }, { SUBSYSTEM::IMAGE_SUBSYSTEM_EFI_APPLICATION, "EFI_APPLICATION" }, { SUBSYSTEM::IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER, "EFI_BOOT_SERVICE_DRIVER" }, { SUBSYSTEM::IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER, "EFI_RUNTIME_DRIVER" }, { SUBSYSTEM::IMAGE_SUBSYSTEM_EFI_ROM, "EFI_ROM" }, { SUBSYSTEM::IMAGE_SUBSYSTEM_XBOX, "XBOX" }, { SUBSYSTEM::IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION, "WINDOWS_BOOT_APPLICATION" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(DLL_CHARACTERISTICS e) { CONST_MAP(DLL_CHARACTERISTICS, const char*, 11) enumStrings { { DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA, "HIGH_ENTROPY_VA" }, { DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE, "DYNAMIC_BASE" }, { DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY, "FORCE_INTEGRITY" }, { DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_NX_COMPAT, "NX_COMPAT" }, { DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION, "NO_ISOLATION" }, { DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_NO_SEH, "NO_SEH" }, { DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_NO_BIND, "NO_BIND" }, { DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_APPCONTAINER, "APPCONTAINER" }, { DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER, "WDM_DRIVER" }, { DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_GUARD_CF, "GUARD_CF" }, { DLL_CHARACTERISTICS::IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE, "TERMINAL_SERVER_AWARE" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(SECTION_CHARACTERISTICS e) { CONST_MAP(SECTION_CHARACTERISTICS, const char*, 35) enumStrings { { SECTION_CHARACTERISTICS::IMAGE_SCN_TYPE_NO_PAD, "TYPE_NO_PAD" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_CNT_CODE, "CNT_CODE" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_CNT_INITIALIZED_DATA, "CNT_INITIALIZED_DATA" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_CNT_UNINITIALIZED_DATA, "CNT_UNINITIALIZED_DATA" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_LNK_OTHER, "LNK_OTHER" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_LNK_INFO, "LNK_INFO" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_LNK_REMOVE, "LNK_REMOVE" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_LNK_COMDAT, "LNK_COMDAT" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_GPREL, "GPREL" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_PURGEABLE, "MEM_PURGEABLE" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_16BIT, "MEM_16BIT" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_LOCKED, "MEM_LOCKED" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_PRELOAD, "MEM_PRELOAD" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_1BYTES, "ALIGN_1BYTES" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_2BYTES, "ALIGN_2BYTES" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_4BYTES, "ALIGN_4BYTES" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_8BYTES, "ALIGN_8BYTES" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_16BYTES, "ALIGN_16BYTES" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_32BYTES, "ALIGN_32BYTES" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_64BYTES, "ALIGN_64BYTES" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_128BYTES, "ALIGN_128BYTES" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_256BYTES, "ALIGN_256BYTES" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_512BYTES, "ALIGN_512BYTES" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_1024BYTES, "ALIGN_1024BYTES" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_2048BYTES, "ALIGN_2048BYTES" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_4096BYTES, "ALIGN_4096BYTES" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_ALIGN_8192BYTES, "ALIGN_8192BYTES" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_LNK_NRELOC_OVFL, "LNK_NRELOC_OVFL" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_DISCARDABLE, "MEM_DISCARDABLE" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_NOT_CACHED, "MEM_NOT_CACHED" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_NOT_PAGED, "MEM_NOT_PAGED" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_SHARED, "MEM_SHARED" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_EXECUTE, "MEM_EXECUTE" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_READ, "MEM_READ" }, { SECTION_CHARACTERISTICS::IMAGE_SCN_MEM_WRITE, "MEM_WRITE" } }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(PE_SECTION_TYPES e) { CONST_MAP(PE_SECTION_TYPES, const char*, 10) enumStrings { { PE_SECTION_TYPES::TEXT, "TEXT" }, { PE_SECTION_TYPES::TLS, "TLS_" }, { PE_SECTION_TYPES::IMPORT, "IDATA" }, { PE_SECTION_TYPES::DATA, "DATA" }, { PE_SECTION_TYPES::BSS, "BSS" }, { PE_SECTION_TYPES::RESOURCE, "RESOURCE" }, { PE_SECTION_TYPES::RELOCATION, "RELOCATION" }, { PE_SECTION_TYPES::EXPORT, "EXPORT" }, { PE_SECTION_TYPES::DEBUG, "DEBUG" }, { PE_SECTION_TYPES::UNKNOWN, "UNKNOWN" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(SYMBOL_BASE_TYPES e) { CONST_MAP(SYMBOL_BASE_TYPES, const char*, 16) enumStrings { { SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_NULL, "NULL" }, { SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_VOID, "VOID" }, { SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_CHAR, "CHAR" }, { SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_SHORT, "SHORT" }, { SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_INT, "INT" }, { SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_LONG, "LONG" }, { SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_FLOAT, "FLOAT" }, { SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_DOUBLE, "DOUBLE" }, { SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_STRUCT, "STRUCT" }, { SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_UNION, "UNION" }, { SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_ENUM, "ENUM" }, { SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_MOE, "MOE" }, { SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_BYTE, "BYTE" }, { SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_WORD, "WORD" }, { SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_UINT, "UINT" }, { SYMBOL_BASE_TYPES::IMAGE_SYM_TYPE_DWORD, "DWORD" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(SYMBOL_COMPLEX_TYPES e) { CONST_MAP(SYMBOL_COMPLEX_TYPES, const char*, 5) enumStrings { { SYMBOL_COMPLEX_TYPES::IMAGE_SYM_DTYPE_NULL, "NULL" }, { SYMBOL_COMPLEX_TYPES::IMAGE_SYM_DTYPE_POINTER, "POINTER" }, { SYMBOL_COMPLEX_TYPES::IMAGE_SYM_DTYPE_FUNCTION, "FUNCTION" }, { SYMBOL_COMPLEX_TYPES::IMAGE_SYM_DTYPE_ARRAY, "ARRAY" }, { SYMBOL_COMPLEX_TYPES::SCT_COMPLEX_TYPE_SHIFT, "COMPLEX_TYPE_SHIFT" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(SYMBOL_SECTION_NUMBER e) { CONST_MAP(SYMBOL_SECTION_NUMBER, const char*, 3) enumStrings { { SYMBOL_SECTION_NUMBER::IMAGE_SYM_DEBUG, "DEBUG" }, { SYMBOL_SECTION_NUMBER::IMAGE_SYM_ABSOLUTE, "ABSOLUTE" }, { SYMBOL_SECTION_NUMBER::IMAGE_SYM_UNDEFINED, "UNDEFINED" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(SYMBOL_STORAGE_CLASS e) { CONST_MAP(SYMBOL_STORAGE_CLASS, const char*, 24) enumStrings { { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_END_OF_FUNCTION, "END_OF_FUNCTION" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_NULL, "NULL" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_AUTOMATIC, "AUTOMATIC" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_EXTERNAL, "EXTERNAL" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_STATIC, "STATIC" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_REGISTER, "REGISTER" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_EXTERNAL_DEF, "EXTERNAL_DEF" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_LABEL, "LABEL" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_UNDEFINED_LABEL, "UNDEFINED_LABEL" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_MEMBER_OF_STRUCT, "MEMBER_OF_STRUCT" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_UNION_TAG, "UNION_TAG" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_TYPE_DEFINITION, "TYPE_DEFINITION" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_UNDEFINED_STATIC, "UDEFINED_STATIC" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_ENUM_TAG, "ENUM_TAG" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_MEMBER_OF_ENUM, "MEMBER_OF_ENUM" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_REGISTER_PARAM, "REGISTER_PARAM" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_BIT_FIELD, "BIT_FIELD" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_BLOCK, "BLOCK" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_FUNCTION, "FUNCTION" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_END_OF_STRUCT, "END_OF_STRUCT" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_FILE, "FILE" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_SECTION, "SECTION" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_WEAK_EXTERNAL, "WEAK_EXTERNAL" }, { SYMBOL_STORAGE_CLASS::IMAGE_SYM_CLASS_CLR_TOKEN, "CLR_TOKEN" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(RELOCATIONS_I386 e) { CONST_MAP(RELOCATIONS_I386, const char*, 11) enumStrings { { RELOCATIONS_I386::IMAGE_REL_I386_ABSOLUTE, "ABSOLUTE" }, { RELOCATIONS_I386::IMAGE_REL_I386_DIR16, "DIR16" }, { RELOCATIONS_I386::IMAGE_REL_I386_REL16, "REL16" }, { RELOCATIONS_I386::IMAGE_REL_I386_DIR32, "DIR32" }, { RELOCATIONS_I386::IMAGE_REL_I386_DIR32NB, "DIR32NB" }, { RELOCATIONS_I386::IMAGE_REL_I386_SEG12, "SEG12" }, { RELOCATIONS_I386::IMAGE_REL_I386_SECTION, "SECTION" }, { RELOCATIONS_I386::IMAGE_REL_I386_SECREL, "SECREL" }, { RELOCATIONS_I386::IMAGE_REL_I386_TOKEN, "TOKEN" }, { RELOCATIONS_I386::IMAGE_REL_I386_SECREL7, "SECREL7" }, { RELOCATIONS_I386::IMAGE_REL_I386_REL32, "REL32" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(RELOCATIONS_AMD64 e) { CONST_MAP(RELOCATIONS_AMD64, const char*, 17) enumStrings { { RELOCATIONS_AMD64::IMAGE_REL_AMD64_ABSOLUTE, "ABSOLUTE" }, { RELOCATIONS_AMD64::IMAGE_REL_AMD64_ADDR64, "ADDR64" }, { RELOCATIONS_AMD64::IMAGE_REL_AMD64_ADDR32, "ADDR32" }, { RELOCATIONS_AMD64::IMAGE_REL_AMD64_ADDR32NB, "ADDR32NB" }, { RELOCATIONS_AMD64::IMAGE_REL_AMD64_REL32, "REL32" }, { RELOCATIONS_AMD64::IMAGE_REL_AMD64_REL32_1, "REL32_1" }, { RELOCATIONS_AMD64::IMAGE_REL_AMD64_REL32_2, "REL32_2" }, { RELOCATIONS_AMD64::IMAGE_REL_AMD64_REL32_3, "REL32_3" }, { RELOCATIONS_AMD64::IMAGE_REL_AMD64_REL32_4, "REL32_4" }, { RELOCATIONS_AMD64::IMAGE_REL_AMD64_REL32_5, "REL32_5" }, { RELOCATIONS_AMD64::IMAGE_REL_AMD64_SECTION, "SECTION" }, { RELOCATIONS_AMD64::IMAGE_REL_AMD64_SECREL, "SECREL" }, { RELOCATIONS_AMD64::IMAGE_REL_AMD64_SECREL7, "SECREL7" }, { RELOCATIONS_AMD64::IMAGE_REL_AMD64_TOKEN, "TOKEN" }, { RELOCATIONS_AMD64::IMAGE_REL_AMD64_SREL32, "SREL32" }, { RELOCATIONS_AMD64::IMAGE_REL_AMD64_PAIR, "PAIR" }, { RELOCATIONS_AMD64::IMAGE_REL_AMD64_SSPAN32, "SSPAN32" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(RELOCATIONS_ARM e) { CONST_MAP(RELOCATIONS_ARM, const char*, 15) enumStrings { { RELOCATIONS_ARM::IMAGE_REL_ARM_ABSOLUTE, "ABSOLUTE" }, { RELOCATIONS_ARM::IMAGE_REL_ARM_ADDR32, "ADDR32" }, { RELOCATIONS_ARM::IMAGE_REL_ARM_ADDR32NB, "ADDR32NB" }, { RELOCATIONS_ARM::IMAGE_REL_ARM_BRANCH24, "BRANCH24" }, { RELOCATIONS_ARM::IMAGE_REL_ARM_BRANCH11, "BRANCH11" }, { RELOCATIONS_ARM::IMAGE_REL_ARM_TOKEN, "TOKEN" }, { RELOCATIONS_ARM::IMAGE_REL_ARM_BLX24, "BLX24" }, { RELOCATIONS_ARM::IMAGE_REL_ARM_BLX11, "BLX11" }, { RELOCATIONS_ARM::IMAGE_REL_ARM_SECTION, "SECTION" }, { RELOCATIONS_ARM::IMAGE_REL_ARM_SECREL, "SECREL" }, { RELOCATIONS_ARM::IMAGE_REL_ARM_MOV32A, "MOV32A" }, { RELOCATIONS_ARM::IMAGE_REL_ARM_MOV32T, "MOV32T" }, { RELOCATIONS_ARM::IMAGE_REL_ARM_BRANCH20T, "BRANCH20T" }, { RELOCATIONS_ARM::IMAGE_REL_ARM_BRANCH24T, "BRANCH24T" }, { RELOCATIONS_ARM::IMAGE_REL_ARM_BLX23T, "BLX23T" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(RELOCATIONS_BASE_TYPES e) { CONST_MAP(RELOCATIONS_BASE_TYPES, const char*, 19) enumStrings { { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_ABSOLUTE, "ABSOLUTE" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_HIGH, "HIGH" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_LOW, "LOW" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_HIGHLOW, "HIGHLOW" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_HIGHADJ, "HIGHADJ" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_MIPS_JMPADDR, "MIPS_JMPADDR | ARM_MOV32A | ARM_MOV32 | RISCV_HI20" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_ARM_MOV32A, "MIPS_JMPADDR | ARM_MOV32A | ARM_MOV32 | RISCV_HI20" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_ARM_MOV32, "MIPS_JMPADDR | ARM_MOV32A | ARM_MOV32 | RISCV_HI20" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_RISCV_HI20, "MIPS_JMPADDR | ARM_MOV32A | ARM_MOV32 | RISCV_HI20" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_SECTION, "SECTION" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_REL, "REL | ARM_MOV32T | THUMB_MOV32 | RISCV_LOW12I" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_ARM_MOV32T, "REL | ARM_MOV32T | THUMB_MOV32 | RISCV_LOW12I" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_THUMB_MOV32, "REL | ARM_MOV32T | THUMB_MOV32 | RISCV_LOW12I" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_RISCV_LOW12I, "REL | ARM_MOV32T | THUMB_MOV32 | RISCV_LOW12I" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_RISCV_LOW12S, "RISCV_LOW12S" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_MIPS_JMPADDR16, "MIPS_JMPADDR16 | IA64_IMM64" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_IA64_IMM64, "MIPS_JMPADDR16 | IA64_IMM64" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_DIR64, "DIR64" }, { RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_HIGH3ADJ, "HIGH3ADJ" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(DEBUG_TYPES e) { CONST_MAP(DEBUG_TYPES, const char*, 18) enumStrings { { DEBUG_TYPES::IMAGE_DEBUG_TYPE_UNKNOWN, "UNKNOWN" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_COFF, "COFF" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_CODEVIEW, "CODEVIEW" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_FPO, "FPO" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_MISC, "MISC" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_EXCEPTION, "EXCEPTION" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_FIXUP, "FIXUP" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_OMAP_TO_SRC, "OMAP_TO_SRC" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_OMAP_FROM_SRC, "OMAP_FROM_SRC" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_BORLAND, "BORLAND" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_RESERVED10, "RESERVED" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_CLSID, "CLSID" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_VC_FEATURE, "VC_FEATURE" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_POGO, "POGO" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_ILTCG, "ILTCG" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_MPX, "MPX" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_REPRO, "REPRO" }, { DEBUG_TYPES::IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS, "EX_DLLCHARACTERISTICS" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(RESOURCE_TYPES e) { CONST_MAP(RESOURCE_TYPES, const char*, 21) enumStrings { { RESOURCE_TYPES::CURSOR, "CURSOR" }, { RESOURCE_TYPES::BITMAP, "BITMAP" }, { RESOURCE_TYPES::ICON, "ICON" }, { RESOURCE_TYPES::MENU, "MENU" }, { RESOURCE_TYPES::DIALOG, "DIALOG" }, { RESOURCE_TYPES::STRING, "STRING" }, { RESOURCE_TYPES::FONTDIR, "FONTDIR" }, { RESOURCE_TYPES::FONT, "FONT" }, { RESOURCE_TYPES::ACCELERATOR, "ACCELERATOR" }, { RESOURCE_TYPES::RCDATA, "RCDATA" }, { RESOURCE_TYPES::MESSAGETABLE, "MESSAGETABLE" }, { RESOURCE_TYPES::GROUP_CURSOR, "GROUP_CURSOR" }, { RESOURCE_TYPES::GROUP_ICON, "GROUP_ICON" }, { RESOURCE_TYPES::VERSION, "VERSION" }, { RESOURCE_TYPES::DLGINCLUDE, "DLGINCLUDE" }, { RESOURCE_TYPES::PLUGPLAY, "PLUGPLAY" }, { RESOURCE_TYPES::VXD, "VXD" }, { RESOURCE_TYPES::ANICURSOR, "ANICURSOR" }, { RESOURCE_TYPES::ANIICON, "ANIICON" }, { RESOURCE_TYPES::HTML, "HTML" }, { RESOURCE_TYPES::MANIFEST, "MANIFEST" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(RESOURCE_LANGS e) { CONST_MAP(RESOURCE_LANGS, const char*, 98) enumStrings { { RESOURCE_LANGS::LANG_NEUTRAL, "NEUTRAL" }, { RESOURCE_LANGS::LANG_INVARIANT, "INVARIANT" }, { RESOURCE_LANGS::LANG_AFRIKAANS, "AFRIKAANS" }, { RESOURCE_LANGS::LANG_ALBANIAN, "ALBANIAN" }, { RESOURCE_LANGS::LANG_ARABIC, "ARABIC" }, { RESOURCE_LANGS::LANG_ARMENIAN, "ARMENIAN" }, { RESOURCE_LANGS::LANG_ASSAMESE, "ASSAMESE" }, { RESOURCE_LANGS::LANG_AZERI, "AZERI" }, { RESOURCE_LANGS::LANG_BASQUE, "BASQUE" }, { RESOURCE_LANGS::LANG_BELARUSIAN, "BELARUSIAN" }, { RESOURCE_LANGS::LANG_BANGLA, "BANGLA" }, { RESOURCE_LANGS::LANG_BULGARIAN, "BULGARIAN" }, { RESOURCE_LANGS::LANG_CATALAN, "CATALAN" }, { RESOURCE_LANGS::LANG_CHINESE, "CHINESE" }, { RESOURCE_LANGS::LANG_CROATIAN, "CROATIAN" }, { RESOURCE_LANGS::LANG_CZECH, "CZECH" }, { RESOURCE_LANGS::LANG_DANISH, "DANISH" }, { RESOURCE_LANGS::LANG_DIVEHI, "DIVEHI" }, { RESOURCE_LANGS::LANG_DUTCH, "DUTCH" }, { RESOURCE_LANGS::LANG_ENGLISH, "ENGLISH" }, { RESOURCE_LANGS::LANG_ESTONIAN, "ESTONIAN" }, { RESOURCE_LANGS::LANG_FAEROESE, "FAEROESE" }, { RESOURCE_LANGS::LANG_FARSI, "FARSI" }, { RESOURCE_LANGS::LANG_FINNISH, "FINNISH" }, { RESOURCE_LANGS::LANG_FRENCH, "FRENCH" }, { RESOURCE_LANGS::LANG_GALICIAN, "GALICIAN" }, { RESOURCE_LANGS::LANG_GEORGIAN, "GEORGIAN" }, { RESOURCE_LANGS::LANG_GERMAN, "GERMAN" }, { RESOURCE_LANGS::LANG_GREEK, "GREEK" }, { RESOURCE_LANGS::LANG_GUJARATI, "GUJARATI" }, { RESOURCE_LANGS::LANG_HEBREW, "HEBREW" }, { RESOURCE_LANGS::LANG_HINDI, "HINDI" }, { RESOURCE_LANGS::LANG_HUNGARIAN, "HUNGARIAN" }, { RESOURCE_LANGS::LANG_ICELANDIC, "ICELANDIC" }, { RESOURCE_LANGS::LANG_INDONESIAN, "INDONESIAN" }, { RESOURCE_LANGS::LANG_ITALIAN, "ITALIAN" }, { RESOURCE_LANGS::LANG_JAPANESE, "JAPANESE" }, { RESOURCE_LANGS::LANG_KANNADA, "KANNADA" }, { RESOURCE_LANGS::LANG_KASHMIRI, "KASHMIRI" }, { RESOURCE_LANGS::LANG_KAZAK, "KAZAK" }, { RESOURCE_LANGS::LANG_KONKANI, "KONKANI" }, { RESOURCE_LANGS::LANG_KOREAN, "KOREAN" }, { RESOURCE_LANGS::LANG_KYRGYZ, "KYRGYZ" }, { RESOURCE_LANGS::LANG_LATVIAN, "LATVIAN" }, { RESOURCE_LANGS::LANG_LITHUANIAN, "LITHUANIAN" }, { RESOURCE_LANGS::LANG_MACEDONIAN, "MACEDONIAN" }, { RESOURCE_LANGS::LANG_MALAY, "MALAY" }, { RESOURCE_LANGS::LANG_MALAYALAM, "MALAYALAM" }, { RESOURCE_LANGS::LANG_MANIPURI, "MANIPURI" }, { RESOURCE_LANGS::LANG_MARATHI, "MARATHI" }, { RESOURCE_LANGS::LANG_MONGOLIAN, "MONGOLIAN" }, { RESOURCE_LANGS::LANG_NEPALI, "NEPALI" }, { RESOURCE_LANGS::LANG_NORWEGIAN, "NORWEGIAN" }, { RESOURCE_LANGS::LANG_ORIYA, "ORIYA" }, { RESOURCE_LANGS::LANG_POLISH, "POLISH" }, { RESOURCE_LANGS::LANG_PORTUGUESE, "PORTUGUESE" }, { RESOURCE_LANGS::LANG_PUNJABI, "PUNJABI" }, { RESOURCE_LANGS::LANG_ROMANIAN, "ROMANIAN" }, { RESOURCE_LANGS::LANG_RUSSIAN, "RUSSIAN" }, { RESOURCE_LANGS::LANG_SANSKRIT, "SANSKRIT" }, { RESOURCE_LANGS::LANG_SINDHI, "SINDHI" }, { RESOURCE_LANGS::LANG_SLOVAK, "SLOVAK" }, { RESOURCE_LANGS::LANG_SLOVENIAN, "SLOVENIAN" }, { RESOURCE_LANGS::LANG_SPANISH, "SPANISH" }, { RESOURCE_LANGS::LANG_SWAHILI, "SWAHILI" }, { RESOURCE_LANGS::LANG_SWEDISH, "SWEDISH" }, { RESOURCE_LANGS::LANG_SYRIAC, "SYRIAC" }, { RESOURCE_LANGS::LANG_TAMIL, "TAMIL" }, { RESOURCE_LANGS::LANG_TATAR, "TATAR" }, { RESOURCE_LANGS::LANG_TELUGU, "TELUGU" }, { RESOURCE_LANGS::LANG_THAI, "THAI" }, { RESOURCE_LANGS::LANG_TURKISH, "TURKISH" }, { RESOURCE_LANGS::LANG_UKRAINIAN, "UKRAINIAN" }, { RESOURCE_LANGS::LANG_URDU, "URDU" }, { RESOURCE_LANGS::LANG_UZBEK, "UZBEK" }, { RESOURCE_LANGS::LANG_VIETNAMESE, "VIETNAMESE" }, { RESOURCE_LANGS::LANG_MALTESE, "MALTESE" }, { RESOURCE_LANGS::LANG_MAORI, "MAORI" }, { RESOURCE_LANGS::LANG_RHAETO_ROMANCE, "RHAETO_ROMANCE" }, { RESOURCE_LANGS::LANG_SAMI, "SAMI" }, { RESOURCE_LANGS::LANG_SORBIAN, "SORBIAN" }, { RESOURCE_LANGS::LANG_SUTU, "SUTU" }, { RESOURCE_LANGS::LANG_TSONGA, "TSONGA" }, { RESOURCE_LANGS::LANG_TSWANA, "TSWANA" }, { RESOURCE_LANGS::LANG_VENDA, "VENDA" }, { RESOURCE_LANGS::LANG_XHOSA, "XHOSA" }, { RESOURCE_LANGS::LANG_ZULU, "ZULU" }, { RESOURCE_LANGS::LANG_ESPERANTO, "ESPERANTO" }, { RESOURCE_LANGS::LANG_WALON, "WALON" }, { RESOURCE_LANGS::LANG_CORNISH, "CORNISH" }, { RESOURCE_LANGS::LANG_WELSH, "WELSH" }, { RESOURCE_LANGS::LANG_BRETON, "BRETON" }, { RESOURCE_LANGS::LANG_INUKTITUT, "INUKTITUT" }, { RESOURCE_LANGS::LANG_IRISH, "IRISH" }, { RESOURCE_LANGS::LANG_PULAR, "PULAR" }, { RESOURCE_LANGS::LANG_QUECHUA, "QUECHUA" }, { RESOURCE_LANGS::LANG_TAMAZIGHT, "TAMAZIGHT" }, { RESOURCE_LANGS::LANG_TIGRINYA, "TIGRINYA" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(RESOURCE_SUBLANGS e) { CONST_MAP(RESOURCE_SUBLANGS, const char*, 229) enumStrings { { RESOURCE_SUBLANGS::SUBLANG_AFRIKAANS_SOUTH_AFRICA, "AFRIKAANS_SOUTH_AFRICA" }, { RESOURCE_SUBLANGS::SUBLANG_ALBANIAN_ALBANIA, "ALBANIAN_ALBANIA" }, { RESOURCE_SUBLANGS::SUBLANG_ALSATIAN_FRANCE, "ALSATIAN_FRANCE" }, { RESOURCE_SUBLANGS::SUBLANG_AMHARIC_ETHIOPIA, "AMHARIC_ETHIOPIA" }, { RESOURCE_SUBLANGS::SUBLANG_ARABIC_ALGERIA, "ARABIC_ALGERIA" }, { RESOURCE_SUBLANGS::SUBLANG_ARABIC_BAHRAIN, "ARABIC_BAHRAIN" }, { RESOURCE_SUBLANGS::SUBLANG_ARABIC_EGYPT, "ARABIC_EGYPT" }, { RESOURCE_SUBLANGS::SUBLANG_ARABIC_IRAQ, "ARABIC_IRAQ" }, { RESOURCE_SUBLANGS::SUBLANG_ARABIC_JORDAN, "ARABIC_JORDAN" }, { RESOURCE_SUBLANGS::SUBLANG_ARABIC_KUWAIT, "ARABIC_KUWAIT" }, { RESOURCE_SUBLANGS::SUBLANG_ARABIC_LEBANON, "ARABIC_LEBANON" }, { RESOURCE_SUBLANGS::SUBLANG_ARABIC_LIBYA, "ARABIC_LIBYA" }, { RESOURCE_SUBLANGS::SUBLANG_ARABIC_MOROCCO, "ARABIC_MOROCCO" }, { RESOURCE_SUBLANGS::SUBLANG_ARABIC_OMAN, "ARABIC_OMAN" }, { RESOURCE_SUBLANGS::SUBLANG_ARABIC_QATAR, "ARABIC_QATAR" }, { RESOURCE_SUBLANGS::SUBLANG_ARABIC_SAUDI_ARABIA, "ARABIC_SAUDI_ARABIA" }, { RESOURCE_SUBLANGS::SUBLANG_ARABIC_SYRIA, "ARABIC_SYRIA" }, { RESOURCE_SUBLANGS::SUBLANG_ARABIC_TUNISIA, "ARABIC_TUNISIA" }, { RESOURCE_SUBLANGS::SUBLANG_ARABIC_UAE, "ARABIC_UAE" }, { RESOURCE_SUBLANGS::SUBLANG_ARABIC_YEMEN, "ARABIC_YEMEN" }, { RESOURCE_SUBLANGS::SUBLANG_ARMENIAN_ARMENIA, "ARMENIAN_ARMENIA" }, { RESOURCE_SUBLANGS::SUBLANG_ASSAMESE_INDIA, "ASSAMESE_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_AZERI_CYRILLIC, "AZERI_CYRILLIC" }, { RESOURCE_SUBLANGS::SUBLANG_AZERI_LATIN, "AZERI_LATIN" }, { RESOURCE_SUBLANGS::SUBLANG_BASHKIR_RUSSIA, "BASHKIR_RUSSIA" }, { RESOURCE_SUBLANGS::SUBLANG_BASQUE_BASQUE, "BASQUE_BASQUE" }, { RESOURCE_SUBLANGS::SUBLANG_BELARUSIAN_BELARUS, "BELARUSIAN_BELARUS" }, { RESOURCE_SUBLANGS::SUBLANG_BANGLA_BANGLADESH, "BANGLA_BANGLADESH" }, { RESOURCE_SUBLANGS::SUBLANG_BANGLA_INDIA, "BANGLA_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_CYRILLIC, "BOSNIAN_BOSNIA_HERZEGOVINA_CYRILLIC" }, { RESOURCE_SUBLANGS::SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_LATIN, "BOSNIAN_BOSNIA_HERZEGOVINA_LATIN" }, { RESOURCE_SUBLANGS::SUBLANG_BRETON_FRANCE, "BRETON_FRANCE" }, { RESOURCE_SUBLANGS::SUBLANG_BULGARIAN_BULGARIA, "BULGARIAN_BULGARIA" }, { RESOURCE_SUBLANGS::SUBLANG_CATALAN_CATALAN, "CATALAN_CATALAN" }, { RESOURCE_SUBLANGS::SUBLANG_CHINESE_HONGKONG, "CHINESE_HONGKONG" }, { RESOURCE_SUBLANGS::SUBLANG_CHINESE_MACAU, "CHINESE_MACAU" }, { RESOURCE_SUBLANGS::SUBLANG_CHINESE_SIMPLIFIED, "CHINESE_SIMPLIFIED" }, { RESOURCE_SUBLANGS::SUBLANG_CHINESE_SINGAPORE, "CHINESE_SINGAPORE" }, { RESOURCE_SUBLANGS::SUBLANG_CHINESE_TRADITIONAL, "CHINESE_TRADITIONAL" }, { RESOURCE_SUBLANGS::SUBLANG_CORSICAN_FRANCE, "CORSICAN_FRANCE" }, { RESOURCE_SUBLANGS::SUBLANG_CROATIAN_BOSNIA_HERZEGOVINA_LATIN, "CROATIAN_BOSNIA_HERZEGOVINA_LATIN" }, { RESOURCE_SUBLANGS::SUBLANG_CROATIAN_CROATIA, "CROATIAN_CROATIA" }, { RESOURCE_SUBLANGS::SUBLANG_CUSTOM_DEFAULT, "CUSTOM_DEFAULT" }, { RESOURCE_SUBLANGS::SUBLANG_CUSTOM_UNSPECIFIED, "CUSTOM_UNSPECIFIED" }, { RESOURCE_SUBLANGS::SUBLANG_CZECH_CZECH_REPUBLIC, "CZECH_CZECH_REPUBLIC" }, { RESOURCE_SUBLANGS::SUBLANG_DANISH_DENMARK, "DANISH_DENMARK" }, { RESOURCE_SUBLANGS::SUBLANG_DARI_AFGHANISTAN, "DARI_AFGHANISTAN" }, { RESOURCE_SUBLANGS::SUBLANG_DEFAULT, "DEFAULT" }, { RESOURCE_SUBLANGS::SUBLANG_DIVEHI_MALDIVES, "DIVEHI_MALDIVES" }, { RESOURCE_SUBLANGS::SUBLANG_DUTCH_BELGIAN, "DUTCH_BELGIAN" }, { RESOURCE_SUBLANGS::SUBLANG_DUTCH, "DUTCH" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_AUS, "ENGLISH_AUS" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_BELIZE, "ENGLISH_BELIZE" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_CAN, "ENGLISH_CAN" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_CARIBBEAN, "ENGLISH_CARIBBEAN" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_EIRE, "ENGLISH_EIRE" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_INDIA, "ENGLISH_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_JAMAICA, "ENGLISH_JAMAICA" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_MALAYSIA, "ENGLISH_MALAYSIA" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_NZ, "ENGLISH_NZ" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_PHILIPPINES, "ENGLISH_PHILIPPINES" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_SINGAPORE, "ENGLISH_SINGAPORE" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_SOUTH_AFRICA, "ENGLISH_SOUTH_AFRICA" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_TRINIDAD, "ENGLISH_TRINIDAD" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_UK, "ENGLISH_UK" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_US, "ENGLISH_US" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_ZIMBABWE, "ENGLISH_ZIMBABWE" }, { RESOURCE_SUBLANGS::SUBLANG_ENGLISH_IRELAND, "ENGLISH_IRELAND" }, { RESOURCE_SUBLANGS::SUBLANG_ESTONIAN_ESTONIA, "ESTONIAN_ESTONIA" }, { RESOURCE_SUBLANGS::SUBLANG_FAEROESE_FAROE_ISLANDS, "FAEROESE_FAROE_ISLANDS" }, { RESOURCE_SUBLANGS::SUBLANG_FILIPINO_PHILIPPINES, "FILIPINO_PHILIPPINES" }, { RESOURCE_SUBLANGS::SUBLANG_FINNISH_FINLAND, "FINNISH_FINLAND" }, { RESOURCE_SUBLANGS::SUBLANG_FRENCH_BELGIAN, "FRENCH_BELGIAN" }, { RESOURCE_SUBLANGS::SUBLANG_FRENCH_CANADIAN, "FRENCH_CANADIAN" }, { RESOURCE_SUBLANGS::SUBLANG_FRENCH_LUXEMBOURG, "FRENCH_LUXEMBOURG" }, { RESOURCE_SUBLANGS::SUBLANG_FRENCH_MONACO, "FRENCH_MONACO" }, { RESOURCE_SUBLANGS::SUBLANG_FRENCH_SWISS, "FRENCH_SWISS" }, { RESOURCE_SUBLANGS::SUBLANG_FRENCH, "FRENCH" }, { RESOURCE_SUBLANGS::SUBLANG_FRISIAN_NETHERLANDS, "FRISIAN_NETHERLANDS" }, { RESOURCE_SUBLANGS::SUBLANG_GALICIAN_GALICIAN, "GALICIAN_GALICIAN" }, { RESOURCE_SUBLANGS::SUBLANG_GEORGIAN_GEORGIA, "GEORGIAN_GEORGIA" }, { RESOURCE_SUBLANGS::SUBLANG_GERMAN_AUSTRIAN, "GERMAN_AUSTRIAN" }, { RESOURCE_SUBLANGS::SUBLANG_GERMAN_LIECHTENSTEIN, "GERMAN_LIECHTENSTEIN" }, { RESOURCE_SUBLANGS::SUBLANG_GERMAN_LUXEMBOURG, "GERMAN_LUXEMBOURG" }, { RESOURCE_SUBLANGS::SUBLANG_GERMAN_SWISS, "GERMAN_SWISS" }, { RESOURCE_SUBLANGS::SUBLANG_GERMAN, "GERMAN" }, { RESOURCE_SUBLANGS::SUBLANG_GREEK_GREECE, "GREEK_GREECE" }, { RESOURCE_SUBLANGS::SUBLANG_GREENLANDIC_GREENLAND, "GREENLANDIC_GREENLAND" }, { RESOURCE_SUBLANGS::SUBLANG_GUJARATI_INDIA, "GUJARATI_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_HAUSA_NIGERIA_LATIN, "HAUSA_NIGERIA_LATIN" }, { RESOURCE_SUBLANGS::SUBLANG_HEBREW_ISRAEL, "HEBREW_ISRAEL" }, { RESOURCE_SUBLANGS::SUBLANG_HINDI_INDIA, "HINDI_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_HUNGARIAN_HUNGARY, "HUNGARIAN_HUNGARY" }, { RESOURCE_SUBLANGS::SUBLANG_ICELANDIC_ICELAND, "ICELANDIC_ICELAND" }, { RESOURCE_SUBLANGS::SUBLANG_IGBO_NIGERIA, "IGBO_NIGERIA" }, { RESOURCE_SUBLANGS::SUBLANG_INDONESIAN_INDONESIA, "INDONESIAN_INDONESIA" }, { RESOURCE_SUBLANGS::SUBLANG_INUKTITUT_CANADA_LATIN, "INUKTITUT_CANADA_LATIN" }, { RESOURCE_SUBLANGS::SUBLANG_INUKTITUT_CANADA, "INUKTITUT_CANADA" }, { RESOURCE_SUBLANGS::SUBLANG_IRISH_IRELAND, "IRISH_IRELAND" }, { RESOURCE_SUBLANGS::SUBLANG_ITALIAN_SWISS, "ITALIAN_SWISS" }, { RESOURCE_SUBLANGS::SUBLANG_ITALIAN, "ITALIAN" }, { RESOURCE_SUBLANGS::SUBLANG_JAPANESE_JAPAN, "JAPANESE_JAPAN" }, { RESOURCE_SUBLANGS::SUBLANG_KANNADA_INDIA, "KANNADA_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_KASHMIRI_INDIA, "KASHMIRI_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_KASHMIRI_SASIA, "KASHMIRI_SASIA" }, { RESOURCE_SUBLANGS::SUBLANG_KAZAK_KAZAKHSTAN, "KAZAK_KAZAKHSTAN" }, { RESOURCE_SUBLANGS::SUBLANG_KHMER_CAMBODIA, "KHMER_CAMBODIA" }, { RESOURCE_SUBLANGS::SUBLANG_KICHE_GUATEMALA, "KICHE_GUATEMALA" }, { RESOURCE_SUBLANGS::SUBLANG_KINYARWANDA_RWANDA, "KINYARWANDA_RWANDA" }, { RESOURCE_SUBLANGS::SUBLANG_KONKANI_INDIA, "KONKANI_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_KOREAN, "KOREAN" }, { RESOURCE_SUBLANGS::SUBLANG_KYRGYZ_KYRGYZSTAN, "KYRGYZ_KYRGYZSTAN" }, { RESOURCE_SUBLANGS::SUBLANG_LAO_LAO, "LAO_LAO" }, { RESOURCE_SUBLANGS::SUBLANG_LATVIAN_LATVIA, "LATVIAN_LATVIA" }, { RESOURCE_SUBLANGS::SUBLANG_LITHUANIAN_CLASSIC, "LITHUANIAN_CLASSIC" }, { RESOURCE_SUBLANGS::SUBLANG_LITHUANIAN, "LITHUANIAN" }, { RESOURCE_SUBLANGS::SUBLANG_LOWER_SORBIAN_GERMANY, "LOWER_SORBIAN_GERMANY" }, { RESOURCE_SUBLANGS::SUBLANG_LUXEMBOURGISH_LUXEMBOURG, "LUXEMBOURGISH_LUXEMBOURG" }, { RESOURCE_SUBLANGS::SUBLANG_MACEDONIAN_MACEDONIA, "MACEDONIAN_MACEDONIA" }, { RESOURCE_SUBLANGS::SUBLANG_MALAY_BRUNEI_DARUSSALAM, "MALAY_BRUNEI_DARUSSALAM" }, { RESOURCE_SUBLANGS::SUBLANG_MALAY_MALAYSIA, "MALAY_MALAYSIA" }, { RESOURCE_SUBLANGS::SUBLANG_MALAYALAM_INDIA, "MALAYALAM_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_MALTESE_MALTA, "MALTESE_MALTA" }, { RESOURCE_SUBLANGS::SUBLANG_MAORI_NEW_ZEALAND, "MAORI_NEW_ZEALAND" }, { RESOURCE_SUBLANGS::SUBLANG_MAPUDUNGUN_CHILE, "MAPUDUNGUN_CHILE" }, { RESOURCE_SUBLANGS::SUBLANG_MARATHI_INDIA, "MARATHI_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_MOHAWK_MOHAWK, "MOHAWK_MOHAWK" }, { RESOURCE_SUBLANGS::SUBLANG_MONGOLIAN_CYRILLIC_MONGOLIA, "MONGOLIAN_CYRILLIC_MONGOLIA" }, { RESOURCE_SUBLANGS::SUBLANG_MONGOLIAN_PRC, "MONGOLIAN_PRC" }, { RESOURCE_SUBLANGS::SUBLANG_NEPALI_INDIA, "NEPALI_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_NEPALI_NEPAL, "NEPALI_NEPAL" }, { RESOURCE_SUBLANGS::SUBLANG_NEUTRAL, "NEUTRAL" }, { RESOURCE_SUBLANGS::SUBLANG_NORWEGIAN_BOKMAL, "NORWEGIAN_BOKMAL" }, { RESOURCE_SUBLANGS::SUBLANG_NORWEGIAN_NYNORSK, "NORWEGIAN_NYNORSK" }, { RESOURCE_SUBLANGS::SUBLANG_OCCITAN_FRANCE, "OCCITAN_FRANCE" }, { RESOURCE_SUBLANGS::SUBLANG_ORIYA_INDIA, "ORIYA_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_PASHTO_AFGHANISTAN, "PASHTO_AFGHANISTAN" }, { RESOURCE_SUBLANGS::SUBLANG_PERSIAN_IRAN, "PERSIAN_IRAN" }, { RESOURCE_SUBLANGS::SUBLANG_POLISH_POLAND, "POLISH_POLAND" }, { RESOURCE_SUBLANGS::SUBLANG_PORTUGUESE_BRAZILIAN, "PORTUGUESE_BRAZILIAN" }, { RESOURCE_SUBLANGS::SUBLANG_PORTUGUESE, "PORTUGUESE" }, { RESOURCE_SUBLANGS::SUBLANG_PUNJABI_INDIA, "PUNJABI_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_QUECHUA_BOLIVIA, "QUECHUA_BOLIVIA" }, { RESOURCE_SUBLANGS::SUBLANG_QUECHUA_ECUADOR, "QUECHUA_ECUADOR" }, { RESOURCE_SUBLANGS::SUBLANG_QUECHUA_PERU, "QUECHUA_PERU" }, { RESOURCE_SUBLANGS::SUBLANG_ROMANIAN_ROMANIA, "ROMANIAN_ROMANIA" }, { RESOURCE_SUBLANGS::SUBLANG_ROMANSH_SWITZERLAND, "ROMANSH_SWITZERLAND" }, { RESOURCE_SUBLANGS::SUBLANG_RUSSIAN_RUSSIA, "RUSSIAN_RUSSIA" }, { RESOURCE_SUBLANGS::SUBLANG_SAMI_INARI_FINLAND, "SAMI_INARI_FINLAND" }, { RESOURCE_SUBLANGS::SUBLANG_SAMI_LULE_NORWAY, "SAMI_LULE_NORWAY" }, { RESOURCE_SUBLANGS::SUBLANG_SAMI_LULE_SWEDEN, "SAMI_LULE_SWEDEN" }, { RESOURCE_SUBLANGS::SUBLANG_SAMI_NORTHERN_FINLAND, "SAMI_NORTHERN_FINLAND" }, { RESOURCE_SUBLANGS::SUBLANG_SAMI_NORTHERN_NORWAY, "SAMI_NORTHERN_NORWAY" }, { RESOURCE_SUBLANGS::SUBLANG_SAMI_NORTHERN_SWEDEN, "SAMI_NORTHERN_SWEDEN" }, { RESOURCE_SUBLANGS::SUBLANG_SAMI_SKOLT_FINLAND, "SAMI_SKOLT_FINLAND" }, { RESOURCE_SUBLANGS::SUBLANG_SAMI_SOUTHERN_NORWAY, "SAMI_SOUTHERN_NORWAY" }, { RESOURCE_SUBLANGS::SUBLANG_SAMI_SOUTHERN_SWEDEN, "SAMI_SOUTHERN_SWEDEN" }, { RESOURCE_SUBLANGS::SUBLANG_SANSKRIT_INDIA, "SANSKRIT_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_CYRILLIC, "SERBIAN_BOSNIA_HERZEGOVINA_CYRILLIC" }, { RESOURCE_SUBLANGS::SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_LATIN, "SERBIAN_BOSNIA_HERZEGOVINA_LATIN" }, { RESOURCE_SUBLANGS::SUBLANG_SERBIAN_CROATIA, "SERBIAN_CROATIA" }, { RESOURCE_SUBLANGS::SUBLANG_SERBIAN_CYRILLIC, "SERBIAN_CYRILLIC" }, { RESOURCE_SUBLANGS::SUBLANG_SERBIAN_LATIN, "SERBIAN_LATIN" }, { RESOURCE_SUBLANGS::SUBLANG_SINDHI_AFGHANISTAN, "SINDHI_AFGHANISTAN" }, { RESOURCE_SUBLANGS::SUBLANG_SINDHI_INDIA, "SINDHI_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_SINDHI_PAKISTAN, "SINDHI_PAKISTAN" }, { RESOURCE_SUBLANGS::SUBLANG_SINHALESE_SRI_LANKA, "SINHALESE_SRI_LANKA" }, { RESOURCE_SUBLANGS::SUBLANG_SLOVAK_SLOVAKIA, "SLOVAK_SLOVAKIA" }, { RESOURCE_SUBLANGS::SUBLANG_SLOVENIAN_SLOVENIA, "SLOVENIAN_SLOVENIA" }, { RESOURCE_SUBLANGS::SUBLANG_SOTHO_NORTHERN_SOUTH_AFRICA, "SOTHO_NORTHERN_SOUTH_AFRICA" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_ARGENTINA, "SPANISH_ARGENTINA" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_BOLIVIA, "SPANISH_BOLIVIA" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_CHILE, "SPANISH_CHILE" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_COLOMBIA, "SPANISH_COLOMBIA" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_COSTA_RICA, "SPANISH_COSTA_RICA" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_DOMINICAN_REPUBLIC, "SPANISH_DOMINICAN_REPUBLIC" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_ECUADOR, "SPANISH_ECUADOR" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_EL_SALVADOR, "SPANISH_EL_SALVADOR" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_GUATEMALA, "SPANISH_GUATEMALA" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_HONDURAS, "SPANISH_HONDURAS" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_MEXICAN, "SPANISH_MEXICAN" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_MODERN, "SPANISH_MODERN" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_NICARAGUA, "SPANISH_NICARAGUA" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_PANAMA, "SPANISH_PANAMA" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_PARAGUAY, "SPANISH_PARAGUAY" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_PERU, "SPANISH_PERU" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_PUERTO_RICO, "SPANISH_PUERTO_RICO" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_URUGUAY, "SPANISH_URUGUAY" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_US, "SPANISH_US" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH_VENEZUELA, "SPANISH_VENEZUELA" }, { RESOURCE_SUBLANGS::SUBLANG_SPANISH, "SPANISH" }, { RESOURCE_SUBLANGS::SUBLANG_SWAHILI_KENYA, "SWAHILI_KENYA" }, { RESOURCE_SUBLANGS::SUBLANG_SWEDISH_FINLAND, "SWEDISH_FINLAND" }, { RESOURCE_SUBLANGS::SUBLANG_SWEDISH, "SWEDISH" }, { RESOURCE_SUBLANGS::SUBLANG_SYRIAC_SYRIA, "SYRIAC_SYRIA" }, { RESOURCE_SUBLANGS::SUBLANG_SYS_DEFAULT, "SYS_DEFAULT" }, { RESOURCE_SUBLANGS::SUBLANG_TAJIK_TAJIKISTAN, "TAJIK_TAJIKISTAN" }, { RESOURCE_SUBLANGS::SUBLANG_TAMAZIGHT_ALGERIA_LATIN, "TAMAZIGHT_ALGERIA_LATIN" }, { RESOURCE_SUBLANGS::SUBLANG_TAMIL_INDIA, "TAMIL_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_TATAR_RUSSIA, "TATAR_RUSSIA" }, { RESOURCE_SUBLANGS::SUBLANG_TELUGU_INDIA, "TELUGU_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_THAI_THAILAND, "THAI_THAILAND" }, { RESOURCE_SUBLANGS::SUBLANG_TIBETAN_PRC, "TIBETAN_PRC" }, { RESOURCE_SUBLANGS::SUBLANG_TIGRIGNA_ERITREA, "TIGRIGNA_ERITREA" }, { RESOURCE_SUBLANGS::SUBLANG_TSWANA_SOUTH_AFRICA, "TSWANA_SOUTH_AFRICA" }, { RESOURCE_SUBLANGS::SUBLANG_TURKISH_TURKEY, "TURKISH_TURKEY" }, { RESOURCE_SUBLANGS::SUBLANG_TURKMEN_TURKMENISTAN, "TURKMEN_TURKMENISTAN" }, { RESOURCE_SUBLANGS::SUBLANG_UI_CUSTOM_DEFAULT, "UI_CUSTOM_DEFAULT" }, { RESOURCE_SUBLANGS::SUBLANG_UIGHUR_PRC, "UIGHUR_PRC" }, { RESOURCE_SUBLANGS::SUBLANG_UKRAINIAN_UKRAINE, "UKRAINIAN_UKRAINE" }, { RESOURCE_SUBLANGS::SUBLANG_UPPER_SORBIAN_GERMANY, "UPPER_SORBIAN_GERMANY" }, { RESOURCE_SUBLANGS::SUBLANG_URDU_INDIA, "URDU_INDIA" }, { RESOURCE_SUBLANGS::SUBLANG_URDU_PAKISTAN, "URDU_PAKISTAN" }, { RESOURCE_SUBLANGS::SUBLANG_UZBEK_CYRILLIC, "UZBEK_CYRILLIC" }, { RESOURCE_SUBLANGS::SUBLANG_UZBEK_LATIN, "UZBEK_LATIN" }, { RESOURCE_SUBLANGS::SUBLANG_VIETNAMESE_VIETNAM, "VIETNAMESE_VIETNAM" }, { RESOURCE_SUBLANGS::SUBLANG_WELSH_UNITED_KINGDOM, "WELSH_UNITED_KINGDOM" }, { RESOURCE_SUBLANGS::SUBLANG_WOLOF_SENEGAL, "WOLOF_SENEGAL" }, { RESOURCE_SUBLANGS::SUBLANG_XHOSA_SOUTH_AFRICA, "XHOSA_SOUTH_AFRICA" }, { RESOURCE_SUBLANGS::SUBLANG_YAKUT_RUSSIA, "YAKUT_RUSSIA" }, { RESOURCE_SUBLANGS::SUBLANG_YI_PRC, "YI_PRC" }, { RESOURCE_SUBLANGS::SUBLANG_YORUBA_NIGERIA, "YORUBA_NIGERIA" }, { RESOURCE_SUBLANGS::SUBLANG_ZULU_SOUTH_AFRICA, "ZULU_SOUTH_AFRICA" }, { RESOURCE_SUBLANGS::SUBLANG_PUNJABI_PAKISTAN, "PUNJABI_PAKISTAN" }, { RESOURCE_SUBLANGS::SUBLANG_TSWANA_BOTSWANA, "TSWANA_BOTSWANA" }, { RESOURCE_SUBLANGS::SUBLANG_TAMIL_SRI_LANKA, "TAMIL_SRI_LANKA" }, { RESOURCE_SUBLANGS::SUBLANG_TIGRINYA_ETHIOPIA, "TIGRINYA_ETHIOPIA" }, { RESOURCE_SUBLANGS::SUBLANG_TIGRINYA_ERITREA, "TIGRINYA_ERITREA" }, { RESOURCE_SUBLANGS::SUBLANG_VALENCIAN_VALENCIA, "VALENCIAN_VALENCIA" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(EXTENDED_WINDOW_STYLES e) { CONST_MAP(EXTENDED_WINDOW_STYLES, const char*, 17) enumStrings { { EXTENDED_WINDOW_STYLES::WS_EX_DLGMODALFRAME, "DLGMODALFRAME" }, { EXTENDED_WINDOW_STYLES::WS_EX_NOPARENTNOTIFY, "NOPARENTNOTIFY" }, { EXTENDED_WINDOW_STYLES::WS_EX_TOPMOST, "TOPMOST" }, { EXTENDED_WINDOW_STYLES::WS_EX_ACCEPTFILES, "ACCEPTFILES" }, { EXTENDED_WINDOW_STYLES::WS_EX_TRANSPARENT, "TRANSPARENT" }, { EXTENDED_WINDOW_STYLES::WS_EX_MDICHILD, "MDICHILD" }, { EXTENDED_WINDOW_STYLES::WS_EX_TOOLWINDOW, "TOOLWINDOW" }, { EXTENDED_WINDOW_STYLES::WS_EX_WINDOWEDGE, "WINDOWEDGE" }, { EXTENDED_WINDOW_STYLES::WS_EX_CLIENTEDGE, "CLIENTEDGE" }, { EXTENDED_WINDOW_STYLES::WS_EX_CONTEXTHELP, "CONTEXTHELP" }, { EXTENDED_WINDOW_STYLES::WS_EX_RIGHT, "RIGHT" }, { EXTENDED_WINDOW_STYLES::WS_EX_LEFT, "LEFT" }, { EXTENDED_WINDOW_STYLES::WS_EX_RTLREADING, "RTLREADING" }, { EXTENDED_WINDOW_STYLES::WS_EX_LEFTSCROLLBAR, "LEFTSCROLLBAR" }, { EXTENDED_WINDOW_STYLES::WS_EX_CONTROLPARENT, "CONTROLPARENT" }, { EXTENDED_WINDOW_STYLES::WS_EX_STATICEDGE, "STATICEDGE" }, { EXTENDED_WINDOW_STYLES::WS_EX_APPWINDOW, "APPWINDOW" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(WINDOW_STYLES e) { CONST_MAP(WINDOW_STYLES, const char*, 18) enumStrings { { WINDOW_STYLES::WS_OVERLAPPED, "OVERLAPPED" }, { WINDOW_STYLES::WS_POPUP, "POPUP" }, { WINDOW_STYLES::WS_CHILD, "CHILD" }, { WINDOW_STYLES::WS_MINIMIZE, "MINIMIZE" }, { WINDOW_STYLES::WS_VISIBLE, "VISIBLE" }, { WINDOW_STYLES::WS_DISABLED, "DISABLED" }, { WINDOW_STYLES::WS_CLIPSIBLINGS, "CLIPSIBLINGS" }, { WINDOW_STYLES::WS_CLIPCHILDREN, "CLIPCHILDREN" }, { WINDOW_STYLES::WS_MAXIMIZE, "MAXIMIZE" }, { WINDOW_STYLES::WS_CAPTION, "CAPTION" }, { WINDOW_STYLES::WS_BORDER, "BORDER" }, { WINDOW_STYLES::WS_DLGFRAME, "DLGFRAME" }, { WINDOW_STYLES::WS_VSCROLL, "VSCROLL" }, { WINDOW_STYLES::WS_HSCROLL, "HSCROLL" }, { WINDOW_STYLES::WS_SYSMENU, "SYSMENU" }, { WINDOW_STYLES::WS_THICKFRAME, "THICKFRAME" }, { WINDOW_STYLES::WS_MINIMIZEBOX, "MINIMIZEBOX" }, { WINDOW_STYLES::WS_MAXIMIZEBOX, "MAXIMIZEBOX" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(DIALOG_BOX_STYLES e) { CONST_MAP(DIALOG_BOX_STYLES, const char*, 15) enumStrings { { DIALOG_BOX_STYLES::DS_ABSALIGN, "ABSALIGN" }, { DIALOG_BOX_STYLES::DS_SYSMODAL, "SYSMODAL" }, { DIALOG_BOX_STYLES::DS_LOCALEDIT, "LOCALEDIT" }, { DIALOG_BOX_STYLES::DS_SETFONT, "SETFONT" }, { DIALOG_BOX_STYLES::DS_MODALFRAME, "MODALFRAME" }, { DIALOG_BOX_STYLES::DS_NOIDLEMSG, "NOIDLEMSG" }, { DIALOG_BOX_STYLES::DS_SETFOREGROUND, "SETFOREGROUND" }, { DIALOG_BOX_STYLES::DS_3DLOOK, "D3DLOOK" }, { DIALOG_BOX_STYLES::DS_FIXEDSYS, "FIXEDSYS" }, { DIALOG_BOX_STYLES::DS_NOFAILCREATE, "NOFAILCREATE" }, { DIALOG_BOX_STYLES::DS_CONTROL, "CONTROL" }, { DIALOG_BOX_STYLES::DS_CENTER, "CENTER" }, { DIALOG_BOX_STYLES::DS_CENTERMOUSE, "CENTERMOUSE" }, { DIALOG_BOX_STYLES::DS_CONTEXTHELP, "CONTEXTHELP" }, { DIALOG_BOX_STYLES::DS_SHELLFONT, "SHELLFONT" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(FIXED_VERSION_OS e) { CONST_MAP(FIXED_VERSION_OS, const char*, 14) enumStrings { { FIXED_VERSION_OS::VOS_UNKNOWN, "UNKNOWN" }, { FIXED_VERSION_OS::VOS_DOS, "DOS" }, { FIXED_VERSION_OS::VOS_NT, "NT" }, { FIXED_VERSION_OS::VOS__WINDOWS16, "WINDOWS16" }, { FIXED_VERSION_OS::VOS__WINDOWS32, "WINDOWS32" }, { FIXED_VERSION_OS::VOS_OS216, "OS216" }, { FIXED_VERSION_OS::VOS_OS232, "OS232" }, { FIXED_VERSION_OS::VOS__PM16, "PM16" }, { FIXED_VERSION_OS::VOS__PM32, "PM32" }, { FIXED_VERSION_OS::VOS_DOS_WINDOWS16, "DOS_WINDOWS16" }, { FIXED_VERSION_OS::VOS_DOS_WINDOWS32, "DOS_WINDOWS32" }, { FIXED_VERSION_OS::VOS_NT_WINDOWS32, "NT_WINDOWS32" }, { FIXED_VERSION_OS::VOS_OS216_PM16, "OS216_PM16" }, { FIXED_VERSION_OS::VOS_OS232_PM32, "OS232_PM32" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(FIXED_VERSION_FILE_FLAGS e) { CONST_MAP(FIXED_VERSION_FILE_FLAGS, const char*, 6) enumStrings { { FIXED_VERSION_FILE_FLAGS::VS_FF_DEBUG, "DEBUG" }, { FIXED_VERSION_FILE_FLAGS::VS_FF_INFOINFERRED, "INFOINFERRED" }, { FIXED_VERSION_FILE_FLAGS::VS_FF_PATCHED, "PATCHED" }, { FIXED_VERSION_FILE_FLAGS::VS_FF_PRERELEASE, "PRERELEASE" }, { FIXED_VERSION_FILE_FLAGS::VS_FF_PRIVATEBUILD, "PRIVATEBUILD" }, { FIXED_VERSION_FILE_FLAGS::VS_FF_SPECIALBUILD, "SPECIALBUILD" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(FIXED_VERSION_FILE_TYPES e) { CONST_MAP(FIXED_VERSION_FILE_TYPES, const char*, 7) enumStrings { { FIXED_VERSION_FILE_TYPES::VFT_APP, "APP" }, { FIXED_VERSION_FILE_TYPES::VFT_DLL, "DLL" }, { FIXED_VERSION_FILE_TYPES::VFT_DRV, "DRV" }, { FIXED_VERSION_FILE_TYPES::VFT_FONT, "FONT" }, { FIXED_VERSION_FILE_TYPES::VFT_STATIC_LIB, "STATIC_LIB" }, { FIXED_VERSION_FILE_TYPES::VFT_UNKNOWN, "UNKNOWN" }, { FIXED_VERSION_FILE_TYPES::VFT_VXD, "VXD" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(FIXED_VERSION_FILE_SUB_TYPES e) { CONST_MAP(FIXED_VERSION_FILE_SUB_TYPES, const char*, 12) enumStrings { { FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_COMM, "DRV_COMM" }, { FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_DISPLAY, "DRV_DISPLAY" }, { FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_INSTALLABLE, "DRV_INSTALLABLE" }, { FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_KEYBOARD, "DRV_KEYBOARD" }, { FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_LANGUAGE, "DRV_LANGUAGE" }, { FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_MOUSE, "DRV_MOUSE" }, { FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_NETWORK, "DRV_NETWORK" }, { FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_PRINTER, "DRV_PRINTER" }, { FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_SOUND, "DRV_SOUND" }, { FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_SYSTEM, "DRV_SYSTEM" }, { FIXED_VERSION_FILE_SUB_TYPES::VFT2_DRV_VERSIONED_PRINTER, "DRV_VERSIONED_PRINTER" }, { FIXED_VERSION_FILE_SUB_TYPES::VFT2_UNKNOWN, "UNKNOWN" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(CODE_PAGES e) { CONST_MAP(CODE_PAGES, const char*, 140) enumStrings { { CODE_PAGES::CP_IBM037, "IBM037"}, { CODE_PAGES::CP_IBM437, "IBM437"}, { CODE_PAGES::CP_IBM500, "IBM500"}, { CODE_PAGES::CP_ASMO_708, "ASMO_708"}, { CODE_PAGES::CP_DOS_720, "DOS_720"}, { CODE_PAGES::CP_IBM737, "IBM737"}, { CODE_PAGES::CP_IBM775, "IBM775"}, { CODE_PAGES::CP_IBM850, "IBM850"}, { CODE_PAGES::CP_IBM852, "IBM852"}, { CODE_PAGES::CP_IBM855, "IBM855"}, { CODE_PAGES::CP_IBM857, "IBM857"}, { CODE_PAGES::CP_IBM00858, "IBM00858"}, { CODE_PAGES::CP_IBM860, "IBM860"}, { CODE_PAGES::CP_IBM861, "IBM861"}, { CODE_PAGES::CP_DOS_862, "DOS_862"}, { CODE_PAGES::CP_IBM863, "IBM863"}, { CODE_PAGES::CP_IBM864, "IBM864"}, { CODE_PAGES::CP_IBM865, "IBM865"}, { CODE_PAGES::CP_CP866, "CP866"}, { CODE_PAGES::CP_IBM869, "IBM869"}, { CODE_PAGES::CP_IBM870, "IBM870"}, { CODE_PAGES::CP_WINDOWS_874, "WINDOWS_874"}, { CODE_PAGES::CP_CP875, "CP875"}, { CODE_PAGES::CP_SHIFT_JIS, "SHIFT_JIS"}, { CODE_PAGES::CP_GB2312, "GB2312"}, { CODE_PAGES::CP_KS_C_5601_1987, "KS_C_5601_1987"}, { CODE_PAGES::CP_BIG5, "BIG5"}, { CODE_PAGES::CP_IBM1026, "IBM1026"}, { CODE_PAGES::CP_IBM01047, "IBM01047"}, { CODE_PAGES::CP_IBM01140, "IBM01140"}, { CODE_PAGES::CP_IBM01141, "IBM01141"}, { CODE_PAGES::CP_IBM01142, "IBM01142"}, { CODE_PAGES::CP_IBM01143, "IBM01143"}, { CODE_PAGES::CP_IBM01144, "IBM01144"}, { CODE_PAGES::CP_IBM01145, "IBM01145"}, { CODE_PAGES::CP_IBM01146, "IBM01146"}, { CODE_PAGES::CP_IBM01147, "IBM01147"}, { CODE_PAGES::CP_IBM01148, "IBM01148"}, { CODE_PAGES::CP_IBM01149, "IBM01149"}, { CODE_PAGES::CP_UTF_16, "UTF_16"}, { CODE_PAGES::CP_UNICODEFFFE, "UNICODEFFFE"}, { CODE_PAGES::CP_WINDOWS_1250, "WINDOWS_1250"}, { CODE_PAGES::CP_WINDOWS_1251, "WINDOWS_1251"}, { CODE_PAGES::CP_WINDOWS_1252, "WINDOWS_1252"}, { CODE_PAGES::CP_WINDOWS_1253, "WINDOWS_1253"}, { CODE_PAGES::CP_WINDOWS_1254, "WINDOWS_1254"}, { CODE_PAGES::CP_WINDOWS_1255, "WINDOWS_1255"}, { CODE_PAGES::CP_WINDOWS_1256, "WINDOWS_1256"}, { CODE_PAGES::CP_WINDOWS_1257, "WINDOWS_1257"}, { CODE_PAGES::CP_WINDOWS_1258, "WINDOWS_1258"}, { CODE_PAGES::CP_JOHAB, "JOHAB"}, { CODE_PAGES::CP_MACINTOSH, "MACINTOSH"}, { CODE_PAGES::CP_X_MAC_JAPANESE, "X_MAC_JAPANESE"}, { CODE_PAGES::CP_X_MAC_CHINESETRAD, "X_MAC_CHINESETRAD"}, { CODE_PAGES::CP_X_MAC_KOREAN, "X_MAC_KOREAN"}, { CODE_PAGES::CP_X_MAC_ARABIC, "X_MAC_ARABIC"}, { CODE_PAGES::CP_X_MAC_HEBREW, "X_MAC_HEBREW"}, { CODE_PAGES::CP_X_MAC_GREEK, "X_MAC_GREEK"}, { CODE_PAGES::CP_X_MAC_CYRILLIC, "X_MAC_CYRILLIC"}, { CODE_PAGES::CP_X_MAC_CHINESESIMP, "X_MAC_CHINESESIMP"}, { CODE_PAGES::CP_X_MAC_ROMANIAN, "X_MAC_ROMANIAN"}, { CODE_PAGES::CP_X_MAC_UKRAINIAN, "X_MAC_UKRAINIAN"}, { CODE_PAGES::CP_X_MAC_THAI, "X_MAC_THAI"}, { CODE_PAGES::CP_X_MAC_CE, "X_MAC_CE"}, { CODE_PAGES::CP_X_MAC_ICELANDIC, "X_MAC_ICELANDIC"}, { CODE_PAGES::CP_X_MAC_TURKISH, "X_MAC_TURKISH"}, { CODE_PAGES::CP_X_MAC_CROATIAN, "X_MAC_CROATIAN"}, { CODE_PAGES::CP_UTF_32, "UTF_32"}, { CODE_PAGES::CP_UTF_32BE, "UTF_32BE"}, { CODE_PAGES::CP_X_CHINESE_CNS, "X_CHINESE_CNS"}, { CODE_PAGES::CP_X_CP20001, "X_CP20001"}, { CODE_PAGES::CP_X_CHINESE_ETEN, "X_CHINESE_ETEN"}, { CODE_PAGES::CP_X_CP20003, "X_CP20003"}, { CODE_PAGES::CP_X_CP20004, "X_CP20004"}, { CODE_PAGES::CP_X_CP20005, "X_CP20005"}, { CODE_PAGES::CP_X_IA5, "X_IA5"}, { CODE_PAGES::CP_X_IA5_GERMAN, "X_IA5_GERMAN"}, { CODE_PAGES::CP_X_IA5_SWEDISH, "X_IA5_SWEDISH"}, { CODE_PAGES::CP_X_IA5_NORWEGIAN, "X_IA5_NORWEGIAN"}, { CODE_PAGES::CP_US_ASCII, "US_ASCII"}, { CODE_PAGES::CP_X_CP20261, "X_CP20261"}, { CODE_PAGES::CP_X_CP20269, "X_CP20269"}, { CODE_PAGES::CP_IBM273, "IBM273"}, { CODE_PAGES::CP_IBM277, "IBM277"}, { CODE_PAGES::CP_IBM278, "IBM278"}, { CODE_PAGES::CP_IBM280, "IBM280"}, { CODE_PAGES::CP_IBM284, "IBM284"}, { CODE_PAGES::CP_IBM285, "IBM285"}, { CODE_PAGES::CP_IBM290, "IBM290"}, { CODE_PAGES::CP_IBM297, "IBM297"}, { CODE_PAGES::CP_IBM420, "IBM420"}, { CODE_PAGES::CP_IBM423, "IBM423"}, { CODE_PAGES::CP_IBM424, "IBM424"}, { CODE_PAGES::CP_X_EBCDIC_KOREANEXTENDED, "X_EBCDIC_KOREANEXTENDED"}, { CODE_PAGES::CP_IBM_THAI, "IBM_THAI"}, { CODE_PAGES::CP_KOI8_R, "KOI8_R"}, { CODE_PAGES::CP_IBM871, "IBM871"}, { CODE_PAGES::CP_IBM880, "IBM880"}, { CODE_PAGES::CP_IBM905, "IBM905"}, { CODE_PAGES::CP_IBM00924, "IBM00924"}, { CODE_PAGES::CP_EUC_JP_JIS, "EUC_JP_JIS"}, { CODE_PAGES::CP_X_CP20936, "X_CP20936"}, { CODE_PAGES::CP_X_CP20949, "X_CP20949"}, { CODE_PAGES::CP_CP1025, "CP1025"}, { CODE_PAGES::CP_KOI8_U, "KOI8_U"}, { CODE_PAGES::CP_ISO_8859_1, "ISO_8859_1"}, { CODE_PAGES::CP_ISO_8859_2, "ISO_8859_2"}, { CODE_PAGES::CP_ISO_8859_3, "ISO_8859_3"}, { CODE_PAGES::CP_ISO_8859_4, "ISO_8859_4"}, { CODE_PAGES::CP_ISO_8859_5, "ISO_8859_5"}, { CODE_PAGES::CP_ISO_8859_6, "ISO_8859_6"}, { CODE_PAGES::CP_ISO_8859_7, "ISO_8859_7"}, { CODE_PAGES::CP_ISO_8859_8, "ISO_8859_8"}, { CODE_PAGES::CP_ISO_8859_9, "ISO_8859_9"}, { CODE_PAGES::CP_ISO_8859_13, "ISO_8859_13"}, { CODE_PAGES::CP_ISO_8859_15, "ISO_8859_15"}, { CODE_PAGES::CP_X_EUROPA, "X_EUROPA"}, { CODE_PAGES::CP_ISO_8859_8_I, "ISO_8859_8_I"}, { CODE_PAGES::CP_ISO_2022_JP, "ISO_2022_JP"}, { CODE_PAGES::CP_CSISO2022JP, "CSISO2022JP"}, { CODE_PAGES::CP_ISO_2022_JP_JIS, "ISO_2022_JP_JIS"}, { CODE_PAGES::CP_ISO_2022_KR, "ISO_2022_KR"}, { CODE_PAGES::CP_X_CP50227, "X_CP50227"}, { CODE_PAGES::CP_EUC_JP, "EUC_JP"}, { CODE_PAGES::CP_EUC_CN, "EUC_CN"}, { CODE_PAGES::CP_EUC_KR, "EUC_KR"}, { CODE_PAGES::CP_HZ_GB_2312, "HZ_GB_2312"}, { CODE_PAGES::CP_GB18030, "GB18030"}, { CODE_PAGES::CP_X_ISCII_DE, "X_ISCII_DE"}, { CODE_PAGES::CP_X_ISCII_BE, "X_ISCII_BE"}, { CODE_PAGES::CP_X_ISCII_TA, "X_ISCII_TA"}, { CODE_PAGES::CP_X_ISCII_TE, "X_ISCII_TE"}, { CODE_PAGES::CP_X_ISCII_AS, "X_ISCII_AS"}, { CODE_PAGES::CP_X_ISCII_OR, "X_ISCII_OR"}, { CODE_PAGES::CP_X_ISCII_KA, "X_ISCII_KA"}, { CODE_PAGES::CP_X_ISCII_MA, "X_ISCII_MA"}, { CODE_PAGES::CP_X_ISCII_GU, "X_ISCII_GU"}, { CODE_PAGES::CP_X_ISCII_PA, "X_ISCII_PA"}, { CODE_PAGES::CP_UTF_7, "UTF_7"}, { CODE_PAGES::CP_UTF_8, "UTF_8"}, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(WIN_VERSION e) { CONST_MAP(WIN_VERSION, const char*, 9) enumStrings { { WIN_VERSION::WIN_UNKNOWN, "UNKNOWN" }, { WIN_VERSION::WIN_SEH, "SEH" }, { WIN_VERSION::WIN8_1, "WIN_8_1" }, { WIN_VERSION::WIN10_0_9879, "WIN10_0_9879" }, { WIN_VERSION::WIN10_0_14286, "WIN10_0_14286" }, { WIN_VERSION::WIN10_0_14383, "WIN10_0_14383" }, { WIN_VERSION::WIN10_0_14901, "WIN10_0_14901" }, { WIN_VERSION::WIN10_0_15002, "WIN10_0_15002" }, { WIN_VERSION::WIN10_0_16237, "WIN10_0_16237" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(GUARD_CF_FLAGS e) { CONST_MAP(GUARD_CF_FLAGS, const char*, 10) enumStrings { { GUARD_CF_FLAGS::GCF_NONE, "GCF_NONE" }, { GUARD_CF_FLAGS::GCF_INSTRUMENTED, "GCF_INSTRUMENTED" }, { GUARD_CF_FLAGS::GCF_W_INSTRUMENTED, "GCF_W_INSTRUMENTED" }, { GUARD_CF_FLAGS::GCF_FUNCTION_TABLE_PRESENT, "GCF_FUNCTION_TABLE_PRESENT" }, { GUARD_CF_FLAGS::GCF_EXPORT_SUPPRESSION_INFO_PRESENT, "GCF_EXPORT_SUPPRESSION_INFO_PRESENT" }, { GUARD_CF_FLAGS::GCF_ENABLE_EXPORT_SUPPRESSION, "GCF_ENABLE_EXPORT_SUPPRESSION" }, { GUARD_CF_FLAGS::GCF_LONGJUMP_TABLE_PRESENT, "GCF_LONGJUMP_TABLE_PRESENT" }, { GUARD_CF_FLAGS::GRF_INSTRUMENTED, "GRF_INSTRUMENTED" }, { GUARD_CF_FLAGS::GRF_ENABLE, "GRF_ENABLE" }, { GUARD_CF_FLAGS::GRF_STRICT, "GRF_STRICT" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(CODE_VIEW_SIGNATURES e) { CONST_MAP(CODE_VIEW_SIGNATURES, const char*, 5) enumStrings { { CODE_VIEW_SIGNATURES::CVS_UNKNOWN, "UNKNOWN" }, { CODE_VIEW_SIGNATURES::CVS_PDB_70, "PDB_70" }, { CODE_VIEW_SIGNATURES::CVS_PDB_20, "PDB_20" }, { CODE_VIEW_SIGNATURES::CVS_CV_50, "CV_50" }, { CODE_VIEW_SIGNATURES::CVS_CV_41, "CV_41" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? to_string(CODE_VIEW_SIGNATURES::CVS_UNKNOWN) : it->second; } const char* to_string(POGO_SIGNATURES e) { CONST_MAP(POGO_SIGNATURES, const char*, 3) enumStrings { { POGO_SIGNATURES::POGO_UNKNOWN, "UNKNOWN" }, { POGO_SIGNATURES::POGO_LCTG, "LCTG" }, { POGO_SIGNATURES::POGO_PGI, "PGI" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? to_string(POGO_SIGNATURES::POGO_UNKNOWN) : it->second; } const char* to_string(ACCELERATOR_FLAGS e) { CONST_MAP(ACCELERATOR_FLAGS, const char*, 6) enumStrings { { ACCELERATOR_FLAGS::FVIRTKEY, "FVIRTKEY" }, { ACCELERATOR_FLAGS::FNOINVERT, "FNOINVERT" }, { ACCELERATOR_FLAGS::FSHIFT, "FSHIFT" }, { ACCELERATOR_FLAGS::FCONTROL, "FCONTROL" }, { ACCELERATOR_FLAGS::FALT, "FALT" }, { ACCELERATOR_FLAGS::END, "END" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "Out of range" : it->second; } const char* to_string(ACCELERATOR_VK_CODES e) { CONST_MAP(ACCELERATOR_VK_CODES, const char*, 174) enumStrings { { ACCELERATOR_VK_CODES::VK_LBUTTON, "VK_LBUTTON" }, { ACCELERATOR_VK_CODES::VK_RBUTTON, "VK_RBUTTON" }, { ACCELERATOR_VK_CODES::VK_CANCEL, "VK_CANCEL" }, { ACCELERATOR_VK_CODES::VK_MBUTTON, "VK_MBUTTON" }, { ACCELERATOR_VK_CODES::VK_XBUTTON1, "VK_XBUTTON1" }, { ACCELERATOR_VK_CODES::VK_XBUTTON2, "VK_XBUTTON2" }, { ACCELERATOR_VK_CODES::VK_BACK, "VK_BACK" }, { ACCELERATOR_VK_CODES::VK_TAB, "VK_TAB" }, { ACCELERATOR_VK_CODES::VK_CLEAR, "VK_CLEAR" }, { ACCELERATOR_VK_CODES::VK_RETURN, "VK_RETURN" }, { ACCELERATOR_VK_CODES::VK_SHIFT, "VK_SHIFT" }, { ACCELERATOR_VK_CODES::VK_CONTROL, "VK_CONTROL" }, { ACCELERATOR_VK_CODES::VK_MENU, "VK_MENU" }, { ACCELERATOR_VK_CODES::VK_PAUSE, "VK_PAUSE" }, { ACCELERATOR_VK_CODES::VK_CAPITAL, "VK_CAPITAL" }, { ACCELERATOR_VK_CODES::VK_KANA, "VK_KANA" }, { ACCELERATOR_VK_CODES::VK_HANGUEL, "VK_HANGUEL" }, { ACCELERATOR_VK_CODES::VK_HANGUL, "VK_HANGUL" }, { ACCELERATOR_VK_CODES::VK_IME_ON, "VK_IME_ON" }, { ACCELERATOR_VK_CODES::VK_JUNJA, "VK_JUNJA" }, { ACCELERATOR_VK_CODES::VK_FINAL, "VK_FINAL" }, { ACCELERATOR_VK_CODES::VK_HANJA, "VK_HANJA" }, { ACCELERATOR_VK_CODES::VK_KANJI, "VK_KANJI" }, { ACCELERATOR_VK_CODES::VK_IME_OFF, "VK_IME_OFF" }, { ACCELERATOR_VK_CODES::VK_ESCAPE, "VK_ESCAPE" }, { ACCELERATOR_VK_CODES::VK_CONVERT, "VK_CONVERT" }, { ACCELERATOR_VK_CODES::VK_NONCONVERT, "VK_NONCONVERT" }, { ACCELERATOR_VK_CODES::VK_ACCEPT, "VK_ACCEPT" }, { ACCELERATOR_VK_CODES::VK_MODECHANGE, "VK_MODECHANGE" }, { ACCELERATOR_VK_CODES::VK_SPACE, "VK_SPACE" }, { ACCELERATOR_VK_CODES::VK_PRIOR, "VK_PRIOR" }, { ACCELERATOR_VK_CODES::VK_NEXT, "VK_NEXT" }, { ACCELERATOR_VK_CODES::VK_END, "VK_END" }, { ACCELERATOR_VK_CODES::VK_HOME, "VK_HOME" }, { ACCELERATOR_VK_CODES::VK_LEFT, "VK_LEFT" }, { ACCELERATOR_VK_CODES::VK_UP, "VK_UP" }, { ACCELERATOR_VK_CODES::VK_RIGHT, "VK_RIGHT" }, { ACCELERATOR_VK_CODES::VK_DOWN, "VK_DOWN" }, { ACCELERATOR_VK_CODES::VK_SELECT, "VK_SELECT" }, { ACCELERATOR_VK_CODES::VK_PRINT, "VK_PRINT" }, { ACCELERATOR_VK_CODES::VK_EXECUTE, "VK_EXECUTE" }, { ACCELERATOR_VK_CODES::VK_SNAPSHOT, "VK_SNAPSHOT" }, { ACCELERATOR_VK_CODES::VK_INSERT, "VK_INSERT" }, { ACCELERATOR_VK_CODES::VK_DELETE, "VK_DELETE" }, { ACCELERATOR_VK_CODES::VK_HELP, "VK_HELP" }, { ACCELERATOR_VK_CODES::VK_0, "VK_0" }, { ACCELERATOR_VK_CODES::VK_1, "VK_1" }, { ACCELERATOR_VK_CODES::VK_2, "VK_2" }, { ACCELERATOR_VK_CODES::VK_3, "VK_3" }, { ACCELERATOR_VK_CODES::VK_4, "VK_4" }, { ACCELERATOR_VK_CODES::VK_5, "VK_5" }, { ACCELERATOR_VK_CODES::VK_6, "VK_6" }, { ACCELERATOR_VK_CODES::VK_7, "VK_7" }, { ACCELERATOR_VK_CODES::VK_8, "VK_8" }, { ACCELERATOR_VK_CODES::VK_9, "VK_9" }, { ACCELERATOR_VK_CODES::VK_A, "VK_A" }, { ACCELERATOR_VK_CODES::VK_B, "VK_B" }, { ACCELERATOR_VK_CODES::VK_C, "VK_C" }, { ACCELERATOR_VK_CODES::VK_D, "VK_D" }, { ACCELERATOR_VK_CODES::VK_E, "VK_E" }, { ACCELERATOR_VK_CODES::VK_F, "VK_F" }, { ACCELERATOR_VK_CODES::VK_G, "VK_G" }, { ACCELERATOR_VK_CODES::VK_H, "VK_H" }, { ACCELERATOR_VK_CODES::VK_I, "VK_I" }, { ACCELERATOR_VK_CODES::VK_J, "VK_J" }, { ACCELERATOR_VK_CODES::VK_K, "VK_K" }, { ACCELERATOR_VK_CODES::VK_L, "VK_L" }, { ACCELERATOR_VK_CODES::VK_M, "VK_M" }, { ACCELERATOR_VK_CODES::VK_N, "VK_N" }, { ACCELERATOR_VK_CODES::VK_O, "VK_O" }, { ACCELERATOR_VK_CODES::VK_P, "VK_P" }, { ACCELERATOR_VK_CODES::VK_Q, "VK_Q" }, { ACCELERATOR_VK_CODES::VK_R, "VK_R" }, { ACCELERATOR_VK_CODES::VK_S, "VK_S" }, { ACCELERATOR_VK_CODES::VK_T, "VK_T" }, { ACCELERATOR_VK_CODES::VK_U, "VK_U" }, { ACCELERATOR_VK_CODES::VK_V, "VK_V" }, { ACCELERATOR_VK_CODES::VK_W, "VK_W" }, { ACCELERATOR_VK_CODES::VK_X, "VK_X" }, { ACCELERATOR_VK_CODES::VK_Y, "VK_Y" }, { ACCELERATOR_VK_CODES::VK_Z, "VK_Z" }, { ACCELERATOR_VK_CODES::VK_LWIN, "VK_LWIN" }, { ACCELERATOR_VK_CODES::VK_RWIN, "VK_RWIN" }, { ACCELERATOR_VK_CODES::VK_APPS, "VK_APPS" }, { ACCELERATOR_VK_CODES::VK_SLEEP, "VK_SLEEP" }, { ACCELERATOR_VK_CODES::VK_NUMPAD0, "VK_NUMPAD0" }, { ACCELERATOR_VK_CODES::VK_NUMPAD1, "VK_NUMPAD1" }, { ACCELERATOR_VK_CODES::VK_NUMPAD2, "VK_NUMPAD2" }, { ACCELERATOR_VK_CODES::VK_NUMPAD3, "VK_NUMPAD3" }, { ACCELERATOR_VK_CODES::VK_NUMPAD4, "VK_NUMPAD4" }, { ACCELERATOR_VK_CODES::VK_NUMPAD5, "VK_NUMPAD5" }, { ACCELERATOR_VK_CODES::VK_NUMPAD6, "VK_NUMPAD6" }, { ACCELERATOR_VK_CODES::VK_NUMPAD7, "VK_NUMPAD7" }, { ACCELERATOR_VK_CODES::VK_NUMPAD8, "VK_NUMPAD8" }, { ACCELERATOR_VK_CODES::VK_NUMPAD9, "VK_NUMPAD9" }, { ACCELERATOR_VK_CODES::VK_MULTIPLY, "VK_MULTIPLY" }, { ACCELERATOR_VK_CODES::VK_ADD, "VK_ADD" }, { ACCELERATOR_VK_CODES::VK_SEPARATOR, "VK_SEPARATOR" }, { ACCELERATOR_VK_CODES::VK_SUBTRACT, "VK_SUBTRACT" }, { ACCELERATOR_VK_CODES::VK_DECIMAL, "VK_DECIMAL" }, { ACCELERATOR_VK_CODES::VK_DIVIDE, "VK_DIVIDE" }, { ACCELERATOR_VK_CODES::VK_F1, "VK_F1" }, { ACCELERATOR_VK_CODES::VK_F2, "VK_F2" }, { ACCELERATOR_VK_CODES::VK_F3, "VK_F3" }, { ACCELERATOR_VK_CODES::VK_F4, "VK_F4" }, { ACCELERATOR_VK_CODES::VK_F5, "VK_F5" }, { ACCELERATOR_VK_CODES::VK_F6, "VK_F6" }, { ACCELERATOR_VK_CODES::VK_F7, "VK_F7" }, { ACCELERATOR_VK_CODES::VK_F8, "VK_F8" }, { ACCELERATOR_VK_CODES::VK_F9, "VK_F9" }, { ACCELERATOR_VK_CODES::VK_F10, "VK_F10" }, { ACCELERATOR_VK_CODES::VK_F11, "VK_F11" }, { ACCELERATOR_VK_CODES::VK_F12, "VK_F12" }, { ACCELERATOR_VK_CODES::VK_F13, "VK_F13" }, { ACCELERATOR_VK_CODES::VK_F14, "VK_F14" }, { ACCELERATOR_VK_CODES::VK_F15, "VK_F15" }, { ACCELERATOR_VK_CODES::VK_F16, "VK_F16" }, { ACCELERATOR_VK_CODES::VK_F17, "VK_F17" }, { ACCELERATOR_VK_CODES::VK_F18, "VK_F18" }, { ACCELERATOR_VK_CODES::VK_F19, "VK_F19" }, { ACCELERATOR_VK_CODES::VK_F20, "VK_F20" }, { ACCELERATOR_VK_CODES::VK_F21, "VK_F21" }, { ACCELERATOR_VK_CODES::VK_F22, "VK_F22" }, { ACCELERATOR_VK_CODES::VK_F23, "VK_F23" }, { ACCELERATOR_VK_CODES::VK_F24, "VK_F24" }, { ACCELERATOR_VK_CODES::VK_NUMLOCK, "VK_NUMLOCK" }, { ACCELERATOR_VK_CODES::VK_SCROLL, "VK_SCROLL" }, { ACCELERATOR_VK_CODES::VK_LSHIFT, "VK_LSHIFT" }, { ACCELERATOR_VK_CODES::VK_RSHIFT, "VK_RSHIFT" }, { ACCELERATOR_VK_CODES::VK_LCONTROL, "VK_LCONTROL" }, { ACCELERATOR_VK_CODES::VK_RCONTROL, "VK_RCONTROL" }, { ACCELERATOR_VK_CODES::VK_LMENU, "VK_LMENU" }, { ACCELERATOR_VK_CODES::VK_RMENU, "VK_RMENU" }, { ACCELERATOR_VK_CODES::VK_BROWSER_BACK, "VK_BROWSER_BACK" }, { ACCELERATOR_VK_CODES::VK_BROWSER_FORWARD, "VK_BROWSER_FORWARD" }, { ACCELERATOR_VK_CODES::VK_BROWSER_REFRESH, "VK_BROWSER_REFRESH" }, { ACCELERATOR_VK_CODES::VK_BROWSER_STOP, "VK_BROWSER_STOP" }, { ACCELERATOR_VK_CODES::VK_BROWSER_SEARCH, "VK_BROWSER_SEARCH" }, { ACCELERATOR_VK_CODES::VK_BROWSER_FAVORITES, "VK_BROWSER_FAVORITES" }, { ACCELERATOR_VK_CODES::VK_BROWSER_HOME, "VK_BROWSER_HOME" }, { ACCELERATOR_VK_CODES::VK_VOLUME_MUTE, "VK_VOLUME_MUTE" }, { ACCELERATOR_VK_CODES::VK_VOLUME_DOWN, "VK_VOLUME_DOWN" }, { ACCELERATOR_VK_CODES::VK_VOLUME_UP, "VK_VOLUME_UP" }, { ACCELERATOR_VK_CODES::VK_MEDIA_NEXT_TRACK, "VK_MEDIA_NEXT_TRACK" }, { ACCELERATOR_VK_CODES::VK_MEDIA_PREV_TRACK, "VK_MEDIA_PREV_TRACK" }, { ACCELERATOR_VK_CODES::VK_MEDIA_STOP, "VK_MEDIA_STOP" }, { ACCELERATOR_VK_CODES::VK_MEDIA_PLAY_PAUSE, "VK_MEDIA_PLAY_PAUSE" }, { ACCELERATOR_VK_CODES::VK_LAUNCH_MAIL, "VK_LAUNCH_MAIL" }, { ACCELERATOR_VK_CODES::VK_LAUNCH_MEDIA_SELECT, "VK_LAUNCH_MEDIA_SELECT" }, { ACCELERATOR_VK_CODES::VK_LAUNCH_APP1, "VK_LAUNCH_APP1" }, { ACCELERATOR_VK_CODES::VK_LAUNCH_APP2, "VK_LAUNCH_APP2" }, { ACCELERATOR_VK_CODES::VK_OEM_1, "VK_OEM_1" }, { ACCELERATOR_VK_CODES::VK_OEM_PLUS, "VK_OEM_PLUS" }, { ACCELERATOR_VK_CODES::VK_OEM_COMMA, "VK_OEM_COMMA" }, { ACCELERATOR_VK_CODES::VK_OEM_MINUS, "VK_OEM_MINUS" }, { ACCELERATOR_VK_CODES::VK_OEM_PERIOD, "VK_OEM_PERIOD" }, { ACCELERATOR_VK_CODES::VK_OEM_2, "VK_OEM_2" }, { ACCELERATOR_VK_CODES::VK_OEM_4, "VK_OEM_4" }, { ACCELERATOR_VK_CODES::VK_OEM_5, "VK_OEM_5" }, { ACCELERATOR_VK_CODES::VK_OEM_6, "VK_OEM_6" }, { ACCELERATOR_VK_CODES::VK_OEM_7, "VK_OEM_7" }, { ACCELERATOR_VK_CODES::VK_OEM_8, "VK_OEM_8" }, { ACCELERATOR_VK_CODES::VK_OEM_102, "VK_OEM_102" }, { ACCELERATOR_VK_CODES::VK_PROCESSKEY, "VK_PROCESSKEY" }, { ACCELERATOR_VK_CODES::VK_PACKET, "VK_PACKET" }, { ACCELERATOR_VK_CODES::VK_ATTN, "VK_ATTN" }, { ACCELERATOR_VK_CODES::VK_CRSEL, "VK_CRSEL" }, { ACCELERATOR_VK_CODES::VK_EXSEL, "VK_EXSEL" }, { ACCELERATOR_VK_CODES::VK_EREOF, "VK_EREOF" }, { ACCELERATOR_VK_CODES::VK_PLAY, "VK_PLAY" }, { ACCELERATOR_VK_CODES::VK_ZOOM, "VK_ZOOM" }, { ACCELERATOR_VK_CODES::VK_NONAME, "VK_NONAME" }, { ACCELERATOR_VK_CODES::VK_PA1, "VK_PA1" }, { ACCELERATOR_VK_CODES::VK_OEM_CLEAR, "VK_OEM_CLEAR" }, }; auto it = enumStrings.find(e); return it != enumStrings.end() ? it->second : "Undefined or reserved"; } const char* to_string(ALGORITHMS e) { CONST_MAP(ALGORITHMS, const char*, 20) enumStrings { { ALGORITHMS::UNKNOWN, "UNKNOWN" }, { ALGORITHMS::SHA_512, "SHA_512" }, { ALGORITHMS::SHA_384, "SHA_384" }, { ALGORITHMS::SHA_256, "SHA_256" }, { ALGORITHMS::SHA_1, "SHA_1" }, { ALGORITHMS::MD5, "MD5" }, { ALGORITHMS::MD4, "MD4" }, { ALGORITHMS::MD2, "MD2" }, { ALGORITHMS::RSA, "RSA" }, { ALGORITHMS::EC, "EC" }, { ALGORITHMS::MD5_RSA, "MD5_RSA" }, { ALGORITHMS::SHA1_DSA, "SHA1_DSA" }, { ALGORITHMS::SHA1_RSA, "SHA1_RSA" }, { ALGORITHMS::SHA_256_RSA, "SHA_256_RSA" }, { ALGORITHMS::SHA_384_RSA, "SHA_384_RSA" }, { ALGORITHMS::SHA_512_RSA, "SHA_512_RSA" }, { ALGORITHMS::SHA1_ECDSA, "SHA1_ECDSA" }, { ALGORITHMS::SHA_256_ECDSA, "SHA_256_ECDSA" }, { ALGORITHMS::SHA_384_ECDSA, "SHA_384_ECDSA" }, { ALGORITHMS::SHA_512_ECDSA, "SHA_512_ECDSA" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "UNKNOWN" : it->second; } const char* to_string(SIG_ATTRIBUTE_TYPES e) { CONST_MAP(SIG_ATTRIBUTE_TYPES, const char*, 11) enumStrings { { SIG_ATTRIBUTE_TYPES::UNKNOWN, "UNKNOWN" }, { SIG_ATTRIBUTE_TYPES::CONTENT_TYPE, "CONTENT_TYPE" }, { SIG_ATTRIBUTE_TYPES::GENERIC_TYPE, "GENERIC_TYPE" }, { SIG_ATTRIBUTE_TYPES::SPC_SP_OPUS_INFO, "SPC_SP_OPUS_INFO" }, { SIG_ATTRIBUTE_TYPES::MS_COUNTER_SIGN, "MS_COUNTER_SIGN" }, { SIG_ATTRIBUTE_TYPES::MS_SPC_NESTED_SIGN, "MS_SPC_NESTED_SIGN" }, { SIG_ATTRIBUTE_TYPES::MS_SPC_STATEMENT_TYPE, "MS_SPC_STATEMENT_TYPE" }, { SIG_ATTRIBUTE_TYPES::PKCS9_AT_SEQUENCE_NUMBER, "PKCS9_AT_SEQUENCE_NUMBER" }, { SIG_ATTRIBUTE_TYPES::PKCS9_COUNTER_SIGNATURE, "PKCS9_COUNTER_SIGNATURE" }, { SIG_ATTRIBUTE_TYPES::PKCS9_MESSAGE_DIGEST, "PKCS9_MESSAGE_DIGEST" }, { SIG_ATTRIBUTE_TYPES::PKCS9_SIGNING_TIME, "PKCS9_SIGNING_TIME" }, }; auto it = enumStrings.find(e); return it == enumStrings.end() ? "UNKNOWN" : it->second; } } // namespace PE } // namespace LIEF
83,350
39,840
/* * @Author: gpinchon * @Date: 2021-04-11 20:53:00 * @Last Modified by: gpinchon * @Last Modified time: 2021-04-11 20:53:22 */ #include <Driver/OpenGL/Renderer/Light/PointLightRenderer.hpp> #include <Light/PointLight.hpp> #include <Surface/SphereMesh.hpp> #include <Renderer/Surface/GeometryRenderer.hpp> #include <Renderer/Renderer.hpp> #include <Shader/Program.hpp> #include <Shader/Stage.hpp> #include <Texture/Framebuffer.hpp> #include <Texture/Texture2D.hpp> #include <GL/glew.h> namespace Renderer { static inline auto PointLightGeometry() { static std::weak_ptr<Geometry> s_geometry; auto geometryPtr = s_geometry.lock(); if (geometryPtr == nullptr) { geometryPtr = SphereMesh::CreateGeometry("PointLightGeometry", 1, 1); s_geometry = geometryPtr; } return geometryPtr; } static inline auto PointLightVertexCode() { auto deferred_vert_code = #include "deferred.vert" ; auto lightVertexCode = #include "Lights/TransformGeometry.vert" ; Shader::Stage::Code shaderCode = Shader::Stage::Code{ lightVertexCode, "TransformGeometry();" }; return shaderCode; } static inline auto PointLightFragmentCode() { auto deferred_frag_code = #include "deferred.frag" ; auto lightFragmentShader = #include "Lights/DeferredPointLight.frag" ; Shader::Stage::Code shaderCode = Shader::Stage::Code{ deferred_frag_code, "FillFragmentData();" } + Shader::Stage::Code{ lightFragmentShader, "Lighting();" }; return shaderCode; } static inline auto PointLightShader() { auto shader = Component::Create<Shader::Program>("PointLightShader"); shader->SetDefine("Pass", "DeferredLighting"); shader->Attach(Shader::Stage(Shader::Stage::Type::Fragment, PointLightFragmentCode())); shader->Attach(Shader::Stage(Shader::Stage::Type::Vertex, PointLightVertexCode())); return shader; } PointLightRenderer::PointLightRenderer(PointLight &light) : LightRenderer(light) { _deferredShader = PointLightShader(); _deferredGeometry = PointLightGeometry(); } void PointLightRenderer::Render(const Renderer::Options& options) { if (options.pass == Renderer::Options::Pass::DeferredLighting) _RenderDeferredLighting(static_cast<PointLight&>(_light), options); else if (options.pass == Renderer::Options::Pass::ShadowDepth) _RenderShadow(static_cast<PointLight&>(_light), options); } void PointLightRenderer::UpdateLightProbe(const Renderer::Options&, LightProbe&) { } void PointLightRenderer::_RenderDeferredLighting(PointLight& light, const Renderer::Options& options) { auto geometryBuffer = options.renderer->DeferredGeometryBuffer(); _deferredShader->Use() .SetUniform("Light.DiffuseFactor", light.GetDiffuseFactor()) .SetUniform("Light.SpecularFactor", light.GetSpecularFactor()) .SetUniform("Light.Power", light.GetPower()) .SetUniform("Light.Radius", light.GetRadius()) .SetUniform("Light.Color", light.GetColor()) .SetUniform("Light.Position", light.WorldPosition()) .SetUniform("GeometryMatrix", light.WorldTranslationMatrix() * glm::scale(glm::vec3(light.GetRadius()))) .SetTexture("Texture.Geometry.F0", geometryBuffer->GetColorBuffer(1)) .SetTexture("Texture.Geometry.Normal", geometryBuffer->GetColorBuffer(2)) .SetTexture("Texture.Geometry.Depth", geometryBuffer->GetDepthBuffer()); glCullFace(GL_FRONT); Renderer::Render(_deferredGeometry); glCullFace(GL_BACK); _deferredShader->Done(); } void PointLightRenderer::_RenderShadow(PointLight&, const Renderer::Options&) { } }
3,749
1,216
/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2016, assimp team All rights reserved. Redistribution and use of this software 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 the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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. ---------------------------------------------------------------------- */ /** @file GenUVCoords step */ #include "ComputeUVMappingProcess.h" #include "ProcessHelper.h" #include "Exceptional.h" using namespace Assimp; namespace { const static aiVector3D base_axis_y(0.0,1.0,0.0); const static aiVector3D base_axis_x(1.0,0.0,0.0); const static aiVector3D base_axis_z(0.0,0.0,1.0); const static ai_real angle_epsilon = 0.95; } // ------------------------------------------------------------------------------------------------ // Constructor to be privately used by Importer ComputeUVMappingProcess::ComputeUVMappingProcess() { // nothing to do here } // ------------------------------------------------------------------------------------------------ // Destructor, private as well ComputeUVMappingProcess::~ComputeUVMappingProcess() { // nothing to do here } // ------------------------------------------------------------------------------------------------ // Returns whether the processing step is present in the given flag field. bool ComputeUVMappingProcess::IsActive( unsigned int pFlags) const { return (pFlags & aiProcess_GenUVCoords) != 0; } // ------------------------------------------------------------------------------------------------ // Check whether a ray intersects a plane and find the intersection point inline bool PlaneIntersect(const aiRay& ray, const aiVector3D& planePos, const aiVector3D& planeNormal, aiVector3D& pos) { const ai_real b = planeNormal * (planePos - ray.pos); ai_real h = ray.dir * planeNormal; if ((h < 10e-5 && h > -10e-5) || (h = b/h) < 0) return false; pos = ray.pos + (ray.dir * h); return true; } // ------------------------------------------------------------------------------------------------ // Find the first empty UV channel in a mesh inline unsigned int FindEmptyUVChannel (aiMesh* mesh) { for (unsigned int m = 0; m < AI_MAX_NUMBER_OF_TEXTURECOORDS;++m) if (!mesh->mTextureCoords[m])return m; DefaultLogger::get()->error("Unable to compute UV coordinates, no free UV slot found"); return UINT_MAX; } // ------------------------------------------------------------------------------------------------ // Try to remove UV seams void RemoveUVSeams (aiMesh* mesh, aiVector3D* out) { // TODO: just a very rough algorithm. I think it could be done // much easier, but I don't know how and am currently too tired to // to think about a better solution. const static ai_real LOWER_LIMIT = 0.1; const static ai_real UPPER_LIMIT = 0.9; const static ai_real LOWER_EPSILON = 10e-3; const static ai_real UPPER_EPSILON = 1.0-10e-3; for (unsigned int fidx = 0; fidx < mesh->mNumFaces;++fidx) { const aiFace& face = mesh->mFaces[fidx]; if (face.mNumIndices < 3) continue; // triangles and polygons only, please unsigned int small = face.mNumIndices, large = small; bool zero = false, one = false, round_to_zero = false; // Check whether this face lies on a UV seam. We can just guess, // but the assumption that a face with at least one very small // on the one side and one very large U coord on the other side // lies on a UV seam should work for most cases. for (unsigned int n = 0; n < face.mNumIndices;++n) { if (out[face.mIndices[n]].x < LOWER_LIMIT) { small = n; // If we have a U value very close to 0 we can't // round the others to 0, too. if (out[face.mIndices[n]].x <= LOWER_EPSILON) zero = true; else round_to_zero = true; } if (out[face.mIndices[n]].x > UPPER_LIMIT) { large = n; // If we have a U value very close to 1 we can't // round the others to 1, too. if (out[face.mIndices[n]].x >= UPPER_EPSILON) one = true; } } if (small != face.mNumIndices && large != face.mNumIndices) { for (unsigned int n = 0; n < face.mNumIndices;++n) { // If the u value is over the upper limit and no other u // value of that face is 0, round it to 0 if (out[face.mIndices[n]].x > UPPER_LIMIT && !zero) out[face.mIndices[n]].x = 0.0; // If the u value is below the lower limit and no other u // value of that face is 1, round it to 1 else if (out[face.mIndices[n]].x < LOWER_LIMIT && !one) out[face.mIndices[n]].x = 1.0; // The face contains both 0 and 1 as UV coords. This can occur // for faces which have an edge that lies directly on the seam. // Due to numerical inaccuracies one U coord becomes 0, the // other 1. But we do still have a third UV coord to determine // to which side we must round to. else if (one && zero) { if (round_to_zero && out[face.mIndices[n]].x >= UPPER_EPSILON) out[face.mIndices[n]].x = 0.0; else if (!round_to_zero && out[face.mIndices[n]].x <= LOWER_EPSILON) out[face.mIndices[n]].x = 1.0; } } } } } // ------------------------------------------------------------------------------------------------ void ComputeUVMappingProcess::ComputeSphereMapping(aiMesh* mesh,const aiVector3D& axis, aiVector3D* out) { aiVector3D center, min, max; FindMeshCenter(mesh, center, min, max); // If the axis is one of x,y,z run a faster code path. It's worth the extra effort ... // currently the mapping axis will always be one of x,y,z, except if the // PretransformVertices step is used (it transforms the meshes into worldspace, // thus changing the mapping axis) if (axis * base_axis_x >= angle_epsilon) { // For each point get a normalized projection vector in the sphere, // get its longitude and latitude and map them to their respective // UV axes. Problems occur around the poles ... unsolvable. // // The spherical coordinate system looks like this: // x = cos(lon)*cos(lat) // y = sin(lon)*cos(lat) // z = sin(lat) // // Thus we can derive: // lat = arcsin (z) // lon = arctan (y/x) for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize(); out[pnt] = aiVector3D((atan2 (diff.z, diff.y) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F, (std::asin (diff.x) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0); } } else if (axis * base_axis_y >= angle_epsilon) { // ... just the same again for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize(); out[pnt] = aiVector3D((atan2 (diff.x, diff.z) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F, (std::asin (diff.y) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0); } } else if (axis * base_axis_z >= angle_epsilon) { // ... just the same again for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { const aiVector3D diff = (mesh->mVertices[pnt]-center).Normalize(); out[pnt] = aiVector3D((atan2 (diff.y, diff.x) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F, (std::asin (diff.z) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0); } } // slower code path in case the mapping axis is not one of the coordinate system axes else { aiMatrix4x4 mTrafo; aiMatrix4x4::FromToMatrix(axis,base_axis_y,mTrafo); // again the same, except we're applying a transformation now for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { const aiVector3D diff = ((mTrafo*mesh->mVertices[pnt])-center).Normalize(); out[pnt] = aiVector3D((atan2 (diff.y, diff.x) + AI_MATH_PI_F ) / AI_MATH_TWO_PI_F, (asin (diff.z) + AI_MATH_HALF_PI_F) / AI_MATH_PI_F, 0.0); } } // Now find and remove UV seams. A seam occurs if a face has a tcoord // close to zero on the one side, and a tcoord close to one on the // other side. RemoveUVSeams(mesh,out); } // ------------------------------------------------------------------------------------------------ void ComputeUVMappingProcess::ComputeCylinderMapping(aiMesh* mesh,const aiVector3D& axis, aiVector3D* out) { aiVector3D center, min, max; // If the axis is one of x,y,z run a faster code path. It's worth the extra effort ... // currently the mapping axis will always be one of x,y,z, except if the // PretransformVertices step is used (it transforms the meshes into worldspace, // thus changing the mapping axis) if (axis * base_axis_x >= angle_epsilon) { FindMeshCenter(mesh, center, min, max); const ai_real diff = max.x - min.x; // If the main axis is 'z', the z coordinate of a point 'p' is mapped // directly to the texture V axis. The other axis is derived from // the angle between ( p.x - c.x, p.y - c.y ) and (1,0), where // 'c' is the center point of the mesh. for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { const aiVector3D& pos = mesh->mVertices[pnt]; aiVector3D& uv = out[pnt]; uv.y = (pos.x - min.x) / diff; uv.x = (atan2 ( pos.z - center.z, pos.y - center.y) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI; } } else if (axis * base_axis_y >= angle_epsilon) { FindMeshCenter(mesh, center, min, max); const ai_real diff = max.y - min.y; // just the same ... for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { const aiVector3D& pos = mesh->mVertices[pnt]; aiVector3D& uv = out[pnt]; uv.y = (pos.y - min.y) / diff; uv.x = (atan2 ( pos.x - center.x, pos.z - center.z) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI; } } else if (axis * base_axis_z >= angle_epsilon) { FindMeshCenter(mesh, center, min, max); const ai_real diff = max.z - min.z; // just the same ... for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { const aiVector3D& pos = mesh->mVertices[pnt]; aiVector3D& uv = out[pnt]; uv.y = (pos.z - min.z) / diff; uv.x = (atan2 ( pos.y - center.y, pos.x - center.x) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI; } } // slower code path in case the mapping axis is not one of the coordinate system axes else { aiMatrix4x4 mTrafo; aiMatrix4x4::FromToMatrix(axis,base_axis_y,mTrafo); FindMeshCenterTransformed(mesh, center, min, max,mTrafo); const ai_real diff = max.y - min.y; // again the same, except we're applying a transformation now for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt){ const aiVector3D pos = mTrafo* mesh->mVertices[pnt]; aiVector3D& uv = out[pnt]; uv.y = (pos.y - min.y) / diff; uv.x = (atan2 ( pos.x - center.x, pos.z - center.z) +(ai_real)AI_MATH_PI ) / (ai_real)AI_MATH_TWO_PI; } } // Now find and remove UV seams. A seam occurs if a face has a tcoord // close to zero on the one side, and a tcoord close to one on the // other side. RemoveUVSeams(mesh,out); } // ------------------------------------------------------------------------------------------------ void ComputeUVMappingProcess::ComputePlaneMapping(aiMesh* mesh,const aiVector3D& axis, aiVector3D* out) { ai_real diffu,diffv; aiVector3D center, min, max; // If the axis is one of x,y,z run a faster code path. It's worth the extra effort ... // currently the mapping axis will always be one of x,y,z, except if the // PretransformVertices step is used (it transforms the meshes into worldspace, // thus changing the mapping axis) if (axis * base_axis_x >= angle_epsilon) { FindMeshCenter(mesh, center, min, max); diffu = max.z - min.z; diffv = max.y - min.y; for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { const aiVector3D& pos = mesh->mVertices[pnt]; out[pnt].Set((pos.z - min.z) / diffu,(pos.y - min.y) / diffv,0.0); } } else if (axis * base_axis_y >= angle_epsilon) { FindMeshCenter(mesh, center, min, max); diffu = max.x - min.x; diffv = max.z - min.z; for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { const aiVector3D& pos = mesh->mVertices[pnt]; out[pnt].Set((pos.x - min.x) / diffu,(pos.z - min.z) / diffv,0.0); } } else if (axis * base_axis_z >= angle_epsilon) { FindMeshCenter(mesh, center, min, max); diffu = max.y - min.y; diffv = max.z - min.z; for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { const aiVector3D& pos = mesh->mVertices[pnt]; out[pnt].Set((pos.y - min.y) / diffu,(pos.x - min.x) / diffv,0.0); } } // slower code path in case the mapping axis is not one of the coordinate system axes else { aiMatrix4x4 mTrafo; aiMatrix4x4::FromToMatrix(axis,base_axis_y,mTrafo); FindMeshCenterTransformed(mesh, center, min, max,mTrafo); diffu = max.x - min.x; diffv = max.z - min.z; // again the same, except we're applying a transformation now for (unsigned int pnt = 0; pnt < mesh->mNumVertices;++pnt) { const aiVector3D pos = mTrafo * mesh->mVertices[pnt]; out[pnt].Set((pos.x - min.x) / diffu,(pos.z - min.z) / diffv,0.0); } } // shouldn't be necessary to remove UV seams ... } // ------------------------------------------------------------------------------------------------ void ComputeUVMappingProcess::ComputeBoxMapping( aiMesh*, aiVector3D* ) { DefaultLogger::get()->error("Mapping type currently not implemented"); } // ------------------------------------------------------------------------------------------------ void ComputeUVMappingProcess::Execute( aiScene* pScene) { DefaultLogger::get()->debug("GenUVCoordsProcess begin"); char buffer[1024]; if (pScene->mFlags & AI_SCENE_FLAGS_NON_VERBOSE_FORMAT) throw DeadlyImportError("Post-processing order mismatch: expecting pseudo-indexed (\"verbose\") vertices here"); std::list<MappingInfo> mappingStack; /* Iterate through all materials and search for non-UV mapped textures */ for (unsigned int i = 0; i < pScene->mNumMaterials;++i) { mappingStack.clear(); aiMaterial* mat = pScene->mMaterials[i]; for (unsigned int a = 0; a < mat->mNumProperties;++a) { aiMaterialProperty* prop = mat->mProperties[a]; if (!::strcmp( prop->mKey.data, "$tex.mapping")) { aiTextureMapping& mapping = *((aiTextureMapping*)prop->mData); if (aiTextureMapping_UV != mapping) { if (!DefaultLogger::isNullLogger()) { ai_snprintf(buffer, 1024, "Found non-UV mapped texture (%s,%u). Mapping type: %s", TextureTypeToString((aiTextureType)prop->mSemantic),prop->mIndex, MappingTypeToString(mapping)); DefaultLogger::get()->info(buffer); } if (aiTextureMapping_OTHER == mapping) continue; MappingInfo info (mapping); // Get further properties - currently only the major axis for (unsigned int a2 = 0; a2 < mat->mNumProperties;++a2) { aiMaterialProperty* prop2 = mat->mProperties[a2]; if (prop2->mSemantic != prop->mSemantic || prop2->mIndex != prop->mIndex) continue; if ( !::strcmp( prop2->mKey.data, "$tex.mapaxis")) { info.axis = *((aiVector3D*)prop2->mData); break; } } unsigned int idx; // Check whether we have this mapping mode already std::list<MappingInfo>::iterator it = std::find (mappingStack.begin(),mappingStack.end(), info); if (mappingStack.end() != it) { idx = (*it).uv; } else { /* We have found a non-UV mapped texture. Now * we need to find all meshes using this material * that we can compute UV channels for them. */ for (unsigned int m = 0; m < pScene->mNumMeshes;++m) { aiMesh* mesh = pScene->mMeshes[m]; unsigned int outIdx = 0; if ( mesh->mMaterialIndex != i || ( outIdx = FindEmptyUVChannel(mesh) ) == UINT_MAX || !mesh->mNumVertices) { continue; } // Allocate output storage aiVector3D* p = mesh->mTextureCoords[outIdx] = new aiVector3D[mesh->mNumVertices]; switch (mapping) { case aiTextureMapping_SPHERE: ComputeSphereMapping(mesh,info.axis,p); break; case aiTextureMapping_CYLINDER: ComputeCylinderMapping(mesh,info.axis,p); break; case aiTextureMapping_PLANE: ComputePlaneMapping(mesh,info.axis,p); break; case aiTextureMapping_BOX: ComputeBoxMapping(mesh,p); break; default: ai_assert(false); } if (m && idx != outIdx) { DefaultLogger::get()->warn("UV index mismatch. Not all meshes assigned to " "this material have equal numbers of UV channels. The UV index stored in " "the material structure does therefore not apply for all meshes. "); } idx = outIdx; } info.uv = idx; mappingStack.push_back(info); } // Update the material property list mapping = aiTextureMapping_UV; ((aiMaterial*)mat)->AddProperty(&idx,1,AI_MATKEY_UVWSRC(prop->mSemantic,prop->mIndex)); } } } } DefaultLogger::get()->debug("GenUVCoordsProcess finished"); }
21,467
6,636
//===-- AddressResolverFileLine.cpp -----------------------------*- C++ -*-===// // // 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 "lldb/Core/AddressResolverFileLine.h" #include "lldb/Core/Address.h" #include "lldb/Core/AddressRange.h" #include "lldb/Symbol/CompileUnit.h" #include "lldb/Symbol/LineEntry.h" #include "lldb/Symbol/SymbolContext.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Logging.h" #include "lldb/Utility/Stream.h" #include "lldb/Utility/StreamString.h" #include "lldb/lldb-enumerations.h" #include "lldb/lldb-types.h" #include <inttypes.h> #include <vector> using namespace lldb; using namespace lldb_private; // AddressResolverFileLine: AddressResolverFileLine::AddressResolverFileLine(const FileSpec &file_spec, uint32_t line_no, bool check_inlines) : AddressResolver(), m_file_spec(file_spec), m_line_number(line_no), m_inlines(check_inlines) {} AddressResolverFileLine::~AddressResolverFileLine() {} Searcher::CallbackReturn AddressResolverFileLine::SearchCallback(SearchFilter &filter, SymbolContext &context, Address *addr, bool containing) { SymbolContextList sc_list; uint32_t sc_list_size; CompileUnit *cu = context.comp_unit; Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); sc_list_size = cu->ResolveSymbolContext(m_file_spec, m_line_number, m_inlines, false, eSymbolContextEverything, sc_list); for (uint32_t i = 0; i < sc_list_size; i++) { SymbolContext sc; if (sc_list.GetContextAtIndex(i, sc)) { Address line_start = sc.line_entry.range.GetBaseAddress(); addr_t byte_size = sc.line_entry.range.GetByteSize(); if (line_start.IsValid()) { AddressRange new_range(line_start, byte_size); m_address_ranges.push_back(new_range); if (log) { StreamString s; // new_bp_loc->GetDescription (&s, lldb::eDescriptionLevelVerbose); // LLDB_LOGF(log, "Added address: %s\n", s.GetData()); } } else { LLDB_LOGF(log, "error: Unable to resolve address at file address 0x%" PRIx64 " for %s:%d\n", line_start.GetFileAddress(), m_file_spec.GetFilename().AsCString("<Unknown>"), m_line_number); } } } return Searcher::eCallbackReturnContinue; } lldb::SearchDepth AddressResolverFileLine::GetDepth() { return lldb::eSearchDepthCompUnit; } void AddressResolverFileLine::GetDescription(Stream *s) { s->Printf("File and line address - file: \"%s\" line: %u", m_file_spec.GetFilename().AsCString("<Unknown>"), m_line_number); }
3,126
1,019
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "src/pch.h" #include <Microsoft/MixedReality/Sharing/StateSync/NetworkConnection.h> #include <Microsoft/MixedReality/Sharing/StateSync/NetworkListener.h> #include <Microsoft/MixedReality/Sharing/StateSync/NetworkManager.h> #include <Microsoft/MixedReality/Sharing/StateSync/ReplicatedState.h> #include <Microsoft/MixedReality/Sharing/StateSync/export.h> #include <Microsoft/MixedReality/Sharing/Common/bit_cast.h> using namespace Microsoft::MixedReality::Sharing; using namespace Microsoft::MixedReality::Sharing::StateSync; namespace { class PInvokeNetworkManager; using ReleaseGCHandleDelegate = void(__stdcall*)(intptr_t gc_handle); using GetConnectionDelegate = void(__stdcall*)(intptr_t connection_string_blob, intptr_t manager_gc_handle, PInvokeNetworkManager* pinvoke_network_manager, std::shared_ptr<NetworkConnection>* result_location); using PollMessageDelegate = bool(__stdcall*)(intptr_t manager_gc_handle, void* listener); using SendMessageDelegate = intptr_t(__stdcall*)(intptr_t connection_gc_handle, const char* message_begin, int message_size); class PInvokeNetworkManager : public NetworkManager { public: PInvokeNetworkManager(intptr_t manager_gc_handle, ReleaseGCHandleDelegate release_gc_handle_delegate, GetConnectionDelegate get_connection_delegate, PollMessageDelegate poll_message_delegate, SendMessageDelegate send_message_delegate) : manager_gc_handle_{manager_gc_handle}, release_gc_handle_delegate_{release_gc_handle_delegate}, get_connection_delegate_{get_connection_delegate}, poll_message_delegate_{poll_message_delegate}, send_message_delegate_{send_message_delegate} {} ~PInvokeNetworkManager() noexcept override { release_gc_handle_delegate_(manager_gc_handle_); } std::shared_ptr<NetworkConnection> GetConnection( const InternedBlob& connection_string) override; bool PollMessage(NetworkListener& listener) override { return poll_message_delegate_(manager_gc_handle_, &listener); } std::shared_ptr<NetworkConnection> CreateConnectionWrapper( const InternedBlob& connection_string, intptr_t connection_handle) { return std::make_shared<Connection>(&connection_string, this, connection_handle); } private: class Connection : public NetworkConnection { public: Connection(RefPtr<const InternedBlob> connection_string, RefPtr<PInvokeNetworkManager> manager, intptr_t connection_handle); ~Connection() noexcept override; void SendMessage(std::string_view message) override; private: RefPtr<PInvokeNetworkManager> manager_; intptr_t connection_handle_; }; intptr_t manager_gc_handle_; ReleaseGCHandleDelegate release_gc_handle_delegate_; GetConnectionDelegate get_connection_delegate_; PollMessageDelegate poll_message_delegate_; SendMessageDelegate send_message_delegate_; }; std::shared_ptr<NetworkConnection> PInvokeNetworkManager::GetConnection( const InternedBlob& connection_string) { std::shared_ptr<NetworkConnection> result; get_connection_delegate_(bit_cast<intptr_t>(&connection_string), manager_gc_handle_, this, &result); return result; } PInvokeNetworkManager::Connection::Connection( RefPtr<const InternedBlob> connection_string, RefPtr<PInvokeNetworkManager> manager, intptr_t connection_handle) : NetworkConnection{std::move(connection_string)}, manager_{std::move(manager)}, connection_handle_{connection_handle} {} PInvokeNetworkManager::Connection::~Connection() noexcept { manager_->release_gc_handle_delegate_(connection_handle_); } void PInvokeNetworkManager::Connection::SendMessage(std::string_view message) { if (message.size() > std::numeric_limits<int>::max()) { throw std::invalid_argument{ "The message is too large to be marshaled to C#"}; } manager_->send_message_delegate_(connection_handle_, message.data(), static_cast<int>(message.size())); } } // namespace extern "C" { MS_MR_SHARING_STATESYNC_API intptr_t MS_MR_CALL Microsoft_MixedReality_Sharing_StateSync_CppNetworkConnectionWeakPtr_Create() noexcept { return bit_cast<intptr_t>(new std::weak_ptr<NetworkConnection>); } MS_MR_SHARING_STATESYNC_API void MS_MR_CALL Microsoft_MixedReality_Sharing_StateSync_CppNetworkConnectionWeakPtr_Destroy( intptr_t weak_ptr_handle) noexcept { auto* wptr = bit_cast<std::weak_ptr<NetworkConnection>*>(weak_ptr_handle); delete wptr; } MS_MR_SHARING_STATESYNC_API bool MS_MR_CALL Microsoft_MixedReality_Sharing_StateSync_CppNetworkConnectionWeakPtr_Lock( intptr_t weak_ptr_handle, std::shared_ptr<NetworkConnection>* result) noexcept { auto* wptr = bit_cast<std::weak_ptr<NetworkConnection>*>(weak_ptr_handle); *result = wptr->lock(); return result; } MS_MR_SHARING_STATESYNC_API void MS_MR_CALL Microsoft_MixedReality_Sharing_StateSync_CppNetworkConnectionWeakPtr_Update( intptr_t weak_ptr_handle, PInvokeNetworkManager* manager, intptr_t connection_string_blob, intptr_t connecton_gc_handle, std::shared_ptr<NetworkConnection>* result) noexcept { *result = manager->CreateConnectionWrapper( *bit_cast<const InternedBlob*>(connection_string_blob), connecton_gc_handle); auto* wptr = bit_cast<std::weak_ptr<NetworkConnection>*>(weak_ptr_handle); *wptr = *result; // Updating the cache. } MS_MR_SHARING_STATESYNC_API void MS_MR_CALL Microsoft_MixedReality_Sharing_StateSync_NetworkListener_OnMessage( NetworkListener* listener, intptr_t sender, const char* messageBegin, int messageSize) noexcept { std::string_view message{messageBegin, static_cast<size_t>(messageSize)}; listener->OnMessage(*bit_cast<const InternedBlob*>(sender), message); } } // extern "C"
6,236
1,839
// Copyright (c) 2012 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. // // This test uses the safebrowsing test server published at // http://code.google.com/p/google-safe-browsing/ to test the safebrowsing // protocol implemetation. Details of the safebrowsing testing flow is // documented at // http://code.google.com/p/google-safe-browsing/wiki/ProtocolTesting // // This test launches safebrowsing test server and issues several update // requests against that server. Each update would get different data and after // each update, the test will get a list of URLs from the test server to verify // its repository. The test will succeed only if all updates are performed and // URLs match what the server expected. #include <vector> #include "base/bind.h" #include "base/command_line.h" #include "base/environment.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/string_number_conversions.h" #include "base/string_split.h" #include "base/stringprintf.h" #include "base/synchronization/lock.h" #include "base/test/test_timeouts.h" #include "base/threading/platform_thread.h" #include "base/threading/thread.h" #include "base/time.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/safe_browsing/protocol_manager.h" #include "chrome/browser/safe_browsing/safe_browsing_service.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/browser_context.h" #include "content/public/common/url_fetcher.h" #include "content/public/common/url_fetcher_delegate.h" #include "content/test/test_browser_thread.h" #include "net/base/host_resolver.h" #include "net/base/load_flags.h" #include "net/base/net_log.h" #include "net/test/python_utils.h" #include "net/url_request/url_request_status.h" #include "testing/gtest/include/gtest/gtest.h" using content::BrowserThread; namespace { const FilePath::CharType kDataFile[] = FILE_PATH_LITERAL("testing_input_nomac.dat"); const char kUrlVerifyPath[] = "/safebrowsing/verify_urls"; const char kDBVerifyPath[] = "/safebrowsing/verify_database"; const char kDBResetPath[] = "/reset"; const char kTestCompletePath[] = "/test_complete"; struct PhishingUrl { std::string url; std::string list_name; bool is_phishing; }; // Parses server response for verify_urls. The expected format is: // // first.random.url.com/ internal-test-shavar yes // second.random.url.com/ internal-test-shavar yes // ... bool ParsePhishingUrls(const std::string& data, std::vector<PhishingUrl>* phishing_urls) { if (data.empty()) return false; std::vector<std::string> urls; base::SplitString(data, '\n', &urls); for (size_t i = 0; i < urls.size(); ++i) { if (urls[i].empty()) continue; PhishingUrl phishing_url; std::vector<std::string> record_parts; base::SplitString(urls[i], '\t', &record_parts); if (record_parts.size() != 3) { LOG(ERROR) << "Unexpected URL format in phishing URL list: " << urls[i]; return false; } phishing_url.url = std::string(chrome::kHttpScheme) + "://" + record_parts[0]; phishing_url.list_name = record_parts[1]; if (record_parts[2] == "yes") { phishing_url.is_phishing = true; } else if (record_parts[2] == "no") { phishing_url.is_phishing = false; } else { LOG(ERROR) << "Unrecognized expectation in " << urls[i] << ": " << record_parts[2]; return false; } phishing_urls->push_back(phishing_url); } return true; } } // namespace class SafeBrowsingTestServer { public: explicit SafeBrowsingTestServer(const FilePath& datafile) : datafile_(datafile), server_handle_(base::kNullProcessHandle) { } ~SafeBrowsingTestServer() { EXPECT_EQ(base::kNullProcessHandle, server_handle_); } // Start the python server test suite. bool Start() { // Get path to python server script FilePath testserver_path; if (!PathService::Get(base::DIR_SOURCE_ROOT, &testserver_path)) { LOG(ERROR) << "Failed to get DIR_SOURCE_ROOT"; return false; } testserver_path = testserver_path .Append(FILE_PATH_LITERAL("third_party")) .Append(FILE_PATH_LITERAL("safe_browsing")) .Append(FILE_PATH_LITERAL("testing")); AppendToPythonPath(testserver_path); FilePath testserver = testserver_path.Append( FILE_PATH_LITERAL("safebrowsing_test_server.py")); FilePath pyproto_code_dir; if (!GetPyProtoPath(&pyproto_code_dir)) { LOG(ERROR) << "Failed to get generated python protobuf dir"; return false; } AppendToPythonPath(pyproto_code_dir); pyproto_code_dir = pyproto_code_dir.Append(FILE_PATH_LITERAL("google")); AppendToPythonPath(pyproto_code_dir); FilePath python_runtime; EXPECT_TRUE(GetPythonRunTime(&python_runtime)); CommandLine cmd_line(python_runtime); // Make python stdout and stderr unbuffered, to prevent incomplete stderr on // win bots, and also fix mixed up ordering of stdout and stderr. cmd_line.AppendSwitch("-u"); FilePath datafile = testserver_path.Append(datafile_); cmd_line.AppendArgPath(testserver); cmd_line.AppendArg(base::StringPrintf("--port=%d", kPort_)); cmd_line.AppendArgNative(FILE_PATH_LITERAL("--datafile=") + datafile.value()); base::LaunchOptions options; #if defined(OS_WIN) options.start_hidden = true; #endif if (!base::LaunchProcess(cmd_line, options, &server_handle_)) { LOG(ERROR) << "Failed to launch server: " << cmd_line.GetCommandLineString(); return false; } return true; } // Stop the python server test suite. bool Stop() { if (server_handle_ == base::kNullProcessHandle) return true; // First check if the process has already terminated. if (!base::WaitForSingleProcess(server_handle_, 0) && !base::KillProcess(server_handle_, 1, true)) { VLOG(1) << "Kill failed?"; return false; } base::CloseProcessHandle(server_handle_); server_handle_ = base::kNullProcessHandle; VLOG(1) << "Stopped."; return true; } static const char* Host() { return kHost_; } static int Port() { return kPort_; } private: static const char kHost_[]; static const int kPort_; FilePath datafile_; base::ProcessHandle server_handle_; DISALLOW_COPY_AND_ASSIGN(SafeBrowsingTestServer); }; const char SafeBrowsingTestServer::kHost_[] = "localhost"; const int SafeBrowsingTestServer::kPort_ = 40102; // This starts the browser and keeps status of states related to SafeBrowsing. class SafeBrowsingServiceTest : public InProcessBrowserTest { public: SafeBrowsingServiceTest() : safe_browsing_service_(NULL), is_database_ready_(true), is_update_scheduled_(false), is_checked_url_in_db_(false), is_checked_url_safe_(false) { } virtual ~SafeBrowsingServiceTest() { } void UpdateSafeBrowsingStatus() { ASSERT_TRUE(safe_browsing_service_); base::AutoLock lock(update_status_mutex_); last_update_ = safe_browsing_service_->protocol_manager_->last_update(); is_update_scheduled_ = safe_browsing_service_->protocol_manager_->update_timer_.IsRunning(); } void ForceUpdate() { ASSERT_TRUE(safe_browsing_service_); safe_browsing_service_->protocol_manager_->ForceScheduleNextUpdate(0); } void CheckIsDatabaseReady() { base::AutoLock lock(update_status_mutex_); is_database_ready_ = !safe_browsing_service_->database_update_in_progress_; } void CheckUrl(SafeBrowsingService::Client* helper, const GURL& url) { ASSERT_TRUE(safe_browsing_service_); base::AutoLock lock(update_status_mutex_); if (safe_browsing_service_->CheckBrowseUrl(url, helper)) { is_checked_url_in_db_ = false; is_checked_url_safe_ = true; } else { // In this case, Safebrowsing service will fetch the full hash // from the server and examine that. Once it is done, // set_is_checked_url_safe() will be called via callback. is_checked_url_in_db_ = true; } } bool is_checked_url_in_db() { base::AutoLock l(update_status_mutex_); return is_checked_url_in_db_; } void set_is_checked_url_safe(bool safe) { base::AutoLock l(update_status_mutex_); is_checked_url_safe_ = safe; } bool is_checked_url_safe() { base::AutoLock l(update_status_mutex_); return is_checked_url_safe_; } bool is_database_ready() { base::AutoLock l(update_status_mutex_); return is_database_ready_; } base::Time last_update() { base::AutoLock l(update_status_mutex_); return last_update_; } bool is_update_scheduled() { base::AutoLock l(update_status_mutex_); return is_update_scheduled_; } MessageLoop* SafeBrowsingMessageLoop() { return safe_browsing_service_->safe_browsing_thread_->message_loop(); } protected: bool InitSafeBrowsingService() { safe_browsing_service_ = g_browser_process->safe_browsing_service(); return safe_browsing_service_ != NULL; } virtual void SetUpCommandLine(CommandLine* command_line) { // Makes sure the auto update is not triggered. This test will force the // update when needed. command_line->AppendSwitch(switches::kSbDisableAutoUpdate); // This test uses loopback. No need to use IPv6 especially it makes // local requests slow on Windows trybot when ipv6 local address [::1] // is not setup. command_line->AppendSwitch(switches::kDisableIPv6); // TODO(lzheng): The test server does not understand download related // requests. We need to fix the server. command_line->AppendSwitch(switches::kSbDisableDownloadProtection); // TODO(gcasto): Generate new testing data that includes the // client-side phishing whitelist. command_line->AppendSwitch( switches::kDisableClientSidePhishingDetection); // Point to the testing server for all SafeBrowsing requests. std::string url_prefix = base::StringPrintf("http://%s:%d/safebrowsing", SafeBrowsingTestServer::Host(), SafeBrowsingTestServer::Port()); command_line->AppendSwitchASCII(switches::kSbURLPrefix, url_prefix); } void SetTestStep(int step) { std::string test_step = base::StringPrintf("test_step=%d", step); safe_browsing_service_->protocol_manager_->set_additional_query(test_step); } private: SafeBrowsingService* safe_browsing_service_; // Protects all variables below since they are read on UI thread // but updated on IO thread or safebrowsing thread. base::Lock update_status_mutex_; // States associated with safebrowsing service updates. bool is_database_ready_; base::Time last_update_; bool is_update_scheduled_; // Indicates if there is a match between a URL's prefix and safebrowsing // database (thus potentially it is a phishing URL). bool is_checked_url_in_db_; // True if last verified URL is not a phishing URL and thus it is safe. bool is_checked_url_safe_; DISALLOW_COPY_AND_ASSIGN(SafeBrowsingServiceTest); }; // A ref counted helper class that handles callbacks between IO thread and UI // thread. class SafeBrowsingServiceTestHelper : public base::RefCountedThreadSafe<SafeBrowsingServiceTestHelper>, public SafeBrowsingService::Client, public content::URLFetcherDelegate { public: SafeBrowsingServiceTestHelper(SafeBrowsingServiceTest* safe_browsing_test, net::URLRequestContextGetter* request_context) : safe_browsing_test_(safe_browsing_test), response_status_(net::URLRequestStatus::FAILED), request_context_(request_context) { } // Callbacks for SafeBrowsingService::Client. virtual void OnBrowseUrlCheckResult( const GURL& url, SafeBrowsingService::UrlCheckResult result) { EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO)); EXPECT_TRUE(safe_browsing_test_->is_checked_url_in_db()); safe_browsing_test_->set_is_checked_url_safe( result == SafeBrowsingService::SAFE); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&SafeBrowsingServiceTestHelper::OnCheckUrlDone, this)); } virtual void OnDownloadUrlCheckResult( const std::vector<GURL>& url_chain, SafeBrowsingService::UrlCheckResult result) { // TODO(lzheng): Add test for DownloadUrl. } virtual void OnBlockingPageComplete(bool proceed) { NOTREACHED() << "Not implemented."; } // Functions and callbacks to start the safebrowsing database update. void ForceUpdate() { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&SafeBrowsingServiceTestHelper::ForceUpdateInIOThread, this)); // Will continue after OnForceUpdateDone(). ui_test_utils::RunMessageLoop(); } void ForceUpdateInIOThread() { EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO)); safe_browsing_test_->ForceUpdate(); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&SafeBrowsingServiceTestHelper::OnForceUpdateDone, this)); } void OnForceUpdateDone() { StopUILoop(); } // Functions and callbacks related to CheckUrl. These are used to verify // phishing URLs. void CheckUrl(const GURL& url) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&SafeBrowsingServiceTestHelper::CheckUrlOnIOThread, this, url)); ui_test_utils::RunMessageLoop(); } void CheckUrlOnIOThread(const GURL& url) { EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO)); safe_browsing_test_->CheckUrl(this, url); if (!safe_browsing_test_->is_checked_url_in_db()) { // Ends the checking since this URL's prefix is not in database. BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&SafeBrowsingServiceTestHelper::OnCheckUrlDone, this)); } // Otherwise, OnCheckUrlDone is called in OnUrlCheckResult since // safebrowsing service further fetches hashes from safebrowsing server. } void OnCheckUrlDone() { StopUILoop(); } // Updates status from IO Thread. void CheckStatusOnIOThread() { EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO)); safe_browsing_test_->UpdateSafeBrowsingStatus(); safe_browsing_test_->SafeBrowsingMessageLoop()->PostTask(FROM_HERE, base::Bind(&SafeBrowsingServiceTestHelper::CheckIsDatabaseReady, this)); } // Checks status in SafeBrowsing Thread. void CheckIsDatabaseReady() { EXPECT_EQ(MessageLoop::current(), safe_browsing_test_->SafeBrowsingMessageLoop()); safe_browsing_test_->CheckIsDatabaseReady(); BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&SafeBrowsingServiceTestHelper::OnWaitForStatusUpdateDone, this)); } void OnWaitForStatusUpdateDone() { StopUILoop(); } // Wait for a given period to get safebrowsing status updated. void WaitForStatusUpdate(int64 wait_time_msec) { BrowserThread::PostDelayedTask( BrowserThread::IO, FROM_HERE, base::Bind(&SafeBrowsingServiceTestHelper::CheckStatusOnIOThread, this), base::TimeDelta::FromMilliseconds(wait_time_msec)); // Will continue after OnWaitForStatusUpdateDone(). ui_test_utils::RunMessageLoop(); } void WaitTillServerReady(const char* host, int port) { response_status_ = net::URLRequestStatus::FAILED; GURL url(base::StringPrintf("http://%s:%d%s?test_step=0", host, port, kDBResetPath)); // TODO(lzheng): We should have a way to reliably tell when a server is // ready so we could get rid of the Sleep and retry loop. while (true) { if (FetchUrl(url) == net::URLRequestStatus::SUCCESS) break; // Wait and try again if last fetch was failed. The loop will hit the // timeout in OutOfProcTestRunner if the fetch can not get success // response. base::PlatformThread::Sleep(TestTimeouts::tiny_timeout()); } } // Calls test server to fetch database for verification. net::URLRequestStatus::Status FetchDBToVerify(const char* host, int port, int test_step) { // TODO(lzheng): Remove chunk_type=add once it is not needed by the server. GURL url(base::StringPrintf( "http://%s:%d%s?" "client=chromium&appver=1.0&pver=2.2&test_step=%d&" "chunk_type=add", host, port, kDBVerifyPath, test_step)); return FetchUrl(url); } // Calls test server to fetch URLs for verification. net::URLRequestStatus::Status FetchUrlsToVerify(const char* host, int port, int test_step) { GURL url(base::StringPrintf( "http://%s:%d%s?" "client=chromium&appver=1.0&pver=2.2&test_step=%d", host, port, kUrlVerifyPath, test_step)); return FetchUrl(url); } // Calls test server to check if test data is done. E.g.: if there is a // bad URL that server expects test to fetch full hash but the test didn't, // this verification will fail. net::URLRequestStatus::Status VerifyTestComplete(const char* host, int port, int test_step) { GURL url(StringPrintf("http://%s:%d%s?test_step=%d", host, port, kTestCompletePath, test_step)); return FetchUrl(url); } // Callback for URLFetcher. virtual void OnURLFetchComplete(const net::URLFetcher* source) { source->GetResponseAsString(&response_data_); response_status_ = source->GetStatus().status(); StopUILoop(); } const std::string& response_data() { return response_data_; } private: friend class base::RefCountedThreadSafe<SafeBrowsingServiceTestHelper>; virtual ~SafeBrowsingServiceTestHelper() {} // Stops UI loop after desired status is updated. void StopUILoop() { EXPECT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::UI)); MessageLoopForUI::current()->Quit(); } // Fetch a URL. If message_loop_started is true, starts the message loop // so the caller could wait till OnURLFetchComplete is called. net::URLRequestStatus::Status FetchUrl(const GURL& url) { url_fetcher_.reset(content::URLFetcher::Create( url, content::URLFetcher::GET, this)); url_fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE); url_fetcher_->SetRequestContext(request_context_); url_fetcher_->Start(); ui_test_utils::RunMessageLoop(); return response_status_; } base::OneShotTimer<SafeBrowsingServiceTestHelper> check_update_timer_; SafeBrowsingServiceTest* safe_browsing_test_; scoped_ptr<content::URLFetcher> url_fetcher_; std::string response_data_; net::URLRequestStatus::Status response_status_; net::URLRequestContextGetter* request_context_; DISALLOW_COPY_AND_ASSIGN(SafeBrowsingServiceTestHelper); }; // See http://crbug.com/96459 IN_PROC_BROWSER_TEST_F(SafeBrowsingServiceTest, DISABLED_SafeBrowsingSystemTest) { LOG(INFO) << "Start test"; const char* server_host = SafeBrowsingTestServer::Host(); int server_port = SafeBrowsingTestServer::Port(); ASSERT_TRUE(InitSafeBrowsingService()); net::URLRequestContextGetter* request_context = GetBrowserContext()->GetRequestContext(); scoped_refptr<SafeBrowsingServiceTestHelper> safe_browsing_helper( new SafeBrowsingServiceTestHelper(this, request_context)); int last_step = 0; FilePath datafile_path = FilePath(kDataFile); SafeBrowsingTestServer test_server(datafile_path); ASSERT_TRUE(test_server.Start()); // Make sure the server is running. safe_browsing_helper->WaitTillServerReady(server_host, server_port); // Waits and makes sure safebrowsing update is not happening. // The wait will stop once OnWaitForStatusUpdateDone in // safe_browsing_helper is called and status from safe_browsing_service_ // is checked. safe_browsing_helper->WaitForStatusUpdate(0); EXPECT_TRUE(is_database_ready()); EXPECT_FALSE(is_update_scheduled()); EXPECT_TRUE(last_update().is_null()); // Starts updates. After each update, the test will fetch a list of URLs with // expected results to verify with safebrowsing service. If there is no error, // the test moves on to the next step to get more update chunks. // This repeats till there is no update data. for (int step = 1;; step++) { // Every step should be a fresh start. SCOPED_TRACE(base::StringPrintf("step=%d", step)); EXPECT_TRUE(is_database_ready()); EXPECT_FALSE(is_update_scheduled()); // Starts safebrowsing update on IO thread. Waits till scheduled // update finishes. Stops waiting after kMaxWaitSecPerStep if the update // could not finish. base::Time now = base::Time::Now(); SetTestStep(step); safe_browsing_helper->ForceUpdate(); do { // Periodically pull the status. safe_browsing_helper->WaitForStatusUpdate( TestTimeouts::tiny_timeout_ms()); } while (is_update_scheduled() || !is_database_ready()); if (last_update() < now) { // This means no data available anymore. break; } // Fetches URLs to verify and waits till server responses with data. EXPECT_EQ(net::URLRequestStatus::SUCCESS, safe_browsing_helper->FetchUrlsToVerify(server_host, server_port, step)); std::vector<PhishingUrl> phishing_urls; EXPECT_TRUE(ParsePhishingUrls(safe_browsing_helper->response_data(), &phishing_urls)); EXPECT_GT(phishing_urls.size(), 0U); for (size_t j = 0; j < phishing_urls.size(); ++j) { // Verifes with server if a URL is a phishing URL and waits till server // responses. safe_browsing_helper->CheckUrl(GURL(phishing_urls[j].url)); if (phishing_urls[j].is_phishing) { EXPECT_TRUE(is_checked_url_in_db()) << phishing_urls[j].url << " is_phishing: " << phishing_urls[j].is_phishing << " test step: " << step; EXPECT_FALSE(is_checked_url_safe()) << phishing_urls[j].url << " is_phishing: " << phishing_urls[j].is_phishing << " test step: " << step; } else { EXPECT_TRUE(is_checked_url_safe()) << phishing_urls[j].url << " is_phishing: " << phishing_urls[j].is_phishing << " test step: " << step; } } // TODO(lzheng): We should verify the fetched database with local // database to make sure they match. EXPECT_EQ(net::URLRequestStatus::SUCCESS, safe_browsing_helper->FetchDBToVerify(server_host, server_port, step)); EXPECT_GT(safe_browsing_helper->response_data().size(), 0U); last_step = step; } // Verifies with server if test is done and waits till server responses. EXPECT_EQ(net::URLRequestStatus::SUCCESS, safe_browsing_helper->VerifyTestComplete(server_host, server_port, last_step)); EXPECT_EQ("yes", safe_browsing_helper->response_data()); test_server.Stop(); }
23,824
7,543
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #include "directorywatcher.h" #include <QDir> #include <QTimer> #include <QUrl> #include <util/xpc/util.h> #include "xmlsettingsmanager.h" namespace LeechCraft { namespace Nacheku { DirectoryWatcher::DirectoryWatcher (QObject *parent) : QObject (parent) , Watcher_ (new QFileSystemWatcher) { XmlSettingsManager::Instance ().RegisterObject ("WatchDirectory", this, "settingsChanged"); QTimer::singleShot (5000, this, SLOT (settingsChanged ())); connect (Watcher_.get (), SIGNAL (directoryChanged (const QString&)), this, SLOT (handleDirectoryChanged (const QString&)), Qt::QueuedConnection); } void DirectoryWatcher::settingsChanged () { const QString& path = XmlSettingsManager::Instance () .property ("WatchDirectory").toString (); const QStringList& dirs = Watcher_->directories (); if (dirs.size () == 1 && dirs.at (0) == path) return; if (!dirs.isEmpty ()) Watcher_->removePaths (dirs); if (!path.isEmpty ()) { QDir dir (path); Olds_ = dir.entryInfoList (QDir::Files); Watcher_->addPath (path); handleDirectoryChanged (path); } } void DirectoryWatcher::handleDirectoryChanged (const QString& path) { QDir dir (path); const auto& cur = dir.entryInfoList (QDir::Files); auto nl = cur; Q_FOREACH (const QFileInfo& oldFi, Olds_) { const QString& fname = oldFi.absoluteFilePath (); Q_FOREACH (const QFileInfo& newFi, nl) if (newFi.absoluteFilePath () == fname) { nl.removeOne (newFi); break; } } Olds_ = cur; Q_FOREACH (const QFileInfo& newFi, nl) emit gotEntity (Util::MakeEntity (QUrl::fromLocalFile (newFi.absoluteFilePath ()), path, FromUserInitiated)); } } }
3,385
1,201
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://wsic_dockosettacommons.org. Questions about this casic_dock // (c) addressed to University of Waprotocolsgton UW TechTransfer, email: license@u.washington.eprotocols #include <riflib/rifdock_tasks/OutputResultsTasks.hh> #include <riflib/types.hh> #include <riflib/scaffold/ScaffoldDataCache.hh> #include <riflib/rifdock_tasks/HackPackTasks.hh> #include <riflib/ScoreRotamerVsTarget.hh> #include <riflib/RifFactory.hh> #include <core/chemical/ChemicalManager.hh> #include <core/chemical/ResidueTypeSet.hh> #include <core/conformation/ResidueFactory.hh> #include <core/pose/PDBInfo.hh> #include <core/pose/util.hh> #include <core/pose/Pose.hh> #include <core/io/silent/BinarySilentStruct.hh> #include <core/io/silent/SilentFileData.hh> #include <core/io/silent/SilentFileOptions.hh> #include <string> #include <vector> #include <ObjexxFCL/format.hh> namespace devel { namespace scheme { shared_ptr<std::vector<RifDockResult>> OutputResultsTask::return_rif_dock_results( shared_ptr<std::vector<RifDockResult>> selected_results_p, RifDockData & rdd, ProtocolData & pd ) { std::vector<RifDockResult> & selected_results = *selected_results_p; using std::cout; using std::endl; using ObjexxFCL::format::F; using ObjexxFCL::format::I; std::cout << " selected_results.size(): " << selected_results.size() << std::endl; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// print_header( "timing info" ); ////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// std::cout<<"total RIF time: "<<KMGT(pd.time_rif)<<" fraction: "<<pd.time_rif/(pd.time_rif+pd.time_pck+pd.time_ros)<<std::endl; std::cout<<"total Pack time: "<<KMGT(pd.time_pck)<<" fraction: "<<pd.time_pck/(pd.time_rif+pd.time_pck+pd.time_ros)<<std::endl; std::cout<<"total Rosetta time: "<<KMGT(pd.time_ros)<<" fraction: "<<pd.time_ros/(pd.time_rif+pd.time_pck+pd.time_ros)<<std::endl; if ( rdd.unsat_manager && rdd.opt.report_common_unsats ) { std::vector<shared_ptr<UnsatManager>> & unsatperthread = rdd.rif_factory->get_unsatperthread( rdd.objectives.back() ); for ( shared_ptr<UnsatManager> const & man : unsatperthread ) { rdd.unsat_manager->sum_unsat_counts( *man ); } rdd.unsat_manager->print_unsat_counts(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// print_header( "output results" ); ////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if( rdd.opt.align_to_scaffold ) std::cout << "ALIGN TO SCAFFOLD" << std::endl; else std::cout << "ALIGN TO TARGET" << std::endl; utility::io::ozstream out_silent_stream; if ( rdd.opt.outputsilent ) { ScaffoldDataCacheOP example_data_cache = rdd.scaffold_provider->get_data_cache_slow( ScaffoldIndex() ); out_silent_stream.open_append( rdd.opt.outdir + "/" + example_data_cache->scafftag + ".silent" ); } for( int i_selected_result = 0; i_selected_result < selected_results.size(); ++i_selected_result ){ RifDockResult const & selected_result = selected_results.at( i_selected_result ); // Brian Injection ScaffoldIndex si = selected_result.index.scaffold_index; ScaffoldDataCacheOP sdc = rdd.scaffold_provider->get_data_cache_slow( si ); std::string seeding_tag = ""; if ( selected_result.index.seeding_index < pd.seeding_tags.size() ) seeding_tag = pd.seeding_tags[ selected_result.index.seeding_index ]; std::string const & use_scafftag = sdc->scafftag + seeding_tag; ///// rdd.director->set_scene( selected_result.index, director_resl_, *rdd.scene_minimal ); std::vector<float> unsat_scores; int unsats = -1; int buried = -1; if ( rdd.unsat_manager ) { std::vector<EigenXform> bb_positions; for ( int i_actor = 0; i_actor < rdd.scene_minimal->template num_actors<BBActor>(1); i_actor++ ) { bb_positions.push_back( rdd.scene_minimal->template get_actor<BBActor>(1,i_actor).position() ); } std::vector<float> burial = rdd.burial_manager->get_burial_weights( rdd.scene_minimal->position(1), sdc->burial_grid ); unsat_scores = rdd.unsat_manager->get_buried_unsats( burial, selected_result.rotamers(), bb_positions, rdd.rot_tgt_scorer ); buried = 0; for ( float this_burial : burial ) if ( this_burial > 0 ) buried++; unsats = 0; for ( float this_unsat_score : unsat_scores ) if ( this_unsat_score > 0 ) unsats++; } std::stringstream extra_output; int hydrophobic_residue_contacts; float hydrophobic_ddg = 0; if ( rdd.hydrophobic_manager ) { std::vector<int> hydrophobic_counts, seqposs, per_irot_counts; std::vector<std::pair<intRot, EigenXform>> irot_and_bbpos; selected_result.rotamers(); for( int i = 0; i < selected_result.rotamers_->size(); ++i ){ BBActor const & bb = rdd.scene_minimal->template get_actor<BBActor>( 1, selected_result.rotamers_->at(i).first ); int seqpos = sdc->scaffres_l2g_p->at( bb.index_ ) + 1; int irot = selected_result.rotamers_->at(i).second; irot_and_bbpos.emplace_back( irot, bb.position() ); seqposs.push_back( seqpos ); } bool pass_better_than = true, pass_cation_pi = true; hydrophobic_residue_contacts = rdd.hydrophobic_manager->find_hydrophobic_residue_contacts( irot_and_bbpos, hydrophobic_counts, hydrophobic_ddg, per_irot_counts, pass_better_than, pass_cation_pi, rdd.rot_tgt_scorer ); rdd.hydrophobic_manager->print_hydrophobic_counts( rdd.target, hydrophobic_counts, irot_and_bbpos, seqposs, per_irot_counts, sdc->scaffres_g2l_p->size(), extra_output ); } std::string pdboutfile = rdd.opt.outdir + "/" + use_scafftag + "_" + devel::scheme::str(i_selected_result,9)+".pdb.gz"; if( rdd.opt.output_tag.size() ){ pdboutfile = rdd.opt.outdir + "/" + use_scafftag+"_" + rdd.opt.output_tag + "_" + devel::scheme::str(i_selected_result,9)+".pdb.gz"; } std::string resfileoutfile = rdd.opt.outdir + "/" + use_scafftag+"_"+devel::scheme::str(i_selected_result,9)+".resfile"; std::string allrifrotsoutfile = rdd.opt.outdir + "/" + use_scafftag+"_allrifrots_"+devel::scheme::str(i_selected_result,9)+".pdb.gz"; std::ostringstream oss; oss << "rif score: " << I(4,i_selected_result) << " rank " << I(9,selected_result.isamp) << " dist0: " << F(7,2,selected_result.dist0) << " packscore: " << F(7,3,selected_result.score) << " score: " << F(7,3,selected_result.nopackscore) // << " rif: " << F(7,3,selected_result.rifscore) << " steric: " << F(7,3,selected_result.stericscore); if (rdd.opt.scaff_bb_hbond_weight > 0) { oss << " bb-hbond: " << F(7,3,selected_result.scaff_bb_hbond); } oss << " cluster: " << I(7,selected_result.cluster_score) << " rifrank: " << I(7,selected_result.prepack_rank) << " " << F(7,5,(float)selected_result.prepack_rank/(float)pd.npack); if ( rdd.unsat_manager ) { oss << " buried:" << I(4,buried); oss << " unsats:" << I(4, unsats); } if ( rdd.opt.need_to_calculate_sasa ) { oss << " sasa:" << I(5, selected_result.sasa); } if ( rdd.hydrophobic_manager ) { oss << " hyd-cont:" << I(3, hydrophobic_residue_contacts); oss << " hyd-ddg: " << F(7,3, hydrophobic_ddg); } oss << " " << pdboutfile << std::endl; std::cout << oss.str(); rdd.dokout << oss.str(); rdd.dokout.flush(); dump_rif_result_(rdd, selected_result, pdboutfile, director_resl_, rif_resl_, out_silent_stream, false, resfileoutfile, allrifrotsoutfile, unsat_scores); std::cout << extra_output.str() << std::flush; } return selected_results_p; } void dump_rif_result_( RifDockData & rdd, RifDockResult const & selected_result, std::string const & pdboutfile, int director_resl, int rif_resl, utility::io::ozstream & out_silent_stream, bool quiet /* = true */, std::string const & resfileoutfile /* = "" */, std::string const & allrifrotsoutfile, /* = "" */ std::vector<float> const & unsat_scores /* = std::vector<float>() */ ) { using ObjexxFCL::format::F; using ObjexxFCL::format::I; using namespace devel::scheme; using std::cout; using std::endl; ScaffoldIndex si = selected_result.index.scaffold_index; ScaffoldDataCacheOP sdc = rdd.scaffold_provider->get_data_cache_slow( si ); std::vector<int> const & scaffres_g2l = *(sdc->scaffres_g2l_p); std::vector<int> const & scaffres_l2g = *(sdc->scaffres_l2g_p); std::vector<std::vector<float> > const & scaffold_onebody_glob0 = *(sdc->scaffold_onebody_glob0_p); uint64_t const scaffold_size = scaffres_g2l.size(); core::pose::Pose pose_from_rif; if ( rdd.opt.output_full_scaffold ) { sdc->setup_both_full_pose( rdd.target ); pose_from_rif = *(sdc->mpc_both_full_pose.get_pose()); } else if( rdd.opt.output_scaffold_only ) { pose_from_rif = *(sdc->scaffold_centered_p); } else if( rdd.opt.output_full_scaffold_only ) { pose_from_rif = *(sdc->scaffold_full_centered_p); } else { sdc->setup_both_pose( rdd.target ); pose_from_rif = *(sdc->mpc_both_pose.get_pose()); } rdd.director->set_scene( selected_result.index, director_resl, *rdd.scene_minimal ); EigenXform xposition1 = rdd.scene_minimal->position(1); EigenXform xalignout = EigenXform::Identity(); if( rdd.opt.align_to_scaffold ){ xalignout = xposition1.inverse(); } xform_pose( pose_from_rif, eigen2xyz(xalignout) , scaffold_size+1, pose_from_rif.size()); xform_pose( pose_from_rif, eigen2xyz(xalignout*xposition1), 1, scaffold_size ); std::vector< std::pair< int, std::string > > brians_infolabels; std::ostringstream packout, allout; // TYU change to vector of strings instead of string std::map< int, std::vector<std::string> > pikaa; std::map< int, std::map<std::string,float> > pssm; int chain_no = pose_from_rif.num_chains(); int res_num = pose_from_rif.size() + 1; const std::string chains = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for( int i_actor = 0; i_actor < rdd.scene_minimal->template num_actors<BBActor>(1); ++i_actor ){ BBActor bba = rdd.scene_minimal->template get_actor<BBActor>(1,i_actor); int const ires = scaffres_l2g.at( bba.index_ ); { std::vector< std::pair< float, int > > rotscores; rdd.rif_ptrs[rif_resl]->get_rotamers_for_xform( bba.position(), rotscores ); typedef std::pair<float,int> PairFI; BOOST_FOREACH( PairFI const & p, rotscores ){ int const irot = p.second; float const onebody = scaffold_onebody_glob0.at( ires ).at( irot ); float const sc = p.first + onebody; float const rescore = rdd.rot_tgt_scorer.score_rotamer_v_target( irot, bba.position(), 10.0, 4 ); if( sc < 0 || rescore + onebody < 0 || p.first + onebody < 0){ if ( ! rdd.opt.rif_rots_as_chains) { allout << "MODEL" << endl; } BOOST_FOREACH( SchemeAtom a, rdd.rot_index_p->rotamers_.at( irot ).atoms_ ){ a.set_position( xalignout * bba.position() * a.position() ); // is copy a.nonconst_data().resnum = rdd.opt.rif_rots_as_chains ? res_num : ires; a.nonconst_data().chain = rdd.opt.rif_rots_as_chains ? chains.at( chain_no % 52 ) : 'A'; ::scheme::actor::write_pdb( allout, a, nullptr ); } if (! rdd.opt.rif_rots_as_chains) { allout << "ENDMDL" << endl; } else { allout << "TER" << endl; res_num++; chain_no++; } // TYU change to std::string for expanded oneletter map std::string oneletter = rdd.rot_index_p->oneletter(irot); if( std::find( pikaa[ires+1].begin(), pikaa[ires+1].end(), oneletter ) == pikaa[ires+1].end() ){ pikaa[ires+1].push_back(oneletter); } // Brian std::pair< int, int > sat1_sat2 = rdd.rif_ptrs.back()->get_sat1_sat2(bba.position(), irot); // This should probably take into account more than just the sat scores // This is supposed to capture the score from RotamerFactory.cc operator() float effective_score = p.first; if ( rdd.opt.sat_score_bonus.size() > 0 ) { if ( sat1_sat2.first != -1 ) { float bonus_or_override = rdd.opt.sat_score_bonus.at( sat1_sat2.first ); if ( rdd.opt.sat_score_override.at( sat1_sat2.first ) ) { effective_score = bonus_or_override; } else { effective_score += bonus_or_override; } } } float pssm_score = effective_score; if ( pssm[ires+1].count( oneletter ) ) { pssm_score = std::min<float>( pssm[ires+1].at( oneletter ), pssm_score ); } pssm[ires+1][oneletter] = pssm_score; bool rot_was_placed = false; for ( std::pair<intRot,intRot> const & placed_rot : selected_result.rotamers() ) { if ( placed_rot.first == bba.index_ && placed_rot.second == irot ) { rot_was_placed = true; break; } } float rotboltz = 0; if ( sdc->rotboltz_data_p ) { if ( sdc->rotboltz_data_p->at(ires).size() > 0 ) { rotboltz = sdc->rotboltz_data_p->at(ires)[irot]; } } if ( ! quiet ) { std::cout << ( rot_was_placed ? "*" : " " ); std::cout << "seqpos:" << I(3, ires+1); std::cout << " " << oneletter; std::cout << " score:" << F(7, 2, sc); std::cout << " irot:" << I(3, irot); std::cout << " 1-body:" << F(7, 2, onebody ); if ( sdc->rotboltz_data_p ) { std::cout << " rotboltz:" << F(7, 2, rotboltz ); } std::cout << " rif score:" << F(7, 2, p.first); std::cout << " rif rescore:" << F(7, 2, rescore); std::cout << " sats:" << I(3, sat1_sat2.first) << " " << I(3, sat1_sat2.second) << " "; std::cout << std::endl; } if (sat1_sat2.first > -1) { std::pair< int, std::string > brian_pair; brian_pair.first = ires + 1; brian_pair.second = "HOT_IN:" + str(sat1_sat2.first); brians_infolabels.push_back(brian_pair); } } } } } if ( unsat_scores.size() > 0 ) { rdd.unsat_manager->print_buried_unsats( unsat_scores, scaffold_size ); } // // TEMP debug: // for (auto i: scaffold_phi_psi) { // std::cout << std::get<0>(i) << " " << std::get<1>(i) << std::endl; // } // for (auto i: scaffold_d_pos) { // std::cout << i << " "; // } // Actually place the rotamers on the pose core::chemical::ResidueTypeSetCAP rts = core::chemical::ChemicalManager::get_instance()->residue_type_set("fa_standard"); std::ostringstream resfile, expdb; resfile << "ALLAA" << std::endl; resfile << "start" << std::endl; expdb << "rif_residues "; if ( selected_result.rotamers_ ) { sanity_check_hackpack( rdd, selected_result.index, selected_result.rotamers_, rdd.scene_pt.front(), director_resl, rif_resl); } std::vector<int> needs_RIFRES; for( int ipr = 0; ipr < selected_result.numrots(); ++ipr ){ int ires = scaffres_l2g.at( selected_result.rotamers().at(ipr).first ); int irot = selected_result.rotamers().at(ipr).second; std::string myResName = rdd.rot_index_p->resname(irot); auto myIt = rdd.rot_index_p -> d_l_map_.find(myResName); core::conformation::ResidueOP newrsd; if (myIt != rdd.rot_index_p -> d_l_map_.end()){ core::chemical::ResidueType const & rtype = rts.lock()->name_map( myIt -> second ); newrsd = core::conformation::ResidueFactory::create_residue( rtype ); core::pose::Pose pose; pose.append_residue_by_jump(*newrsd,1); core::chemical::ResidueTypeSetCOP pose_rts = pose.residue_type_set_for_pose(); core::chemical::ResidueTypeCOP pose_rt = get_restype_for_pose(pose, myIt -> second); core::chemical::ResidueTypeCOP d_pose_rt = pose_rts -> get_d_equivalent(pose_rt); newrsd = core::conformation::ResidueFactory::create_residue( *d_pose_rt ); } else { newrsd = core::conformation::ResidueFactory::create_residue( rts.lock()->name_map(rdd.rot_index_p->resname(irot)) ); } //core::conformation::ResidueOP newrsd = core::conformation::ResidueFactory::create_residue( rts.lock()->name_map(rdd.rot_index_p->resname(irot)) ); pose_from_rif.replace_residue( ires+1, *newrsd, true ); resfile << ires+1 << " A NATRO" << std::endl; expdb << ires+1 << (ipr+1<selected_result.numrots()?",":""); // skip comma on last one for( int ichi = 0; ichi < rdd.rot_index_p->nchi(irot); ++ichi ){ pose_from_rif.set_chi( ichi+1, ires+1, rdd.rot_index_p->chi( irot, ichi ) ); } needs_RIFRES.push_back(ires+1); } // Add PDBInfo labels if they are applicable bool using_rosetta_model = (selected_result.pose_ != nullptr) && !rdd.opt.override_rosetta_pose; core::pose::PoseOP stored_pose = selected_result.pose_; if ( using_rosetta_model && ( rdd.opt.output_scaffold_only || rdd.opt.output_full_scaffold_only ) ) { stored_pose = stored_pose->split_by_chain().front(); } core::pose::Pose & pose_to_dump( using_rosetta_model ? *stored_pose : pose_from_rif ); if( !using_rosetta_model ){ if( rdd.opt.pdb_info_pikaa ){ for( auto p : pikaa ){ std::sort( p.second.begin(), p.second.end() ); pose_to_dump.pdb_info()->add_reslabel(p.first, "PIKAA" ); // TYU create output string for reslabel std::string out_string; for (auto i : p.second) { out_string += i; out_string += ","; } pose_to_dump.pdb_info()->add_reslabel(p.first, out_string ); //pose_to_dump.pdb_info()->add_reslabel(p.first, p.second ); } } else { std::sort(needs_RIFRES.begin(), needs_RIFRES.end()); for( int seq_pos : needs_RIFRES ){ pose_to_dump.pdb_info()->add_reslabel(seq_pos, "RIFRES" ); } } } if ( rdd.opt.pdb_info_pssm ) { // For now, only output stuff at positions where we actually placed something. for ( int seq_pos : needs_RIFRES ) { utility::vector1<std::string> parts; for ( auto name_score : pssm[seq_pos] ) { std::string this_string = boost::str(boost::format("%s:%.1f")%name_score.first%name_score.second); parts.push_back( this_string ); } if ( parts.size() > 0 ) { std::string full_string = "PSSM:" + utility::join(parts, ","); pose_to_dump.pdb_info()->add_reslabel(seq_pos, full_string ); } } } for ( auto p : brians_infolabels ) { pose_to_dump.pdb_info()->add_reslabel(p.first, p.second); } rdd.scaffold_provider->modify_pose_for_output(si, pose_to_dump); // Dump the main output if (!rdd.opt.outputsilent) { utility::io::ozstream out1( pdboutfile ); out1 << expdb.str() << std::endl; pose_to_dump.dump_pdb(out1); if ( rdd.opt.dump_all_rif_rots_into_output ) { if ( rdd.opt.rif_rots_as_chains ) out1 << "TER" << endl; out1 << allout.str(); } out1.close(); } // Dump a resfile if( rdd.opt.dump_resfile ){ utility::io::ozstream out1res( resfileoutfile ); out1res << resfile.str(); out1res.close(); } // Dump the rif rots if( rdd.opt.dump_all_rif_rots ){ utility::io::ozstream out2( allrifrotsoutfile ); out2 << allout.str(); out2.close(); } // Dump silent file if (rdd.opt.outputsilent) { // silly thing to take care of multiple chains in PDBInfo for silentstruct core::Size const ch1end(1); //set chain ID utility::vector1<char> chainID_vec(pose_to_dump.conformation().size()); for (auto i = 1; i <= pose_to_dump.conformation().chain_end(ch1end); i++) chainID_vec[i] = 'A'; for (auto i = pose_to_dump.conformation().chain_end(ch1end) + 1; i <= pose_to_dump.conformation().size(); i++) chainID_vec[i] = 'B'; pose_to_dump.pdb_info() -> set_chains(chainID_vec); //set chain num std::vector<int> v(pose_to_dump.conformation().size()); std::iota (std::begin(v), std::end(v), 1); pose_to_dump.pdb_info() -> set_numbering(v.begin(), v.end()); //dump to silent std::string model_tag = pdb_name(pdboutfile); core::io::silent::SilentFileOptions sf_option; sf_option.read_from_global_options(); core::io::silent::SilentFileData sfd("", false, false, "binary", sf_option); core::io::silent::SilentStructOP ss = sfd.create_SilentStructOP(); ss->fill_struct( pose_to_dump, model_tag ); sfd._write_silent_struct(*ss, out_silent_stream); } } void dump_search_point_( RifDockData & rdd, SearchPoint const & search_point, std::string const & pdboutfile, int director_resl, int rif_resl, bool quiet) { RifDockResult result; result = search_point; utility::io::ozstream trash; dump_rif_result_( rdd, result, pdboutfile, director_resl, rif_resl, trash,quiet, "", "" ); trash.close(); } }}
24,414
8,382
/* * The MIT License * * Copyright 2017-2019 azarias. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * File: Fireworkparticle.cpp * Author: azarias * * Created on 08/05/2019 */ #include "FireworkParticle.hpp" #include "src/client/Renderer.hpp" #include "src/common/Config.hpp" namespace mp { FireworkParticle::FireworkParticle(): Particle (this), m_line(sf::PrimitiveType::Lines, 2) { } const sf::Vector2f &FireworkParticle::getExplosionPosition() const { return m_target; } void FireworkParticle::init(const sf::Vector2f &target, const sf::Time &climbTime) { m_target = target; const sf::Time added = sf::milliseconds(static_cast<sf::Int32>(ARENA_HEIGHT - target.y)) * ARENA_HEIGHT; m_length = twin::makeTwin(10.f, 0.f, added + climbTime, twin::easing::quadIn); m_yPos = twin::makeTwin(ARENA_HEIGHT, target.y, added + climbTime, twin::easing::quadOut); m_line[0] = sf::Vertex(sf::Vector2f(m_target.x, ARENA_HEIGHT), sf::Color::White); m_line[1] = sf::Vertex(sf::Vector2f(m_target.x, ARENA_HEIGHT) , sf::Color::Transparent); } bool FireworkParticle::isFinished() const { return m_yPos.progress() == 1.f; } void FireworkParticle::render(Renderer &renderer) const { renderer.draw(m_line); } void FireworkParticle::update(const sf::Time &elapsed) { m_length.step(elapsed); m_yPos.step(elapsed); const float yPos = m_yPos.get(); m_line[0].position.y = yPos; m_line[1].position.y = yPos + m_length.get(); } }
2,528
929
#include <stdio.h> #include <string.h> #include <assert.h> #include <stdlib.h> #include <lua.hpp> #include <stdio.h> #include "malloc_hook.h" #include "ls.h" // turn on MEMORY_CHECK can do more memory check, such as double free // #define MEMORY_CHECK #define MEMORY_ALLOCTAG 0x20140605 #define MEMORY_FREETAG 0x0badf00d static size_t _used_memory = 0; static size_t _memory_block = 0; struct mem_data { uint32_t handle; size_t allocated; }; struct mem_cookie { uint32_t handle; }; #define SLOT_SIZE 0x10000 #define PREFIX_SIZE sizeof(struct mem_cookie) static struct mem_data mem_stats[SLOT_SIZE]; // for ls_lalloc use #define raw_realloc realloc #define raw_free free void memory_info_dump(void) { ls_error(NULL, "No jemalloc"); } size_t mallctl_int64(const char* name, size_t* newval) { ls_error(NULL, "No jemalloc : mallctl_int64 %s.", name); return 0; } int mallctl_opt(const char* name, int* newval) { ls_error(NULL, "No jemalloc : mallctl_opt %s.", name); return 0; } size_t malloc_used_memory(void) { return _used_memory; } size_t malloc_memory_block(void) { return _memory_block; } void dump_c_mem() { int i; size_t total = 0; ls_error(NULL, "dump all service mem:"); for (i = 0; i < SLOT_SIZE; i++) { struct mem_data* data = &mem_stats[i]; if (data->handle != 0 && data->allocated != 0) { total += data->allocated; ls_error(NULL, ":%08x -> %zdkb %db", data->handle, data->allocated >> 10, (int)(data->allocated % 1024)); } } ls_error(NULL, "+total: %zdkb", total >> 10); } char* ls_strdup(const char* str) { size_t sz = strlen(str); char* ret = (char*)ls_malloc(sz + 1); memcpy(ret, str, sz + 1); return ret; } void* ls_lalloc(void* ptr, size_t osize, size_t nsize) { if (nsize == 0) { raw_free(ptr); return NULL; } else { return raw_realloc(ptr, nsize); } } int dump_mem_lua(lua_State * L) { int i; lua_newtable(L); for (i = 0; i < SLOT_SIZE; i++) { struct mem_data* data = &mem_stats[i]; if (data->handle != 0 && data->allocated != 0) { lua_pushinteger(L, data->allocated); lua_rawseti(L, -2, (lua_Integer)data->handle); } } return 1; } size_t malloc_current_memory(void) { uint32_t handle = ls_current_handle(); int i; for (i = 0; i < SLOT_SIZE; i++) { struct mem_data* data = &mem_stats[i]; if (data->handle == (uint32_t)handle && data->allocated != 0) { return (size_t)data->allocated; } } return 0; } void ls_debug_memory(const char* info) { // for debug use uint32_t handle = ls_current_handle(); size_t mem = malloc_current_memory(); fprintf(stderr, "[:%08x] %s %p\n", handle, info, (void*)mem); }
2,616
1,171
/** * * 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. */ #undef NDEBUG #include <cstdio> #include <memory> #include <string> #include <sstream> #include "processors/InvokeHTTP.h" #include "TestBase.h" #include "core/ProcessGroup.h" #include "properties/Configure.h" #include "TestServer.h" #include "HTTPIntegrationBase.h" #include "utils/IntegrationTestUtils.h" class VerifyC2Server : public HTTPIntegrationBase { public: explicit VerifyC2Server() { char format[] = "/tmp/ssth.XXXXXX"; dir = testController.createTempDirectory(format); } void testSetup() override { LogTestController::getInstance().setDebug<processors::InvokeHTTP>(); LogTestController::getInstance().setDebug<minifi::core::ProcessSession>(); std::fstream file; ss << dir << "/" << "tstFile.ext"; file.open(ss.str(), std::ios::out); file << "tempFile"; file.close(); } void cleanup() override { std::remove(ss.str().c_str()); IntegrationBase::cleanup(); } void runAssertions() override { using org::apache::nifi::minifi::utils::verifyLogLinePresenceInPollTime; assert(verifyLogLinePresenceInPollTime(std::chrono::milliseconds(wait_time_), "Import offset 0", "Outputting success and response")); } void queryRootProcessGroup(std::shared_ptr<core::ProcessGroup> pg) override { std::shared_ptr<core::Processor> proc = pg->findProcessorByName("invoke"); assert(proc != nullptr); std::shared_ptr<minifi::processors::InvokeHTTP> inv = std::dynamic_pointer_cast<minifi::processors::InvokeHTTP>(proc); assert(inv != nullptr); std::string url; inv->getProperty(minifi::processors::InvokeHTTP::URL.getName(), url); std::string port, scheme, path; parse_http_components(url, port, scheme, path); configuration->set("nifi.c2.enable", "true"); configuration->set("nifi.c2.agent.class", "test"); configuration->set("nifi.c2.agent.heartbeat.reporter.classes", "RESTReceiver"); configuration->set("nifi.c2.agent.protocol.class", "RESTSender"); configuration->set("nifi.c2.rest.listener.port", port); configuration->set("nifi.c2.agent.heartbeat.period", "10"); configuration->set("nifi.c2.rest.listener.heartbeat.rooturi", path); } protected: std::string dir; std::stringstream ss; TestController testController; }; int main(int argc, char **argv) { const cmd_args args = parse_cmdline_args(argc, argv); VerifyC2Server harness; harness.setKeyDir(args.key_dir); harness.run(args.test_file); return 0; }
3,280
1,033
/* ** Copyright 2011-2019 Centreon ** ** This file is part of Centreon Engine. ** ** Centreon Engine is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Engine 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 Centreon Engine. If not, see ** <http://www.gnu.org/licenses/>. */ #ifndef CCE_MOD_EXTCMD_PROCESSING_HH #define CCE_MOD_EXTCMD_PROCESSING_HH #include <cstring> #include <map> #include <mutex> #include <string> #include <unordered_map> #include "com/centreon/engine/configuration/applier/state.hh" #include "com/centreon/engine/contact.hh" #include "com/centreon/engine/contactgroup.hh" #include "com/centreon/engine/host.hh" #include "com/centreon/engine/hostgroup.hh" #include "com/centreon/engine/namespace.hh" #include "com/centreon/engine/service.hh" #include "com/centreon/engine/servicegroup.hh" CCE_BEGIN() namespace modules { namespace external_commands { class processing { public: processing(); ~processing() throw(); bool execute(std::string const& cmd) const; bool is_thread_safe(char const* cmd) const; private: struct command_info { command_info(int _id = 0, void (*_func)(int, time_t, char*) = NULL, bool is_thread_safe = false) : id(_id), func(_func), thread_safe(is_thread_safe) {} ~command_info() throw() {} int id; void (*func)(int id, time_t entry_time, char* args); bool thread_safe; }; static void _wrapper_read_state_information(); static void _wrapper_save_state_information(); static void _wrapper_enable_host_and_child_notifications(host* hst); static void _wrapper_disable_host_and_child_notifications(host* hst); static void _wrapper_enable_all_notifications_beyond_host(host* hst); static void _wrapper_disable_all_notifications_beyond_host(host* hst); static void _wrapper_enable_host_svc_notifications(host* hst); static void _wrapper_disable_host_svc_notifications(host* hst); static void _wrapper_enable_host_svc_checks(host* hst); static void _wrapper_disable_host_svc_checks(host* hst); static void _wrapper_set_host_notification_number(host* hst, char* args); static void _wrapper_send_custom_host_notification(host* hst, char* args); static void _wrapper_enable_service_notifications(host* hst); static void _wrapper_disable_service_notifications(host* hst); static void _wrapper_enable_service_checks(host* hst); static void _wrapper_disable_service_checks(host* hst); static void _wrapper_enable_passive_service_checks(host* hst); static void _wrapper_disable_passive_service_checks(host* hst); static void _wrapper_set_service_notification_number(service* svc, char* args); static void _wrapper_send_custom_service_notification(service* svc, char* args); template <void (*fptr)()> static void _redirector(int id, time_t entry_time, char* args) { (void)id; (void)entry_time; (void)args; (*fptr)(); } template <int (*fptr)()> static void _redirector(int id, time_t entry_time, char* args) { (void)id; (void)entry_time; (void)args; (*fptr)(); } template <void (*fptr)(int, char*)> static void _redirector(int id, time_t entry_time, char* args) { (void)entry_time; (*fptr)(id, args); } template <int (*fptr)(int, char*)> static void _redirector(int id, time_t entry_time, char* args) { (void)entry_time; (*fptr)(id, args); } template <int (*fptr)(int, time_t, char*)> static void _redirector(int id, time_t entry_time, char* args) { (*fptr)(id, entry_time, args); } template <void (*fptr)(host*)> static void _redirector_host(int id, time_t entry_time, char* args) { (void)id; (void)entry_time; char* name(my_strtok(args, ";")); host* hst{nullptr}; host_map::const_iterator it(host::hosts.find(name)); if (it != host::hosts.end()) hst = it->second.get(); if (!hst) return; (*fptr)(hst); } template <void (*fptr)(host*, char*)> static void _redirector_host(int id, time_t entry_time, char* args) { (void)id; (void)entry_time; char* name(my_strtok(args, ";")); host* hst{nullptr}; host_map::const_iterator it(host::hosts.find(name)); if (it != host::hosts.end()) hst = it->second.get(); if (!hst) return; (*fptr)(hst, args + strlen(name) + 1); } template <void (*fptr)(host*)> static void _redirector_hostgroup(int id, time_t entry_time, char* args) { (void)id; (void)entry_time; char* group_name(my_strtok(args, ";")); hostgroup* group(nullptr); hostgroup_map::const_iterator it{hostgroup::hostgroups.find(group_name)}; if (it != hostgroup::hostgroups.end()) group = it->second.get(); if (!group) return; for (host_map_unsafe::iterator it(group->members.begin()), end(group->members.begin()); it != end; ++it) if (it->second) (*fptr)(it->second); } template <void (*fptr)(service*)> static void _redirector_service(int id, time_t entry_time, char* args) { (void)id; (void)entry_time; char* name(my_strtok(args, ";")); char* description(my_strtok(NULL, ";")); service_map::const_iterator found( service::services.find({name, description})); if (found == service::services.end() || !found->second) return; (*fptr)(found->second.get()); } template <void (*fptr)(service*, char*)> static void _redirector_service(int id, time_t entry_time, char* args) { (void)id; (void)entry_time; char* name{my_strtok(args, ";")}; char* description{my_strtok(NULL, ";")}; service_map::const_iterator found{ service::services.find({name, description})}; if (found == service::services.end() || !found->second) return; (*fptr)(found->second.get(), args + strlen(name) + strlen(description) + 2); } template <void (*fptr)(service*)> static void _redirector_servicegroup(int id, time_t entry_time, char* args) { (void)id; (void)entry_time; char* group_name(my_strtok(args, ";")); servicegroup_map::const_iterator sg_it{ servicegroup::servicegroups.find(group_name)}; if (sg_it == servicegroup::servicegroups.end() || !sg_it->second) return; for (service_map_unsafe::iterator it2(sg_it->second->members.begin()), end2(sg_it->second->members.end()); it2 != end2; ++it2) if (it2->second) (*fptr)(it2->second); } template <void (*fptr)(host*)> static void _redirector_servicegroup(int id, time_t entry_time, char* args) { (void)id; (void)entry_time; char* group_name(my_strtok(args, ";")); servicegroup_map::const_iterator sg_it{ servicegroup::servicegroups.find(group_name)}; if (sg_it == servicegroup::servicegroups.end() || !sg_it->second) return; host* last_host{nullptr}; for (service_map_unsafe::iterator it2(sg_it->second->members.begin()), end2(sg_it->second->members.end()); it2 != end2; ++it2) { host* hst{nullptr}; host_map::const_iterator found(host::hosts.find(it2->first.first)); if (found != host::hosts.end()) hst = found->second.get(); if (!hst || hst == last_host) continue; (*fptr)(hst); last_host = hst; } } template <void (*fptr)(contact*)> static void _redirector_contact(int id, time_t entry_time, char* args) { (void)id; (void)entry_time; char* name(my_strtok(args, ";")); contact_map::const_iterator ct_it{contact::contacts.find(name)}; if (ct_it == contact::contacts.end()) return; (*fptr)(ct_it->second.get()); } template <void (*fptr)(char*)> static void _redirector_file(int id __attribute__((unused)), time_t entry_time __attribute__((unused)), char* args) { char* filename(my_strtok(args, ";")); (*fptr)(filename); } template <void (*fptr)(contact*)> static void _redirector_contactgroup(int id, time_t entry_time, char* args) { (void)id; (void)entry_time; char* group_name(my_strtok(args, ";")); contactgroup_map::iterator it_cg{ contactgroup::contactgroups.find(group_name)}; if (it_cg == contactgroup::contactgroups.end() || !it_cg->second) return; for (contact_map_unsafe::const_iterator it(it_cg->second->get_members().begin()), end(it_cg->second->get_members().end()); it != end; ++it) if (it->second) (*fptr)(it->second); } std::unordered_map<std::string, command_info> _lst_command; mutable std::mutex _mutex; }; } // namespace external_commands } // namespace modules CCE_END() #endif // !CCE_MOD_EXTCMD_PROCESSING_HH
9,214
3,205
//===--- DeclContext.cpp - DeclContext implementation ---------------------===// // // 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 // //===----------------------------------------------------------------------===// #include "swift/AST/DeclContext.h" #include "swift/AST/AccessScope.h" #include "swift/AST/ASTContext.h" #include "swift/AST/ASTWalker.h" #include "swift/AST/Expr.h" #include "swift/AST/GenericEnvironment.h" #include "swift/AST/Initializer.h" #include "swift/AST/LazyResolver.h" #include "swift/AST/Module.h" #include "swift/AST/Types.h" #include "swift/Basic/SourceManager.h" #include "swift/Basic/Statistic.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/SaveAndRestore.h" using namespace swift; #define DEBUG_TYPE "Name lookup" STATISTIC(NumLazyIterableDeclContexts, "# of serialized iterable declaration contexts"); STATISTIC(NumUnloadedLazyIterableDeclContexts, "# of serialized iterable declaration contexts never loaded"); // Only allow allocation of DeclContext using the allocator in ASTContext. void *DeclContext::operator new(size_t Bytes, ASTContext &C, unsigned Alignment) { return C.Allocate(Bytes, Alignment); } ASTContext &DeclContext::getASTContext() const { return getParentModule()->getASTContext(); } GenericTypeDecl *DeclContext::getSelfTypeDecl() const { auto decl = const_cast<Decl*>(getAsDecl()); if (!decl) return nullptr; auto ext = dyn_cast<ExtensionDecl>(decl); if (!ext) return dyn_cast<GenericTypeDecl>(decl); return ext->getExtendedNominal(); } /// If this DeclContext is a NominalType declaration or an /// extension thereof, return the NominalTypeDecl. NominalTypeDecl *DeclContext::getSelfNominalTypeDecl() const { return dyn_cast_or_null<NominalTypeDecl>(getSelfTypeDecl()); } ClassDecl *DeclContext::getSelfClassDecl() const { return dyn_cast_or_null<ClassDecl>(getSelfTypeDecl()); } EnumDecl *DeclContext::getSelfEnumDecl() const { return dyn_cast_or_null<EnumDecl>(getSelfTypeDecl()); } StructDecl *DeclContext::getSelfStructDecl() const { return dyn_cast_or_null<StructDecl>(getSelfTypeDecl()); } ProtocolDecl *DeclContext::getSelfProtocolDecl() const { return dyn_cast_or_null<ProtocolDecl>(getSelfTypeDecl()); } ProtocolDecl *DeclContext::getExtendedProtocolDecl() const { if (auto decl = const_cast<Decl*>(getAsDecl())) if (auto ED = dyn_cast<ExtensionDecl>(decl)) return dyn_cast_or_null<ProtocolDecl>(ED->getExtendedNominal()); return nullptr; } GenericTypeParamType *DeclContext::getProtocolSelfType() const { assert(getSelfProtocolDecl() && "not a protocol"); GenericParamList *genericParams; if (auto proto = dyn_cast<ProtocolDecl>(this)) { genericParams = proto->getGenericParams(); } else { genericParams = cast<ExtensionDecl>(this)->getGenericParams(); } if (genericParams == nullptr) return nullptr; return genericParams->getParams().front() ->getDeclaredInterfaceType() ->castTo<GenericTypeParamType>(); } Type DeclContext::getDeclaredTypeInContext() const { if (auto *ED = dyn_cast<ExtensionDecl>(this)) return ED->mapTypeIntoContext(getDeclaredInterfaceType()); if (auto *NTD = dyn_cast<NominalTypeDecl>(this)) return NTD->getDeclaredTypeInContext(); return Type(); } Type DeclContext::getDeclaredInterfaceType() const { if (auto *ED = dyn_cast<ExtensionDecl>(this)) { auto *NTD = ED->getExtendedNominal(); if (NTD == nullptr) return ErrorType::get(ED->getASTContext()); return NTD->getDeclaredInterfaceType(); } if (auto *NTD = dyn_cast<NominalTypeDecl>(this)) return NTD->getDeclaredInterfaceType(); return Type(); } void DeclContext::forEachGenericContext( llvm::function_ref<void (GenericParamList *)> fn) const { auto dc = this; do { if (auto decl = dc->getAsDecl()) { // Extensions do not capture outer generic parameters. if (auto *ext = dyn_cast<ExtensionDecl>(decl)) { for (auto *gpList = ext->getGenericParams(); gpList != nullptr; gpList = gpList->getOuterParameters()) { fn(gpList); } return; } if (auto genericCtx = decl->getAsGenericContext()) if (auto *gpList = genericCtx->getGenericParams()) fn(gpList); } } while ((dc = dc->getParent())); } unsigned DeclContext::getGenericContextDepth() const { unsigned depth = -1; forEachGenericContext([&](GenericParamList *) { ++depth; }); return depth; } GenericSignature *DeclContext::getGenericSignatureOfContext() const { auto dc = this; do { if (auto decl = dc->getAsDecl()) if (auto GC = decl->getAsGenericContext()) return GC->getGenericSignature(); } while ((dc = dc->getParent())); return nullptr; } GenericEnvironment *DeclContext::getGenericEnvironmentOfContext() const { auto dc = this; do { if (auto decl = dc->getAsDecl()) if (auto GC = decl->getAsGenericContext()) return GC->getGenericEnvironment(); } while ((dc = dc->getParent())); return nullptr; } bool DeclContext::contextHasLazyGenericEnvironment() const { auto dc = this; do { if (auto decl = dc->getAsDecl()) if (auto GC = decl->getAsGenericContext()) return GC->hasLazyGenericEnvironment(); } while ((dc = dc->getParent())); return false; } Type DeclContext::mapTypeIntoContext(Type type) const { return GenericEnvironment::mapTypeIntoContext( getGenericEnvironmentOfContext(), type); } DeclContext *DeclContext::getLocalContext() { if (isLocalContext()) return this; if (isModuleContext()) return nullptr; return getParent()->getLocalContext(); } AbstractFunctionDecl *DeclContext::getInnermostMethodContext() { auto dc = this; do { if (auto decl = dc->getAsDecl()) { auto func = dyn_cast<AbstractFunctionDecl>(decl); // If we found a non-func decl, we're done. if (func == nullptr) return nullptr; if (func->getDeclContext()->isTypeContext()) return func; } } while ((dc = dc->getParent())); return nullptr; } bool DeclContext::isTypeContext() const { if (auto decl = getAsDecl()) return isa<NominalTypeDecl>(decl) || isa<ExtensionDecl>(decl); return false; } DeclContext *DeclContext::getInnermostTypeContext() { auto dc = this; do { if (dc->isTypeContext()) return dc; } while ((dc = dc->getParent())); return nullptr; } Decl *DeclContext::getInnermostDeclarationDeclContext() { auto DC = this; do { if (auto decl = DC->getAsDecl()) return isa<ModuleDecl>(decl) ? nullptr : decl; } while ((DC = DC->getParent())); return nullptr; } DeclContext *DeclContext::getParentForLookup() const { if (isa<ProtocolDecl>(this) || isa<ExtensionDecl>(this)) { // If we are inside a protocol or an extension, skip directly // to the module scope context, without looking at any (invalid) // outer types. return getModuleScopeContext(); } if (isa<NominalTypeDecl>(this)) { // If we are inside a nominal type that is inside a protocol, // skip the protocol. if (isa<ProtocolDecl>(getParent())) return getModuleScopeContext(); } return getParent(); } ModuleDecl *DeclContext::getParentModule() const { const DeclContext *DC = this; while (!DC->isModuleContext()) DC = DC->getParent(); return const_cast<ModuleDecl *>(cast<ModuleDecl>(DC)); } SourceFile *DeclContext::getParentSourceFile() const { const DeclContext *DC = this; while (!DC->isModuleScopeContext()) DC = DC->getParent(); return const_cast<SourceFile *>(dyn_cast<SourceFile>(DC)); } DeclContext *DeclContext::getModuleScopeContext() const { auto DC = const_cast<DeclContext*>(this); while (true) { if (DC->ParentAndKind.getInt() == ASTHierarchy::FileUnit) return DC; if (auto NextDC = DC->getParent()) { DC = NextDC; } else { assert(isa<ModuleDecl>(DC->getAsDecl())); return DC; } } } /// Determine whether the given context is generic at any level. bool DeclContext::isGenericContext() const { auto dc = this; do { if (auto decl = dc->getAsDecl()) { if (auto GC = decl->getAsGenericContext()) { if (GC->getGenericParams()) return true; // Extensions do not capture outer generic parameters. if (isa<ExtensionDecl>(decl)) break; } } } while ((dc = dc->getParent())); return false; } /// Get the most optimal resilience expansion for the body of this function. /// If the body is able to be inlined into functions in other resilience /// domains, this ensures that only sufficiently-conservative access patterns /// are used. ResilienceExpansion DeclContext::getResilienceExpansion() const { for (const auto *dc = this; dc->isLocalContext(); dc = dc->getParent()) { // Default argument initializer contexts have their resilience expansion // set when they're type checked. if (isa<DefaultArgumentInitializer>(dc)) { if (auto *EED = dyn_cast<EnumElementDecl>(dc->getParent())) { return EED->getDefaultArgumentResilienceExpansion(); } return cast<AbstractFunctionDecl>(dc->getParent()) ->getDefaultArgumentResilienceExpansion(); } // Stored property initializer contexts use minimal resilience expansion // if the type is formally fixed layout. if (isa<PatternBindingInitializer>(dc)) { if (auto *NTD = dyn_cast<NominalTypeDecl>(dc->getParent())) { auto nominalAccess = NTD->getFormalAccessScope(/*useDC=*/nullptr, /*treatUsableFromInlineAsPublic=*/true); if (!nominalAccess.isPublic()) return ResilienceExpansion::Maximal; if (NTD->isFormallyResilient()) return ResilienceExpansion::Maximal; return ResilienceExpansion::Minimal; } } if (auto *AFD = dyn_cast<AbstractFunctionDecl>(dc)) { // If the function is a nested function, we will serialize its body if // we serialize the parent's body. if (AFD->getDeclContext()->isLocalContext()) continue; auto funcAccess = AFD->getFormalAccessScope(/*useDC=*/nullptr, /*treatUsableFromInlineAsPublic=*/true); // If the function is not externally visible, we will not be serializing // its body. if (!funcAccess.isPublic()) break; // If the function is public, @_transparent implies @inlinable. if (AFD->isTransparent()) return ResilienceExpansion::Minimal; if (AFD->getAttrs().hasAttribute<InlinableAttr>()) return ResilienceExpansion::Minimal; if (AFD->getAttrs().hasAttribute<AlwaysEmitIntoClientAttr>()) return ResilienceExpansion::Minimal; // If a property or subscript is @inlinable or @_alwaysEmitIntoClient, // the accessors are @inlinable or @_alwaysEmitIntoClient also. if (auto accessor = dyn_cast<AccessorDecl>(AFD)) { auto *storage = accessor->getStorage(); if (storage->getAttrs().getAttribute<InlinableAttr>()) return ResilienceExpansion::Minimal; if (storage->getAttrs().hasAttribute<AlwaysEmitIntoClientAttr>()) return ResilienceExpansion::Minimal; } } } return ResilienceExpansion::Maximal; } /// Determine whether the innermost context is generic. bool DeclContext::isInnermostContextGeneric() const { if (auto Decl = getAsDecl()) if (auto GC = Decl->getAsGenericContext()) return GC->isGeneric(); return false; } bool DeclContext::isCascadingContextForLookup(bool functionsAreNonCascading) const { // FIXME: This is explicitly checking for attributes in some cases because // it can be called before access control is computed. switch (getContextKind()) { case DeclContextKind::AbstractClosureExpr: break; case DeclContextKind::SerializedLocal: llvm_unreachable("should not perform lookups in deserialized contexts"); case DeclContextKind::Initializer: // Default arguments still require a type. if (isa<DefaultArgumentInitializer>(this)) return false; break; case DeclContextKind::TopLevelCodeDecl: // FIXME: Pattern initializers at top-level scope end up here. return true; case DeclContextKind::AbstractFunctionDecl: if (functionsAreNonCascading) return false; break; case DeclContextKind::SubscriptDecl: break; case DeclContextKind::EnumElementDecl: break; case DeclContextKind::Module: case DeclContextKind::FileUnit: return true; case DeclContextKind::GenericTypeDecl: break; case DeclContextKind::ExtensionDecl: return true; } return getParent()->isCascadingContextForLookup(true); } unsigned DeclContext::getSyntacticDepth() const { // Module scope == depth 0. if (isModuleScopeContext()) return 0; return 1 + getParent()->getSyntacticDepth(); } unsigned DeclContext::getSemanticDepth() const { // For extensions, count the depth of the nominal type being extended. if (isa<ExtensionDecl>(this)) { if (auto nominal = getSelfNominalTypeDecl()) return nominal->getSemanticDepth(); return 1; } // Module scope == depth 0. if (isModuleScopeContext()) return 0; return 1 + getParent()->getSemanticDepth(); } bool DeclContext::walkContext(ASTWalker &Walker) { switch (getContextKind()) { case DeclContextKind::Module: return cast<ModuleDecl>(this)->walk(Walker); case DeclContextKind::FileUnit: return cast<FileUnit>(this)->walk(Walker); case DeclContextKind::AbstractClosureExpr: return cast<AbstractClosureExpr>(this)->walk(Walker); case DeclContextKind::GenericTypeDecl: return cast<GenericTypeDecl>(this)->walk(Walker); case DeclContextKind::ExtensionDecl: return cast<ExtensionDecl>(this)->walk(Walker); case DeclContextKind::TopLevelCodeDecl: return cast<TopLevelCodeDecl>(this)->walk(Walker); case DeclContextKind::AbstractFunctionDecl: return cast<AbstractFunctionDecl>(this)->walk(Walker); case DeclContextKind::SubscriptDecl: return cast<SubscriptDecl>(this)->walk(Walker); case DeclContextKind::EnumElementDecl: return cast<EnumElementDecl>(this)->walk(Walker); case DeclContextKind::SerializedLocal: llvm_unreachable("walk is unimplemented for deserialized contexts"); case DeclContextKind::Initializer: // Is there any point in trying to walk the expression? return false; } llvm_unreachable("bad DeclContextKind"); } void DeclContext::dumpContext() const { printContext(llvm::errs()); } void AccessScope::dump() const { llvm::errs() << getAccessLevelSpelling(accessLevelForDiagnostics()) << ": "; if (isPublic()) { llvm::errs() << "(null)\n"; return; } if (auto *file = dyn_cast<SourceFile>(getDeclContext())) { llvm::errs() << "file '" << file->getFilename() << "'\n"; return; } if (auto *decl = getDeclContext()->getAsDecl()) { llvm::errs() << Decl::getKindName(decl->getKind()) << " "; if (auto *ext = dyn_cast<ExtensionDecl>(decl)) llvm::errs() << ext->getExtendedNominal()->getName(); else if (auto *named = dyn_cast<ValueDecl>(decl)) llvm::errs() << named->getFullName(); else llvm::errs() << (const void *)decl; SourceLoc loc = decl->getLoc(); if (loc.isValid()) { llvm::errs() << " at "; loc.print(llvm::errs(), decl->getASTContext().SourceMgr); } llvm::errs() << "\n"; return; } // If all else fails, dump the DeclContext tree. getDeclContext()->printContext(llvm::errs()); } template <typename DCType> static unsigned getLineNumber(DCType *DC) { SourceLoc loc = DC->getLoc(); if (loc.isInvalid()) return 0; const ASTContext &ctx = static_cast<const DeclContext *>(DC)->getASTContext(); return ctx.SourceMgr.getLineAndColumn(loc).first; } unsigned DeclContext::printContext(raw_ostream &OS, const unsigned indent, const bool onlyAPartialLine) const { unsigned Depth = 0; if (!onlyAPartialLine) if (auto *P = getParent()) Depth = P->printContext(OS, indent); const char *Kind; switch (getContextKind()) { case DeclContextKind::Module: Kind = "Module"; break; case DeclContextKind::FileUnit: Kind = "FileUnit"; break; case DeclContextKind::SerializedLocal: Kind = "Serialized Local"; break; case DeclContextKind::AbstractClosureExpr: Kind = "AbstractClosureExpr"; break; case DeclContextKind::GenericTypeDecl: switch (cast<GenericTypeDecl>(this)->getKind()) { #define DECL(ID, PARENT) \ case DeclKind::ID: Kind = #ID "Decl"; break; #include "swift/AST/DeclNodes.def" } break; case DeclContextKind::ExtensionDecl: Kind = "ExtensionDecl"; break; case DeclContextKind::TopLevelCodeDecl: Kind = "TopLevelCodeDecl"; break; case DeclContextKind::Initializer: Kind = "Initializer"; break; case DeclContextKind::AbstractFunctionDecl: Kind = "AbstractFunctionDecl"; break; case DeclContextKind::SubscriptDecl: Kind = "SubscriptDecl"; break; case DeclContextKind::EnumElementDecl: Kind = "EnumElementDecl"; break; } OS.indent(Depth*2 + indent) << (void*)this << " " << Kind; switch (getContextKind()) { case DeclContextKind::Module: OS << " name=" << cast<ModuleDecl>(this)->getName(); break; case DeclContextKind::FileUnit: switch (cast<FileUnit>(this)->getKind()) { case FileUnitKind::Builtin: OS << " Builtin"; break; case FileUnitKind::Source: OS << " file=\"" << cast<SourceFile>(this)->getFilename() << "\""; break; case FileUnitKind::SerializedAST: case FileUnitKind::ClangModule: case FileUnitKind::DWARFModule: OS << " file=\"" << cast<LoadedFile>(this)->getFilename() << "\""; break; } break; case DeclContextKind::AbstractClosureExpr: OS << " line=" << getLineNumber(cast<AbstractClosureExpr>(this)); OS << " : " << cast<AbstractClosureExpr>(this)->getType(); break; case DeclContextKind::GenericTypeDecl: OS << " name=" << cast<GenericTypeDecl>(this)->getName(); break; case DeclContextKind::ExtensionDecl: OS << " line=" << getLineNumber(cast<ExtensionDecl>(this)); OS << " base=" << cast<ExtensionDecl>(this)->getExtendedType(); break; case DeclContextKind::TopLevelCodeDecl: OS << " line=" << getLineNumber(cast<TopLevelCodeDecl>(this)); break; case DeclContextKind::AbstractFunctionDecl: { auto *AFD = cast<AbstractFunctionDecl>(this); OS << " name=" << AFD->getFullName(); if (AFD->hasInterfaceType()) OS << " : " << AFD->getInterfaceType(); else OS << " : (no type set)"; break; } case DeclContextKind::SubscriptDecl: { auto *SD = cast<SubscriptDecl>(this); OS << " name=" << SD->getBaseName(); if (SD->hasInterfaceType()) OS << " : " << SD->getInterfaceType(); else OS << " : (no type set)"; break; } case DeclContextKind::EnumElementDecl: { auto *EED = cast<EnumElementDecl>(this); OS << " name=" << EED->getBaseName(); if (EED->hasInterfaceType()) OS << " : " << EED->getInterfaceType(); else OS << " : (no type set)"; break; } case DeclContextKind::Initializer: switch (cast<Initializer>(this)->getInitializerKind()) { case InitializerKind::PatternBinding: { auto init = cast<PatternBindingInitializer>(this); OS << " PatternBinding 0x" << (void*) init->getBinding() << " #" << init->getBindingIndex(); break; } case InitializerKind::DefaultArgument: { auto init = cast<DefaultArgumentInitializer>(this); OS << " DefaultArgument index=" << init->getIndex(); break; } } break; case DeclContextKind::SerializedLocal: { auto local = cast<SerializedLocalDeclContext>(this); switch (local->getLocalDeclContextKind()) { case LocalDeclContextKind::AbstractClosure: { auto serializedClosure = cast<SerializedAbstractClosureExpr>(local); OS << " closure : " << serializedClosure->getType(); break; } case LocalDeclContextKind::DefaultArgumentInitializer: { auto init = cast<SerializedDefaultArgumentInitializer>(local); OS << "DefaultArgument index=" << init->getIndex(); break; } case LocalDeclContextKind::PatternBindingInitializer: { auto init = cast<SerializedPatternBindingInitializer>(local); OS << " PatternBinding 0x" << (void*) init->getBinding() << " #" << init->getBindingIndex(); break; } case LocalDeclContextKind::TopLevelCodeDecl: OS << " TopLevelCode"; break; } } } if (!onlyAPartialLine) OS << "\n"; return Depth + 1; } const Decl * IterableDeclContext::getDecl() const { switch (getIterableContextKind()) { case IterableDeclContextKind::NominalTypeDecl: return cast<NominalTypeDecl>(this); break; case IterableDeclContextKind::ExtensionDecl: return cast<ExtensionDecl>(this); break; } llvm_unreachable("Unhandled IterableDeclContextKind in switch."); } ASTContext &IterableDeclContext::getASTContext() const { return getDecl()->getASTContext(); } DeclRange IterableDeclContext::getCurrentMembersWithoutLoading() const { return DeclRange(FirstDeclAndLazyMembers.getPointer(), nullptr); } DeclRange IterableDeclContext::getMembers() const { loadAllMembers(); return getCurrentMembersWithoutLoading(); } /// Add a member to this context. void IterableDeclContext::addMember(Decl *member, Decl *Hint) { // Add the member to the list of declarations without notification. addMemberSilently(member, Hint); // Notify our parent declaration that we have added the member, which can // be used to update the lookup tables. switch (getIterableContextKind()) { case IterableDeclContextKind::NominalTypeDecl: { auto nominal = cast<NominalTypeDecl>(this); nominal->addedMember(member); assert(member->getDeclContext() == nominal && "Added member to the wrong context"); break; } case IterableDeclContextKind::ExtensionDecl: { auto ext = cast<ExtensionDecl>(this); ext->addedMember(member); assert(member->getDeclContext() == ext && "Added member to the wrong context"); break; } } } void IterableDeclContext::addMemberSilently(Decl *member, Decl *hint) const { assert(!member->NextDecl && "Already added to a container"); // If there is a hint decl that specifies where to add this, just // link into the chain immediately following it. if (hint) { member->NextDecl = hint->NextDecl; hint->NextDecl = member; // If the hint was the last in the parent context's chain, update it. if (LastDeclAndKind.getPointer() == hint) LastDeclAndKind.setPointer(member); return; } if (auto last = LastDeclAndKind.getPointer()) { last->NextDecl = member; assert(last != member && "Simple cycle in decl list"); } else { FirstDeclAndLazyMembers.setPointer(member); } LastDeclAndKind.setPointer(member); } void IterableDeclContext::setMemberLoader(LazyMemberLoader *loader, uint64_t contextData) { assert(!hasLazyMembers() && "already have lazy members"); ASTContext &ctx = getASTContext(); auto contextInfo = ctx.getOrCreateLazyIterableContextData(this, loader); auto lazyMembers = FirstDeclAndLazyMembers.getInt() | LazyMembers::Present; FirstDeclAndLazyMembers.setInt(LazyMembers(lazyMembers)); contextInfo->memberData = contextData; ++NumLazyIterableDeclContexts; ++NumUnloadedLazyIterableDeclContexts; // FIXME: (transitional) increment the redundant "always-on" counter. if (auto s = ctx.Stats) { ++s->getFrontendCounters().NumLazyIterableDeclContexts; ++s->getFrontendCounters().NumUnloadedLazyIterableDeclContexts; } } void IterableDeclContext::loadAllMembers() const { // Lazily parse members. getASTContext().parseMembers(const_cast<IterableDeclContext*>(this)); if (!hasLazyMembers()) return; // Don't try to load all members re-entrant-ly. ASTContext &ctx = getASTContext(); auto contextInfo = ctx.getOrCreateLazyIterableContextData(this, /*lazyLoader=*/nullptr); auto lazyMembers = FirstDeclAndLazyMembers.getInt() & ~LazyMembers::Present; FirstDeclAndLazyMembers.setInt(LazyMembers(lazyMembers)); const Decl *container = getDecl(); contextInfo->loader->loadAllMembers(const_cast<Decl *>(container), contextInfo->memberData); --NumUnloadedLazyIterableDeclContexts; // FIXME: (transitional) decrement the redundant "always-on" counter. if (auto s = ctx.Stats) s->getFrontendCounters().NumUnloadedLazyIterableDeclContexts--; } bool IterableDeclContext::wasDeserialized() const { const DeclContext *DC = cast<DeclContext>(getDecl()); if (auto F = dyn_cast<FileUnit>(DC->getModuleScopeContext())) { return F->getKind() == FileUnitKind::SerializedAST; } return false; } bool IterableDeclContext::classof(const Decl *D) { switch (D->getKind()) { default: return false; #define DECL(ID, PARENT) // See previous line #define ITERABLE_DECL(ID, PARENT) \ case DeclKind::ID: return true; #include "swift/AST/DeclNodes.def" } } IterableDeclContext * IterableDeclContext::castDeclToIterableDeclContext(const Decl *D) { switch (D->getKind()) { default: llvm_unreachable("Decl is not a IterableDeclContext."); #define DECL(ID, PARENT) // See previous line #define ITERABLE_DECL(ID, PARENT) \ case DeclKind::ID: \ return const_cast<IterableDeclContext *>( \ static_cast<const IterableDeclContext*>(cast<ID##Decl>(D))); #include "swift/AST/DeclNodes.def" } } /// Return the DeclContext to compare when checking private access in /// Swift 4 mode. The context returned is the type declaration if the context /// and the type declaration are in the same file, otherwise it is the types /// last extension in the source file. If the context does not refer to a /// declaration or extension, the supplied context is returned. static const DeclContext * getPrivateDeclContext(const DeclContext *DC, const SourceFile *useSF) { auto NTD = DC->getSelfNominalTypeDecl(); if (!NTD) return DC; // use the type declaration as the private scope if it is in the same // file as useSF. This occurs for both extensions and declarations. if (NTD->getParentSourceFile() == useSF) return NTD; // Otherwise use the last extension declaration in the same file. const DeclContext *lastExtension = nullptr; for (ExtensionDecl *ED : NTD->getExtensions()) if (ED->getParentSourceFile() == useSF) lastExtension = ED; // If there's no last extension, return the supplied context. return lastExtension ? lastExtension : DC; } AccessScope::AccessScope(const DeclContext *DC, bool isPrivate) : Value(DC, isPrivate) { if (isPrivate) { DC = getPrivateDeclContext(DC, DC->getParentSourceFile()); Value.setPointer(DC); } if (!DC || isa<ModuleDecl>(DC)) assert(!isPrivate && "public or internal scope can't be private"); } bool AccessScope::isFileScope() const { auto DC = getDeclContext(); return DC && isa<FileUnit>(DC); } bool AccessScope::isInternal() const { auto DC = getDeclContext(); return DC && isa<ModuleDecl>(DC); } AccessLevel AccessScope::accessLevelForDiagnostics() const { if (isPublic()) return AccessLevel::Public; if (isa<ModuleDecl>(getDeclContext())) return AccessLevel::Internal; if (getDeclContext()->isModuleScopeContext()) { return isPrivate() ? AccessLevel::Private : AccessLevel::FilePrivate; } return AccessLevel::Private; } bool AccessScope::allowsPrivateAccess(const DeclContext *useDC, const DeclContext *sourceDC) { // Check the lexical scope. if (useDC->isChildContextOf(sourceDC)) return true; // Do not allow access if the sourceDC is in a different file auto useSF = useDC->getParentSourceFile(); if (useSF != sourceDC->getParentSourceFile()) return false; // Do not allow access if the sourceDC does not represent a type. auto sourceNTD = sourceDC->getSelfNominalTypeDecl(); if (!sourceNTD) return false; // Compare the private scopes and iterate over the parent types. sourceDC = getPrivateDeclContext(sourceDC, useSF); while (!useDC->isModuleContext()) { useDC = getPrivateDeclContext(useDC, useSF); if (useDC == sourceDC) return true; // Get the parent type. If the context represents a type, look at the types // declaring context instead of the contexts parent. This will crawl up // the type hierarchy in nested extensions correctly. if (auto NTD = useDC->getSelfNominalTypeDecl()) useDC = NTD->getDeclContext(); else useDC = useDC->getParent(); } return false; } DeclContext *Decl::getDeclContextForModule() const { if (auto module = dyn_cast<ModuleDecl>(this)) return const_cast<ModuleDecl *>(module); return nullptr; } DeclContextKind DeclContext::getContextKind() const { switch (ParentAndKind.getInt()) { case ASTHierarchy::Expr: return DeclContextKind::AbstractClosureExpr; case ASTHierarchy::Initializer: return DeclContextKind::Initializer; case ASTHierarchy::SerializedLocal: return DeclContextKind::SerializedLocal; case ASTHierarchy::FileUnit: return DeclContextKind::FileUnit; case ASTHierarchy::Decl: { auto decl = reinterpret_cast<const Decl*>(this + 1); if (isa<AbstractFunctionDecl>(decl)) return DeclContextKind::AbstractFunctionDecl; if (isa<GenericTypeDecl>(decl)) return DeclContextKind::GenericTypeDecl; switch (decl->getKind()) { case DeclKind::Module: return DeclContextKind::Module; case DeclKind::TopLevelCode: return DeclContextKind::TopLevelCodeDecl; case DeclKind::Subscript: return DeclContextKind::SubscriptDecl; case DeclKind::EnumElement: return DeclContextKind::EnumElementDecl; case DeclKind::Extension: return DeclContextKind::ExtensionDecl; default: llvm_unreachable("Unhandled Decl kind"); } } } llvm_unreachable("Unhandled DeclContext ASTHierarchy"); } #define DECL(Id, Parent) \ static_assert(!std::is_base_of<DeclContext, Id##Decl>::value, \ "Non-context Decl node has context?"); #define CONTEXT_DECL(Id, Parent) \ static_assert(alignof(DeclContext) == alignof(Id##Decl), "Alignment error"); \ static_assert(std::is_base_of<DeclContext, Id##Decl>::value, \ "CONTEXT_DECL nodes must inherit from DeclContext"); #define CONTEXT_VALUE_DECL(Id, Parent) \ static_assert(alignof(DeclContext) == alignof(Id##Decl), "Alignment error"); \ static_assert(std::is_base_of<DeclContext, Id##Decl>::value, \ "CONTEXT_VALUE_DECL nodes must inherit from DeclContext"); #include "swift/AST/DeclNodes.def" #define EXPR(Id, Parent) \ static_assert(!std::is_base_of<DeclContext, Id##Expr>::value, \ "Non-context Expr node has context?"); #define CONTEXT_EXPR(Id, Parent) \ static_assert(alignof(DeclContext) == alignof(Id##Expr), "Alignment error"); \ static_assert(std::is_base_of<DeclContext, Id##Expr>::value, \ "CONTEXT_EXPR nodes must inherit from DeclContext"); #include "swift/AST/ExprNodes.def" #ifndef NDEBUG // XXX -- static_cast is not static enough for use with static_assert(). // DO verify this by temporarily breaking a Decl or Expr. // DO NOT assume that the compiler will emit this code blindly. SWIFT_CONSTRUCTOR static void verify_DeclContext_is_start_of_node() { auto decl = reinterpret_cast<Decl*>(0x1000 + sizeof(DeclContext)); #define DECL(Id, Parent) #define CONTEXT_DECL(Id, Parent) \ assert(reinterpret_cast<DeclContext*>(0x1000) == \ static_cast<Id##Decl*>(decl)); #define CONTEXT_VALUE_DECL(Id, Parent) \ assert(reinterpret_cast<DeclContext*>(0x1000) == \ static_cast<Id##Decl*>(decl)); #include "swift/AST/DeclNodes.def" auto expr = reinterpret_cast<Expr*>(0x1000 + sizeof(DeclContext)); #define EXPR(Id, Parent) #define CONTEXT_EXPR(Id, Parent) \ assert(reinterpret_cast<DeclContext*>(0x1000) == \ static_cast<Id##Expr*>(expr)); #include "swift/AST/ExprNodes.def" } #endif
32,679
10,487
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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. * *=========================================================================*/ #ifndef itkConvertPixelBuffer_hxx #define itkConvertPixelBuffer_hxx #include "itkConvertPixelBuffer.h" #include "itkRGBPixel.h" #include "itkDefaultConvertPixelTraits.h" #include <cstddef> namespace itk { template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> template <typename UComponentType> std::enable_if_t<!NumericTraits<UComponentType>::IsInteger, UComponentType> ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::DefaultAlphaValue() { return NumericTraits<UComponentType>::One; } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> template <typename UComponentType> std::enable_if_t<NumericTraits<UComponentType>::IsInteger, UComponentType> ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::DefaultAlphaValue() { return NumericTraits<UComponentType>::max(); } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::Convert(InputPixelType * inputData, int inputNumberOfComponents, OutputPixelType * outputData, size_t size) { switch (OutputConvertTraits::GetNumberOfComponents()) { // output number of components is 1 case 1: { switch (inputNumberOfComponents) { case 1: ConvertGrayToGray(inputData, outputData, size); break; case 3: ConvertRGBToGray(inputData, outputData, size); break; case 4: ConvertRGBAToGray(inputData, outputData, size); break; default: ConvertMultiComponentToGray(inputData, inputNumberOfComponents, outputData, size); break; } break; } // handle the complex case case 2: { switch (inputNumberOfComponents) { case 1: ConvertGrayToComplex(inputData, outputData, size); break; case 2: ConvertComplexToComplex(inputData, outputData, size); break; default: ConvertMultiComponentToComplex(inputData, inputNumberOfComponents, outputData, size); break; } break; } // output number of components is 3 RGB case 3: { switch (inputNumberOfComponents) { case 1: ConvertGrayToRGB(inputData, outputData, size); break; case 3: ConvertRGBToRGB(inputData, outputData, size); break; case 4: ConvertRGBAToRGB(inputData, outputData, size); break; default: ConvertMultiComponentToRGB(inputData, inputNumberOfComponents, outputData, size); } break; } // output number of components is 4 RGBA case 4: { switch (inputNumberOfComponents) { case 1: ConvertGrayToRGBA(inputData, outputData, size); break; case 3: ConvertRGBToRGBA(inputData, outputData, size); break; case 4: ConvertRGBAToRGBA(inputData, outputData, size); break; default: ConvertMultiComponentToRGBA(inputData, inputNumberOfComponents, outputData, size); } break; } // output number of components is 6 (SymmetricSecondRankTensor) case 6: { switch (inputNumberOfComponents) { case 6: ConvertTensor6ToTensor6(inputData, outputData, size); break; case 9: ConvertTensor9ToTensor6(inputData, outputData, size); break; default: itkGenericExceptionMacro("No conversion available from " << inputNumberOfComponents << " components to: 6 components"); break; } break; } default: itkGenericExceptionMacro("No conversion available from " << inputNumberOfComponents << " components to: " << OutputConvertTraits::GetNumberOfComponents() << " components"); break; } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertGrayToGray( InputPixelType * inputData, OutputPixelType * outputData, size_t size) { InputPixelType * endInput = inputData + size; while (inputData != endInput) { OutputConvertTraits::SetNthComponent(0, *outputData++, static_cast<OutputComponentType>(*inputData)); inputData++; } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertRGBToGray(InputPixelType * inputData, OutputPixelType * outputData, size_t size) { // Weights convert from linear RGB to CIE luminance assuming a // modern monitor. See Charles Pontyon's Colour FAQ // http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html // NOTE: The scale factors are converted to whole numbers for precision InputPixelType * endInput = inputData + size * 3; while (inputData != endInput) { auto val = static_cast<OutputComponentType>((2125.0 * static_cast<OutputComponentType>(*inputData) + 7154.0 * static_cast<OutputComponentType>(*(inputData + 1)) + 0721.0 * static_cast<OutputComponentType>(*(inputData + 2))) / 10000.0); inputData += 3; OutputConvertTraits::SetNthComponent(0, *outputData++, val); } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertRGBAToGray( InputPixelType * inputData, OutputPixelType * outputData, size_t size) { // Weights convert from linear RGB to CIE luminance assuming a // modern monitor. See Charles Pontyon's Colour FAQ // http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html // NOTE: The scale factors are converted to whole numbers for // precision InputPixelType * endInput = inputData + size * 4; double maxAlpha(DefaultAlphaValue<InputPixelType>()); // // To be backwards campatible, if the output pixel type // isn't a short or char type, don't fix the problem. if (sizeof(*outputData) > 2) { maxAlpha = 1.0; } while (inputData != endInput) { // this is an ugly implementation of the simple equation // greval = (.2125 * red + .7154 * green + .0721 * blue) / alpha // double tempval = ((2125.0 * static_cast<double>(*inputData) + 7154.0 * static_cast<double>(*(inputData + 1)) + 0721.0 * static_cast<double>(*(inputData + 2))) / 10000.0) * static_cast<double>(*(inputData + 3)) / maxAlpha; inputData += 4; auto val = static_cast<OutputComponentType>(tempval); OutputConvertTraits::SetNthComponent(0, *outputData++, val); } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertMultiComponentToGray( InputPixelType * inputData, int inputNumberOfComponents, OutputPixelType * outputData, size_t size) { // // To be backwards campatible, if the output pixel type // isn't a short or char type, don't fix the problem. double maxAlpha(DefaultAlphaValue<InputPixelType>()); if (sizeof(*outputData) > 2) { maxAlpha = 1.0; } // 2 components assumed intensity and alpha if (inputNumberOfComponents == 2) { InputPixelType * endInput = inputData + size * 2; while (inputData != endInput) { OutputComponentType val = static_cast<OutputComponentType>(*inputData) * static_cast<OutputComponentType>(*(inputData + 1) / maxAlpha); inputData += 2; OutputConvertTraits::SetNthComponent(0, *outputData++, val); } } // just skip the rest of the data else { // Weights convert from linear RGB to CIE luminance assuming a // modern monitor. See Charles Pontyon's Colour FAQ // http://www.poynton.com/notes/colour_and_gamma/ColorFAQ.html // NOTE: The scale factors are converted to whole numbers for // precision ptrdiff_t diff = inputNumberOfComponents - 4; InputPixelType * endInput = inputData + size * (size_t)inputNumberOfComponents; while (inputData != endInput) { double tempval = ((2125.0 * static_cast<double>(*inputData) + 7154.0 * static_cast<double>(*(inputData + 1)) + 0721.0 * static_cast<double>(*(inputData + 2))) / 10000.0) * static_cast<double>(*(inputData + 3)) / maxAlpha; inputData += 4; auto val = static_cast<OutputComponentType>(tempval); OutputConvertTraits::SetNthComponent(0, *outputData++, val); inputData += diff; } } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertGrayToRGB(InputPixelType * inputData, OutputPixelType * outputData, size_t size) { InputPixelType * endInput = inputData + size; while (inputData != endInput) { OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData)); OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*inputData)); OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*inputData)); inputData++; outputData++; } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertRGBToRGB(InputPixelType * inputData, OutputPixelType * outputData, size_t size) { InputPixelType * endInput = inputData + size * 3; while (inputData != endInput) { OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData)); OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1))); OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*(inputData + 2))); inputData += 3; outputData++; } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertRGBAToRGB(InputPixelType * inputData, OutputPixelType * outputData, size_t size) { InputPixelType * endInput = inputData + size * 4; while (inputData != endInput) { OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData)); OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1))); OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*(inputData + 2))); inputData += 3; inputData++; // skip alpha outputData++; } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertMultiComponentToRGB( InputPixelType * inputData, int inputNumberOfComponents, OutputPixelType * outputData, size_t size) { // assume intensity alpha if (inputNumberOfComponents == 2) { InputPixelType * endInput = inputData + size * 2; while (inputData != endInput) { OutputComponentType val = static_cast<OutputComponentType>(*inputData) * static_cast<OutputComponentType>(*(inputData + 1)); inputData += 2; OutputConvertTraits::SetNthComponent(0, *outputData, val); OutputConvertTraits::SetNthComponent(1, *outputData, val); OutputConvertTraits::SetNthComponent(2, *outputData, val); outputData++; } } // just skip the rest of the data else { ptrdiff_t diff = inputNumberOfComponents - 3; InputPixelType * endInput = inputData + size * (size_t)inputNumberOfComponents; while (inputData != endInput) { OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData)); OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1))); OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*(inputData + 2))); inputData += 3; inputData += diff; outputData++; } } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertGrayToRGBA( InputPixelType * inputData, OutputPixelType * outputData, size_t size) { InputPixelType * endInput = inputData + size; while (inputData != endInput) { OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData)); OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*inputData)); OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*inputData)); OutputConvertTraits::SetNthComponent( 3, *outputData, static_cast<OutputComponentType>(DefaultAlphaValue<InputPixelType>())); inputData++; outputData++; } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertRGBToRGBA(InputPixelType * inputData, OutputPixelType * outputData, size_t size) { using InputConvertTraits = itk::DefaultConvertPixelTraits<InputPixelType>; using InputComponentType = typename InputConvertTraits::ComponentType; InputPixelType * endInput = inputData + size * 3; while (inputData != endInput) { OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData)); OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1))); OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*(inputData + 2))); OutputConvertTraits::SetNthComponent( 3, *outputData, static_cast<OutputComponentType>(DefaultAlphaValue<InputComponentType>())); inputData += 3; outputData++; } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertRGBAToRGBA( InputPixelType * inputData, OutputPixelType * outputData, size_t size) { InputPixelType * endInput = inputData + size * 4; while (inputData != endInput) { OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData)); OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1))); OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*(inputData + 2))); OutputConvertTraits::SetNthComponent(3, *outputData, static_cast<OutputComponentType>(*(inputData + 3))); inputData += 4; outputData++; } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertMultiComponentToRGBA( InputPixelType * inputData, int inputNumberOfComponents, OutputPixelType * outputData, size_t size) { // equal weights for 2 components?? if (inputNumberOfComponents == 2) { InputPixelType * endInput = inputData + size * 2; while (inputData != endInput) { auto val = static_cast<OutputComponentType>(*inputData); auto alpha = static_cast<OutputComponentType>(*(inputData + 1)); inputData += 2; OutputConvertTraits::SetNthComponent(0, *outputData, val); OutputConvertTraits::SetNthComponent(1, *outputData, val); OutputConvertTraits::SetNthComponent(2, *outputData, val); OutputConvertTraits::SetNthComponent(3, *outputData, alpha); } } else { ptrdiff_t diff = inputNumberOfComponents - 4; InputPixelType * endInput = inputData + size * (size_t)inputNumberOfComponents; while (inputData != endInput) { OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData)); OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1))); OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*(inputData + 2))); OutputConvertTraits::SetNthComponent(3, *outputData, static_cast<OutputComponentType>(*(inputData + 3))); inputData += 4; inputData += diff; outputData++; } } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertTensor6ToTensor6( InputPixelType * inputData, OutputPixelType * outputData, size_t size) { for (size_t i = 0; i < size; ++i) { OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData)); OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1))); OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*(inputData + 2))); OutputConvertTraits::SetNthComponent(3, *outputData, static_cast<OutputComponentType>(*(inputData + 3))); OutputConvertTraits::SetNthComponent(4, *outputData, static_cast<OutputComponentType>(*(inputData + 4))); OutputConvertTraits::SetNthComponent(5, *outputData, static_cast<OutputComponentType>(*(inputData + 5))); ++outputData; inputData += 6; } } // Convert Grayscale to Complex template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertGrayToComplex( InputPixelType * inputData, OutputPixelType * outputData, size_t size) { InputPixelType * endInput = inputData + size; while (inputData != endInput) { OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData)); OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*inputData)); inputData++; outputData++; } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertComplexToComplex( InputPixelType * inputData, OutputPixelType * outputData, size_t size) { InputPixelType * endInput = inputData + size * 2; while (inputData != endInput) { OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData)); OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1))); inputData += 2; outputData++; } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertTensor9ToTensor6( InputPixelType * inputData, OutputPixelType * outputData, size_t size) { for (size_t i = 0; i < size; ++i) { OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData)); OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1))); OutputConvertTraits::SetNthComponent(2, *outputData, static_cast<OutputComponentType>(*(inputData + 2))); OutputConvertTraits::SetNthComponent(3, *outputData, static_cast<OutputComponentType>(*(inputData + 4))); OutputConvertTraits::SetNthComponent(4, *outputData, static_cast<OutputComponentType>(*(inputData + 5))); OutputConvertTraits::SetNthComponent(5, *outputData, static_cast<OutputComponentType>(*(inputData + 8))); ++outputData; inputData += 9; } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertMultiComponentToComplex( InputPixelType * inputData, int inputNumberOfComponents, OutputPixelType * outputData, size_t size) { ptrdiff_t diff = inputNumberOfComponents - 2; InputPixelType * endInput = inputData + size * (size_t)inputNumberOfComponents; while (inputData != endInput) { OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData)); OutputConvertTraits::SetNthComponent(1, *outputData, static_cast<OutputComponentType>(*(inputData + 1))); inputData += 2; inputData += diff; outputData++; } } template <typename InputPixelType, typename OutputPixelType, typename OutputConvertTraits> void ConvertPixelBuffer<InputPixelType, OutputPixelType, OutputConvertTraits>::ConvertVectorImage( InputPixelType * inputData, int inputNumberOfComponents, OutputPixelType * outputData, size_t size) { size_t length = size * (size_t)inputNumberOfComponents; for (size_t i = 0; i < length; ++i) { OutputConvertTraits::SetNthComponent(0, *outputData, static_cast<OutputComponentType>(*inputData)); ++outputData; ++inputData; } } } // end namespace itk #endif
23,895
6,779
#include "chunker.hpp" #include "sys/time.h" extern Configure config; struct timeval timestartChunker; struct timeval timeendChunker; struct timeval timestartChunker_VarSizeInsert; struct timeval timeendChunker_VarSizeInsert; struct timeval timestartChunker_VarSizeHash; struct timeval timeendChunker_VarSizeHash; uint32_t DivCeil(uint32_t a, uint32_t b) { uint32_t tmp = a / b; if (a % b == 0) { return tmp; } else { return (tmp + 1); } } uint32_t CompareLimit(uint32_t input, uint32_t lower, uint32_t upper) { if (input <= lower) { return lower; } else if (input >= upper) { return upper; } else { return input; } } Chunker::Chunker(std::string path, keyClient* keyClientObjTemp) { loadChunkFile(path); ChunkerInit(path); cryptoObj = new CryptoPrimitive(); keyClientObj = keyClientObjTemp; } Chunker::~Chunker() { if (powerLUT != NULL) { delete powerLUT; } if (removeLUT != NULL) { delete removeLUT; } if (waitingForChunkingBuffer != NULL) { delete waitingForChunkingBuffer; } if (chunkBuffer != NULL) { delete chunkBuffer; } if (cryptoObj != NULL) { delete cryptoObj; } if (chunkingFile.is_open()) { chunkingFile.close(); } } std::ifstream& Chunker::getChunkingFile() { if (!chunkingFile.is_open()) { cerr << "Chunker : chunking file open failed" << endl; exit(1); } return chunkingFile; } void Chunker::loadChunkFile(std::string path) { if (chunkingFile.is_open()) { chunkingFile.close(); } chunkingFile.open(path, std::ios::binary); if (!chunkingFile.is_open()) { cerr << "Chunker : open file: " << path << "error, client exit now" << endl; exit(1); } } void Chunker::ChunkerInit(string path) { u_char filePathHash[FILE_NAME_HASH_SIZE]; cryptoObj->generateHash((u_char*)&path[0], path.length(), filePathHash); memcpy(fileRecipe.recipe.fileRecipeHead.fileNameHash, filePathHash, FILE_NAME_HASH_SIZE); memcpy(fileRecipe.recipe.keyRecipeHead.fileNameHash, filePathHash, FILE_NAME_HASH_SIZE); ChunkerType = (int)config.getChunkingType(); if (ChunkerType == CHUNKER_VAR_SIZE_TYPE) { int numOfMaskBits; avgChunkSize = (int)config.getAverageChunkSize(); minChunkSize = (int)config.getMinChunkSize(); maxChunkSize = (int)config.getMaxChunkSize(); slidingWinSize = (int)config.getSlidingWinSize(); ReadSize = config.getReadSize(); ReadSize = ReadSize * 1024 * 1024; waitingForChunkingBuffer = new u_char[ReadSize]; chunkBuffer = new u_char[maxChunkSize]; if (waitingForChunkingBuffer == NULL || chunkBuffer == NULL) { cerr << "Chunker : Memory malloc error" << endl; exit(1); } if (minChunkSize >= avgChunkSize) { cerr << "Chunker : minChunkSize should be smaller than avgChunkSize!" << endl; exit(1); } if (maxChunkSize <= avgChunkSize) { cerr << "Chunker : maxChunkSize should be larger than avgChunkSize!" << endl; exit(1); } /*initialize the base and modulus for calculating the fingerprint of a window*/ /*these two values were employed in open-vcdiff: "http://code.google.com/p/open-vcdiff/"*/ polyBase = 257; /*a prime larger than 255, the max value of "unsigned char"*/ polyMOD = (1 << 23) - 1; /*polyMOD - 1 = 0x7fffff: use the last 23 bits of a polynomial as its hash*/ /*initialize the lookup table for accelerating the power calculation in rolling hash*/ powerLUT = (uint32_t*)malloc(sizeof(uint32_t) * slidingWinSize); /*powerLUT[i] = power(polyBase, i) mod polyMOD*/ powerLUT[0] = 1; for (int i = 1; i < slidingWinSize; i++) { /*powerLUT[i] = (powerLUT[i-1] * polyBase) mod polyMOD*/ powerLUT[i] = (powerLUT[i - 1] * polyBase) & polyMOD; } /*initialize the lookup table for accelerating the byte remove in rolling hash*/ removeLUT = (uint32_t*)malloc(sizeof(uint32_t) * 256); /*256 for unsigned char*/ for (int i = 0; i < 256; i++) { /*removeLUT[i] = (- i * powerLUT[_slidingWinSize-1]) mod polyMOD*/ removeLUT[i] = (i * powerLUT[slidingWinSize - 1]) & polyMOD; if (removeLUT[i] != 0) { removeLUT[i] = (polyMOD - removeLUT[i] + 1) & polyMOD; } /*note: % is a remainder (rather than modulus) operator*/ /* if a < 0, -polyMOD < a % polyMOD <= 0 */ } /*initialize the anchorMask for depolytermining an anchor*/ /*note: power(2, numOfanchorMaskBits) = avgChunkSize*/ numOfMaskBits = 1; while ((avgChunkSize >> numOfMaskBits) != 1) { numOfMaskBits++; } anchorMask = (1 << numOfMaskBits) - 1; /*initialize the value for depolytermining an anchor*/ anchorValue = 0; } else if (ChunkerType == CHUNKER_FIX_SIZE_TYPE) { avgChunkSize = (int)config.getAverageChunkSize(); minChunkSize = (int)config.getMinChunkSize(); maxChunkSize = (int)config.getMaxChunkSize(); ReadSize = config.getReadSize(); ReadSize = ReadSize * 1024 * 1024; waitingForChunkingBuffer = new u_char[ReadSize]; chunkBuffer = new u_char[avgChunkSize]; if (waitingForChunkingBuffer == NULL || chunkBuffer == NULL) { cerr << "Chunker : Memory Error" << endl; exit(1); } if (minChunkSize != avgChunkSize || maxChunkSize != avgChunkSize) { cerr << "Chunker : Error: minChunkSize and maxChunkSize should be same in fixed size mode!" << endl; exit(1); } if (ReadSize % avgChunkSize != 0) { cerr << "Chunker : Setting fixed size chunking error : ReadSize not compat with average chunk size" << endl; } } else if (ChunkerType == CHUNKER_FAST_CDC) { avgChunkSize = (int)config.getAverageChunkSize(); minChunkSize = (int)config.getMinChunkSize(); maxChunkSize = (int)config.getMaxChunkSize(); ReadSize = config.getReadSize(); ReadSize = ReadSize * 1024 * 1024; waitingForChunkingBuffer = new u_char[ReadSize]; chunkBuffer = new u_char[maxChunkSize]; if (waitingForChunkingBuffer == NULL || chunkBuffer == NULL) { cerr << "Chunker : Memory malloc error" << endl; exit(1); } if (minChunkSize >= avgChunkSize) { cerr << "Chunker : minChunkSize should be smaller than avgChunkSize!" << endl; exit(1); } if (maxChunkSize <= avgChunkSize) { cerr << "Chunker : maxChunkSize should be larger than avgChunkSize!" << endl; exit(1); } normalSize_ = calNormalSize(minChunkSize, avgChunkSize, maxChunkSize); uint32_t bits = (uint32_t) round(log2(static_cast<double>(avgChunkSize))); maskS_ = generateFastCDCMask(bits + 1); maskL_ = generateFastCDCMask(bits - 1); } else if (ChunkerType == CHUNKER_FIX_SIZE_TYPE) { avgChunkSize = (int)config.getAverageChunkSize(); minChunkSize = (int)config.getMinChunkSize(); maxChunkSize = (int)config.getMaxChunkSize(); ReadSize = config.getReadSize(); ReadSize = ReadSize * 1024 * 1024; waitingForChunkingBuffer = new u_char[ReadSize]; chunkBuffer = new u_char[avgChunkSize]; if (waitingForChunkingBuffer == NULL || chunkBuffer == NULL) { cerr << "Chunker : Memory Error" << endl; exit(1); } if (minChunkSize != avgChunkSize || maxChunkSize != avgChunkSize) { cerr << "Chunker : Error: minChunkSize and maxChunkSize should be same in fixed size mode!" << endl; exit(1); } if (ReadSize % avgChunkSize != 0) { cerr << "Chunker : Setting fixed size chunking error : ReadSize not compat with average chunk size" << endl; } } else if (ChunkerType == CHUNKER_TRACE_DRIVEN_TYPE_FSL) { maxChunkSize = (int)config.getMaxChunkSize(); chunkBuffer = new u_char[maxChunkSize + 6]; } else if (ChunkerType == CHUNKER_TRACE_DRIVEN_TYPE_UBC) { maxChunkSize = (int)config.getMaxChunkSize(); chunkBuffer = new u_char[maxChunkSize + 5]; } else { cerr << "Chunker : Error chunker type.\n"; exit(1); } } bool Chunker::chunking() { /*fixed-size Chunker*/ if (ChunkerType == CHUNKER_FIX_SIZE_TYPE) { fixSizeChunking(); } /*variable-size Chunker*/ if (ChunkerType == CHUNKER_VAR_SIZE_TYPE) { varSizeChunking(); } if (ChunkerType == CHUNKER_TRACE_DRIVEN_TYPE_FSL) { traceDrivenChunkingFSL(); } if (ChunkerType == CHUNKER_TRACE_DRIVEN_TYPE_UBC) { traceDrivenChunkingUBC(); } if (ChunkerType == CHUNKER_FAST_CDC) { fastCDC(); } return true; } void Chunker::fixSizeChunking() { double chunkTime = 0; double hashTime = 0; long diff; double second; std::ifstream& fin = getChunkingFile(); uint64_t chunkIDCounter = 0; memset(chunkBuffer, 0, sizeof(char) * avgChunkSize); uint64_t fileSize = 0; u_char hash[CHUNK_HASH_SIZE]; /*start chunking*/ while (true) { memset((char*)waitingForChunkingBuffer, 0, sizeof(unsigned char) * ReadSize); fin.read((char*)waitingForChunkingBuffer, sizeof(char) * ReadSize); uint64_t totalReadSize = fin.gcount(); fileSize += totalReadSize; uint64_t chunkedSize = 0; if (totalReadSize == ReadSize) { while (chunkedSize < totalReadSize) { #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker, NULL); #endif memset(chunkBuffer, 0, sizeof(char) * avgChunkSize); memcpy(chunkBuffer, waitingForChunkingBuffer + chunkedSize, avgChunkSize); #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker, NULL); diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec; second = diff / 1000000.0; chunkTime += second; #endif #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker, NULL); #endif if (!cryptoObj->generateHash(chunkBuffer, avgChunkSize, hash)) { cerr << "Chunker : fixed size chunking: compute hash error" << endl; } #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker, NULL); diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec; second = diff / 1000000.0; hashTime += second; #endif Data_t tempChunk; tempChunk.chunk.ID = chunkIDCounter; tempChunk.chunk.logicDataSize = avgChunkSize; memcpy(tempChunk.chunk.logicData, chunkBuffer, avgChunkSize); memcpy(tempChunk.chunk.chunkHash, hash, CHUNK_HASH_SIZE); tempChunk.dataType = DATA_TYPE_CHUNK; insertMQToKeyClient(tempChunk); chunkIDCounter++; chunkedSize += avgChunkSize; } } else { uint64_t retSize = 0; while (chunkedSize < totalReadSize) { memset(chunkBuffer, 0, sizeof(char) * avgChunkSize); Data_t tempChunk; if (retSize > avgChunkSize) { #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker, NULL); #endif memcpy(chunkBuffer, waitingForChunkingBuffer + chunkedSize, avgChunkSize); #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker, NULL); diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec; second = diff / 1000000.0; chunkTime += second; #endif #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker, NULL); #endif if (!cryptoObj->generateHash(chunkBuffer, avgChunkSize, hash)) { cerr << "Chunker : fixed size chunking: compute hash error" << endl; } #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker, NULL); diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec; second = diff / 1000000.0; hashTime += second; #endif tempChunk.chunk.ID = chunkIDCounter; tempChunk.chunk.logicDataSize = avgChunkSize; memcpy(tempChunk.chunk.logicData, chunkBuffer, avgChunkSize); memcpy(tempChunk.chunk.chunkHash, hash, CHUNK_HASH_SIZE); } else { #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker, NULL); #endif memcpy(chunkBuffer, waitingForChunkingBuffer + chunkedSize, retSize); #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker, NULL); diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec; second = diff / 1000000.0; chunkTime += second; #endif #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker, NULL); #endif if (!cryptoObj->generateHash(chunkBuffer, retSize, hash)) { cerr << "Chunker : fixed size chunking: compute hash error" << endl; } #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker, NULL); diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec; second = diff / 1000000.0; hashTime += second; #endif tempChunk.chunk.ID = chunkIDCounter; tempChunk.chunk.logicDataSize = retSize; memcpy(tempChunk.chunk.logicData, chunkBuffer, retSize); memcpy(tempChunk.chunk.chunkHash, hash, CHUNK_HASH_SIZE); } retSize = totalReadSize - chunkedSize; tempChunk.dataType = DATA_TYPE_CHUNK; insertMQToKeyClient(tempChunk); chunkIDCounter++; chunkedSize += avgChunkSize; } } if (fin.eof()) { break; } } fileRecipe.recipe.fileRecipeHead.totalChunkNumber = chunkIDCounter; fileRecipe.recipe.keyRecipeHead.totalChunkKeyNumber = chunkIDCounter; fileRecipe.recipe.fileRecipeHead.fileSize = fileSize; fileRecipe.recipe.keyRecipeHead.fileSize = fileRecipe.recipe.fileRecipeHead.fileSize; fileRecipe.dataType = DATA_TYPE_RECIPE; insertMQToKeyClient(fileRecipe); if (setJobDoneFlag() == false) { cerr << "Chunker : set chunking done flag error" << endl; } cout << "Chunker : Fixed chunking over:\nTotal file size = " << fileRecipe.recipe.fileRecipeHead.fileSize << "; Total chunk number = " << fileRecipe.recipe.fileRecipeHead.totalChunkNumber << endl; #if SYSTEM_BREAK_DOWN == 1 cout << "Chunker : total chunking time = " << chunkTime << " s" << endl; cout << "Chunker : total hashing time = " << hashTime << " s" << endl; #endif } void Chunker::traceDrivenChunkingFSL() { double chunkTime = 0; double hashTime = 0; long diff; double second; std::ifstream& fin = getChunkingFile(); uint64_t chunkIDCounter = 0; uint64_t fileSize = 0; u_char hash[CHUNK_HASH_SIZE]; char readLineBuffer[256]; string readLineStr; /*start chunking*/ getline(fin, readLineStr); while (true) { getline(fin, readLineStr); if (fin.eof()) { break; } memset(readLineBuffer, 0, 256); memcpy(readLineBuffer, (char*)readLineStr.c_str(), readLineStr.length()); #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker, NULL); #endif u_char chunkFp[7]; memset(chunkFp, 0, 7); char* item; item = strtok(readLineBuffer, ":\t\n "); for (int index = 0; item != NULL && index < 6; index++) { chunkFp[index] = strtol(item, NULL, 16); item = strtok(NULL, ":\t\n"); } chunkFp[6] = '\0'; auto size = atoi(item); int copySize = 0; memset(chunkBuffer, 0, sizeof(char) * maxChunkSize + 6); if (size > maxChunkSize) { continue; } while (copySize < size) { memcpy(chunkBuffer + copySize, chunkFp, 6); copySize += 6; } #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker, NULL); diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec; second = diff / 1000000.0; chunkTime += second; #endif #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker, NULL); #endif if (!cryptoObj->generateHash(chunkBuffer, size, hash)) { cerr << "Chunker : trace driven chunking: compute hash error" << endl; } #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker, NULL); diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec; second = diff / 1000000.0; hashTime += second; #endif Data_t tempChunk; tempChunk.chunk.ID = chunkIDCounter; tempChunk.chunk.logicDataSize = size; memcpy(tempChunk.chunk.logicData, chunkBuffer, size); memcpy(tempChunk.chunk.chunkHash, hash, CHUNK_HASH_SIZE); tempChunk.dataType = DATA_TYPE_CHUNK; insertMQToKeyClient(tempChunk); chunkIDCounter++; fileSize += size; } fileRecipe.recipe.fileRecipeHead.totalChunkNumber = chunkIDCounter; fileRecipe.recipe.keyRecipeHead.totalChunkKeyNumber = chunkIDCounter; fileRecipe.recipe.fileRecipeHead.fileSize = fileSize; fileRecipe.recipe.keyRecipeHead.fileSize = fileRecipe.recipe.fileRecipeHead.fileSize; fileRecipe.dataType = DATA_TYPE_RECIPE; insertMQToKeyClient(fileRecipe); if (setJobDoneFlag() == false) { cerr << "Chunker : set chunking done flag error" << endl; } cout << "Chunker : trace gen over:\nTotal file size = " << fileRecipe.recipe.fileRecipeHead.fileSize << "; Total chunk number = " << fileRecipe.recipe.fileRecipeHead.totalChunkNumber << endl; #if SYSTEM_BREAK_DOWN == 1 cout << "Chunker : total chunking time = " << chunkTime << " s" << endl; cout << "Chunker : total hashing time = " << hashTime << " s" << endl; #endif } void Chunker::traceDrivenChunkingUBC() { double chunkTime = 0; double hashTime = 0; long diff; double second; std::ifstream& fin = getChunkingFile(); uint64_t chunkIDCounter = 0; uint64_t fileSize = 0; u_char hash[CHUNK_HASH_SIZE]; char readLineBuffer[256]; string readLineStr; /*start chunking*/ getline(fin, readLineStr); while (true) { getline(fin, readLineStr); if (fin.eof()) { break; } memset(readLineBuffer, 0, 256); memcpy(readLineBuffer, (char*)readLineStr.c_str(), readLineStr.length()); #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker, NULL); #endif u_char chunkFp[6]; memset(chunkFp, 0, 6); char* item; item = strtok(readLineBuffer, ":\t\n "); for (int index = 0; item != NULL && index < 5; index++) { chunkFp[index] = strtol(item, NULL, 16); item = strtok(NULL, ":\t\n"); } chunkFp[5] = '\0'; auto size = atoi(item); int copySize = 0; memset(chunkBuffer, 0, sizeof(char) * maxChunkSize + 5); if (size > maxChunkSize) { continue; } while (copySize < size) { memcpy(chunkBuffer + copySize, chunkFp, 5); copySize += 5; } #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker, NULL); diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec; second = diff / 1000000.0; chunkTime += second; #endif #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker, NULL); #endif if (!cryptoObj->generateHash(chunkBuffer, size, hash)) { cerr << "Chunker : trace driven chunking: compute hash error" << endl; } #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker, NULL); diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec; second = diff / 1000000.0; hashTime += second; #endif Data_t tempChunk; tempChunk.chunk.ID = chunkIDCounter; tempChunk.chunk.logicDataSize = size; memcpy(tempChunk.chunk.logicData, chunkBuffer, size); memcpy(tempChunk.chunk.chunkHash, hash, CHUNK_HASH_SIZE); tempChunk.dataType = DATA_TYPE_CHUNK; insertMQToKeyClient(tempChunk); chunkIDCounter++; fileSize += size; } fileRecipe.recipe.fileRecipeHead.totalChunkNumber = chunkIDCounter; fileRecipe.recipe.keyRecipeHead.totalChunkKeyNumber = chunkIDCounter; fileRecipe.recipe.fileRecipeHead.fileSize = fileSize; fileRecipe.recipe.keyRecipeHead.fileSize = fileRecipe.recipe.fileRecipeHead.fileSize; fileRecipe.dataType = DATA_TYPE_RECIPE; insertMQToKeyClient(fileRecipe); if (setJobDoneFlag() == false) { cerr << "Chunker : set chunking done flag error" << endl; } cout << "Chunker : trace gen over:\nTotal file size = " << fileRecipe.recipe.fileRecipeHead.fileSize << "; Total chunk number = " << fileRecipe.recipe.fileRecipeHead.totalChunkNumber << endl; #if SYSTEM_BREAK_DOWN == 1 cout << "Chunker : total chunking time = " << chunkTime << " s" << endl; cout << "Chunker : total hashing time = " << hashTime << " s" << endl; #endif } void Chunker::varSizeChunking() { double insertTime = 0; double hashTime = 0; long diff; double second; uint16_t winFp; uint64_t chunkBufferCnt = 0, chunkIDCnt = 0; ifstream& fin = getChunkingFile(); uint64_t fileSize = 0; u_char hash[CHUNK_HASH_SIZE]; /*start chunking*/ #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker, NULL); #endif while (true) { memset((char*)waitingForChunkingBuffer, 0, sizeof(unsigned char) * ReadSize); fin.read((char*)waitingForChunkingBuffer, sizeof(unsigned char) * ReadSize); int len = fin.gcount(); fileSize += len; for (int i = 0; i < len; i++) { chunkBuffer[chunkBufferCnt] = waitingForChunkingBuffer[i]; /*full fill sliding window*/ if (chunkBufferCnt < slidingWinSize) { winFp = winFp + (chunkBuffer[chunkBufferCnt] * powerLUT[slidingWinSize - chunkBufferCnt - 1]) & polyMOD; //Refer to doc/Chunking.md hash function:RabinChunker chunkBufferCnt++; continue; } winFp &= (polyMOD); /*slide window*/ unsigned short int v = chunkBuffer[chunkBufferCnt - slidingWinSize]; //queue winFp = ((winFp + removeLUT[v]) * polyBase + chunkBuffer[chunkBufferCnt]) & polyMOD; //remove queue front and add queue tail chunkBufferCnt++; /*chunk's size less than minChunkSize*/ if (chunkBufferCnt < minChunkSize) continue; /*find chunk pattern*/ if ((winFp & anchorMask) == anchorValue) { #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker_VarSizeHash, NULL); #endif if (!cryptoObj->generateHash(chunkBuffer, chunkBufferCnt, hash)) { cerr << "Chunker : average size chunking compute hash error" << endl; return; } #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker_VarSizeHash, NULL); diff = 1000000 * (timeendChunker_VarSizeHash.tv_sec - timestartChunker_VarSizeHash.tv_sec) + timeendChunker_VarSizeHash.tv_usec - timestartChunker_VarSizeHash.tv_usec; second = diff / 1000000.0; hashTime += second; #endif Data_t tempChunk; tempChunk.chunk.ID = chunkIDCnt; tempChunk.chunk.logicDataSize = chunkBufferCnt; memcpy(tempChunk.chunk.logicData, chunkBuffer, chunkBufferCnt); memcpy(tempChunk.chunk.chunkHash, hash, CHUNK_HASH_SIZE); tempChunk.dataType = DATA_TYPE_CHUNK; #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker_VarSizeInsert, NULL); #endif if (!insertMQToKeyClient(tempChunk)) { cerr << "Chunker : error insert chunk to keyClient message queue for chunk ID = " << tempChunk.chunk.ID << endl; return; } #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker_VarSizeInsert, NULL); diff = 1000000 * (timeendChunker_VarSizeInsert.tv_sec - timestartChunker_VarSizeInsert.tv_sec) + timeendChunker_VarSizeInsert.tv_usec - timestartChunker_VarSizeInsert.tv_usec; second = diff / 1000000.0; insertTime += second; #endif chunkIDCnt++; chunkBufferCnt = winFp = 0; } /*chunk's size exceed maxChunkSize*/ if (chunkBufferCnt >= maxChunkSize) { #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker_VarSizeHash, NULL); #endif if (!cryptoObj->generateHash(chunkBuffer, chunkBufferCnt, hash)) { cerr << "Chunker : average size chunking compute hash error" << endl; return; } #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker_VarSizeHash, NULL); diff = 1000000 * (timeendChunker_VarSizeHash.tv_sec - timestartChunker_VarSizeHash.tv_sec) + timeendChunker_VarSizeHash.tv_usec - timestartChunker_VarSizeHash.tv_usec; second = diff / 1000000.0; hashTime += second; #endif Data_t tempChunk; tempChunk.chunk.ID = chunkIDCnt; tempChunk.chunk.logicDataSize = chunkBufferCnt; memcpy(tempChunk.chunk.logicData, chunkBuffer, chunkBufferCnt); memcpy(tempChunk.chunk.chunkHash, hash, CHUNK_HASH_SIZE); tempChunk.dataType = DATA_TYPE_CHUNK; #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker_VarSizeInsert, NULL); #endif if (!insertMQToKeyClient(tempChunk)) { cerr << "Chunker : error insert chunk to keyClient message queue for chunk ID = " << tempChunk.chunk.ID << endl; return; } #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker_VarSizeInsert, NULL); diff = 1000000 * (timeendChunker_VarSizeInsert.tv_sec - timestartChunker_VarSizeInsert.tv_sec) + timeendChunker_VarSizeInsert.tv_usec - timestartChunker_VarSizeInsert.tv_usec; second = diff / 1000000.0; insertTime += second; #endif chunkIDCnt++; chunkBufferCnt = winFp = 0; } } if (fin.eof()) { break; } } /*add final chunk*/ if (chunkBufferCnt != 0) { #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker_VarSizeHash, NULL); #endif if (!cryptoObj->generateHash(chunkBuffer, chunkBufferCnt, hash)) { cerr << "Chunker : average size chunking compute hash error" << endl; return; } #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker_VarSizeHash, NULL); diff = 1000000 * (timeendChunker_VarSizeHash.tv_sec - timestartChunker_VarSizeHash.tv_sec) + timeendChunker_VarSizeHash.tv_usec - timestartChunker_VarSizeHash.tv_usec; second = diff / 1000000.0; hashTime += second; #endif Data_t tempChunk; tempChunk.chunk.ID = chunkIDCnt; tempChunk.chunk.logicDataSize = chunkBufferCnt; memcpy(tempChunk.chunk.logicData, chunkBuffer, chunkBufferCnt); memcpy(tempChunk.chunk.chunkHash, hash, CHUNK_HASH_SIZE); tempChunk.dataType = DATA_TYPE_CHUNK; #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker_VarSizeInsert, NULL); #endif if (!insertMQToKeyClient(tempChunk)) { cerr << "Chunker : error insert chunk to keyClient message queue for chunk ID = " << tempChunk.chunk.ID << endl; return; } #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker_VarSizeInsert, NULL); diff = 1000000 * (timeendChunker_VarSizeInsert.tv_sec - timestartChunker_VarSizeInsert.tv_sec) + timeendChunker_VarSizeInsert.tv_usec - timestartChunker_VarSizeInsert.tv_usec; second = diff / 1000000.0; insertTime += second; #endif chunkIDCnt++; chunkBufferCnt = winFp = 0; } fileRecipe.recipe.fileRecipeHead.totalChunkNumber = chunkIDCnt; fileRecipe.recipe.keyRecipeHead.totalChunkKeyNumber = chunkIDCnt; fileRecipe.recipe.fileRecipeHead.fileSize = fileSize; fileRecipe.recipe.keyRecipeHead.fileSize = fileRecipe.recipe.fileRecipeHead.fileSize; fileRecipe.dataType = DATA_TYPE_RECIPE; if (!insertMQToKeyClient(fileRecipe)) { cerr << "Chunker : error insert recipe head to keyClient message queue" << endl; return; } if (setJobDoneFlag() == false) { cerr << "Chunker: set chunking done flag error" << endl; return; } cout << "Chunker : variable size chunking over:\nTotal file size = " << fileRecipe.recipe.fileRecipeHead.fileSize << "; Total chunk number = " << fileRecipe.recipe.fileRecipeHead.totalChunkNumber << endl; #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker, NULL); diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec; second = diff / 1000000.0; cout << "Chunker : total chunking time = " << setbase(10) << second - (insertTime + hashTime) << " s" << endl; cout << "Chunker : total hashing time = " << hashTime << " s" << endl; #endif return; } bool Chunker::insertMQToKeyClient(Data_t& newData) { return keyClientObj->insertMQFromChunker(newData); } bool Chunker::setJobDoneFlag() { return keyClientObj->editJobDoneFlag(); } uint32_t Chunker::cutPoint(const uint8_t* src, const uint32_t len) { uint32_t n; uint32_t fp = 0; uint32_t i; i = std::min(len, static_cast<uint32_t>(minChunkSize)); n = std::min(normalSize_, len); for (; i < n; i++) { fp = (fp >> 1) + GEAR[src[i]]; if (!(fp & maskS_)) { return (i + 1); } } n = std::min(static_cast<uint32_t>(maxChunkSize), len); for (; i < n; i++) { fp = (fp >> 1) + GEAR[src[i]]; if (!(fp & maskL_)) { return (i + 1); } } return i; } void Chunker::fastCDC() { double insertTime = 0; double hashTime = 0; long diff; double second; size_t pos = 0; ifstream& fin = getChunkingFile(); uint64_t fileSize = 0; uint64_t chunkIDCnt = 0; size_t totalOffset = 0; bool end = false; /*start chunking*/ #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker, NULL); #endif while (!end) { memset((char*)waitingForChunkingBuffer, 0, sizeof(uint8_t) * ReadSize); fin.read((char*)waitingForChunkingBuffer, sizeof(uint8_t) * ReadSize); end = fin.eof(); size_t len = fin.gcount(); fprintf(stderr, "Chunker: len: %lu\n", len); size_t localOffset = 0; while (((len - localOffset) >= maxChunkSize) || (end && (localOffset < len))) { uint32_t cp = cutPoint(waitingForChunkingBuffer + localOffset, len - localOffset); Data_t tempChunk; tempChunk.chunk.ID = chunkIDCnt; tempChunk.chunk.logicDataSize = cp; memcpy(tempChunk.chunk.logicData, waitingForChunkingBuffer + localOffset, cp); tempChunk.dataType = DATA_TYPE_CHUNK; #if SYSTEM_BREAK_DOWN==1 gettimeofday(&timestartChunker_VarSizeHash, NULL); #endif if (!cryptoObj->generateHash(tempChunk.chunk.logicData, tempChunk.chunk.logicDataSize, tempChunk.chunk.chunkHash)) { cerr << "Chunker : average size chunking compute hash error" << endl; return; } #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker_VarSizeHash, NULL); diff = 1000000 * (timeendChunker_VarSizeHash.tv_sec - timestartChunker_VarSizeHash.tv_sec) + timeendChunker_VarSizeHash.tv_usec - timestartChunker_VarSizeHash.tv_usec; second = diff / 1000000.0; hashTime += second; #endif #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timestartChunker_VarSizeInsert, NULL); #endif if (!insertMQToKeyClient(tempChunk)) { fprintf(stderr, "Chunker, error insert chunk to FPWorker MQ for chunkID: %u.\n", tempChunk.chunk.ID); } #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker_VarSizeInsert, NULL); diff = 1000000 * (timeendChunker_VarSizeInsert.tv_sec - timestartChunker_VarSizeInsert.tv_sec) + timeendChunker_VarSizeInsert.tv_usec - timestartChunker_VarSizeInsert.tv_usec; second = diff / 1000000.0; insertTime += second; #endif localOffset += cp; fileSize += cp; chunkIDCnt++; } pos += localOffset; totalOffset += localOffset; fin.seekg(totalOffset, std::ios_base::beg); } fileRecipe.recipe.fileRecipeHead.totalChunkNumber = chunkIDCnt; fileRecipe.recipe.keyRecipeHead.totalChunkKeyNumber = chunkIDCnt; fileRecipe.recipe.fileRecipeHead.fileSize = fileSize; fileRecipe.recipe.keyRecipeHead.fileSize = fileSize; fileRecipe.dataType = DATA_TYPE_RECIPE; if (!insertMQToKeyClient(fileRecipe)) { cerr << "Chunker : error insert recipe head to keyClient message queue" << endl; return; } if (setJobDoneFlag() == false) { cerr << "Chunker: set chunking done flag error" << endl; return; } cout << "Chunker : variable size chunking over:\nTotal file size = " << fileRecipe.recipe.fileRecipeHead.fileSize << "; Total chunk number = " << fileRecipe.recipe.fileRecipeHead.totalChunkNumber << endl; #if SYSTEM_BREAK_DOWN == 1 gettimeofday(&timeendChunker, NULL); diff = 1000000 * (timeendChunker.tv_sec - timestartChunker.tv_sec) + timeendChunker.tv_usec - timestartChunker.tv_usec; second = diff / 1000000.0; cout << "Chunker : total chunking time = " << setbase(10) << second - (insertTime + hashTime) << " s" << endl; cout << "Chunker : total hashing time = " << hashTime << " s" << endl; #endif return ; } uint32_t Chunker::calNormalSize(const uint32_t min, const uint32_t av, const uint32_t max) { uint32_t off = min + DivCeil(min, 2); if (off > av) { off = av; } uint32_t diff = av - off; if (diff > max) { return max; } return diff; } uint32_t Chunker::generateFastCDCMask(uint32_t bits) { uint32_t tmp; tmp = (1 << CompareLimit(bits, 1, 31)) - 1; return tmp; }
35,998
12,280
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include "base-precomp.h" // Precompiled headers #include <mrpt/utils/CMHPropertiesValuesList.h> #include <mrpt/system/os.h> #include <stdio.h> using namespace mrpt::utils; using namespace mrpt::system; // This must be added to any CSerializable class implementation file. IMPLEMENTS_SERIALIZABLE(CMHPropertiesValuesList, CSerializable, mrpt::utils) /*--------------------------------------------------------------- writeToStream ---------------------------------------------------------------*/ void CMHPropertiesValuesList::writeToStream( mrpt::utils::CStream& out, int* out_Version) const { if (out_Version) *out_Version = 0; else { uint32_t i, n = (uint32_t)m_properties.size(); uint8_t isNull; out << n; for (i = 0; i < n; i++) { // Name: out << m_properties[i].name.c_str(); // Object: isNull = !m_properties[i].value; out << isNull; if (!isNull) out << *m_properties[i].value; // Hypot. ID: out << m_properties[i].ID; } } } /*--------------------------------------------------------------- readFromStream ---------------------------------------------------------------*/ void CMHPropertiesValuesList::readFromStream( mrpt::utils::CStream& in, int version) { switch (version) { case 0: { uint32_t i, n; uint8_t isNull; // Erase previous contents: clear(); in >> n; m_properties.resize(n); for (i = 0; i < n; i++) { char nameBuf[1024]; // Name: in >> nameBuf; m_properties[i].name = nameBuf; // Object: in >> isNull; if (isNull) m_properties[i].value.reset(); else in >> m_properties[i].value; // Hypot. ID: in >> m_properties[i].ID; } } break; default: MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version) }; } /*--------------------------------------------------------------- Constructor ---------------------------------------------------------------*/ CMHPropertiesValuesList::CMHPropertiesValuesList() {} /*--------------------------------------------------------------- Destructor ---------------------------------------------------------------*/ CMHPropertiesValuesList::~CMHPropertiesValuesList() { clear(); } /*--------------------------------------------------------------- clear ---------------------------------------------------------------*/ void CMHPropertiesValuesList::clear() { MRPT_START m_properties.clear(); MRPT_END } /*--------------------------------------------------------------- get ---------------------------------------------------------------*/ CSerializable::Ptr CMHPropertiesValuesList::get( const char* propertyName, const int64_t& hypothesis_ID) const { std::vector<TPropertyValueIDTriplet>::const_iterator it; for (it = m_properties.begin(); it != m_properties.end(); ++it) if (!os::_strcmpi(propertyName, it->name.c_str()) && it->ID == hypothesis_ID) return it->value; for (it = m_properties.begin(); it != m_properties.end(); ++it) if (!os::_strcmpi(propertyName, it->name.c_str()) && it->ID == 0) return it->value; // Not found: return CSerializable::Ptr(); } /*--------------------------------------------------------------- getAnyHypothesis ---------------------------------------------------------------*/ CSerializable::Ptr CMHPropertiesValuesList::getAnyHypothesis( const char* propertyName) const { for (std::vector<TPropertyValueIDTriplet>::const_iterator it = m_properties.begin(); it != m_properties.end(); ++it) { if (!os::_strcmpi(propertyName, it->name.c_str())) return it->value; } // Not found: return CSerializable::Ptr(); } /*--------------------------------------------------------------- set ---------------------------------------------------------------*/ void CMHPropertiesValuesList::set( const char* propertyName, const CSerializable::Ptr& obj, const int64_t& hypothesis_ID) { MRPT_START for (std::vector<TPropertyValueIDTriplet>::iterator it = m_properties.begin(); it != m_properties.end(); ++it) { if (it->ID == hypothesis_ID && !os::_strcmpi(propertyName, it->name.c_str())) { // Delete current contents: // Copy new value: it->value.reset(dynamic_cast<CSerializable*>(obj->clone())); // if (!obj) it->value.clear(); // else it->value = obj; //->clone(); return; } } // Insert: TPropertyValueIDTriplet newPair; newPair.name = std::string(propertyName); newPair.value = obj; newPair.ID = hypothesis_ID; m_properties.push_back(newPair); MRPT_END_WITH_CLEAN_UP( printf("Exception while setting annotation '%s'", propertyName);); } /*--------------------------------------------------------------- setMemoryReference ---------------------------------------------------------------*/ void CMHPropertiesValuesList::setMemoryReference( const char* propertyName, const CSerializable::Ptr& obj, const int64_t& hypothesis_ID) { MRPT_START for (std::vector<TPropertyValueIDTriplet>::iterator it = m_properties.begin(); it != m_properties.end(); ++it) { if (it->ID == hypothesis_ID && !os::_strcmpi(propertyName, it->name.c_str())) { // Delete current contents & set a copy of the same smart pointer: it->value = obj; return; } } // Insert: TPropertyValueIDTriplet newPair; newPair.name = std::string(propertyName); newPair.value = obj; newPair.ID = hypothesis_ID; m_properties.push_back(newPair); MRPT_END_WITH_CLEAN_UP( printf("Exception while setting annotation '%s'", propertyName);); } /*--------------------------------------------------------------- getPropertyNames ---------------------------------------------------------------*/ std::vector<std::string> CMHPropertiesValuesList::getPropertyNames() const { std::vector<std::string> ret; for (std::vector<TPropertyValueIDTriplet>::const_iterator it = m_properties.begin(); it != m_properties.end(); ++it) { bool isNew = true; for (std::vector<std::string>::iterator itS = ret.begin(); itS != ret.end(); ++itS) { if ((*itS) == it->name) { isNew = false; break; } } if (isNew) ret.push_back(it->name); // Yes, it is new: } return ret; } /*--------------------------------------------------------------- remove ---------------------------------------------------------------*/ void CMHPropertiesValuesList::remove( const char* propertyName, const int64_t& hypothesis_ID) { for (std::vector<TPropertyValueIDTriplet>::iterator it = m_properties.begin(); it != m_properties.end();) if (!os::_strcmpi(propertyName, it->name.c_str()) && it->ID == hypothesis_ID) it = m_properties.erase(it); else ++it; } /*--------------------------------------------------------------- removeAll ---------------------------------------------------------------*/ void CMHPropertiesValuesList::removeAll(const int64_t& hypothesis_ID) { for (std::vector<TPropertyValueIDTriplet>::iterator it = m_properties.begin(); it != m_properties.end();) if (it->ID == hypothesis_ID) it = m_properties.erase(it); else ++it; } /*--------------------------------------------------------------- Copy ---------------------------------------------------------------*/ CMHPropertiesValuesList::CMHPropertiesValuesList( const CMHPropertiesValuesList& o) : m_properties(o.m_properties) { for (std::vector<TPropertyValueIDTriplet>::iterator it = m_properties.begin(); it != m_properties.end(); ++it) it->value.reset(dynamic_cast<CSerializable*>(it->value->clone())); } /*--------------------------------------------------------------- Copy ---------------------------------------------------------------*/ CMHPropertiesValuesList& CMHPropertiesValuesList::operator=( const CMHPropertiesValuesList& o) { if (this == &o) return *this; m_properties = o.m_properties; for (std::vector<TPropertyValueIDTriplet>::iterator it = m_properties.begin(); it != m_properties.end(); ++it) it->value.reset(dynamic_cast<CSerializable*>(it->value->clone())); return *this; }
8,664
2,892
#pragma once #include "routing_common/maxspeed_conversion.hpp" #include "platform/measurement_utils.hpp" #include "base/geo_object_id.hpp" #include <cstdint> #include <map> #include <string> #include <vector> namespace routing { using OsmIdToMaxspeed = std::map<base::GeoObjectId, Maxspeed>; /// \brief Parses csv file with path |maxspeedsFilename| and stores the result in |osmIdToMaxspeed|. /// \note There's a detailed description of the csv file in generator/maxspeed_collector.hpp. bool ParseMaxspeeds(std::string const & maxspeedsFilename, OsmIdToMaxspeed & osmIdToMaxspeed); /// \brief Writes |speeds| to maxspeeds section to mwm with |dataPath|. void SerializeMaxspeeds(std::string const & dataPath, std::vector<FeatureMaxspeed> && speeds); void BuildMaxspeedsSection(std::string const & dataPath, std::map<uint32_t, base::GeoObjectId> const & featureIdToOsmId, std::string const & maxspeedsFilename); /// \brief Builds maxspeeds section in mwm with |dataPath|. This section contains max speed limits /// if they are available in file |maxspeedsFilename|. /// \param maxspeedsFilename file name to csv file with maxspeed tag values. /// \note To start building the section, the following steps should be done: /// 1. Calls GenerateIntermediateData(). It stores data about maxspeed tags value of road features // to a csv file. /// 2. Calls GenerateFeatures() /// 3. Generates geometry. void BuildMaxspeedsSection(std::string const & dataPath, std::string const & osmToFeaturePath, std::string const & maxspeedsFilename); } // namespace routing
1,647
495
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "AdHocConnectionImpl.hpp" #include "Utils.hpp" #include "ThreadUtils.hpp" #include "../serial_com/Port.h" #include "../serial_com/SerialPort.hpp" #include "../serial_com/UdpClientPort.hpp" #include "../serial_com/TcpClientPort.hpp" using namespace mavlink_utils; using namespace mavlinkcom_impl; AdHocConnectionImpl::AdHocConnectionImpl() { closed = true; ::memset(&mavlink_intermediate_status_, 0, sizeof(mavlink_status_t)); ::memset(&mavlink_status_, 0, sizeof(mavlink_status_t)); } std::string AdHocConnectionImpl::getName() { return name; } AdHocConnectionImpl::~AdHocConnectionImpl() { con_.reset(); close(); } std::shared_ptr<AdHocConnection> AdHocConnectionImpl::createConnection(const std::string& nodeName, std::shared_ptr<Port> port) { // std::shared_ptr<MavLinkCom> owner, const std::string& nodeName std::shared_ptr<AdHocConnection> con = std::make_shared<AdHocConnection>(); con->startListening(nodeName, port); return con; } std::shared_ptr<AdHocConnection> AdHocConnectionImpl::connectLocalUdp(const std::string& nodeName, std::string localAddr, int localPort) { std::shared_ptr<UdpClientPort> socket = std::make_shared<UdpClientPort>(); socket->connect(localAddr, localPort, "", 0); return createConnection(nodeName, socket); } std::shared_ptr<AdHocConnection> AdHocConnectionImpl::connectRemoteUdp(const std::string& nodeName, std::string localAddr, std::string remoteAddr, int remotePort) { std::string local = localAddr; // just a little sanity check on the local address, if remoteAddr is localhost then localAddr must be also. if (remoteAddr == "127.0.0.1") { local = "127.0.0.1"; } std::shared_ptr<UdpClientPort> socket = std::make_shared<UdpClientPort>(); socket->connect(local, 0, remoteAddr, remotePort); return createConnection(nodeName, socket); } std::shared_ptr<AdHocConnection> AdHocConnectionImpl::connectTcp(const std::string& nodeName, std::string localAddr, const std::string& remoteIpAddr, int remotePort) { std::string local = localAddr; // just a little sanity check on the local address, if remoteAddr is localhost then localAddr must be also. if (remoteIpAddr == "127.0.0.1") { local = "127.0.0.1"; } std::shared_ptr<TcpClientPort> socket = std::make_shared<TcpClientPort>(); socket->connect(local, 0, remoteIpAddr, remotePort); return createConnection(nodeName, socket); } std::shared_ptr<AdHocConnection> AdHocConnectionImpl::connectSerial(const std::string& nodeName, std::string name, int baudRate, const std::string initString) { std::shared_ptr<SerialPort> serial = std::make_shared<SerialPort>(); int hr = serial->connect(name.c_str(), baudRate); if (hr != 0) throw std::runtime_error(Utils::stringf("Could not open the serial port %s, error=%d", name.c_str(), hr)); // send this right away just in case serial link is not already configured if (initString.size() > 0) { serial->write(reinterpret_cast<const uint8_t*>(initString.c_str()), static_cast<int>(initString.size())); } return createConnection(nodeName, serial); } void AdHocConnectionImpl::startListening(std::shared_ptr<AdHocConnection> parent, const std::string& nodeName, std::shared_ptr<Port> connectedPort) { name = nodeName; con_ = parent; close(); closed = false; port = connectedPort; Utils::cleanupThread(read_thread); read_thread = std::thread{ &AdHocConnectionImpl::readPackets, this }; Utils::cleanupThread(publish_thread_); publish_thread_ = std::thread{ &AdHocConnectionImpl::publishPackets, this }; } void AdHocConnectionImpl::close() { closed = true; if (port != nullptr) { port->close(); port = nullptr; } if (read_thread.joinable()) { read_thread.join(); } if (publish_thread_.joinable()) { msg_available_.post(); publish_thread_.join(); } } bool AdHocConnectionImpl::isOpen() { return !closed; } int AdHocConnectionImpl::getTargetComponentId() { return this->other_component_id; } int AdHocConnectionImpl::getTargetSystemId() { return this->other_system_id; } void AdHocConnectionImpl::sendMessage(const std::vector<uint8_t>& msg) { if (closed) { return; } try { port->write(msg.data(), static_cast<int>(msg.size())); } catch (std::exception& e) { throw std::runtime_error(Utils::stringf("AdHocConnectionImpl: Error sending message on connection '%s', details: %s", name.c_str(), e.what())); } } int AdHocConnectionImpl::subscribe(AdHocMessageHandler handler) { MessageHandlerEntry entry = { static_cast<int>(listeners.size() + 1), handler = handler }; std::lock_guard<std::mutex> guard(listener_mutex); listeners.push_back(entry); snapshot_stale = true; return entry.id; } void AdHocConnectionImpl::unsubscribe(int id) { std::lock_guard<std::mutex> guard(listener_mutex); for (auto ptr = listeners.begin(), end = listeners.end(); ptr != end; ptr++) { if ((*ptr).id == id) { listeners.erase(ptr); snapshot_stale = true; break; } } } void AdHocConnectionImpl::readPackets() { //CurrentThread::setMaximumPriority(); std::shared_ptr<Port> safePort = this->port; const int MAXBUFFER = 512; uint8_t* buffer = new uint8_t[MAXBUFFER]; int channel = 0; int hr = 0; while (hr == 0 && con_ != nullptr && !closed) { int read = 0; if (safePort->isClosed()) { // hmmm, wait till it is opened? std::this_thread::sleep_for(std::chrono::milliseconds(10)); continue; } int count = safePort->read(buffer, MAXBUFFER); if (count <= 0) { // error? well let's try again, but we should be careful not to spin too fast and kill the CPU std::this_thread::sleep_for(std::chrono::milliseconds(1)); continue; } if (count >= MAXBUFFER) { std::cerr << "GAH KM911 message size (" << std::to_string(count) << ") is bigger than max buffer size! Time to support frame breaks, Moffitt" << std::endl; // error? well let's try again, but we should be careful not to spin too fast and kill the CPU std::this_thread::sleep_for(std::chrono::milliseconds(1)); continue; } // queue event for publishing. { std::lock_guard<std::mutex> guard(msg_queue_mutex_); std::vector<uint8_t> message(count); memcpy(message.data(), buffer, count); msg_queue_.push(message); } if (waiting_for_msg_) { msg_available_.post(); } } //while delete[] buffer; } //readPackets void AdHocConnectionImpl::drainQueue() { std::vector<uint8_t> message; bool hasMsg = true; while (hasMsg) { hasMsg = false; { std::lock_guard<std::mutex> guard(msg_queue_mutex_); if (!msg_queue_.empty()) { message = msg_queue_.front(); msg_queue_.pop(); hasMsg = true; } } if (!hasMsg) { return; } // publish the message from this thread, this is safer than publishing from the readPackets thread // as it ensures we don't lose messages if the listener is slow. if (snapshot_stale) { // this is tricky, the clear has to be done outside the lock because it is destructing the handlers // and the handler might try and call unsubscribe, which needs to be able to grab the lock, otherwise // we would get a deadlock. snapshot.clear(); std::lock_guard<std::mutex> guard(listener_mutex); snapshot = listeners; snapshot_stale = false; } auto end = snapshot.end(); auto startTime = std::chrono::system_clock::now(); std::shared_ptr<AdHocConnection> sharedPtr = std::shared_ptr<AdHocConnection>(this->con_); for (auto ptr = snapshot.begin(); ptr != end; ptr++) { try { (*ptr).handler(sharedPtr, message); } catch (std::exception& e) { Utils::log(Utils::stringf("AdHocConnectionImpl: Error handling message on connection '%s', details: %s", name.c_str(), e.what()), Utils::kLogLevelError); } } } } void AdHocConnectionImpl::publishPackets() { //CurrentThread::setMaximumPriority(); while (!closed) { drainQueue(); waiting_for_msg_ = true; msg_available_.wait(); waiting_for_msg_ = false; } }
9,199
2,877
#pragma once #include <chrono> #include <functional> namespace FastTransport::Protocol { class PeriodicExecutor { public: PeriodicExecutor(std::function<void()>, const std::chrono::microseconds& interval); void Run(); private: using clock = std::chrono::steady_clock; std::function<void()> _function; std::chrono::microseconds _interval; std::chrono::microseconds _start; clock::time_point _end; void RunFunction(); }; } // namespace FastTransport::Protocol
521
167
// Copyright (c) 2018, ETH Zurich // 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. Neither the name of the copyright holder 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 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. // // Code Author: Niklaus Bamert (bamertn@ethz.ch) #ifndef __NDB_BUFFER #define __NDB_BUFFER #include <vector> #include <png.h> #include <Eigen/Dense> #include <type_traits> using namespace std; namespace ndb { struct RGBColor { uint8_t b, g, r; RGBColor(uint8_t r, uint8_t g, uint8_t b) : r(r), g(g), b(b) {} RGBColor(png_byte* ptr) { this->r = ptr[0]; this->g = ptr[1]; this->b = ptr[2]; } RGBColor() {}; }; struct Point { int x, y; Point(int x, int y) : x(x), y(y) {} Point() {}; }; struct Descriptor { Point point; uint64_t state; bool srcDescr = false; //indicates if this is a descriptor from the source or from the target set Descriptor(ndb::Point point, uint64_t state) : point(point), state(state) {} Descriptor() {}; //ops for sorting and comparing descriptors for matching bool operator==( const Descriptor &d ) const { if (state == d.state ) return true; return false; } //Checks if two descriptors are from different images bool diffImgs(const Descriptor &d) { if (srcDescr != d.srcDescr) return true; return false; } bool operator!=( const Descriptor &d ) const { if (state != d.state) return true; return false; } bool operator<( const Descriptor &d ) const { return state < d.state; } bool operator<=( const Descriptor &d ) const { return state <= d.state; } int operator%( const int &d ) const { return state % d; } }; //Keeps support points with associated disparity //Support points are only used in the left image struct Support { int x, y; float d; Support(int x, int y, float d) : x(x), y(y), d(d) {} Support(int x, int y) : x(x), y(y), d(0.) {} Support() {}; }; // Keeps correspondences in case of non-epipolar matching scenario struct Correspondence{ Point srcPt, tarPt; Correspondence(Point srcPt, Point tarPt) : srcPt(srcPt), tarPt(tarPt) {} }; //The Cg matrix elements used in Disparity Refinement struct ConfidentSupport { int x, y, cost; float d; ConfidentSupport() {}; ConfidentSupport(int x, int y, float d, int cost ) : x(x), y(y), d(d), cost(cost) {} }; struct InvalidMatch { int x, y, cost; InvalidMatch() { cost = 0;}; InvalidMatch(int x, int y, int cost) : x(x), y(y), cost(cost) {} }; struct Triangle { int v1, v2, v3; Triangle(int v1, int v2, int v3) : v1(v1), v2(v2), v3(v3) {} }; struct Edge { Support a, b; Edge(Support& a, Support& b) { if (a.y < b.y) { this->a = a; this->b = b; } else { this->a = b; this->b = a; } } }; struct Span { int x1, x2; Span(int x1, int x2) : x1(x1), x2(x2) {} }; struct Dimension { int w, h; Dimension(int w, int h): w(w), h(h) {} }; #define ALIGN16(X) (X%16) == 0 ? X :((X/16)+1)*16 template<class T> class __attribute__((aligned(32), packed)) Buffer : public Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> { //The actual height and width of the image. public: int width; int height; EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Base; Buffer(const int r, const int c) : Base(r, ALIGN16(c)) { this->width = c; this->height = r; } Buffer(const int r, const int c, T color) : Base(r, ALIGN16(c)) { this->width = c; this->height = r; T *ptr = reinterpret_cast<T *>(Base::data()); for (int i = 0; i < Base::cols()*Base::rows(); i++) { *ptr = color; ptr++; } } //Create new buffer from two side by side Buffer(Buffer& i1, Buffer& i2) : Base(i1.rows(), i1.cols() + i2.cols()) { for (int x = 0; x < i1.cols(); x++) { for (int y = 0; y < i1.rows(); y++) { setPixel(x, y, i1.getPixel(x, y)); setPixel(x + i1.cols(), y, i2.getPixel(x, y)); } } this->height = Base::rows(); this->width = Base::cols(); } Buffer(const Eigen::Vector2i &size = Eigen::Vector2i(0, 0)) : Base(size.y(), ALIGN16(size.x())) { this->width = size.x(); this->height = size.y(); } Buffer(const Eigen::Vector2i &size , T color) : Base(size.y(), ALIGN16(size.x())) { this->width = size.x(); this->height = size.y(); T *ptr = reinterpret_cast<T *>(Base::data()); for (int i = 0; i < Base::cols()*Base::rows(); i++) { *ptr = color; ptr++; } } // original sources provided by Guillaume Cottenceau under the X11 license // from http://zarb.org/~gc/html/libpng.html int readPNG(std::string filename) { unsigned char header[8]; // 8 is the maximum size that can be checked png_byte colorType; png_byte bitDepth; png_structp pngPtr; png_infop infoPtr; png_bytep * rowPointers; // open file and test for it being a png FILE *fp = fopen(filename.c_str(), "rb"); if (!fp) { cout << "ERR: File" << filename << " could not be opened for reading" << endl; return 1; } size_t res = fread(header, 1, 8, fp); if (png_sig_cmp(header, 0, 8)) { cout << "ERR: File" << filename << " is not recognized as a PNG file" << endl; return 1; } // initialize stuff pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!pngPtr) { cout << "ERR: png_create_read_struct failed" << endl; return 1; } infoPtr = png_create_info_struct(pngPtr); if (!infoPtr) { cout << "ERR: png_create_info_struct failed" << endl; return 1; } if (setjmp(png_jmpbuf(pngPtr))) { cout << "ERR: Error during init_io" << endl; return 1; } png_init_io(pngPtr, fp); png_set_sig_bytes(pngPtr, 8); png_read_info(pngPtr, infoPtr); this->width = png_get_image_width(pngPtr, infoPtr); this->height = png_get_image_height(pngPtr, infoPtr); colorType = png_get_color_type(pngPtr, infoPtr); bitDepth = png_get_bit_depth(pngPtr, infoPtr); //We will do a conservative resize after reading in the data, //such that we don't have to translate addresses ourselves Base::resize(this->height, this->width); int numberOfPasses = png_set_interlace_handling(pngPtr); png_read_update_info(pngPtr, infoPtr); // read file if (setjmp(png_jmpbuf(pngPtr))) { cout << "ERR: Error during read_image" << endl; return 1; } rowPointers = (png_bytep*) malloc(sizeof(png_bytep) * height); for (int y = 0; y < height; y++) rowPointers[y] = (png_byte*) malloc(png_get_rowbytes(pngPtr, infoPtr)); png_read_image(pngPtr, rowPointers); fclose(fp); //Read image into buffer (row-major) int nChannels; switch (png_get_color_type(pngPtr, infoPtr)) { case PNG_COLOR_TYPE_GRAY: nChannels = 1; break; case PNG_COLOR_TYPE_RGB: nChannels = 3; break; case PNG_COLOR_TYPE_RGBA: nChannels = 4; break; default: nChannels = 0; break; } T *ptr = reinterpret_cast<T *>(Base::data()); if (bitDepth == 16) { for (int y = 0; y < this->height; y++) { png_byte* row = rowPointers[y]; for (int x = 0; x < this->width; x++) { int val = ((int)row[x * 2] << 8) + row[x * 2 + 1]; *ptr = val; ptr++; } } } else { for (int y = 0; y < this->height; y++) { png_byte* row = rowPointers[y]; for (int x = 0; x < this->width; x++) { int offset = y * this->width + x; if ( nChannels == 1 ) { *ptr = row[x]; ptr++; } else if (nChannels == 3) { //convert to grayscale if color *ptr = (row[3 * x] + row[3 * x + 1] + row[3 * x + 2]) / 3; ptr++; } } } } //Conservative resize of underlying matrix to align with 16 byte boundary Base::conservativeResize(this->height, ALIGN16(this->width)); if (nChannels == 0 || nChannels == 4) { cout << "ERR: found something other than gray or 3 channel color image(" << int(png_get_color_type(pngPtr, infoPtr)) << ") aborting!" << endl; return 1; } for (int y = 0; y < this->height; y++) free(rowPointers[y]); free(rowPointers); return 0; } void writePNG(std::string filename) { png_byte colorType = PNG_COLOR_TYPE_GRAY; int nChannels = 1; png_byte bitDepth = 8; png_structp pngPtr; png_infop infoPtr; png_bytep * rowPointers; //Copy Image matrix such that we can do a conservative resize to its correct size Base img = *this; img.conservativeResize(this->height, this->width); FILE *fp = fopen(filename.c_str(), "wb"); if (!fp) cout << "ERR: File" << filename << " could not be opened for writing" << endl; // init pngPtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!pngPtr) cout << "ERR: png_create_write_struct failed" << endl; infoPtr = png_create_info_struct(pngPtr); if (!infoPtr) cout << "ERR: png_create_info_struct failed" << endl; if (setjmp(png_jmpbuf(pngPtr))) cout << "ERR: Error during init_io" << endl; png_init_io(pngPtr, fp); // write header if (setjmp(png_jmpbuf(pngPtr))) cout << "ERR: Error during writing header" << endl; png_set_IHDR(pngPtr, infoPtr, img.cols(), img.rows(), bitDepth, colorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(pngPtr, infoPtr); // write bytes if (setjmp(png_jmpbuf(pngPtr))) cout << "ERR: Error during writing bytes" << endl; //Allocate row pointers rowPointers = (png_bytep*) malloc(sizeof(png_bytep) * img.rows()); for (int y = 0; y < img.rows(); y++) rowPointers[y] = (png_byte*) malloc(png_get_rowbytes(pngPtr, infoPtr)); T *ptr = reinterpret_cast<T *>(img.data()); //Copy our data from std::vector into allocated memory region for (int y = 0; y < img.rows(); y++) { png_byte* row = rowPointers[y]; for (int x = 0; x < img.cols(); x++) { int offset; offset = y * img.cols() + x; row[x * nChannels] = ptr[offset]; } } png_write_image(pngPtr, rowPointers); // end write if (setjmp(png_jmpbuf(pngPtr))) cout << "ERR: Error during end of write" << endl; png_write_end(pngPtr, NULL); for (int y = 0; y < img.rows(); y++) free(rowPointers[y]); free(rowPointers); fclose(fp); } void writePNGRGB(std::string filename) { png_byte colorType = PNG_COLOR_TYPE_RGB; int nChannels = 3; png_byte bitDepth = 8; png_structp pngPtr; png_infop infoPtr; png_bytep * rowPointers; //Make copy of self that we can resize to actual size Base img = *this; img.conservativeResize(this->height, this->width); // create file FILE *fp = fopen(filename.c_str(), "wb"); if (!fp) cout << "ERR: File" << filename << " could not be opened for writing" << endl; // initialize stuff pngPtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!pngPtr) cout << "ERR: png_create_write_struct failed" << endl; infoPtr = png_create_info_struct(pngPtr); if (!infoPtr) cout << "ERR: png_create_info_struct failed" << endl; if (setjmp(png_jmpbuf(pngPtr))) cout << "ERR: Error during init_io" << endl; png_init_io(pngPtr, fp); // write header if (setjmp(png_jmpbuf(pngPtr))) cout << "ERR: Error during writing header" << endl; png_set_IHDR(pngPtr, infoPtr, img.cols(), img.rows(), bitDepth, colorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(pngPtr, infoPtr); // write bytes if (setjmp(png_jmpbuf(pngPtr))) cout << "ERR: Error during writing bytes" << endl; // Allocate row pointers rowPointers = (png_bytep*) malloc(sizeof(png_bytep) * img.rows()); for (int y = 0; y < img.rows(); y++) rowPointers[y] = (png_byte*) malloc(png_get_rowbytes(pngPtr, infoPtr)); T *ptr = reinterpret_cast<T *>(img.data()); //Copy our data from std::vector into allocated memory region for (int y = 0; y < img.rows(); y++) { png_byte* row = rowPointers[y]; for (int x = 0; x < img.cols(); x++) { int offset; offset = y * img.cols() + x; row[x * nChannels] = ptr[offset].r; row[x * nChannels + 1] = ptr[offset].g; row[x * nChannels + 2] = ptr[offset].b; } } png_write_image(pngPtr, rowPointers); // end write if (setjmp(png_jmpbuf(pngPtr))) cout << "ERR: Error during end of write" << endl; png_write_end(pngPtr, NULL); // cleanup heap allocation for (int y = 0; y < img.rows(); y++) free(rowPointers[y]); free(rowPointers); fclose(fp); } /** * @brief "Unsafe" but fast pixel set method (no dimension check. If you write * outside the bounds, it'll segfault!) * * @param[in] x { parameter_description } * @param[in] y { parameter_description } */ void setPixel(int x, int y, T color) { T *ptr = reinterpret_cast<T *>(Base::data()); *(ptr + Base::cols()*y + x) = color; } /** * @brief Set all values in matrix to same value * * @param[in] color The color */ void set(T color) { T *ptr = reinterpret_cast<T *>(Base::data()); int size = Base::cols() * Base::rows(); for (int i = 0; i < size; i++) { *ptr = color; ptr++; } } /** * @brief Gets the pixel. * * @param[in] x { parameter_description } * @param[in] y { parameter_description } * * @return The pixel. */ T getPixel(int x, int y) { T *ptr = reinterpret_cast<T *>(Base::data()); return *(ptr + Base::cols() * y + x); } /** * @brief Gets the pixel. Const method overload for calls from GPC. * * @param[in] x { parameter_description } * @param[in] y { parameter_description } * * @return The pixel. */ T getPixel(int x, int y) const { T *ptr = const_cast<T *>(Base::data()); return *(ptr + Base::cols() * y + x); } /** * @brief Gets a patch from the buffer * * @param[in] x { parameter_description } * @param[in] y { parameter_description } * @param[in] size The size * * @return The patch. */ void getPatch(ndb::Buffer<uint8_t>& patch, int x, int y, int size) { patch.resize(size, size); //extract patch for (int ix = 0; ix < size; ix++) { for (int iy = 0; iy < size; iy++) { patch(ix, iy) = getPixel(x + ix - (size / 2), y + iy - (size / 2)); } } } Dimension getDimension() { return Dimension(Base::cols(), Base::rows()); } /** * @brief Draws a line. * * @param a { parameter_description } * @param b { parameter_description } * @param[in] color The color */ void drawLine(Support& a, Support& b, T color) { float xdiff = (b.x - a.x); float ydiff = (b.y - a.y); if (xdiff == 0.0f && ydiff == 0.0f) { setPixel(a.x, a.y, color); return; } if (fabs(xdiff) > fabs(ydiff)) { float xmin, xmax; // set xmin to the lower x value given // and xmax to the higher value if (a.x < b.x) { xmin = a.x; xmax = b.x; } else { xmin = b.x; xmax = a.x; } // draw line in terms of y slope float slope = ydiff / xdiff; for (float x = xmin; x <= xmax; x += 1.0f) { float y = a.y + ((x - a.x) * slope); setPixel(x, y, color); } } else { float ymin, ymax; // set ymin to the lower y value given // and ymax to the higher value if (a.y < b.y) { ymin = a.y; ymax = b.y; } else { ymin = b.y; ymax = a.y; } // draw line in terms of x slope float slope = xdiff / ydiff; for (float y = ymin; y <= ymax; y += 1.0f) { float x = a.x + ((y - a.y) * slope); setPixel(x, y, color); } } } void drawLine(Point& a, Point& b, T color) { Support aa(a.x, a.y, 0), bb(b.x, b.y, 0); drawLine(aa, bb, color); } void drawLine(Point a, Point b, T color) { Support aa(a.x, a.y, 0), bb(b.x, b.y, 0); drawLine(aa, bb, color); } /** * @brief Draws a span. * * @param[in] span The span * @param[in] y * @param color The color */ void drawSpan(const Span& span, int y, T& color) { int xdiff = span.x2 - span.x1; if (xdiff == 0) { return; } for (int x = span.x1; x < span.x2; x++) setPixel(x, y, color); } void clearBoundary() { T *ptr = reinterpret_cast<T *>(Base::data()); //Dimension of the (visible) image int h = this->height; int w = this->width; //Width of 16-aligned container int waligned = this->cols(); //first 2 columns contains invalid data -> set them zero. for (int x = 0; x < 2; x++) { for (int y = 0; y < h; y++) { ptr[y * waligned + x] = 0x00; } } //first row for (int x = 0; x < w; x++) ptr[x] = 0x00; //last two rowsrow for (int x = 0; x < w; x++) for (int y = h - 2; y < h; y++) ptr[y * waligned + x] = 0x00; //last column for (int y = 0; y < h; y++) ptr[y * waligned + (waligned - 1)] = 0x00; } /** * @brief Draws spans between edges. * modified from * https://github.com/joshb/triangleraster * @param[in] e1 The e 1 (long edge) * @param[in] e2 The e 2 (short edge) */ void drawSpansBetweenEdges(const Edge &e1, const Edge &e2, T& color) { // calculate difference between the y coordinates // of the first edge and return if 0 float e1ydiff = (float)(e1.b.y - e1.a.y); if (e1ydiff == 0.0f) { return; } // calculate difference between the y coordinates // of the second edge and return if 0 float e2ydiff = (float)(e2.b.y - e2.a.y); if (e2ydiff == 0.0f) { return; } // calculate differences between the x coordinates float e1xdiff = (float)(e1.b.x - e1.a.x); float e2xdiff = (float)(e2.b.x - e2.a.x); // calculate factors to use for interpolation // with the edges and the step values to increase // them by after drawing each span float factor1 = (float)(e2.a.y - e1.a.y) / e1ydiff; float factorStep1 = 1.0f / e1ydiff; float factor2 = 0.0f; float factorStep2 = 1.0f / e2ydiff; // loop through the lines between the edges and draw spans for (int y = e2.a.y; y < e2.b.y; y++) { // create and draw span Span span(e1.a.x + (int)(e1xdiff * factor1), e2.a.x + (int)(e2xdiff * factor2)); if (span.x1 > span.x2) std::swap(span.x1, span.x2); drawSpan(span, y, color); // increase factors factor1 += factorStep1; factor2 += factorStep2; } } /** * @brief Draw a triangle from three vertices and fill it. modified from * https://github.com/joshb/triangleraster * released under BSD licence * * @param a { parameter_description } * @param b { parameter_description } * @param c { parameter_description } * @param[in] color The color */ void fillTriangle(Support a, Support b, Support c, T color) { // create edges for the triangle Edge edges[3] = { Edge(a, b), Edge(b, c), Edge(c, a) }; int maxLength = 0; int longEdge = 0; // find edge with the greatest length in the y axis for (int i = 0; i < 3; i++) { int length = edges[i].b.y - edges[i].a.y; if (length > maxLength) { maxLength = length; longEdge = i; } } int shortEdge1 = (longEdge + 1) % 3; int shortEdge2 = (longEdge + 2) % 3; // draw spans between edges; the long edge can be drawn // with the shorter edges to draw the full triangle drawSpansBetweenEdges(edges[longEdge], edges[shortEdge1], color); drawSpansBetweenEdges(edges[longEdge], edges[shortEdge2], color); } /** * @brief Draws a triangle. * * @param a { parameter_description } * @param b { parameter_description } * @param c { parameter_description } * @param[in] color The color */ void drawTriangle(Support& a, Support& b, Support& c, T color) { drawLine(a, b, color); drawLine(b, c, color); drawLine(c, a, color); } Buffer<RGBColor> convertToRGB() { Buffer<RGBColor> out(Eigen::Vector2i(Base::cols(), Base::rows())); T *ptr = reinterpret_cast<T *>(Base::data()); int width = Base::cols(); int height = Base::rows(); out.width = this->width; //should fail graciously if heights incompatible for (int y = 0; y < height; y++) { for (int x = 0; x < width ; x++) { out(y, x) = ndb::RGBColor(*ptr, *ptr, *ptr); ptr++; } } return out; } }; class RGBBuffer : public Buffer<RGBColor>{ public: RGBBuffer(){ } int readPNGRGB(std::string filename) { unsigned char header[8]; // 8 is the maximum size that can be checked png_byte colorType; png_byte bitDepth; png_structp pngPtr; png_infop infoPtr; png_bytep * rowPointers; // open file and test for it being a png FILE *fp = fopen(filename.c_str(), "rb"); if (!fp) { cout << "ERR: File" << filename << " could not be opened for reading" << endl; return 1; } size_t res = fread(header, 1, 8, fp); if (png_sig_cmp(header, 0, 8)) { cout << "ERR: File" << filename << " is not recognized as a PNG file" << endl; return 1; } pngPtr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!pngPtr) { cout << "ERR: png_create_read_struct failed" << endl; return 1; } infoPtr = png_create_info_struct(pngPtr); if (!infoPtr) { cout << "ERR: png_create_info_struct failed" << endl; return 1; } if (setjmp(png_jmpbuf(pngPtr))) { cout << "ERR: Error during init_io" << endl; return 1; } png_init_io(pngPtr, fp); png_set_sig_bytes(pngPtr, 8); png_read_info(pngPtr, infoPtr); this->width = png_get_image_width(pngPtr, infoPtr); this->height = png_get_image_height(pngPtr, infoPtr); colorType = png_get_color_type(pngPtr, infoPtr); bitDepth = png_get_bit_depth(pngPtr, infoPtr); //We will do a conservative resize after reading in the data, //such that we don't have to translate addresses ourselves Base::resize(this->height, this->width); png_read_update_info(pngPtr, infoPtr); if (setjmp(png_jmpbuf(pngPtr))) { cout << "ERR: Error during read_image" << endl; return 1; } rowPointers = (png_bytep*) malloc(sizeof(png_bytep) * height); for (int y = 0; y < height; y++) rowPointers[y] = (png_byte*) malloc(png_get_rowbytes(pngPtr, infoPtr)); png_read_image(pngPtr, rowPointers); fclose(fp); //Read image into buffer (row-major) int nChannels; switch (png_get_color_type(pngPtr, infoPtr)) { case PNG_COLOR_TYPE_GRAY: nChannels = 1; break; case PNG_COLOR_TYPE_RGB: nChannels = 3; break; case PNG_COLOR_TYPE_RGBA: nChannels = 4; break; default: nChannels = 0; break; } RGBColor *ptr = reinterpret_cast<RGBColor *>(Base::data()); if (bitDepth == 8) { if (nChannels == 3) for (int y = 0; y < this->height; y++) { png_byte* row = rowPointers[y]; for (int x = 0; x < this->width; x++) { int offset = y * this->cols() + x; ptr[offset] = RGBColor(row[3 * x], row[3 * x + 1], row[3 * x + 2]); } } } //Conservative resize of underlying matrix to align with 16 byte boundary Base::conservativeResize(this->height, ALIGN16(this->width)); if (nChannels == 0 || nChannels == 4) { cout << "ERR: found something other than gray or 3 channel color image(" << int(png_get_color_type(pngPtr, infoPtr)) << ") aborting!" << endl; return 1; } for (int y = 0; y < this->height; y++) free(rowPointers[y]); free(rowPointers); return 0; } }; Buffer<RGBColor> getDisparityVisualization(ndb::Buffer<uint8_t>& srcImg, std::vector<int>& validEstimateIndices, ndb::Buffer<float>& disparity) { float min_disparity = 0; float max_disparity = 128; Buffer<RGBColor> dispVis(Eigen::Vector2i(srcImg.width, srcImg.rows())); for(int x=0;x<srcImg.width;x++){ for(int y=0;y<srcImg.height;y++) { uint8_t c= srcImg.getPixel(x,y); dispVis.setPixel(x,y,RGBColor(c,c,c)); } } // Create color-coded reconstruction disparity visualization. // This uses Andreas Geiger's color map from the Kitti benchmark: float map[8][4] = {{0, 0, 0, 114}, {0, 0, 1, 185}, {1, 0, 0, 114}, {1, 0, 1, 174}, {0, 1, 0, 114}, {0, 1, 1, 185}, {1, 1, 0, 114}, {1, 1, 1, 0} }; float sum = 0; for (int32_t i = 0; i < 8; ++ i) { sum += map[i][3]; } float weights[8]; // relative weights float cumsum[8]; // cumulative weights cumsum[0] = 0; for (int32_t i = 0; i < 7; ++ i) { weights[i] = sum / map[i][3]; cumsum[i + 1] = cumsum[i] + map[i][3] / sum; } //Copy image into a three channel color image first: for (auto& idx : validEstimateIndices) { //Pixel coords of disparity value int x = idx % srcImg.cols(); int y = idx / srcImg.cols(); uint8_t p = srcImg.getPixel(x, y); dispVis.setPixel(x, y, RGBColor(p, p, p)); //Overwrite pixel in red if we have significant error. float reconstruction_disp = disparity.getPixel(x,y); float value = std::max(0.f, std::min(0.8f, (reconstruction_disp - min_disparity) / (max_disparity - min_disparity))); int32_t bin; for (bin = 0; bin < 7; ++ bin) { if (value < cumsum[bin + 1]) { break; } } uint8_t colR, colG, colB; // Compute red/green/blue values. float w = 1.0f - (value - cumsum[bin]) * weights[bin]; colR = static_cast<uint8_t>( (w * map[bin][0] + (1.0f - w) * map[bin + 1][0]) * 255.0f); colG = static_cast<uint8_t>( (w * map[bin][1] + (1.0f - w) * map[bin + 1][1]) * 255.0f); colB = static_cast<uint8_t>( (w * map[bin][2] + (1.0f - w) * map[bin + 1][2]) * 255.0f); dispVis.setPixel(x, y, RGBColor(colR,colG,colB)); } return dispVis; } Buffer<RGBColor> getDisparityVisualization(ndb::Buffer<uint8_t>& srcImg, std::vector<Support>& support) { float min_disparity = 0; float max_disparity = 128; Buffer<RGBColor> dispVis(Eigen::Vector2i(srcImg.width, srcImg.rows())); dispVis = srcImg.convertToRGB();; for(auto& s:support) dispVis.setPixel(s.x,s.y,RGBColor(s.d,s.d,s.d)); // Create color-coded reconstruction disparity visualization. // This uses Andreas Geiger's color map from the Kitti benchmark: float map[8][4] = { {0, 0, 1, 185}, {1, 0, 0, 114}, {1, 0, 1, 174}, {0, 1, 0, 114}, {0, 1, 1, 185}, {1, 1, 0, 114}, {1, 1, 1, 0} ,{0, 0, 0, 114}, }; float sum = 0; for (int32_t i = 0; i < 8; ++ i) { sum += map[i][3]; } float weights[8]; // relative weights float cumsum[8]; // cumulative weights cumsum[0] = 0; for (int32_t i = 0; i < 7; ++ i) { weights[i] = sum / map[i][3]; cumsum[i + 1] = cumsum[i] + map[i][3] / sum; } //Copy image into a three channel color image first: for (auto& s : support) { //Pixel coords of disparity value int x = s.x; int y = s.y; //Overwrite pixel in red if we have significant error. float reconstruction_disp = s.d; float value = std::max(0.f, std::min(0.8f, (reconstruction_disp - min_disparity) / (max_disparity - min_disparity))); int32_t bin; for (bin = 0; bin < 7; ++ bin) { if (value < cumsum[bin + 1]) { break; } } uint8_t colR, colG, colB; // Compute red/green/blue values. float w = 1.0f - (value - cumsum[bin]) * weights[bin]; colR = static_cast<uint8_t>( (w * map[bin][0] + (1.0f - w) * map[bin + 1][0]) * 255.0f); colG = static_cast<uint8_t>( (w * map[bin][1] + (1.0f - w) * map[bin + 1][1]) * 255.0f); colB = static_cast<uint8_t>( (w * map[bin][2] + (1.0f - w) * map[bin + 1][2]) * 255.0f); dispVis.setPixel(x, y, RGBColor(colR,colG,colB)); } return dispVis; } } #endif
34,188
11,627
// Copyright 2017 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 "android_webview/browser/aw_web_ui_controller_factory.h" #include "components/safe_browsing/web_ui/constants.h" #include "components/safe_browsing/web_ui/safe_browsing_ui.h" #include "content/public/browser/web_ui.h" using content::WebUI; using content::WebUIController; namespace { const WebUI::TypeID kSafeBrowsingID = &kSafeBrowsingID; // A function for creating a new WebUI. The caller owns the return value, which // may be nullptr (for example, if the URL refers to an non-existent extension). typedef WebUIController* (*WebUIFactoryFunctionPointer)(WebUI* web_ui, const GURL& url); // Template for defining WebUIFactoryFunctionPointer. template <class T> WebUIController* NewWebUI(WebUI* web_ui, const GURL& url) { return new T(web_ui); } WebUIFactoryFunctionPointer GetWebUIFactoryFunctionPointer(const GURL& url) { if (url.host() == safe_browsing::kChromeUISafeBrowsingHost) { return &NewWebUI<safe_browsing::SafeBrowsingUI>; } return nullptr; } WebUI::TypeID GetWebUITypeID(const GURL& url) { if (url.host() == safe_browsing::kChromeUISafeBrowsingHost) { return kSafeBrowsingID; } return WebUI::kNoWebUI; } } // namespace namespace android_webview { // static AwWebUIControllerFactory* AwWebUIControllerFactory::GetInstance() { return base::Singleton<AwWebUIControllerFactory>::get(); } AwWebUIControllerFactory::AwWebUIControllerFactory() {} AwWebUIControllerFactory::~AwWebUIControllerFactory() {} WebUI::TypeID AwWebUIControllerFactory::GetWebUIType( content::BrowserContext* browser_context, const GURL& url) const { return GetWebUITypeID(url); } bool AwWebUIControllerFactory::UseWebUIForURL( content::BrowserContext* browser_context, const GURL& url) const { return GetWebUIType(browser_context, url) != WebUI::kNoWebUI; } bool AwWebUIControllerFactory::UseWebUIBindingsForURL( content::BrowserContext* browser_context, const GURL& url) const { return UseWebUIForURL(browser_context, url); } WebUIController* AwWebUIControllerFactory::CreateWebUIControllerForURL( WebUI* web_ui, const GURL& url) const { WebUIFactoryFunctionPointer function = GetWebUIFactoryFunctionPointer(url); if (!function) return nullptr; return (*function)(web_ui, url); } } // namespace android_webview
2,519
815
//===== utility.hpp ==================================================================================================== // // Author: Immanuel Haffner <haffner.immanuel@gmail.com> // // Licence: // Copyright 2019 Immanuel Haffner // // 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. // // Description: // This file provides utility definitions. // //====================================================================================================================== #pragma once #include <cstdlib> #include <initializer_list> template<typename T> T * allocate(std::size_t count) { return static_cast<T*>(malloc(count * sizeof(T))); } template<typename T> T * reallocate(T *ptr, std::size_t count) { return static_cast<T*>(realloc(ptr, count * sizeof(T))); } template<typename T> void deallocate(T *ptr) { free(static_cast<void*>(ptr)); } template<typename T> T * stack_allocate(std::size_t count) { return static_cast<T*>(alloca(count * sizeof(T))); } void clear_page_cache(); void bind_to_cpus(std::initializer_list<unsigned> cpus);
1,609
465
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup() { ofSetVerticalSync(true); // load an image from disk img.loadImage("linzer.png"); // we're going to load a ton of points into an ofMesh mesh.setMode(OF_PRIMITIVE_POINTS); // loop through the image in the x and y axes int skip = 4; // load a subset of the points for(int y = 0; y < img.getHeight(); y += skip) { for(int x = 0; x < img.getWidth(); x += skip) { ofColor cur = img.getColor(x, y); if(cur.a > 0) { // the alpha value encodes depth, let's remap it to a good depth range float z = ofMap(cur.a, 0, 255, -300, 300); cur.a = 255; cur.r = 255; cur.g = 255; cur.b = 255; mesh.addColor(cur); ofVec3f pos(x, y, z); mesh.addVertex(pos); } } } ofEnableDepthTest(); //glEnable(GL_POINT_SMOOTH); // use circular points instead of square points //glPointSize(3); // make the points bigger } //-------------------------------------------------------------- void ofApp::update() { } //-------------------------------------------------------------- void ofApp::draw() { ofBackgroundGradient(ofColor::gray, ofColor::black, OF_GRADIENT_CIRCULAR); // even points can overlap with each other, let's avoid that cam.begin(); ofScale(2, -2, 2); // flip the y axis and zoom in a bit ofRotateY(90); ofTranslate(-img.getWidth() / 2, -img.getHeight() / 2); mesh.draw(); cam.end(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
2,460
813
// ArduinoJson - arduinojson.org // Copyright Benoit Blanchon 2014-2018 // MIT License #pragma once #include "../Polyfills/attributes.hpp" namespace ARDUINOJSON_NAMESPACE { template <typename TImpl> class VariantCasts { public: template <typename T> FORCE_INLINE operator T() const { return impl()->template as<T>(); } private: const TImpl *impl() const { return static_cast<const TImpl *>(this); } }; } // namespace ARDUINOJSON_NAMESPACE
465
166
#include <libgba-sprite-engine/scene.h> #include <libgba-sprite-engine/sprites/sprite_builder.h> #include <libgba-sprite-engine/background/text_stream.h> #include <libgba-sprite-engine/gba/tonc_memdef.h> #include <libgba-sprite-engine/gba_engine.h> #include "karakter.h" #include "SongSelect.h" #include "song1.h" #include "danceroom1.h" #include "Menu.h" #include "music1.h" #include "data.h" #include "Highscore.h" extern data data1; song1::song1(const std::shared_ptr<GBAEngine> &engine) : Scene(engine) {} std::vector<Sprite *> song1::sprites() { return {animation.get(), animation2.get(), animation3.get(), animation4.get(), buttons.get()}; } std::vector<Background *> song1::backgrounds() { return { bg.get() }; } void song1::tick(u16 keys) { //ga terug naar startscene if (keys & KEY_R) { engine->setScene(new SongSelect(engine)); } //topscore timer if(engine->getTimer()->getMinutes()>=1){ data1.setEndgameScore(score1); engine->setScene(new Highscore(engine)); } TextStream::instance().setText("score:", 1, 1); TextStream::instance().setText(std::to_string(score1), 2, 1); TextStream::instance().setText(std::to_string(60-(engine->getTimer()->getSecs())),3,1); //moving and generating the buttons if(buttons->isOffScreen()) { int frame=(rand()%6+6); buttons->animateToFrame(frame); TextStream::instance().setText(std::to_string(frame), 4, 1); buttons->moveTo((GBA_SCREEN_WIDTH/2)-16,0); pressed = 0; }else{ buttons->setVelocity(0, data1.getFallSpeed()); } //y pos checker /*TextStream::instance().setText("Y-position:", 3, 1); TextStream::instance().setText(std::to_string(buttons->getY()), 4, 1);*/ //points detection if(buttons->getY()>=60 && buttons->getY() <= 75 && pressed == 0){ if(keys & KEY_B && buttons->getCurrentFrame() == 6){ score1+=buttons->getY(); pressed = 1; }else if(keys & KEY_A && buttons->getCurrentFrame() == 7){ score1+=buttons->getY(); pressed = 1; }else if(keys & KEY_LEFT && buttons->getCurrentFrame() == 8){ score1+=buttons->getY(); pressed = 1; }else if(keys & KEY_DOWN && buttons->getCurrentFrame() == 9){ score1+=buttons->getY(); pressed = 1; }else if(keys & KEY_RIGHT && buttons->getCurrentFrame() == 10){ score1+=buttons->getY(); pressed = 1; }else if(keys & KEY_UP && buttons->getCurrentFrame() == 11){ score1+=buttons->getY(); pressed = 1; } } } void song1::load() { foregroundPalette = std::unique_ptr<ForegroundPaletteManager>(new ForegroundPaletteManager(SharedPal, sizeof(SharedPal))); backgroundPalette = std::unique_ptr<BackgroundPaletteManager>(new BackgroundPaletteManager(danceroomPal, sizeof(danceroomPal))); engine.get()->enableText(); engine->getTimer()->reset(); engine->getTimer()->start(); engine->enqueueMusic(music1, music1_bytes, data1.getSpeed()); bg = std::unique_ptr<Background>(new Background(1, danceroomTiles, sizeof(danceroomTiles), danceroomMap, sizeof(danceroomMap))); bg.get()->useMapScreenBlock(16); SpriteBuilder<Sprite> builder; buttons = builder .withData(buttonsTiles, sizeof(buttonsTiles)) .withSize(SIZE_32_32) .withLocation((GBA_SCREEN_WIDTH/2)-16, 0) .buildPtr(); animation = builder .withData(bokmanTiles, sizeof(bokmanTiles)) .withSize(SIZE_32_32) .withAnimated(3, (16-(data1.getFallSpeed()*5))) .withLocation((GBA_SCREEN_WIDTH/4)-16, (GBA_SCREEN_HEIGHT/4)) .withinBounds() .buildPtr(); animation2 = builder .withData(dancingmichmanTiles, sizeof(dancingmichmanTiles)) .withSize(SIZE_32_32) .withAnimated(3, (16-(data1.getFallSpeed()*5))) .withLocation((GBA_SCREEN_WIDTH/4)-16, ((GBA_SCREEN_HEIGHT*3)/4)-32) .withinBounds() .buildPtr(); animation3= builder .withData(nederlandmanTiles, sizeof(nederlandmanTiles)) .withSize(SIZE_32_32) .withAnimated(3, (16-(data1.getFallSpeed()*5))) .withLocation(((GBA_SCREEN_WIDTH*3)/4)-16, (GBA_SCREEN_HEIGHT/4)) .withinBounds() .buildPtr(); animation4 = builder .withData(j_germanTiles, sizeof(j_germanTiles)) .withSize(SIZE_32_32) .withAnimated(3, (16-(data1.getFallSpeed()*5))) .withLocation(((GBA_SCREEN_WIDTH*3)/4)-16, ((GBA_SCREEN_HEIGHT*3)/4)-32) .withinBounds() .buildPtr(); score1 = 0; }
4,845
1,694
/** * $File: JCS_TreeNode.cpp $ * $Date: $ * $Revision: $ * $Creator: Jen-Chieh Shen $ * $Notice: See LICENSE.txt for modification and distribution information * Copyright (c) 2016 by Shen, Jen-Chieh $ */ #include "JCS_TreeNode.h" #include "JCS_TreeView.h" namespace JCS_GUI { JCS_TreeNode::JCS_TreeNode() { } JCS_TreeNode::~JCS_TreeNode() { } #ifdef _WIN32 void JCS_TreeNode::Create( const HWND treeView, const LPWSTR name, const HTREEITEM node/*= nullptr*/) { TVINSERTSTRUCT tvis = { 0 }; tvis.item.mask = TVIF_TEXT; tvis.item.pszText = name; tvis.hInsertAfter = TVI_LAST; // set default as root if (node == nullptr) tvis.hParent = TVI_ROOT; // if there is root already add it on. else tvis.hParent = node; m_node = reinterpret_cast<HTREEITEM>( SendMessage(treeView, TVM_INSERTITEM, 0, reinterpret_cast<LPARAM>(&tvis))); } void JCS_TreeNode::Create( const JCS_TreeView treeView, const LPWSTR name, const JCS_TreeNode* node/*= nullptr*/) { TVINSERTSTRUCT tvis = { 0 }; tvis.item.mask = TVIF_TEXT; tvis.item.pszText = name; tvis.hInsertAfter = TVI_LAST; // set default as root if (node == nullptr) tvis.hParent = TVI_ROOT; // if there is root already add it on. else tvis.hParent = node->GetNode(); m_node = reinterpret_cast<HTREEITEM>( SendMessage(treeView.GetOwnWindowHandle(), TVM_INSERTITEM, 0, reinterpret_cast<LPARAM>(&tvis))); } #endif // _WIN32 }
1,788
640
// Copyright 2014 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 "chrome/browser/banners/app_banner_settings_helper.h" #include <algorithm> #include <string> #include "base/command_line.h" #include "chrome/browser/banners/app_banner_metrics.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_switches.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings_pattern.h" #include "content/public/browser/web_contents.h" #include "net/base/escape.h" #include "url/gurl.h" namespace { // Max number of apps (including ServiceWorker based web apps) that a particular // site may show a banner for. const size_t kMaxAppsPerSite = 3; // Oldest could show banner event we care about, in days. const unsigned int kOldestCouldShowBannerEventInDays = 14; // Number of times that the banner could have been shown before the banner will // actually be triggered. const unsigned int kCouldShowEventsToTrigger = 2; // Number of days that showing the banner will prevent it being seen again for. const unsigned int kMinimumDaysBetweenBannerShows = 60; // Number of days that the banner being blocked will prevent it being seen again // for. const unsigned int kMinimumBannerBlockedToBannerShown = 90; // Dictionary keys to use for the events. const char* kBannerEventKeys[] = { "couldShowBannerEvents", "didShowBannerEvent", "didBlockBannerEvent", "didAddToHomescreenEvent", }; // Dictionary key to use whether the banner has been blocked. const char kHasBlockedKey[] = "hasBlocked"; scoped_ptr<base::DictionaryValue> GetOriginDict( HostContentSettingsMap* settings, const GURL& origin_url) { if (!settings) return scoped_ptr<base::DictionaryValue>(); scoped_ptr<base::Value> value = settings->GetWebsiteSetting( origin_url, origin_url, CONTENT_SETTINGS_TYPE_APP_BANNER, std::string(), NULL); if (!value.get()) return make_scoped_ptr(new base::DictionaryValue()); if (!value->IsType(base::Value::TYPE_DICTIONARY)) return make_scoped_ptr(new base::DictionaryValue()); return make_scoped_ptr(static_cast<base::DictionaryValue*>(value.release())); } base::DictionaryValue* GetAppDict(base::DictionaryValue* origin_dict, const std::string& key_name) { base::DictionaryValue* app_dict = nullptr; if (!origin_dict->GetDictionaryWithoutPathExpansion(key_name, &app_dict)) { // Don't allow more than kMaxAppsPerSite dictionaries. if (origin_dict->size() < kMaxAppsPerSite) { app_dict = new base::DictionaryValue(); origin_dict->SetWithoutPathExpansion(key_name, make_scoped_ptr(app_dict)); } } return app_dict; } } // namespace void AppBannerSettingsHelper::ClearHistoryForURLs( Profile* profile, const std::set<GURL>& origin_urls) { HostContentSettingsMap* settings = profile->GetHostContentSettingsMap(); for (const GURL& origin_url : origin_urls) { ContentSettingsPattern pattern(ContentSettingsPattern::FromURL(origin_url)); if (!pattern.IsValid()) continue; settings->SetWebsiteSetting(pattern, ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_APP_BANNER, std::string(), nullptr); } } void AppBannerSettingsHelper::RecordBannerEvent( content::WebContents* web_contents, const GURL& origin_url, const std::string& package_name_or_start_url, AppBannerEvent event, base::Time time) { Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); if (profile->IsOffTheRecord() || web_contents->GetURL() != origin_url || package_name_or_start_url.empty()) { return; } ContentSettingsPattern pattern(ContentSettingsPattern::FromURL(origin_url)); if (!pattern.IsValid()) return; HostContentSettingsMap* settings = profile->GetHostContentSettingsMap(); scoped_ptr<base::DictionaryValue> origin_dict = GetOriginDict(settings, origin_url); if (!origin_dict) return; base::DictionaryValue* app_dict = GetAppDict(origin_dict.get(), package_name_or_start_url); if (!app_dict) return; std::string event_key(kBannerEventKeys[event]); if (event == APP_BANNER_EVENT_COULD_SHOW) { base::ListValue* could_show_list = nullptr; if (!app_dict->GetList(event_key, &could_show_list)) { could_show_list = new base::ListValue(); app_dict->Set(event_key, make_scoped_ptr(could_show_list)); } // Trim any items that are older than we should care about. For comparisons // the times are converted to local dates. base::Time date = time.LocalMidnight(); base::ValueVector::iterator it = could_show_list->begin(); while (it != could_show_list->end()) { if ((*it)->IsType(base::Value::TYPE_DOUBLE)) { double internal_date; (*it)->GetAsDouble(&internal_date); base::Time other_date = base::Time::FromInternalValue(internal_date).LocalMidnight(); // This date has already been added. Don't add the date again, and don't // bother trimming values as it will have been done the first time the // date was added (unless the local date has changed, which we can live // with). if (other_date == date) return; base::TimeDelta delta = date - other_date; if (delta < base::TimeDelta::FromDays(kOldestCouldShowBannerEventInDays)) { ++it; continue; } } // Either this date is older than we care about, or it isn't a date, so // remove it; it = could_show_list->Erase(it, nullptr); } // Dates are stored in their raw form (i.e. not local dates) to be resilient // to time zone changes. could_show_list->AppendDouble(time.ToInternalValue()); } else { app_dict->SetDouble(event_key, time.ToInternalValue()); } settings->SetWebsiteSetting(pattern, ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_APP_BANNER, std::string(), origin_dict.release()); } bool AppBannerSettingsHelper::ShouldShowBanner( content::WebContents* web_contents, const GURL& origin_url, const std::string& package_name_or_start_url, base::Time time) { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kBypassAppBannerEngagementChecks)) { return true; } // Don't show if it has been added to the homescreen. base::Time added_time = GetSingleBannerEvent(web_contents, origin_url, package_name_or_start_url, APP_BANNER_EVENT_DID_ADD_TO_HOMESCREEN); if (!added_time.is_null()) { banners::TrackDisplayEvent(banners::DISPLAY_EVENT_INSTALLED_PREVIOUSLY); return false; } base::Time blocked_time = GetSingleBannerEvent(web_contents, origin_url, package_name_or_start_url, APP_BANNER_EVENT_DID_BLOCK); // Null times are in the distant past, so the delta between real times and // null events will always be greater than the limits. if (time - blocked_time < base::TimeDelta::FromDays(kMinimumBannerBlockedToBannerShown)) { banners::TrackDisplayEvent(banners::DISPLAY_EVENT_BLOCKED_PREVIOUSLY); return false; } base::Time shown_time = GetSingleBannerEvent(web_contents, origin_url, package_name_or_start_url, APP_BANNER_EVENT_DID_SHOW); if (time - shown_time < base::TimeDelta::FromDays(kMinimumDaysBetweenBannerShows)) { banners::TrackDisplayEvent(banners::DISPLAY_EVENT_IGNORED_PREVIOUSLY); return false; } std::vector<base::Time> could_show_events = GetCouldShowBannerEvents( web_contents, origin_url, package_name_or_start_url); if (could_show_events.size() < kCouldShowEventsToTrigger) { banners::TrackDisplayEvent(banners::DISPLAY_EVENT_NOT_VISITED_ENOUGH); return false; } return true; } std::vector<base::Time> AppBannerSettingsHelper::GetCouldShowBannerEvents( content::WebContents* web_contents, const GURL& origin_url, const std::string& package_name_or_start_url) { std::vector<base::Time> result; if (package_name_or_start_url.empty()) return result; Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); HostContentSettingsMap* settings = profile->GetHostContentSettingsMap(); scoped_ptr<base::DictionaryValue> origin_dict = GetOriginDict(settings, origin_url); if (!origin_dict) return result; base::DictionaryValue* app_dict = GetAppDict(origin_dict.get(), package_name_or_start_url); if (!app_dict) return result; std::string event_key(kBannerEventKeys[APP_BANNER_EVENT_COULD_SHOW]); base::ListValue* could_show_list = nullptr; if (!app_dict->GetList(event_key, &could_show_list)) return result; for (auto value : *could_show_list) { if (value->IsType(base::Value::TYPE_DOUBLE)) { double internal_date; value->GetAsDouble(&internal_date); base::Time date = base::Time::FromInternalValue(internal_date); result.push_back(date); } } return result; } base::Time AppBannerSettingsHelper::GetSingleBannerEvent( content::WebContents* web_contents, const GURL& origin_url, const std::string& package_name_or_start_url, AppBannerEvent event) { DCHECK(event != APP_BANNER_EVENT_COULD_SHOW); DCHECK(event < APP_BANNER_EVENT_NUM_EVENTS); if (package_name_or_start_url.empty()) return base::Time(); Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); HostContentSettingsMap* settings = profile->GetHostContentSettingsMap(); scoped_ptr<base::DictionaryValue> origin_dict = GetOriginDict(settings, origin_url); if (!origin_dict) return base::Time(); base::DictionaryValue* app_dict = GetAppDict(origin_dict.get(), package_name_or_start_url); if (!app_dict) return base::Time(); std::string event_key(kBannerEventKeys[event]); double internal_time; if (!app_dict->GetDouble(event_key, &internal_time)) return base::Time(); return base::Time::FromInternalValue(internal_time); } bool AppBannerSettingsHelper::IsAllowed( content::WebContents* web_contents, const GURL& origin_url, const std::string& package_name_or_start_url) { Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); if (profile->IsOffTheRecord() || web_contents->GetURL() != origin_url || package_name_or_start_url.empty()) { return false; } HostContentSettingsMap* settings = profile->GetHostContentSettingsMap(); scoped_ptr<base::DictionaryValue> origin_dict = GetOriginDict(settings, origin_url); if (!origin_dict) return true; base::DictionaryValue* app_dict = GetAppDict(origin_dict.get(), package_name_or_start_url); if (!app_dict) return true; bool has_blocked; if (!app_dict->GetBoolean(kHasBlockedKey, &has_blocked)) return true; return !has_blocked; } void AppBannerSettingsHelper::Block( content::WebContents* web_contents, const GURL& origin_url, const std::string& package_name_or_start_url) { Profile* profile = Profile::FromBrowserContext(web_contents->GetBrowserContext()); if (profile->IsOffTheRecord() || web_contents->GetURL() != origin_url || package_name_or_start_url.empty()) { return; } ContentSettingsPattern pattern(ContentSettingsPattern::FromURL(origin_url)); if (!pattern.IsValid()) return; HostContentSettingsMap* settings = profile->GetHostContentSettingsMap(); scoped_ptr<base::DictionaryValue> origin_dict = GetOriginDict(settings, origin_url); if (!origin_dict) return; base::DictionaryValue* app_dict = GetAppDict(origin_dict.get(), package_name_or_start_url); if (!app_dict) return; // Update the setting and save it back. app_dict->SetBoolean(kHasBlockedKey, true); settings->SetWebsiteSetting(pattern, ContentSettingsPattern::Wildcard(), CONTENT_SETTINGS_TYPE_APP_BANNER, std::string(), origin_dict.release()); }
12,365
3,905
#include "fipch.h" #include "VertexArray.h" #include "Renderer.h" #include "Platform/OpenGL/OpenGLVertexArray.h" namespace Flick { VertexArray* VertexArray::Create() { switch (Renderer::GetAPI()) { case RendererAPI::API::None: FI_CORE_ASSERT(false, "RendererAPI::None is not yet supported by Flick!"); return nullptr; case RendererAPI::API::OpenGL: return new OpenGLVertexArray(); } FI_CORE_ASSERT(false, "Unknown RendererAPI!"); return 0; } }
465
175
// Copyright 2015 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/android_affiliation/affiliated_match_helper.h" #include <stddef.h> #include <memory> #include <utility> #include "base/bind.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_refptr.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "base/test/scoped_feature_list.h" #include "base/test/scoped_mock_time_message_loop_task_runner.h" #include "base/test/task_environment.h" #include "components/password_manager/core/browser/android_affiliation/affiliation_utils.h" #include "components/password_manager/core/browser/android_affiliation/android_affiliation_service.h" #include "components/password_manager/core/browser/test_password_store.h" #include "components/password_manager/core/common/password_manager_features.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace password_manager { namespace { using StrategyOnCacheMiss = AndroidAffiliationService::StrategyOnCacheMiss; class MockAndroidAffiliationService : public AndroidAffiliationService { public: MockAndroidAffiliationService() : AndroidAffiliationService(nullptr) { testing::DefaultValue<AffiliatedFacets>::Set(AffiliatedFacets()); } MOCK_METHOD2(OnGetAffiliationsAndBrandingCalled, AffiliatedFacets(const FacetURI&, StrategyOnCacheMiss)); MOCK_METHOD2(Prefetch, void(const FacetURI&, const base::Time&)); MOCK_METHOD2(CancelPrefetch, void(const FacetURI&, const base::Time&)); MOCK_METHOD1(TrimCacheForFacetURI, void(const FacetURI&)); void GetAffiliationsAndBranding(const FacetURI& facet_uri, StrategyOnCacheMiss cache_miss_strategy, ResultCallback result_callback) override { AffiliatedFacets affiliation = OnGetAffiliationsAndBrandingCalled(facet_uri, cache_miss_strategy); std::move(result_callback).Run(affiliation, !affiliation.empty()); } void ExpectCallToGetAffiliationsAndBrandingAndSucceedWithResult( const FacetURI& expected_facet_uri, StrategyOnCacheMiss expected_cache_miss_strategy, const AffiliatedFacets& affiliations_to_return) { EXPECT_CALL(*this, OnGetAffiliationsAndBrandingCalled( expected_facet_uri, expected_cache_miss_strategy)) .WillOnce(testing::Return(affiliations_to_return)); } void ExpectCallToGetAffiliationsAndBrandingAndEmulateFailure( const FacetURI& expected_facet_uri, StrategyOnCacheMiss expected_cache_miss_strategy) { EXPECT_CALL(*this, OnGetAffiliationsAndBrandingCalled( expected_facet_uri, expected_cache_miss_strategy)) .WillOnce(testing::Return(AffiliatedFacets())); } void ExpectCallToPrefetch(const char* expected_facet_uri_spec) { EXPECT_CALL(*this, Prefetch(FacetURI::FromCanonicalSpec(expected_facet_uri_spec), base::Time::Max())) .RetiresOnSaturation(); } void ExpectCallToCancelPrefetch(const char* expected_facet_uri_spec) { EXPECT_CALL(*this, CancelPrefetch( FacetURI::FromCanonicalSpec(expected_facet_uri_spec), base::Time::Max())) .RetiresOnSaturation(); } void ExpectCallToTrimCacheForFacetURI(const char* expected_facet_uri_spec) { EXPECT_CALL(*this, TrimCacheForFacetURI(FacetURI::FromCanonicalSpec( expected_facet_uri_spec))) .RetiresOnSaturation(); } }; const char kTestWebFacetURIAlpha1[] = "https://one.alpha.example.com"; const char kTestWebFacetURIAlpha2[] = "https://two.alpha.example.com"; const char kTestAndroidFacetURIAlpha3[] = "android://hash@com.example.alpha.android"; const char kTestAndroidFacetNameAlpha3[] = "Facet Name Alpha 3"; const char kTestAndroidFacetIconURLAlpha3[] = "https://example.com/alpha_3.png"; const char kTestWebRealmAlpha1[] = "https://one.alpha.example.com/"; const char kTestWebRealmAlpha2[] = "https://two.alpha.example.com/"; const char kTestAndroidRealmAlpha3[] = "android://hash@com.example.alpha.android/"; const char kTestWebFacetURIBeta1[] = "https://one.beta.example.com"; const char kTestAndroidFacetURIBeta2[] = "android://hash@com.example.beta.android"; const char kTestAndroidFacetNameBeta2[] = "Facet Name Beta 2"; const char kTestAndroidFacetIconURLBeta2[] = "https://example.com/beta_2.png"; const char kTestAndroidFacetURIBeta3[] = "android://hash@com.yetanother.beta.android"; const char kTestAndroidFacetNameBeta3[] = "Facet Name Beta 3"; const char kTestAndroidFacetIconURLBeta3[] = "https://example.com/beta_3.png"; const char kTestWebRealmBeta1[] = "https://one.beta.example.com/"; const char kTestAndroidRealmBeta2[] = "android://hash@com.example.beta.android/"; const char kTestAndroidRealmBeta3[] = "android://hash@com.yetanother.beta.android/"; const char kTestAndroidFacetURIGamma[] = "android://hash@com.example.gamma.android"; const char kTestAndroidRealmGamma[] = "android://hash@com.example.gamma.android"; const char kTestUsername[] = "JohnDoe"; const char kTestPassword[] = "secret"; AffiliatedFacets GetTestEquivalenceClassAlpha() { return { {FacetURI::FromCanonicalSpec(kTestWebFacetURIAlpha1)}, {FacetURI::FromCanonicalSpec(kTestWebFacetURIAlpha2)}, {FacetURI::FromCanonicalSpec(kTestAndroidFacetURIAlpha3), FacetBrandingInfo{kTestAndroidFacetNameAlpha3, GURL(kTestAndroidFacetIconURLAlpha3)}}, }; } AffiliatedFacets GetTestEquivalenceClassBeta() { return { {FacetURI::FromCanonicalSpec(kTestWebFacetURIBeta1)}, {FacetURI::FromCanonicalSpec(kTestAndroidFacetURIBeta2), FacetBrandingInfo{kTestAndroidFacetNameBeta2, GURL(kTestAndroidFacetIconURLBeta2)}}, {FacetURI::FromCanonicalSpec(kTestAndroidFacetURIBeta3), FacetBrandingInfo{kTestAndroidFacetNameBeta3, GURL(kTestAndroidFacetIconURLBeta3)}}, }; } PasswordForm GetTestAndroidCredentials(const char* signon_realm) { PasswordForm form; form.scheme = PasswordForm::Scheme::kHtml; form.signon_realm = signon_realm; form.username_value = base::ASCIIToUTF16(kTestUsername); form.password_value = base::ASCIIToUTF16(kTestPassword); return form; } PasswordForm GetTestBlocklistedAndroidCredentials(const char* signon_realm) { PasswordForm form = GetTestAndroidCredentials(signon_realm); form.blocked_by_user = true; return form; } PasswordStore::FormDigest GetTestObservedWebForm(const char* signon_realm, const char* origin) { return {PasswordForm::Scheme::kHtml, signon_realm, origin ? GURL(origin) : GURL()}; } } // namespace class AffiliatedMatchHelperTest : public testing::Test, public ::testing::WithParamInterface<bool> { public: AffiliatedMatchHelperTest() { feature_list_.InitWithFeatureState( features::kFillingAcrossAffiliatedWebsites, GetParam()); } protected: void RunDeferredInitialization() { mock_time_task_runner_->RunUntilIdle(); ASSERT_EQ(AffiliatedMatchHelper::kInitializationDelayOnStartup, mock_time_task_runner_->NextPendingTaskDelay()); mock_time_task_runner_->FastForwardBy( AffiliatedMatchHelper::kInitializationDelayOnStartup); } void ExpectNoDeferredTasks() { mock_time_task_runner_->RunUntilIdle(); ASSERT_FALSE(mock_time_task_runner_->HasPendingTask()); } void RunUntilIdle() { // TODO(gab): Add support for base::RunLoop().RunUntilIdle() in scope of // ScopedMockTimeMessageLoopTaskRunner and use it instead of this helper // method. mock_time_task_runner_->RunUntilIdle(); } void AddLogin(const PasswordForm& form) { password_store_->AddLogin(form); RunUntilIdle(); } void UpdateLoginWithPrimaryKey(const PasswordForm& new_form, const PasswordForm& old_primary_key) { password_store_->UpdateLoginWithPrimaryKey(new_form, old_primary_key); RunUntilIdle(); } void RemoveLogin(const PasswordForm& form) { password_store_->RemoveLogin(form); RunUntilIdle(); } void AddAndroidAndNonAndroidTestLogins() { AddLogin(GetTestAndroidCredentials(kTestAndroidRealmAlpha3)); AddLogin(GetTestAndroidCredentials(kTestAndroidRealmBeta2)); AddLogin(GetTestBlocklistedAndroidCredentials(kTestAndroidRealmBeta3)); AddLogin(GetTestAndroidCredentials(kTestAndroidRealmGamma)); AddLogin(GetTestAndroidCredentials(kTestWebRealmAlpha1)); AddLogin(GetTestAndroidCredentials(kTestWebRealmAlpha2)); } void RemoveAndroidAndNonAndroidTestLogins() { RemoveLogin(GetTestAndroidCredentials(kTestAndroidRealmAlpha3)); RemoveLogin(GetTestAndroidCredentials(kTestAndroidRealmBeta2)); RemoveLogin(GetTestBlocklistedAndroidCredentials(kTestAndroidRealmBeta3)); RemoveLogin(GetTestAndroidCredentials(kTestAndroidRealmGamma)); RemoveLogin(GetTestAndroidCredentials(kTestWebRealmAlpha1)); RemoveLogin(GetTestAndroidCredentials(kTestWebRealmAlpha2)); } void ExpectPrefetchForTestLogins() { mock_affiliation_service()->ExpectCallToPrefetch( kTestAndroidFacetURIAlpha3); mock_affiliation_service()->ExpectCallToPrefetch(kTestAndroidFacetURIBeta2); mock_affiliation_service()->ExpectCallToPrefetch(kTestAndroidFacetURIBeta3); mock_affiliation_service()->ExpectCallToPrefetch(kTestAndroidFacetURIGamma); if (base::FeatureList::IsEnabled( features::kFillingAcrossAffiliatedWebsites)) { mock_affiliation_service()->ExpectCallToPrefetch(kTestWebFacetURIAlpha1); mock_affiliation_service()->ExpectCallToPrefetch(kTestWebFacetURIAlpha2); } } void ExpectCancelPrefetchForTestLogins() { mock_affiliation_service()->ExpectCallToCancelPrefetch( kTestAndroidFacetURIAlpha3); mock_affiliation_service()->ExpectCallToCancelPrefetch( kTestAndroidFacetURIBeta2); mock_affiliation_service()->ExpectCallToCancelPrefetch( kTestAndroidFacetURIBeta3); mock_affiliation_service()->ExpectCallToCancelPrefetch( kTestAndroidFacetURIGamma); if (base::FeatureList::IsEnabled( features::kFillingAcrossAffiliatedWebsites)) { mock_affiliation_service()->ExpectCallToCancelPrefetch( kTestWebFacetURIAlpha1); mock_affiliation_service()->ExpectCallToCancelPrefetch( kTestWebFacetURIAlpha2); } } void ExpectTrimCacheForTestLogins() { mock_affiliation_service()->ExpectCallToTrimCacheForFacetURI( kTestAndroidFacetURIAlpha3); mock_affiliation_service()->ExpectCallToTrimCacheForFacetURI( kTestAndroidFacetURIBeta2); mock_affiliation_service()->ExpectCallToTrimCacheForFacetURI( kTestAndroidFacetURIBeta3); mock_affiliation_service()->ExpectCallToTrimCacheForFacetURI( kTestAndroidFacetURIGamma); if (base::FeatureList::IsEnabled( features::kFillingAcrossAffiliatedWebsites)) { mock_affiliation_service()->ExpectCallToTrimCacheForFacetURI( kTestWebFacetURIAlpha1); mock_affiliation_service()->ExpectCallToTrimCacheForFacetURI( kTestWebFacetURIAlpha2); } } std::vector<std::string> GetAffiliatedAndroidRealms( const PasswordStore::FormDigest& observed_form) { expecting_result_callback_ = true; match_helper()->GetAffiliatedAndroidAndWebRealms( observed_form, base::BindOnce(&AffiliatedMatchHelperTest::OnAffiliatedRealmsCallback, base::Unretained(this))); RunUntilIdle(); EXPECT_FALSE(expecting_result_callback_); return last_result_realms_; } std::vector<std::string> GetAffiliatedWebRealms( const PasswordStore::FormDigest& android_form) { expecting_result_callback_ = true; match_helper()->GetAffiliatedWebRealms( android_form, base::BindOnce(&AffiliatedMatchHelperTest::OnAffiliatedRealmsCallback, base::Unretained(this))); RunUntilIdle(); EXPECT_FALSE(expecting_result_callback_); return last_result_realms_; } std::vector<std::unique_ptr<PasswordForm>> InjectAffiliationAndBrandingInformation( std::vector<std::unique_ptr<PasswordForm>> forms) { expecting_result_callback_ = true; match_helper()->InjectAffiliationAndBrandingInformation( std::move(forms), AndroidAffiliationService::StrategyOnCacheMiss::FAIL, base::BindOnce(&AffiliatedMatchHelperTest::OnFormsCallback, base::Unretained(this))); RunUntilIdle(); EXPECT_FALSE(expecting_result_callback_); return std::move(last_result_forms_); } void DestroyMatchHelper() { match_helper_.reset(); } TestPasswordStore* password_store() { return password_store_.get(); } MockAndroidAffiliationService* mock_affiliation_service() { return mock_affiliation_service_; } AffiliatedMatchHelper* match_helper() { return match_helper_.get(); } private: void OnAffiliatedRealmsCallback( const std::vector<std::string>& affiliated_realms) { EXPECT_TRUE(expecting_result_callback_); expecting_result_callback_ = false; last_result_realms_ = affiliated_realms; } void OnFormsCallback(std::vector<std::unique_ptr<PasswordForm>> forms) { EXPECT_TRUE(expecting_result_callback_); expecting_result_callback_ = false; last_result_forms_.swap(forms); } // testing::Test: void SetUp() override { auto service = std::make_unique<testing::StrictMock<MockAndroidAffiliationService>>(); mock_affiliation_service_ = service.get(); password_store_->Init(nullptr); match_helper_ = std::make_unique<AffiliatedMatchHelper>( password_store_.get(), std::move(service)); } void TearDown() override { match_helper_.reset(); password_store_->ShutdownOnUIThread(); password_store_ = nullptr; // Clean up on the background thread. RunUntilIdle(); } base::test::ScopedFeatureList feature_list_; base::test::SingleThreadTaskEnvironment task_environment_; base::ScopedMockTimeMessageLoopTaskRunner mock_time_task_runner_; std::vector<std::string> last_result_realms_; std::vector<std::unique_ptr<PasswordForm>> last_result_forms_; bool expecting_result_callback_ = false; scoped_refptr<TestPasswordStore> password_store_ = base::MakeRefCounted<TestPasswordStore>(); std::unique_ptr<AffiliatedMatchHelper> match_helper_; // Owned by |match_helper_|. MockAndroidAffiliationService* mock_affiliation_service_ = nullptr; }; // GetAffiliatedAndroidRealm* tests verify that GetAffiliatedAndroidRealms() // returns the realms of affiliated Android applications, but only Android // applications, and only if the observed form is a secure HTML login form. TEST_P(AffiliatedMatchHelperTest, GetAffiliatedAndroidRealmsYieldsResults) { mock_affiliation_service() ->ExpectCallToGetAffiliationsAndBrandingAndSucceedWithResult( FacetURI::FromCanonicalSpec(kTestWebFacetURIBeta1), StrategyOnCacheMiss::FAIL, GetTestEquivalenceClassBeta()); EXPECT_THAT(GetAffiliatedAndroidRealms( GetTestObservedWebForm(kTestWebRealmBeta1, nullptr)), testing::UnorderedElementsAre(kTestAndroidRealmBeta2, kTestAndroidRealmBeta3)); } TEST_P(AffiliatedMatchHelperTest, GetAffiliatedAndroidRealmsYieldsOnlyAndroidApps) { // Disable this test when filling across affiliated websites enabled. if (base::FeatureList::IsEnabled(features::kFillingAcrossAffiliatedWebsites)) return; mock_affiliation_service() ->ExpectCallToGetAffiliationsAndBrandingAndSucceedWithResult( FacetURI::FromCanonicalSpec(kTestWebFacetURIAlpha1), StrategyOnCacheMiss::FAIL, GetTestEquivalenceClassAlpha()); // This verifies that |kTestWebRealmAlpha2| is not returned. EXPECT_THAT(GetAffiliatedAndroidRealms( GetTestObservedWebForm(kTestWebRealmAlpha1, nullptr)), testing::UnorderedElementsAre(kTestAndroidRealmAlpha3)); } TEST_P(AffiliatedMatchHelperTest, GetAffiliatedAndroidRealmsYieldsEmptyResultsForHTTPBasicAuthForms) { PasswordStore::FormDigest http_auth_observed_form( GetTestObservedWebForm(kTestWebRealmAlpha1, nullptr)); http_auth_observed_form.scheme = PasswordForm::Scheme::kBasic; EXPECT_THAT(GetAffiliatedAndroidRealms(http_auth_observed_form), testing::IsEmpty()); } TEST_P(AffiliatedMatchHelperTest, GetAffiliatedAndroidRealmsYieldsEmptyResultsForHTTPDigestAuthForms) { PasswordStore::FormDigest http_auth_observed_form( GetTestObservedWebForm(kTestWebRealmAlpha1, nullptr)); http_auth_observed_form.scheme = PasswordForm::Scheme::kDigest; EXPECT_THAT(GetAffiliatedAndroidRealms(http_auth_observed_form), testing::IsEmpty()); } TEST_P(AffiliatedMatchHelperTest, GetAffiliatedAndroidRealmsYieldsEmptyResultsForAndroidKeyedForms) { PasswordStore::FormDigest android_observed_form( GetTestAndroidCredentials(kTestAndroidRealmBeta2)); EXPECT_THAT(GetAffiliatedAndroidRealms(android_observed_form), testing::IsEmpty()); } TEST_P(AffiliatedMatchHelperTest, GetAffiliatedAndroidRealmsYieldsEmptyResultsWhenNoPrefetch) { mock_affiliation_service() ->ExpectCallToGetAffiliationsAndBrandingAndEmulateFailure( FacetURI::FromCanonicalSpec(kTestWebFacetURIAlpha1), StrategyOnCacheMiss::FAIL); EXPECT_THAT(GetAffiliatedAndroidRealms( GetTestObservedWebForm(kTestWebRealmAlpha1, nullptr)), testing::IsEmpty()); } // GetAffiliatedWebRealms* tests verify that GetAffiliatedWebRealms() returns // the realms of web sites affiliated with the given Android application, but // only web sites, and only if an Android application is queried. TEST_P(AffiliatedMatchHelperTest, GetAffiliatedWebRealmsYieldsResults) { mock_affiliation_service() ->ExpectCallToGetAffiliationsAndBrandingAndSucceedWithResult( FacetURI::FromCanonicalSpec(kTestAndroidFacetURIAlpha3), StrategyOnCacheMiss::FETCH_OVER_NETWORK, GetTestEquivalenceClassAlpha()); PasswordStore::FormDigest android_form( GetTestAndroidCredentials(kTestAndroidRealmAlpha3)); EXPECT_THAT( GetAffiliatedWebRealms(android_form), testing::UnorderedElementsAre(kTestWebRealmAlpha1, kTestWebRealmAlpha2)); } TEST_P(AffiliatedMatchHelperTest, GetAffiliatedWebRealmsYieldsOnlyWebsites) { mock_affiliation_service() ->ExpectCallToGetAffiliationsAndBrandingAndSucceedWithResult( FacetURI::FromCanonicalSpec(kTestAndroidFacetURIBeta2), StrategyOnCacheMiss::FETCH_OVER_NETWORK, GetTestEquivalenceClassBeta()); PasswordStore::FormDigest android_form( GetTestAndroidCredentials(kTestAndroidRealmBeta2)); // This verifies that |kTestAndroidRealmBeta3| is not returned. EXPECT_THAT(GetAffiliatedWebRealms(android_form), testing::UnorderedElementsAre(kTestWebRealmBeta1)); } TEST_P(AffiliatedMatchHelperTest, GetAffiliatedWebRealmsYieldsEmptyResultsForWebKeyedForms) { EXPECT_THAT(GetAffiliatedWebRealms( GetTestObservedWebForm(kTestWebRealmBeta1, nullptr)), testing::IsEmpty()); } // Verifies that InjectAffiliationAndBrandingInformation() injects the realms of // web sites affiliated with the given Android application into the password // forms, as well as branding information corresponding to the application, if // any. TEST_P(AffiliatedMatchHelperTest, InjectAffiliationAndBrandingInformation) { std::vector<std::unique_ptr<PasswordForm>> forms; forms.push_back(std::make_unique<PasswordForm>( GetTestAndroidCredentials(kTestAndroidRealmAlpha3))); mock_affiliation_service() ->ExpectCallToGetAffiliationsAndBrandingAndSucceedWithResult( FacetURI::FromCanonicalSpec(kTestAndroidFacetURIAlpha3), StrategyOnCacheMiss::FAIL, GetTestEquivalenceClassAlpha()); forms.push_back(std::make_unique<PasswordForm>( GetTestAndroidCredentials(kTestAndroidRealmBeta2))); mock_affiliation_service() ->ExpectCallToGetAffiliationsAndBrandingAndSucceedWithResult( FacetURI::FromCanonicalSpec(kTestAndroidFacetURIBeta2), StrategyOnCacheMiss::FAIL, GetTestEquivalenceClassBeta()); forms.push_back(std::make_unique<PasswordForm>( GetTestAndroidCredentials(kTestAndroidRealmBeta3))); mock_affiliation_service() ->ExpectCallToGetAffiliationsAndBrandingAndSucceedWithResult( FacetURI::FromCanonicalSpec(kTestAndroidFacetURIBeta3), StrategyOnCacheMiss::FAIL, GetTestEquivalenceClassBeta()); forms.push_back(std::make_unique<PasswordForm>( GetTestAndroidCredentials(kTestAndroidRealmGamma))); mock_affiliation_service() ->ExpectCallToGetAffiliationsAndBrandingAndEmulateFailure( FacetURI::FromCanonicalSpec(kTestAndroidFacetURIGamma), StrategyOnCacheMiss::FAIL); PasswordStore::FormDigest digest = GetTestObservedWebForm(kTestWebRealmBeta1, nullptr); PasswordForm web_form; web_form.scheme = digest.scheme; web_form.signon_realm = digest.signon_realm; web_form.url = digest.url; forms.push_back(std::make_unique<PasswordForm>(web_form)); size_t expected_form_count = forms.size(); std::vector<std::unique_ptr<PasswordForm>> results( InjectAffiliationAndBrandingInformation(std::move(forms))); ASSERT_EQ(expected_form_count, results.size()); EXPECT_THAT(results[0]->affiliated_web_realm, testing::AnyOf(kTestWebRealmAlpha1, kTestWebRealmAlpha2)); EXPECT_EQ(kTestAndroidFacetNameAlpha3, results[0]->app_display_name); EXPECT_EQ(kTestAndroidFacetIconURLAlpha3, results[0]->app_icon_url.possibly_invalid_spec()); EXPECT_THAT(results[1]->affiliated_web_realm, testing::Eq(kTestWebRealmBeta1)); EXPECT_EQ(kTestAndroidFacetNameBeta2, results[1]->app_display_name); EXPECT_EQ(kTestAndroidFacetIconURLBeta2, results[1]->app_icon_url.possibly_invalid_spec()); EXPECT_THAT(results[2]->affiliated_web_realm, testing::Eq(kTestWebRealmBeta1)); EXPECT_EQ(kTestAndroidFacetNameBeta3, results[2]->app_display_name); EXPECT_EQ(kTestAndroidFacetIconURLBeta3, results[2]->app_icon_url.possibly_invalid_spec()); EXPECT_THAT(results[3]->affiliated_web_realm, testing::IsEmpty()); EXPECT_THAT(results[4]->affiliated_web_realm, testing::IsEmpty()); } // Note: IsValidWebCredential() is tested as part of GetAffiliatedAndroidRealms // tests above. TEST_P(AffiliatedMatchHelperTest, IsValidAndroidCredential) { EXPECT_FALSE(AffiliatedMatchHelper::IsValidAndroidCredential( GetTestObservedWebForm(kTestWebRealmBeta1, nullptr))); PasswordStore::FormDigest android_credential( GetTestAndroidCredentials(kTestAndroidRealmBeta2)); EXPECT_TRUE( AffiliatedMatchHelper::IsValidAndroidCredential(android_credential)); } // Verifies that affiliations for Android applications with pre-existing // credentials on start-up are prefetched. TEST_P( AffiliatedMatchHelperTest, PrefetchAffiliationsAndBrandingForPreexistingAndroidCredentialsOnStartup) { AddAndroidAndNonAndroidTestLogins(); match_helper()->Initialize(); RunUntilIdle(); ExpectPrefetchForTestLogins(); ASSERT_NO_FATAL_FAILURE(RunDeferredInitialization()); } // Stores credentials for Android applications between Initialize() and // DoDeferredInitialization(). Verifies that corresponding affiliation // information gets prefetched. TEST_P(AffiliatedMatchHelperTest, PrefetchAffiliationsForAndroidCredentialsAddedInInitializationDelay) { match_helper()->Initialize(); RunUntilIdle(); AddAndroidAndNonAndroidTestLogins(); ExpectPrefetchForTestLogins(); ASSERT_NO_FATAL_FAILURE(RunDeferredInitialization()); } // Stores credentials for Android applications after DoDeferredInitialization(). // Verifies that corresponding affiliation information gets prefetched. TEST_P(AffiliatedMatchHelperTest, PrefetchAffiliationsForAndroidCredentialsAddedAfterInitialization) { match_helper()->Initialize(); ASSERT_NO_FATAL_FAILURE(RunDeferredInitialization()); ExpectPrefetchForTestLogins(); AddAndroidAndNonAndroidTestLogins(); } TEST_P(AffiliatedMatchHelperTest, CancelPrefetchingAffiliationsAndBrandingForRemovedAndroidCredentials) { AddAndroidAndNonAndroidTestLogins(); match_helper()->Initialize(); ExpectPrefetchForTestLogins(); ASSERT_NO_FATAL_FAILURE(RunDeferredInitialization()); ExpectCancelPrefetchForTestLogins(); ExpectTrimCacheForTestLogins(); RemoveAndroidAndNonAndroidTestLogins(); } // Verify that whenever the primary key is updated for a credential (in which // case both REMOVE and ADD change notifications are sent out), then Prefetch() // is called in response to the addition before the call to // TrimCacheForFacetURI() in response to the removal, so that cached data is not // deleted and then immediately re-fetched. TEST_P(AffiliatedMatchHelperTest, PrefetchBeforeTrimForPrimaryKeyUpdates) { AddAndroidAndNonAndroidTestLogins(); match_helper()->Initialize(); ExpectPrefetchForTestLogins(); ASSERT_NO_FATAL_FAILURE(RunDeferredInitialization()); mock_affiliation_service()->ExpectCallToCancelPrefetch( kTestAndroidFacetURIAlpha3); { testing::InSequence in_sequence; mock_affiliation_service()->ExpectCallToPrefetch( kTestAndroidFacetURIAlpha3); mock_affiliation_service()->ExpectCallToTrimCacheForFacetURI( kTestAndroidFacetURIAlpha3); } PasswordForm old_form(GetTestAndroidCredentials(kTestAndroidRealmAlpha3)); PasswordForm new_form(old_form); new_form.username_value = base::ASCIIToUTF16("NewUserName"); UpdateLoginWithPrimaryKey(new_form, old_form); } // Stores and removes four credentials for the same an Android application, and // expects that Prefetch() and CancelPrefetch() will each be called four times. TEST_P(AffiliatedMatchHelperTest, DuplicateCredentialsArePrefetchWithMultiplicity) { EXPECT_CALL(*mock_affiliation_service(), Prefetch(FacetURI::FromCanonicalSpec(kTestAndroidFacetURIAlpha3), base::Time::Max())) .Times(4); PasswordForm android_form(GetTestAndroidCredentials(kTestAndroidRealmAlpha3)); AddLogin(android_form); // Store two credentials before initialization. PasswordForm android_form2(android_form); android_form2.username_value = base::ASCIIToUTF16("JohnDoe2"); AddLogin(android_form2); match_helper()->Initialize(); RunUntilIdle(); // Store one credential between initialization and deferred initialization. PasswordForm android_form3(android_form); android_form3.username_value = base::ASCIIToUTF16("JohnDoe3"); AddLogin(android_form3); ASSERT_NO_FATAL_FAILURE(RunDeferredInitialization()); // Store one credential after deferred initialization. PasswordForm android_form4(android_form); android_form4.username_value = base::ASCIIToUTF16("JohnDoe4"); AddLogin(android_form4); for (size_t i = 0; i < 4; ++i) { mock_affiliation_service()->ExpectCallToCancelPrefetch( kTestAndroidFacetURIAlpha3); mock_affiliation_service()->ExpectCallToTrimCacheForFacetURI( kTestAndroidFacetURIAlpha3); } RemoveLogin(android_form); RemoveLogin(android_form2); RemoveLogin(android_form3); RemoveLogin(android_form4); } TEST_P(AffiliatedMatchHelperTest, DestroyBeforeDeferredInitialization) { match_helper()->Initialize(); RunUntilIdle(); DestroyMatchHelper(); ASSERT_NO_FATAL_FAILURE(ExpectNoDeferredTasks()); } TEST_P(AffiliatedMatchHelperTest, GetAffiliatedAndroidRealmsAndWebsites) { // Disable this test when filling across affiliated websites disabled. if (!base::FeatureList::IsEnabled(features::kFillingAcrossAffiliatedWebsites)) return; mock_affiliation_service() ->ExpectCallToGetAffiliationsAndBrandingAndSucceedWithResult( FacetURI::FromCanonicalSpec(kTestWebFacetURIAlpha1), StrategyOnCacheMiss::FAIL, GetTestEquivalenceClassAlpha()); // This verifies that |kTestWebRealmAlpha2| is returned. EXPECT_THAT(GetAffiliatedAndroidRealms( GetTestObservedWebForm(kTestWebRealmAlpha1, nullptr)), testing::UnorderedElementsAre(kTestWebRealmAlpha2, kTestAndroidRealmAlpha3)); } INSTANTIATE_TEST_SUITE_P(FillingAcrossAffiliatedWebsites, AffiliatedMatchHelperTest, ::testing::Bool()); } // namespace password_manager
28,944
9,262
 #include "osm.ReferenceObject.h" namespace osm { ReferenceObject::ReferenceObject() : m_reference(1) {} ReferenceObject::~ReferenceObject() {} int ReferenceObject::AddRef() { std::atomic_fetch_add_explicit(&m_reference, 1, std::memory_order_consume); return m_reference; } int ReferenceObject::GetRef() { return m_reference; } int ReferenceObject::Release() { assert(m_reference > 0); bool destroy = std::atomic_fetch_sub_explicit(&m_reference, 1, std::memory_order_consume) == 1; if (destroy) { delete this; return 0; } return m_reference; } } // namespace osm
616
206
/* * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org) * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #include "StyleDeprecatedFlexibleBoxData.h" #include "RenderStyle.h" namespace WebCore { StyleDeprecatedFlexibleBoxData::StyleDeprecatedFlexibleBoxData() : flex(RenderStyle::initialBoxFlex()) , flex_group(RenderStyle::initialBoxFlexGroup()) , ordinal_group(RenderStyle::initialBoxOrdinalGroup()) , align(RenderStyle::initialBoxAlign()) , pack(RenderStyle::initialBoxPack()) , orient(RenderStyle::initialBoxOrient()) , lines(RenderStyle::initialBoxLines()) { } StyleDeprecatedFlexibleBoxData::StyleDeprecatedFlexibleBoxData(const StyleDeprecatedFlexibleBoxData& o) : RefCounted<StyleDeprecatedFlexibleBoxData>() , flex(o.flex) , flex_group(o.flex_group) , ordinal_group(o.ordinal_group) , align(o.align) , pack(o.pack) , orient(o.orient) , lines(o.lines) { } bool StyleDeprecatedFlexibleBoxData::operator==(const StyleDeprecatedFlexibleBoxData& o) const { return flex == o.flex && flex_group == o.flex_group && ordinal_group == o.ordinal_group && align == o.align && pack == o.pack && orient == o.orient && lines == o.lines; } } // namespace WebCore
2,081
694
#include <iostream> using namespace std; int main() { int n, reversedNumber = 0, remainder; cout << "Enter an integer: "; cin >> n; while(n != 0) { remainder = n%10; reversedNumber = reversedNumber*10 + remainder; n /= 10; } cout << "Reversed Number = " << reversedNumber; return 0; }
342
122
// $Id: SOCK_Dgram_Mcast_QoS.cpp 96985 2013-04-11 15:50:32Z huangh $ #include "SOCK_Dgram_Mcast_QoS.h" #include "ace/Log_Category.h" #include "ace/OS_NS_sys_socket.h" #if defined (ACE_WIN32) #include "ace/Sock_Connect.h" // needed for subscribe_ifs() #endif /* ACE_WIN32 */ #if !defined (__ACE_INLINE__) #include "SOCK_Dgram_Mcast_QoS.inl" #endif /* __ACE_INLINE__ */ // This is a workaround for platforms with non-standard // definitions of the ip_mreq structure #if ! defined (IMR_MULTIADDR) #define IMR_MULTIADDR imr_multiaddr #endif /* ! defined (IMR_MULTIADDR) */ ACE_BEGIN_VERSIONED_NAMESPACE_DECL ACE_ALLOC_HOOK_DEFINE(ACE_SOCK_Dgram_Mcast_QoS) // Dummy default constructor... ACE_SOCK_Dgram_Mcast_QoS::ACE_SOCK_Dgram_Mcast_QoS (options opts) : ACE_SOCK_Dgram_Mcast (opts) { ACE_TRACE ("ACE_SOCK_Dgram_Mcast_QoS::ACE_SOCK_Dgram_Mcast_QoS"); } int ACE_SOCK_Dgram_Mcast_QoS::open (const ACE_INET_Addr &addr, const ACE_QoS_Params &qos_params, int protocol_family, int protocol, ACE_Protocol_Info *protocolinfo, ACE_SOCK_GROUP g, u_long flags, int reuse_addr) { ACE_TRACE ("ACE_SOCK_Dgram_Mcast_QoS::open"); ACE_UNUSED_ARG (qos_params); // Only perform the <open> initialization if we haven't been opened // earlier. if (this->get_handle () != ACE_INVALID_HANDLE) return 0; ACELIB_DEBUG ((LM_DEBUG, "Get Handle Returns Invalid Handle\n")); if (ACE_SOCK::open (SOCK_DGRAM, protocol_family, protocol, protocolinfo, g, flags, reuse_addr) == -1) return -1; return this->open_i (addr, 0, reuse_addr); } int ACE_SOCK_Dgram_Mcast_QoS::subscribe_ifs (const ACE_INET_Addr &mcast_addr, const ACE_QoS_Params &qos_params, const ACE_TCHAR *net_if, int protocol_family, int protocol, int reuse_addr, ACE_Protocol_Info *protocolinfo) { ACE_TRACE ("ACE_SOCK_Dgram_Mcast_QoS::subscribe_ifs"); #if defined (ACE_WIN32) // Windows NT's winsock has trouble with multicast subscribes in the // presence of multiple network interfaces when the IP address is // given as INADDR_ANY. It will pick the first interface and only // accept mcast there. So, to work around this, cycle through all // of the interfaces known and subscribe to all the non-loopback // ones. // // Note that this only needs to be done on NT, but there's no way to // tell at this point if the code will be running on NT - only if it // is compiled for NT-only or for NT/95, and that doesn't really // help us. It doesn't hurt to do this on Win95, it's just a little // slower than it normally would be. // // NOTE - <ACE_Sock_Connect::get_ip_interfaces> doesn't always get all // of the interfaces. In particular, it may not get a PPP interface. This // is a limitation of the way <ACE_Sock_Connect::get_ip_interfaces> works // with MSVC. The reliable way of getting the interface list is // available only with MSVC 5. if (net_if == 0) { ACE_INET_Addr *if_addrs = 0; size_t if_cnt; if (ACE::get_ip_interfaces (if_cnt, if_addrs) != 0) return -1; size_t nr_subscribed = 0; if (if_cnt < 2) { if (this->subscribe (mcast_addr, qos_params, reuse_addr, ACE_TEXT ("0.0.0.0"), protocol_family, protocol, protocolinfo) == 0) ++nr_subscribed; } else // Iterate through all the interfaces, figure out which ones // offer multicast service, and subscribe to them. while (if_cnt > 0) { --if_cnt; // Convert to 0-based for indexing, next loop check. if (if_addrs[if_cnt].is_loopback()) continue; if (this->subscribe (mcast_addr, qos_params, reuse_addr, ACE_TEXT_CHAR_TO_TCHAR (if_addrs[if_cnt].get_host_addr()), protocol_family, protocol, protocolinfo) == 0) ++nr_subscribed; } delete [] if_addrs; if (nr_subscribed == 0) { errno = ENODEV; return -1; } else // 1 indicates a "short-circuit" return. This handles the // rather bizarre semantics of checking all the interfaces on // NT. return 1; } #else ACE_UNUSED_ARG (mcast_addr); ACE_UNUSED_ARG (qos_params); ACE_UNUSED_ARG (protocol_family); ACE_UNUSED_ARG (protocol); ACE_UNUSED_ARG (reuse_addr); ACE_UNUSED_ARG (protocolinfo); #endif /* ACE_WIN32 */ // Otherwise, do it like everyone else... // Create multicast request. if (this->make_multicast_ifaddr (0, mcast_addr, net_if) == -1) return -1; else return 0; } int ACE_SOCK_Dgram_Mcast_QoS::subscribe (const ACE_INET_Addr &mcast_addr, const ACE_QoS_Params &qos_params, int reuse_addr, const ACE_TCHAR *net_if, int protocol_family, int protocol, ACE_Protocol_Info *protocolinfo, ACE_SOCK_GROUP g, u_long flags, ACE_QoS_Session *qos_session) { ACE_TRACE ("ACE_SOCK_Dgram_Mcast_QoS::subscribe"); if (this->open (mcast_addr, qos_params, protocol_family, protocol, protocolinfo, g, flags, reuse_addr) == -1) return -1; // The following method call only applies to Win32 currently. int result = this->subscribe_ifs (mcast_addr, qos_params, net_if, protocol_family, protocol, reuse_addr, protocolinfo); // Check for the "short-circuit" return value of 1 (for NT). if (result != 0) return result; // Tell network device driver to read datagrams with a // <mcast_request_if_> IP interface. else { // Check if the mcast_addr passed into this method is the // same as the QoS session address. if (qos_session != 0 && mcast_addr == qos_session->dest_addr ()) { // Subscribe to the QoS session. if (this->qos_manager_.join_qos_session (qos_session) == -1) ACELIB_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("Unable to join QoS Session\n")), -1); } else { if (this->close () != 0) ACELIB_ERROR ((LM_ERROR, ACE_TEXT ("Unable to close socket\n"))); ACELIB_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("Dest Addr in the QoS Session does") ACE_TEXT (" not match the address passed into") ACE_TEXT (" subscribe\n")), -1); } ip_mreq ret_mreq; this->make_multicast_ifaddr (&ret_mreq, mcast_addr, net_if); // XX This is windows stuff only. fredk if (ACE_OS::join_leaf (this->get_handle (), reinterpret_cast<const sockaddr *> (&ret_mreq.IMR_MULTIADDR.s_addr), sizeof ret_mreq.IMR_MULTIADDR.s_addr, qos_params) == ACE_INVALID_HANDLE && errno != ENOTSUP) return -1; else if (qos_params.socket_qos () != 0 && qos_session != 0) qos_session->qos (*(qos_params.socket_qos ())); return 0; } } ACE_END_VERSIONED_NAMESPACE_DECL
8,758
2,734
/***************************************************************************************** * * * GHOUL * * General Helpful Open Utility Library * * * * Copyright (c) 2012-2021 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <ghoul/opengl/debugcontext.h> #include <ghoul/misc/assert.h> #include <ghoul/misc/exception.h> #include <map> #include <type_traits> namespace ghoul::opengl::debug { namespace { void internalCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei, const GLchar* message, const GLvoid* userParam) { const CallbackFunction& cb = *reinterpret_cast<const CallbackFunction*>(userParam); cb(Source(source), Type(type), Severity(severity), id, std::string(message)); } } // namespace void setDebugOutput(DebugOutput debug, SynchronousOutput synchronous) { if (debug) { glEnable(GL_DEBUG_OUTPUT); } else { glDisable(GL_DEBUG_OUTPUT); } if (synchronous) { glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); } else { glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS); } } void setDebugMessageControl(Source source, Type type, Severity severity, Enabled enabled) { glDebugMessageControl( static_cast<GLenum>(source), static_cast<GLenum>(type), static_cast<GLenum>(severity), 0, nullptr, enabled ? GL_TRUE : GL_FALSE ); } void setDebugMessageControl(Source source, Type type, const std::vector<unsigned int>& identifiers, Enabled enabled) { ghoul_assert(source != Source::DontCare, "source must not be Source::Dontcare"); ghoul_assert(type != Type::DontCare, "type must not be Type::Dontcare"); static_assert( std::is_same<unsigned int, GLuint>::value, "We exploit that 'int' and 'GLsizei' are the same for glDebugMessageControl" ); glDebugMessageControl( static_cast<GLenum>(source), static_cast<GLenum>(type), GL_DONT_CARE, static_cast<GLsizei>(identifiers.size()), identifiers.data(), enabled ? GL_TRUE : GL_FALSE ); } void setDebugCallback(CallbackFunction callback) { // We have to store the function pointer that is passed into this function locally as // it might otherwise be destroyed (and still be referenced by \c internalCallback. // In a perfect world, we'd want to capture the function pointer, but the OpenGL // callback only allows pure C functions static CallbackFunction storage; storage = callback; glDebugMessageCallback(internalCallback, &storage); } } // namespace ghoul::opengl::debug
4,589
1,207
#include "default_partitioner_inputs.hpp" DefaultPartitionerInputs::DefaultPartitionerInputs(const MeshMetaData& mesh) { for (const auto& elt : mesh.elements) { weights.insert(std::make_pair(elt.first, std::vector<double>{1.})); } }
249
85
// Copyright (c) 2021 PaddlePaddle 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 <iostream> #include <vector> #include "paddle/extension.h" template <typename data_t> void assign_cpu_kernel(const data_t* x_data, data_t* out_data, int64_t x_numel) { for (int i = 0; i < x_numel; ++i) { out_data[i] = x_data[i]; } } std::vector<paddle::Tensor> DispatchTestInterger(const paddle::Tensor& x) { auto out = paddle::Tensor(paddle::PlaceType::kCPU); out.reshape(x.shape()); PD_DISPATCH_INTEGRAL_TYPES( x.type(), "assign_cpu_kernel", ([&] { assign_cpu_kernel<data_t>( x.data<data_t>(), out.mutable_data<data_t>(), x.size()); })); return {out}; } PD_BUILD_OP(dispatch_test_integer) .Inputs({"X"}) .Outputs({"Out"}) .SetKernelFn(PD_KERNEL(DispatchTestInterger)); std::vector<paddle::Tensor> DispatchTestFloatAndInteger( const paddle::Tensor& x) { auto out = paddle::Tensor(paddle::PlaceType::kCPU); out.reshape(x.shape()); PD_DISPATCH_FLOATING_AND_INTEGRAL_TYPES( x.type(), "assign_cpu_kernel", ([&] { assign_cpu_kernel<data_t>( x.data<data_t>(), out.mutable_data<data_t>(), x.size()); })); return {out}; } PD_BUILD_OP(dispatch_test_float_and_integer) .Inputs({"X"}) .Outputs({"Out"}) .SetKernelFn(PD_KERNEL(DispatchTestFloatAndInteger));
1,952
716
/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) 2014 Steven Lovegrove * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include <pangolin/geometry/geometry_ply.h> #include <pangolin/utils/file_utils.h> #include <pangolin/utils/variadic_all.h> #include <pangolin/utils/parse.h> #include <pangolin/utils/type_convert.h> #include <pangolin/utils/simple_math.h> // TODO: Should really remove need for GL here. #include <pangolin/gl/gl.h> namespace pangolin { #define FORMAT_STRING_LIST(x) #x, const char* PlyHeaderString[] = { PLY_HEADER_LIST(FORMAT_STRING_LIST) }; const char* PlyFormatString[] = { PLY_FORMAT_LIST(FORMAT_STRING_LIST) }; const char* PlyTypeString[] = { PLY_TYPE_LIST(FORMAT_STRING_LIST) }; #undef FORMAT_STRING_LIST PLY_GROUP_LIST(PANGOLIN_DEFINE_PARSE_TOKEN) void ParsePlyHeader(PlyHeaderDetails& ply, std::istream& is) { // 'Active' element for property definitions. int current_element = -1; // Check header is correct PlyHeader token = ParseTokenPlyHeader(is); if( token != PlyHeader_ply) { throw std::runtime_error("Bad PLY header magic."); } ConsumeToNewline(is); while(is.good() && token != PlyHeader_end_header) { token = ParseTokenPlyHeader(is); switch (token) { case PlyHeader_format: // parse PLY format and version ConsumeWhitespace(is); ply.format = ParseTokenPlyFormat(is); ConsumeWhitespace(is); ply.version = ReadToken(is); break; case PlyHeader_element: { current_element = ply.elements.size(); PlyElementDetails el; el.stride_bytes = 0; ConsumeWhitespace(is); el.name = ReadToken(is); ConsumeWhitespace(is); el.num_items = FromString<int>(ReadToken(is)); ply.elements.push_back(el); break; } case PlyHeader_property: if(current_element >= 0) { PlyElementDetails& el = ply.elements[current_element]; PlyPropertyDetails prop; ConsumeWhitespace(is); const PlyType t = ParseTokenPlyType(is); if( t == PlyType_list) { ConsumeWhitespace(is); const PlyType idtype = ParseTokenPlyType(is); ConsumeWhitespace(is); const PlyType itemtype = ParseTokenPlyType(is); prop.list_index_type = PlyTypeGl[idtype]; prop.type = PlyTypeGl[itemtype]; prop.offset_bytes = el.stride_bytes; prop.num_items = -1; el.stride_bytes = -1; }else{ prop.type = PlyTypeGl[t]; prop.list_index_type = GL_NONE; prop.offset_bytes = el.stride_bytes; prop.num_items = 1; const size_t size_bytes = GlDataTypeBytes(prop.type); if( el.stride_bytes >= 0) { el.stride_bytes += size_bytes; } } ConsumeWhitespace(is); prop.name = ReadToken(is); el.properties.push_back(prop); }else{ pango_print_warn("PLY Parser: property declaration before element. Ignoring line."); } break; case PlyHeader_comment: case PlyHeader_end_header: break; default: pango_print_warn("PLY Parser: Unknown token - ignoring line."); } ConsumeToNewline(is); } } void ParsePlyAscii(pangolin::Geometry& /*geom*/, const PlyHeaderDetails& /*ply*/, std::istream& /*is*/) { throw std::runtime_error("Not implemented."); } void AddVertexNormals(pangolin::Geometry& geom) { auto it_geom = geom.buffers.find("geometry"); auto it_face = geom.objects.find("default"); if(it_geom != geom.buffers.end() && it_face != geom.objects.end()) { const auto it_vbo = it_geom->second.attributes.find("vertex"); const auto it_ibo = it_face->second.attributes.find("vertex_indices"); if(it_vbo != it_geom->second.attributes.end() && it_ibo != it_face->second.attributes.end()) { const auto& ibo = get<Image<uint32_t>>(it_ibo->second); const auto& vbo = get<Image<float>>(it_vbo->second); // Assume we have triangles. PANGO_ASSERT(ibo.w == 3 && vbo.w == 3); ManagedImage<float> vert_normals(3, vbo.h); ManagedImage<size_t> vert_face_count(1, vbo.h); vert_normals.Fill(0.0f); vert_face_count.Fill(0); float ab[3]; float ac[3]; float fn[3]; for(size_t i=0; i < ibo.h; ++i) { uint32_t i0 = ibo(0,i); uint32_t i1 = ibo(1,i); uint32_t i2 = ibo(2,i); MatSub<3,1>(ab, vbo.RowPtr(i1), vbo.RowPtr(i0)); MatSub<3,1>(ac, vbo.RowPtr(i2), vbo.RowPtr(i0)); VecCross3(fn, ab, ac); Normalise<3>(fn); for(size_t v=0; v < 3; ++v) { MatAdd<3,1>(vert_normals.RowPtr(ibo(v,i)), vert_normals.RowPtr(ibo(v,i)), fn); ++vert_face_count(0,ibo(v,i)); } } for(size_t v=0; v < vert_normals.h; ++v) { // Compute average MatMul<3,1>(vert_normals.RowPtr(v), 1.0f / vert_face_count(0,v)); } auto& el = geom.buffers["normal"]; (ManagedImage<float>&)el = std::move(vert_normals); auto& attr_norm = el.attributes["normal"]; attr_norm = MakeAttribute(GL_FLOAT, el.h, 3, el.ptr, el.pitch); } } } void StandardizeXyzToVertex(pangolin::Geometry& geom) { auto it_verts = geom.buffers.find("geometry"); if(it_verts != geom.buffers.end()) { auto& verts = it_verts->second; auto it_x = verts.attributes.find("x"); auto it_y = verts.attributes.find("y"); auto it_z = verts.attributes.find("z"); if(all_found(verts.attributes, it_x, it_y, it_z)) { if(verts.attributes.find("vertex") == verts.attributes.end()) { auto& vertex = verts.attributes["vertex"]; auto& imx = get<Image<float>>(it_x->second); auto& imy = get<Image<float>>(it_y->second); auto& imz = get<Image<float>>(it_z->second); if(imx.ptr + 1 == imy.ptr && imy.ptr + 1 == imz.ptr) { vertex = MakeAttribute(GL_FLOAT, verts.h, 3, imx.ptr, imx.pitch); }else{ throw std::runtime_error("Ooops"); } } verts.attributes.erase(it_x); verts.attributes.erase(it_y); verts.attributes.erase(it_z); } } } void StandardizeRgbToColor(pangolin::Geometry& geom) { auto it_verts = geom.buffers.find("geometry"); if(it_verts != geom.buffers.end()) { auto& verts = it_verts->second; auto it_r = verts.attributes.find("r"); auto it_g = verts.attributes.find("g"); auto it_b = verts.attributes.find("b"); auto it_a = verts.attributes.find("a"); if(!all_found(verts.attributes, it_r, it_b, it_g)) { it_r = verts.attributes.find("red"); it_g = verts.attributes.find("green"); it_b = verts.attributes.find("blue"); it_a = verts.attributes.find("alpha"); } if(all_found(verts.attributes, it_r, it_g, it_b)) { const bool have_alpha = it_a != verts.attributes.end(); if(verts.attributes.find("color") == verts.attributes.end()) { Geometry::Element::Attribute& red = it_r->second; Geometry::Element::Attribute& color = verts.attributes["color"]; // TODO: Check that these really are contiguous in memory... if(auto attrib = get_if<Image<float>>(&red)) { color = Image<float>(attrib->ptr, have_alpha ? 4 : 3, verts.h, verts.pitch); }else if(auto attrib = get_if<Image<uint8_t>>(&red)) { color = Image<uint8_t>(attrib->ptr, have_alpha ? 4 : 3, verts.h, verts.pitch); }else if(auto attrib = get_if<Image<uint16_t>>(&red)) { color = Image<uint16_t>(attrib->ptr, have_alpha ? 4 : 3, verts.h, verts.pitch); }else if(auto attrib = get_if<Image<uint32_t>>(&red)) { color = Image<uint32_t>(attrib->ptr, have_alpha ? 4 : 3, verts.h, verts.pitch); } } verts.attributes.erase(it_r); verts.attributes.erase(it_g); verts.attributes.erase(it_b); if(have_alpha) verts.attributes.erase(it_a); } } } void StandardizeMultiTextureFaceToXyzuv(pangolin::Geometry& geom) { const auto it_multi_texture_face = geom.buffers.find("multi_texture_face"); const auto it_multi_texture_vertex = geom.buffers.find("multi_texture_vertex"); const auto it_geom = geom.buffers.find("geometry"); const auto it_face = geom.objects.find("default"); if(it_geom != geom.buffers.end() && it_face != geom.objects.end()) { const auto it_vbo = it_geom->second.attributes.find("vertex"); const auto it_ibo = it_face->second.attributes.find("vertex_indices"); if(all_found(geom.buffers, it_multi_texture_face, it_multi_texture_vertex) && it_vbo != it_geom->second.attributes.end() && it_ibo != it_face->second.attributes.end() ) { const auto it_uv_ibo = it_multi_texture_face->second.attributes.find("texture_vertex_indices"); const auto it_tx = it_multi_texture_face->second.attributes.find("tx"); const auto it_tn = it_multi_texture_face->second.attributes.find("tn"); const auto it_u = it_multi_texture_vertex->second.attributes.find("u"); const auto it_v = it_multi_texture_vertex->second.attributes.find("v"); if(all_found(it_multi_texture_vertex->second.attributes, it_u, it_v) && it_uv_ibo != it_multi_texture_face->second.attributes.end() ) { // We're going to create a new vertex buffer to hold uv's too auto& orig_ibo = get<Image<uint32_t>>(it_ibo->second); const auto& orig_xyz = get<Image<float>>(it_vbo->second); const auto& uv_ibo = get<Image<uint32_t>>(it_uv_ibo->second); const auto& u = get<Image<float>>(it_u->second); const auto& v = get<Image<float>>(it_v->second); const auto& tx = get<Image<uint8_t>>(it_tx->second); const auto& tn = get<Image<uint32_t>>(it_tn->second); PANGO_ASSERT(u.h == v.h); PANGO_ASSERT(orig_ibo.w == 3 && uv_ibo.w == 3); pangolin::Geometry::Element new_xyzuv(5*sizeof(float), u.h); Image<float> new_xyz = new_xyzuv.UnsafeReinterpret<float>().SubImage(0,0,3,new_xyzuv.h); Image<float> new_uv = new_xyzuv.UnsafeReinterpret<float>().SubImage(3,0,2,new_xyzuv.h); new_xyzuv.attributes["vertex"] = new_xyz; new_xyzuv.attributes["uv"] = new_uv; for(size_t face=0; face < orig_ibo.h; ++face) { uint32_t vtn = tn(0,face); uint8_t vtx = tx(0,face); PANGO_ASSERT(vtx==0, "Haven't implemented multi-texture yet."); for(size_t vert=0; vert < 3; ++vert) { uint32_t& orig_xyz_index = orig_ibo(vert,vtn); const uint32_t uv_index = uv_ibo(vert,face); PANGO_ASSERT(uv_index < new_xyzuv.h && orig_xyz_index < orig_xyz.h); for(int el=0; el < 3; ++el) { new_xyz(el,uv_index) = orig_xyz(el,orig_xyz_index); } new_uv(0,uv_index) = u(0,uv_index); new_uv(1,uv_index) = v(0,uv_index); orig_xyz_index = uv_index; } } geom.buffers["geometry"] = std::move(new_xyzuv); geom.buffers.erase(it_multi_texture_face); geom.buffers.erase(it_multi_texture_vertex); } } } } void Standardize(pangolin::Geometry& geom) { StandardizeXyzToVertex(geom); StandardizeRgbToColor(geom); StandardizeMultiTextureFaceToXyzuv(geom); AddVertexNormals(geom); } inline int ReadGlIntType(GLenum type, std::istream& is) { // TODO: This seems really dodgey... // int may not be big enough and if the datatype is smaller will it be padded? int v = 0; is.read( (char*)&v, GlDataTypeBytes(type)); return v; } inline void ReadInto(std::vector<unsigned char>& vec, std::istream& is, size_t num_bytes) { const size_t current_size = vec.size(); vec.resize(current_size + num_bytes); is.read((char*)vec.data() + current_size, num_bytes); } void ParsePlyLE(pangolin::Geometry& geom, PlyHeaderDetails& ply, std::istream& is) { std::vector<uint8_t> buffer; for(auto& el : ply.elements) { pangolin::Geometry::Element geom_el; if(el.stride_bytes > 0) { // This will usually be the case for vertex buffers with a known number of attributes PANGO_ASSERT(el.num_items > 0); geom_el.Reinitialise(el.stride_bytes, el.num_items); is.read((char*)geom_el.ptr, geom_el.Area()); }else { // This will generally be the case for face data (containing a list of vertex indices) // Reserve enough space for a list of quads buffer.clear(); buffer.reserve(el.num_items * el.properties.size() * 4); for(int i=0; i< el.num_items; ++i) { size_t offset_bytes = 0; for(auto& prop : el.properties) { if(prop.isList()) { const int list_items = ReadGlIntType(prop.list_index_type, is); if(prop.num_items == -1) { prop.num_items = list_items; prop.offset_bytes = offset_bytes; }else{ PANGO_ASSERT(prop.num_items == list_items); } } const size_t num_bytes = prop.num_items * GlDataTypeBytes(prop.type); ReadInto(buffer, is, num_bytes); offset_bytes += num_bytes; } } // Update element stride now we know el.stride_bytes = 0; for(auto& prop : el.properties) { el.stride_bytes += prop.num_items * GlDataTypeBytes(prop.type); } geom_el.Reinitialise(el.stride_bytes, el.num_items); PANGO_ASSERT(geom_el.SizeBytes() == buffer.size()); std::memcpy(geom_el.ptr, buffer.data(), buffer.size()); } for(auto& prop : el.properties) { geom_el.attributes[prop.name] = MakeAttribute( prop.type, el.num_items, prop.num_items, geom_el.ptr + prop.offset_bytes, geom_el.pitch ); } if(el.name == "vertex") { geom.buffers["geometry"] = std::move(geom_el); }else if(el.name == "face") { geom.objects.emplace("default", std::move(geom_el)); }else{ geom.buffers[el.name] = std::move(geom_el); } } Standardize(geom); } void ParsePlyBE(pangolin::Geometry& /*geom*/, const PlyHeaderDetails& /*ply*/, std::istream& /*is*/) { throw std::runtime_error("Not implemented."); } void AttachAssociatedTexturesPly(pangolin::Geometry& geom, const std::string& filename) { // For PLY, texture names are generally implicit auto dot = filename.find_last_of('.'); if(dot != filename.npos) { const std::string base = filename.substr(0, dot); for(int i=0; i < 10; ++i) { const std::string glob = FormatString("%_%.*", base, i); std::vector<std::string> file_vec; if(FilesMatchingWildcard(glob, file_vec)) { for(const auto& file : file_vec) { try { geom.textures[FormatString("texture_%",i)] = LoadImage(file); break; }catch(std::runtime_error&) { } } } } } } pangolin::Geometry LoadGeometryPly(const std::string& filename) { std::ifstream bFile( filename.c_str(), std::ios::in | std::ios::binary ); if( !bFile.is_open() ) throw std::runtime_error("Unable to open PLY file: " + filename); PlyHeaderDetails ply; ParsePlyHeader(ply, bFile); // Initialise geom object pangolin::Geometry geom; // Fill in geometry from file. if(ply.format == PlyFormat_ascii) { ParsePlyAscii(geom, ply, bFile); }else if(ply.format == PlyFormat_binary_little_endian) { ParsePlyLE(geom, ply, bFile); }else if(ply.format == PlyFormat_binary_big_endian) { ParsePlyBE(geom, ply, bFile); } AttachAssociatedTexturesPly(geom, filename); return geom; } }
18,658
6,144
#include <iostream> #include <memory> #include "columnar_batch_encoder.h" std::unique_ptr<fpvc::columnarbatch::ColumnarBatchEncoder> encoder; std::unique_ptr<fpvc::columnarbatch::ColumnarBatchEncoder> encoder2; void printRecordBatch(fpvc::columnarbatch::BatchPtr batch) { if (batch) { std::cout << "Got the Batch! \n" << batch->LatestTimestamp() << std::endl; encoder->ReturnProcessedBatch(batch); } else { std::cout << "Got the NULLPTR!" << std::endl; } } void printRecordBatch2(fpvc::columnarbatch::BatchPtr batch) { if (batch) { for (int i=0;i<10000000;i++) std::cout << ""; std::cout << "Got the Batch!" << batch->LatestTimestamp() << std::endl; encoder2->ReturnProcessedBatch(batch); } else { std::cout << "Got the NULLPTR!" << std::endl; } } int main() { std::cout << "FPV Arrow Encoder Test" << std::endl; encoder = std::make_unique<fpvc::columnarbatch::ColumnarBatchEncoder>(100,100,0,false,&printRecordBatch,2); uint16_t img[100*100]; std::cout << "Pushing frame." << std::endl; encoder->PushFrame(123456,img,img).wait(); std::cout << "Pushing second frame." << std::endl; encoder->PushFrame(234567,img,img).wait(); std::cout << "Frame buffer available again." << std::endl; auto end = encoder->Close().get(); std::cout << "Closed - " << end << "." << std::endl; std::cout << "Second part" << std::endl; encoder2 = std::make_unique<fpvc::columnarbatch::ColumnarBatchEncoder>(100,100,0,false,&printRecordBatch2,13); for (int i=0;i<500;i++) { uint16_t img2[100*100]; img2[0] = i; for (int j=1;j<100*100;j++) { img2[j] = std::rand(); } std::cout << "Pushing frame " << std::to_string(i) << std::endl; std::shared_future<void*> fut = encoder2->PushFrame(i,img2,img2); std::async(std::launch::async, [](std::shared_future<void*> fut_) { fut_.get(); std::cout << "Buffer is back!" << std::endl;}, std::move(fut)); } auto end2 = encoder2->Close().get(); std::cout << "Closed - " << end2 << "." << std::endl; }
2,128
794