text string | size int64 | token_count int64 |
|---|---|---|
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* Copyright (C) 2003, 2007, 2010 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 "core/html/HTMLMarqueeElement.h"
#include "bindings/core/v8/PrivateScriptRunner.h"
#include "bindings/core/v8/V8HTMLMarqueeElement.h"
#include "core/HTMLNames.h"
#include "core/dom/Document.h"
#include "core/frame/UseCounter.h"
namespace blink {
inline HTMLMarqueeElement::HTMLMarqueeElement(Document& document)
: HTMLElement(HTMLNames::marqueeTag, document)
{
if (document.contextDocument()) {
v8::Local<v8::Value> classObject = PrivateScriptRunner::installClassIfNeeded(&document, "HTMLMarqueeElement");
RELEASE_ASSERT(!classObject.IsEmpty());
}
UseCounter::count(document, UseCounter::HTMLMarqueeElement);
}
HTMLMarqueeElement* HTMLMarqueeElement::create(Document& document)
{
HTMLMarqueeElement* marqueeElement = new HTMLMarqueeElement(document);
V8HTMLMarqueeElement::PrivateScript::createdCallbackMethod(document.frame(), marqueeElement);
return marqueeElement;
}
void HTMLMarqueeElement::attributeChanged(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue, AttributeModificationReason reason)
{
HTMLElement::attributeChanged(name, oldValue, newValue, reason);
V8HTMLMarqueeElement::PrivateScript::attributeChangedCallbackMethod(document().frame(), this, name.toString(), oldValue, newValue);
}
Node::InsertionNotificationRequest HTMLMarqueeElement::insertedInto(ContainerNode* insertionPoint)
{
HTMLElement::insertedInto(insertionPoint);
if (inShadowIncludingDocument()) {
V8HTMLMarqueeElement::PrivateScript::attachedCallbackMethod(document().frame(), this);
}
return InsertionDone;
}
void HTMLMarqueeElement::removedFrom(ContainerNode* insertionPoint)
{
HTMLElement::removedFrom(insertionPoint);
if (insertionPoint->inShadowIncludingDocument()) {
V8HTMLMarqueeElement::PrivateScript::detachedCallbackMethod(insertionPoint->document().frame(), this);
}
}
bool HTMLMarqueeElement::isHorizontal() const
{
AtomicString direction = getAttribute(HTMLNames::directionAttr);
return direction != "down" && direction != "up";
}
} // namespace blink
| 3,062 | 942 |
#include "draw_hook.h"
#include "../SCBW/api.h"
#include "../hook_tools.h"
#include "graphics_misc.h"
namespace {
//-------- Draw hook taken from BWAPI --------//
bool wantRefresh = false;
void __stdcall DrawHook(graphics::Bitmap *surface, Bounds *bounds) {
if (wantRefresh) {
wantRefresh = false;
scbw::refreshScreen();
}
oldDrawGameProc(surface, bounds);
//if ( BW::BWDATA::GameScreenBuffer->isValid() )
//{
// unsigned int numShapes = BWAPI::BroodwarImpl.drawShapes();
//
// if ( numShapes )
// wantRefresh = true;
//}
if (graphics::drawAllShapes() > 0)
wantRefresh = true;
}
} //unnamed namespace
namespace hooks {
void injectDrawHook() {
memoryPatch(0x004BD68D, &DrawHook);
}
} //hooks
| 782 | 324 |
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkPlanarFigureIOFactory.h"
#include "mitkIOAdapter.h"
#include "mitkPlanarFigureReader.h"
#include "itkVersion.h"
namespace mitk
{
PlanarFigureIOFactory::PlanarFigureIOFactory()
{
this->RegisterOverride("mitkIOAdapter",
"mitkPlanarFigureReader",
"mitk PlanarFigure IO",
true,
itk::CreateObjectFunction<IOAdapter<PlanarFigureReader>>::New());
}
PlanarFigureIOFactory::~PlanarFigureIOFactory() {}
const char *PlanarFigureIOFactory::GetITKSourceVersion() const { return ITK_SOURCE_VERSION; }
const char *PlanarFigureIOFactory::GetDescription() const
{
return "PlanarFigure IO Factory, allows the loading of .pf files";
}
} // end namespace mitk
| 1,173 | 329 |
#if !defined(ARCADIA_BUILD)
# include "config_formats.h"
#endif
#if USE_PROTOBUF
# include <Formats/FormatSchemaInfo.h>
# include <Formats/ProtobufSchemas.h>
# include <google/protobuf/compiler/importer.h>
# include <Common/Exception.h>
namespace DB
{
namespace ErrorCodes
{
extern const int BAD_ARGUMENTS;
extern const int CANNOT_PARSE_PROTOBUF_SCHEMA;
}
ProtobufSchemas & ProtobufSchemas::instance()
{
static ProtobufSchemas instance;
return instance;
}
class ProtobufSchemas::ImporterWithSourceTree : public google::protobuf::compiler::MultiFileErrorCollector
{
public:
explicit ImporterWithSourceTree(const String & schema_directory) : importer(&disk_source_tree, this)
{
disk_source_tree.MapPath("", schema_directory);
}
~ImporterWithSourceTree() override = default;
const google::protobuf::Descriptor * import(const String & schema_path, const String & message_name)
{
// Search the message type among already imported ones.
const auto * descriptor = importer.pool()->FindMessageTypeByName(message_name);
if (descriptor)
return descriptor;
const auto * file_descriptor = importer.Import(schema_path);
// If there are parsing errors AddError() throws an exception and in this case the following line
// isn't executed.
assert(file_descriptor);
descriptor = file_descriptor->FindMessageTypeByName(message_name);
if (!descriptor)
throw Exception(
"Not found a message named '" + message_name + "' in the schema file '" + schema_path + "'", ErrorCodes::BAD_ARGUMENTS);
return descriptor;
}
private:
// Overrides google::protobuf::compiler::MultiFileErrorCollector:
void AddError(const String & filename, int line, int column, const String & message) override
{
throw Exception(
"Cannot parse '" + filename + "' file, found an error at line " + std::to_string(line) + ", column " + std::to_string(column)
+ ", " + message,
ErrorCodes::CANNOT_PARSE_PROTOBUF_SCHEMA);
}
google::protobuf::compiler::DiskSourceTree disk_source_tree;
google::protobuf::compiler::Importer importer;
};
ProtobufSchemas::ProtobufSchemas() = default;
ProtobufSchemas::~ProtobufSchemas() = default;
const google::protobuf::Descriptor * ProtobufSchemas::getMessageTypeForFormatSchema(const FormatSchemaInfo & info)
{
auto it = importers.find(info.schemaDirectory());
if (it == importers.end())
it = importers.emplace(info.schemaDirectory(), std::make_unique<ImporterWithSourceTree>(info.schemaDirectory())).first;
auto * importer = it->second.get();
return importer->import(info.schemaPath(), info.messageName());
}
}
#endif
| 2,798 | 833 |
/* hook */
/* Version 1.1 (with Win32 GUI) by Juce. */
#include <windows.h>
#include <windef.h>
#include <string.h>
#include <stdio.h>
#include "mydll.h"
#include "shared.h"
#include "win32gui.h"
#include "config.h"
#include "hook.h"
FILE* log = NULL;
// Program Configuration
static TAXI_CONFIG config = {
DEFAULT_DEBUG,
DEFAULT_CAPTURE_DIR,
DEFAULT_TARGET_FRAME_RATE,
DEFAULT_VKEY_INDICATOR, DEFAULT_VKEY_HOOK_MODE,
DEFAULT_VKEY_SMALL_SCREENSHOT, DEFAULT_VKEY_SCREENSHOT,
DEFAULT_VKEY_VIDEO_CAPTURE,
DEFAULT_USE_DIRECT_INPUT,
DEFAULT_STARTUP_MODE_SYSTEM_WIDE,
DEFAULT_FULL_SIZE_VIDEO,
DEFAULT_CUSTOM_LIST
};
BOOL dropDownSelecting = false;
TAXI_CUSTOM_CONFIG* g_curCfg = NULL;
// function prototypes
void ApplySettings(void);
void ForceReconf(void);
void RestoreSettings(void);
void InitializeCustomConfigs(void);
BOOL GetDevice8Methods(HWND hWnd, DWORD* present, DWORD* reset);
BOOL GetDevice9Methods(HWND hWnd, DWORD* present, DWORD* reset);
/**
* Increase the reconf-counter thus telling all the mapped DLLs that
* they need to reconfigure themselves.
*/
void ForceReconf(void)
{
ZeroMemory(config.captureDir, BUFLEN);
SendMessage(g_captureDirectoryControl, WM_GETTEXT, (WPARAM)BUFLEN, (LPARAM)config.captureDir);
// make sure it ends with backslash.
if (config.captureDir[lstrlen(config.captureDir)-1] != '\\')
{
lstrcat(config.captureDir, "\\");
SendMessage(g_captureDirectoryControl, WM_SETTEXT, 0, (LPARAM)config.captureDir);
}
int frate = 0;
char buf[BUFLEN];
ZeroMemory(buf, BUFLEN);
SendMessage(g_frameRateControl, WM_GETTEXT, (WPARAM)BUFLEN, (LPARAM)buf);
if (sscanf(buf, "%d", &frate) == 1 && frate > 0)
{
config.targetFrameRate = frate;
}
else
{
config.targetFrameRate = GetTargetFrameRate();
sprintf(buf, "%d", config.targetFrameRate);
SendMessage(g_frameRateControl, WM_SETTEXT, 0, (LPARAM)buf);
}
// Apply new settings
ApplySettings();
// Save
if (WriteConfig(&config))
{
SetReconfCounter(GetReconfCounter() + 1);
}
}
/**
* Apply settings from config
*/
void ApplySettings(void)
{
char buf[BUFLEN];
// apply general settings
SetDebug(config.debug);
if (lstrlen(config.captureDir)==0)
{
// If capture directory is still unknown at this point
// set it to the current directory then.
ZeroMemory(config.captureDir, BUFLEN);
GetModuleFileName(NULL, config.captureDir, BUFLEN);
// strip off file name
char* p = config.captureDir + lstrlen(config.captureDir);
while (p > config.captureDir && *p != '\\') p--;
p[1] = '\0';
}
SetCaptureDir(config.captureDir);
SendMessage(g_captureDirectoryControl, WM_SETTEXT, 0, (LPARAM)config.captureDir);
SetTargetFrameRate(config.targetFrameRate);
ZeroMemory(buf, BUFLEN);
sprintf(buf,"%d",config.targetFrameRate);
SendMessage(g_frameRateControl, WM_SETTEXT, 0, (LPARAM)buf);
// apply keys
SetKey(VKEY_INDICATOR_TOGGLE, config.vKeyIndicator);
VKEY_TEXT(VKEY_INDICATOR_TOGGLE, buf, BUFLEN);
SendMessage(g_keyIndicatorControl, WM_SETTEXT, 0, (LPARAM)buf);
SetKey(VKEY_HOOK_MODE_TOGGLE, config.vKeyHookMode);
VKEY_TEXT(VKEY_HOOK_MODE_TOGGLE, buf, BUFLEN);
SendMessage(g_keyModeToggleControl, WM_SETTEXT, 0, (LPARAM)buf);
SetKey(VKEY_SMALL_SCREENSHOT, config.vKeySmallScreenShot);
VKEY_TEXT(VKEY_SMALL_SCREENSHOT, buf, BUFLEN);
SendMessage(g_keySmallScreenshotControl, WM_SETTEXT, 0, (LPARAM)buf);
SetKey(VKEY_SCREENSHOT, config.vKeyScreenShot);
VKEY_TEXT(VKEY_SCREENSHOT, buf, BUFLEN);
SendMessage(g_keyScreenshotControl, WM_SETTEXT, 0, (LPARAM)buf);
SetKey(VKEY_VIDEO_CAPTURE, config.vKeyVideoCapture);
VKEY_TEXT(VKEY_VIDEO_CAPTURE, buf, BUFLEN);
SendMessage(g_keyVideoToggleControl, WM_SETTEXT, 0, (LPARAM)buf);
// apply useDirectInput
SetUseDirectInput(config.useDirectInput);
// apply startupModeSystemWide
SetStartupModeSystemWide(config.startupModeSystemWide);
// apply fullSizeVideo
SetFullSizeVideo(config.fullSizeVideo);
// apply custom configs
SendMessage(g_customSettingsListControl, CB_RESETCONTENT, 0, 0);
SendMessage(g_customPatternControl, WM_SETTEXT, 0, (LPARAM)"");
SendMessage(g_customFrameRateControl, WM_SETTEXT, 0, (LPARAM)"");
SendMessage(g_customFrameWeightControl, WM_SETTEXT, 0, (LPARAM)"");
InitializeCustomConfigs();
}
/**
* Restores last saved settings.
*/
void RestoreSettings(void)
{
g_curCfg = NULL;
FreeCustomConfigs(&config);
// read optional configuration file
ReadConfig(&config);
// check for "silent" mode
if (config.debug == 0)
{
if (log != NULL) fclose(log);
DeleteFile(MAINLOGFILE);
log = NULL;
}
ApplySettings();
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
int home, away, timecode;
char buf[BUFLEN];
switch(uMsg)
{
case WM_DESTROY:
// Set flag, so that mydll knows to unhook device methods
SetUnhookFlag(true);
SetExiting(true);
// Free memory taken by custom configs
FreeCustomConfigs(&config);
// close LOG file
if (log != NULL) fclose(log);
// Uninstall the hook
UninstallTheHook();
// Exit the application when the window closes
PostQuitMessage(1);
return true;
case WM_APP_REHOOK:
// Re-install system-wide hook
LOG(log, (log, "Received message to re-hook GetMsgProc\n"));
if (InstallTheHook())
{
LOG(log, (log, "GetMsgProc successfully re-hooked.\n"));
}
break;
case WM_COMMAND:
if (HIWORD(wParam) == BN_CLICKED)
{
if ((HWND)lParam == g_saveButtonControl)
{
// update current custom config
if (g_curCfg != NULL)
{
SendMessage(g_customPatternControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)g_curCfg->pattern);
int value = 0;
ZeroMemory(buf, BUFLEN);
SendMessage(g_customFrameRateControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf);
if (sscanf(buf,"%d",&value)==1 && value >= 0) g_curCfg->frameRate = value;
float dvalue = 0.0f;
ZeroMemory(buf, BUFLEN);
SendMessage(g_customFrameWeightControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf);
if (sscanf(buf,"%f",&dvalue)==1 && dvalue >= 0.0) g_curCfg->frameWeight = dvalue;
}
ForceReconf();
// modify status text
SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)"SAVED");
}
else if ((HWND)lParam == g_restoreButtonControl)
{
RestoreSettings();
// modify status text
SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)"RESTORED");
}
else if ((HWND)lParam == g_customAddButtonControl)
{
// update current custom config
if (g_curCfg != NULL)
{
SendMessage(g_customPatternControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)g_curCfg->pattern);
int value = 0;
ZeroMemory(buf, BUFLEN);
SendMessage(g_customFrameRateControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf);
if (sscanf(buf,"%d",&value)==1 && value >= 0) g_curCfg->frameRate = value;
float dvalue = 0.0f;
ZeroMemory(buf, BUFLEN);
SendMessage(g_customFrameWeightControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf);
if (sscanf(buf,"%f",&dvalue)==1 && dvalue >= 0.0) g_curCfg->frameWeight = dvalue;
}
g_curCfg = NULL;
// clear out controls
SendMessage(g_customSettingsListControl,WM_SETTEXT,(WPARAM)0,(LPARAM)"");
SendMessage(g_customPatternControl,WM_SETTEXT,(WPARAM)0,(LPARAM)"");
SendMessage(g_customFrameRateControl,WM_SETTEXT,(WPARAM)0,(LPARAM)"");
SendMessage(g_customFrameWeightControl,WM_SETTEXT,(WPARAM)0,(LPARAM)"");
// set focus on appId comboBox
SendMessage(g_customSettingsListControl,WM_SETFOCUS, 0, 0);
}
else if ((HWND)lParam == g_customDropButtonControl)
{
// remove current custom config
if (g_curCfg != NULL)
{
int idx = (int)SendMessage(g_customSettingsListControl, CB_FINDSTRING, BUFLEN, (LPARAM)g_curCfg->appId);
//ZeroMemory(buf, BUFLEN);
//sprintf(buf,"idx = %d", idx);
//SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)buf);
if (idx != -1)
{
SendMessage(g_customSettingsListControl, CB_DELETESTRING, idx, 0);
DeleteCustomConfig(&config, g_curCfg->appId);
}
SendMessage(g_customSettingsListControl, CB_SETCURSEL, 0, 0);
ZeroMemory(buf, BUFLEN);
SendMessage(g_customSettingsListControl, CB_GETLBTEXT, 0, (LPARAM)buf);
g_curCfg = LookupExistingCustomConfig(&config, buf);
if (g_curCfg != NULL)
{
// update custom controls
SendMessage(g_customPatternControl,WM_SETTEXT,(WPARAM)0,(LPARAM)g_curCfg->pattern);
ZeroMemory(buf, BUFLEN);
sprintf(buf, "%d", g_curCfg->frameRate);
SendMessage(g_customFrameRateControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf);
ZeroMemory(buf, BUFLEN);
sprintf(buf, "%1.4f", g_curCfg->frameWeight);
SendMessage(g_customFrameWeightControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf);
}
else
{
// clear out controls
SendMessage(g_customPatternControl,WM_SETTEXT,(WPARAM)0,(LPARAM)"");
SendMessage(g_customFrameRateControl,WM_SETTEXT,(WPARAM)0,(LPARAM)"");
SendMessage(g_customFrameWeightControl,WM_SETTEXT,(WPARAM)0,(LPARAM)"");
}
}
}
}
else if (HIWORD(wParam) == CBN_KILLFOCUS)
{
ZeroMemory(buf, BUFLEN);
SendMessage(g_customSettingsListControl, WM_GETTEXT, (WPARAM)BUFLEN, (LPARAM)buf);
if (lstrlen(buf)>0)
{
if (lstrcmp(buf, g_curCfg->appId)!=0)
{
if (g_curCfg != NULL)
{
// find list item with old appId
int idx = SendMessage(g_customSettingsListControl, CB_FINDSTRING, BUFLEN, (LPARAM)g_curCfg->appId);
// delete this item, if found
if (idx != -1) SendMessage(g_customSettingsListControl, CB_DELETESTRING, idx, 0);
// change appId
strncpy(g_curCfg->appId, buf, BUFLEN-1);
// add a new list item
SendMessage(g_customSettingsListControl, CB_ADDSTRING, 0, (LPARAM)g_curCfg->appId);
}
else
{
// we have a new custom config
g_curCfg = LookupCustomConfig(&config, buf);
// add a new list item
SendMessage(g_customSettingsListControl, CB_ADDSTRING, 0, (LPARAM)g_curCfg->appId);
}
}
}
else
{
// cannot use empty string. Restore the old one, if known.
if (g_curCfg != NULL)
{
// restore previous text
SendMessage(g_customSettingsListControl, WM_SETTEXT, 0, (LPARAM)g_curCfg->appId);
}
}
}
else if (HIWORD(wParam) == CBN_SELCHANGE)
{
// update previously selected custom config
if (g_curCfg != NULL)
{
SendMessage(g_customPatternControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)g_curCfg->pattern);
int value = 0;
ZeroMemory(buf, BUFLEN);
SendMessage(g_customFrameRateControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf);
if (sscanf(buf,"%d",&value)==1 && value >= 0) g_curCfg->frameRate = value;
float dvalue = 0.0f;
ZeroMemory(buf, BUFLEN);
SendMessage(g_customFrameWeightControl,WM_GETTEXT,(WPARAM)BUFLEN,(LPARAM)buf);
if (sscanf(buf,"%f",&dvalue)==1 && dvalue >= 0.0) g_curCfg->frameWeight = dvalue;
}
// user selected different custom setting in drop-down
int idx = (int)SendMessage(g_customSettingsListControl, CB_GETCURSEL, 0, 0);
ZeroMemory(buf, BUFLEN);
SendMessage(g_customSettingsListControl, CB_GETLBTEXT, idx, (LPARAM)buf);
TAXI_CUSTOM_CONFIG* cfg = LookupExistingCustomConfig(&config, buf);
if (cfg == NULL) break;
// update custom controls
dropDownSelecting = true;
SendMessage(g_customPatternControl,WM_SETTEXT,(WPARAM)0,(LPARAM)cfg->pattern);
ZeroMemory(buf, BUFLEN);
sprintf(buf, "%d", cfg->frameRate);
SendMessage(g_customFrameRateControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf);
ZeroMemory(buf, BUFLEN);
sprintf(buf, "%1.4f", cfg->frameWeight);
SendMessage(g_customFrameWeightControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf);
dropDownSelecting = false;
// remember new current config
g_curCfg = cfg;
}
else if (HIWORD(wParam) == EN_CHANGE)
{
HWND control = (HWND)lParam;
if (!dropDownSelecting)
{
// modify status text
SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)"CHANGES MADE");
}
}
else if (HIWORD(wParam) == CBN_EDITCHANGE)
{
HWND control = (HWND)lParam;
// modify status text
SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)"CHANGES MADE");
}
break;
case WM_APP_KEYDEF:
HWND target = (HWND)lParam;
ZeroMemory(buf, BUFLEN);
GetKeyNameText(MapVirtualKey(wParam, 0) << 16, buf, BUFLEN);
SendMessage(target, WM_SETTEXT, 0, (LPARAM)buf);
SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)"CHANGES MADE");
// update config
if (target == g_keyIndicatorControl) config.vKeyIndicator = (WORD)wParam;
else if (target == g_keyModeToggleControl) config.vKeyHookMode = (WORD)wParam;
else if (target == g_keySmallScreenshotControl) config.vKeySmallScreenShot = (WORD)wParam;
else if (target == g_keyScreenshotControl) config.vKeyScreenShot = (WORD)wParam;
else if (target == g_keyVideoToggleControl) config.vKeyVideoCapture = (WORD)wParam;
break;
}
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
bool InitApp(HINSTANCE hInstance, LPSTR lpCmdLine)
{
WNDCLASSEX wcx;
// cbSize - the size of the structure.
wcx.cbSize = sizeof(WNDCLASSEX);
wcx.style = CS_HREDRAW | CS_VREDRAW;
wcx.lpfnWndProc = (WNDPROC)WindowProc;
wcx.cbClsExtra = 0;
wcx.cbWndExtra = 0;
wcx.hInstance = hInstance;
wcx.hIcon = LoadIcon(NULL,IDI_APPLICATION);
wcx.hCursor = LoadCursor(NULL,IDC_ARROW);
wcx.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
wcx.lpszMenuName = NULL;
wcx.lpszClassName = "TAXICLS";
wcx.hIconSm = NULL;
// Register the class with Windows
if(!RegisterClassEx(&wcx))
return false;
// open log
log = fopen(MAINLOGFILE, "wt");
// read optional configuration file
ReadConfig(&config);
// check for "silent" mode
if (config.debug == 0)
{
if (log != NULL) fclose(log);
DeleteFile(MAINLOGFILE);
log = NULL;
}
// clear exiting flag
SetExiting(false);
return true;
}
HWND BuildWindow(int nCmdShow)
{
DWORD style, xstyle;
HWND retval;
style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX;
xstyle = WS_EX_LEFT;
retval = CreateWindowEx(xstyle,
"TAXICLS", // class name
TAXI_WINDOW_TITLE, // title for our window (appears in the titlebar)
style,
CW_USEDEFAULT, // initial x coordinate
CW_USEDEFAULT, // initial y coordinate
WIN_WIDTH, WIN_HEIGHT, // width and height of the window
NULL, // no parent window.
NULL, // no menu
NULL, // no creator
NULL); // no extra data
if (retval == NULL) return NULL; // BAD.
ShowWindow(retval,nCmdShow); // Show the window
return retval; // return its handle for future use.
}
void InitializeCustomConfigs(void)
{
TAXI_CUSTOM_CONFIG* cfg = config.customList;
while (cfg != NULL)
{
SendMessage(g_customSettingsListControl,CB_INSERTSTRING,(WPARAM)0, (LPARAM)cfg->appId);
if (cfg->next == NULL)
{
// Pre-select iteam
SendMessage(g_customSettingsListControl,CB_SETCURSEL,(WPARAM)0,(LPARAM)0);
SendMessage(g_customPatternControl,WM_SETTEXT,(WPARAM)0,(LPARAM)cfg->pattern);
char buf[BUFLEN];
ZeroMemory(buf, BUFLEN);
sprintf(buf, "%d", cfg->frameRate);
SendMessage(g_customFrameRateControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf);
ZeroMemory(buf, BUFLEN);
sprintf(buf, "%1.4f", cfg->frameWeight);
SendMessage(g_customFrameWeightControl,WM_SETTEXT,(WPARAM)0,(LPARAM)buf);
// remember current config
g_curCfg = cfg;
}
cfg = cfg->next;
}
// clear status text
SendMessage(g_statusTextControl, WM_SETTEXT, (WPARAM)0, (LPARAM)"");
}
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
MSG msg; int retval;
if(InitApp(hInstance, lpCmdLine) == false)
return 0;
HWND hWnd = BuildWindow(nCmdShow);
if(hWnd == NULL)
return 0;
// build GUI
if (!BuildControls(hWnd))
return 0;
// Initialize all controls
ApplySettings();
// show credits
char buf[BUFLEN];
ZeroMemory(buf, BUFLEN);
strncpy(buf, CREDITS, BUFLEN-1);
SendMessage(g_statusTextControl, WM_SETTEXT, 0, (LPARAM)buf);
// Get method pointers of IDirect3DDevice8 vtable
DWORD present8_addr = 0, reset8_addr = 0;
if (GetDevice8Methods(hWnd, &present8_addr, &reset8_addr))
{
SetPresent8(present8_addr);
SetReset8(reset8_addr);
}
// Get method pointers of IDirect3DDevice9 vtable
DWORD present9_addr = 0, reset9_addr = 0;
if (GetDevice9Methods(hWnd, &present9_addr, &reset9_addr))
{
SetPresent9(present9_addr);
SetReset9(reset9_addr);
}
// Clear the flag, so that mydll hooks on device methods
SetUnhookFlag(false);
// Set HWND for later use
SetServerWnd(hWnd);
// Install the hook
InstallTheHook();
while((retval = GetMessage(&msg,NULL,0,0)) != 0)
{
// capture key-def events
if ((msg.hwnd == g_keyIndicatorControl || msg.hwnd == g_keyModeToggleControl ||
msg.hwnd == g_keySmallScreenshotControl || msg.hwnd == g_keyScreenshotControl ||
msg.hwnd == g_keyVideoToggleControl) &&
(msg.message == WM_KEYDOWN || msg.message == WM_SYSKEYDOWN))
{
PostMessage(hWnd, WM_APP_KEYDEF, msg.wParam, (LPARAM)msg.hwnd);
continue;
}
if(retval == -1)
return 0; // an error occured while getting a message
if (!IsDialogMessage(hWnd, &msg)) // need to call this to make WS_TABSTOP work
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
| 18,170 | 7,873 |
//
// EntityDynamicInterface.cpp
// libraries/entities/src
//
// Created by Seth Alves on 2015-6-4
// Copyright 2015 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
/*
+-------------------------+ +--------------------------------+
| | | |
| EntityDynamicsInterface | | EntityDynamicsFactoryInterface |
| (entities) | | (entities) |
+-------------------------+ +--------------------------------+
| | | |
+----+ +--+ | |
| | | |
+---------------------+ +----------------+ +--------------------------+ +---------------------------+
| | | | | | | |
| AssignmentDynamics | | ObjectDynamics | | InterfaceDynamicsFactory | | AssignmentDynamicsFactory |
|(assignment client) | | (physics) | | (interface) | | (assignment client) |
+---------------------+ +----------------+ +--------------------------+ +---------------------------+
| |
| |
+---------------------+ | |
| | | |
| btActionInterface | | |
| (bullet) | | |
+---------------------+ | |
| | |
+--------------+ +------------------+ +-------------------+
| | | | | |
| ObjectAction | | ObjectConstraint | | btTypedConstraint |
| (physics) | | (physics) --|--->| (bullet) |
+--------------+ +------------------+ +-------------------+
| |
| |
+--------------------+ +-----------------------+
| | | |
| ObjectActionTractor| | ObjectConstraintHinge |
| (physics) | | (physics) |
+--------------------+ +-----------------------+
A dynamic is a callback which is registered with bullet. A dynamic is called-back every physics
simulation step and can do whatever it wants with the various datastructures it has available. A
dynamic, for example, can pull an EntityItem toward a point as if that EntityItem were connected to that
point by a spring.
In this system, a dynamic is a property of an EntityItem (rather, an EntityItem has a property which
encodes a list of dynamics). Each dynamic has a type and some arguments. Dynamics can be created by a
script or when receiving information via an EntityTree data-stream (either over the network or from an
svo file).
In the interface, if an EntityItem has dynamics, this EntityItem will have pointers to ObjectDynamic
subclass (like ObjectDynamicTractor) instantiations. Code in the entities library affects a dynamic-object
via the EntityDynamicInterface (which knows nothing about bullet). When the ObjectDynamic subclass
instance is created, it is registered as a dynamic with bullet. Bullet will call into code in this
instance with the btDynamicInterface every physics-simulation step.
Because the dynamic can exist next to the interface's EntityTree or the entity-server's EntityTree,
parallel versions of the factories and dynamics are needed.
In an entity-server, any type of dynamic is instantiated as an AssignmentDynamic. This dynamic isn't called
by bullet (which isn't part of an assignment-client). It does nothing but remember its type and its
arguments. This may change as we try to make the entity-server's simple physics simulation better, but
right now the AssignmentDynamic class is a place-holder.
The dynamic-objects are instantiated by singleton (dependecy) subclasses of EntityDynamicFactoryInterface.
In the interface, the subclass is an InterfaceDynamicFactory and it will produce things like
ObjectDynamicTractor. In an entity-server the subclass is an AssignmentDynamicFactory and it always
produces AssignmentDynamics.
Depending on the dynamic's type, it will have various arguments. When a script changes an argument of an
dynamic, the argument-holding member-variables of ObjectDynamicTractor (in this example) are updated and
also serialized into _dynamicData in the EntityItem. Each subclass of ObjectDynamic knows how to serialize
and deserialize its own arguments. _dynamicData is what gets sent over the wire or saved in an svo file.
When a packet-reader receives data for _dynamicData, it will save it in the EntityItem; this causes the
deserializer in the ObjectDynamic subclass to be called with the new data, thereby updating its argument
variables. These argument variables are used by the code which is run when bullet does a callback.
*/
#include "EntityDynamicInterface.h"
#include "EntityItem.h"
/**jsdoc
* <p>An entity action may be one of the following types:</p>
* <table>
* <thead>
* <tr><th>Value</th><th>Type</th><th>Description</th><th>Arguments</th></tr>
* </thead>
* <tbody>
* <tr><td><code>"far-grab"</code></td><td>Avatar action</td>
* <td>Moves and rotates an entity to a target position and orientation, optionally relative to another entity. Collisions
* between the entity and the user's avatar are disabled during the far-grab.</td>
* <td>{@link Entities.ActionArguments-FarGrab}</td></tr>
* <tr><td><code>"hold"</code></td><td>Avatar action</td>
* <td>Positions and rotates an entity relative to an avatar's hand. Collisions between the entity and the user's avatar
* are disabled during the hold.</td>
* <td>{@link Entities.ActionArguments-Hold}</td></tr>
* <tr><td><code>"offset"</code></td><td>Object action</td>
* <td>Moves an entity so that it is a defined distance away from a target point.</td>
* <td>{@link Entities.ActionArguments-Offset}</td></tr>
* <tr><td><code>"tractor"</code></td><td>Object action</td>
* <td>Moves and rotates an entity to a target position and orientation, optionally relative to another entity.</td>
* <td>{@link Entities.ActionArguments-Tractor}</td></tr>
* <tr><td><code>"travel-oriented"</code></td><td>Object action</td>
* <td>Orients an entity to align with its direction of travel.</td>
* <td>{@link Entities.ActionArguments-TravelOriented}</td></tr>
* <tr><td><code>"hinge"</code></td><td>Object constraint</td>
* <td>Lets an entity pivot about an axis or connects two entities with a hinge joint.</td>
* <td>{@link Entities.ActionArguments-Hinge}</td></tr>
* <tr><td><code>"slider"</code></td><td>Object constraint</td>
* <td>Lets an entity slide and rotate along an axis, or connects two entities that slide and rotate along a shared
* axis.</td>
* <td>{@link Entities.ActionArguments-Slider|ActionArguments-Slider}</td></tr>
* <tr><td><code>"cone-twist"</code></td><td>Object constraint</td>
* <td>Connects two entities with a joint that can move through a cone and can twist.</td>
* <td>{@link Entities.ActionArguments-ConeTwist}</td></tr>
* <tr><td><code>"ball-socket"</code></td><td>Object constraint</td>
* <td>Connects two entities with a ball and socket joint.</td>
* <td>{@link Entities.ActionArguments-BallSocket}</td></tr>
* <tr><td><code>"spring"</code></td><td> </td><td>Synonym for <code>"tractor"</code>.
* <p class="important">Deprecated.</p></td><td> </td></tr>
* </tbody>
* </table>
* @typedef {string} Entities.ActionType
*/
// Note: The "none" action type is not listed because it's an internal "uninitialized" value and not useful for scripts.
EntityDynamicType EntityDynamicInterface::dynamicTypeFromString(QString dynamicTypeString) {
QString normalizedDynamicTypeString = dynamicTypeString.toLower().remove('-').remove('_');
if (normalizedDynamicTypeString == "none") {
return DYNAMIC_TYPE_NONE;
}
if (normalizedDynamicTypeString == "offset") {
return DYNAMIC_TYPE_OFFSET;
}
if (normalizedDynamicTypeString == "spring") {
return DYNAMIC_TYPE_TRACTOR;
}
if (normalizedDynamicTypeString == "tractor") {
return DYNAMIC_TYPE_TRACTOR;
}
if (normalizedDynamicTypeString == "hold") {
return DYNAMIC_TYPE_HOLD;
}
if (normalizedDynamicTypeString == "traveloriented") {
return DYNAMIC_TYPE_TRAVEL_ORIENTED;
}
if (normalizedDynamicTypeString == "hinge") {
return DYNAMIC_TYPE_HINGE;
}
if (normalizedDynamicTypeString == "fargrab") {
return DYNAMIC_TYPE_FAR_GRAB;
}
if (normalizedDynamicTypeString == "slider") {
return DYNAMIC_TYPE_SLIDER;
}
if (normalizedDynamicTypeString == "ballsocket") {
return DYNAMIC_TYPE_BALL_SOCKET;
}
if (normalizedDynamicTypeString == "conetwist") {
return DYNAMIC_TYPE_CONE_TWIST;
}
qCDebug(entities) << "Warning -- EntityDynamicInterface::dynamicTypeFromString got unknown dynamic-type name"
<< dynamicTypeString;
return DYNAMIC_TYPE_NONE;
}
QString EntityDynamicInterface::dynamicTypeToString(EntityDynamicType dynamicType) {
switch(dynamicType) {
case DYNAMIC_TYPE_NONE:
return "none";
case DYNAMIC_TYPE_OFFSET:
return "offset";
case DYNAMIC_TYPE_SPRING:
case DYNAMIC_TYPE_TRACTOR:
return "tractor";
case DYNAMIC_TYPE_HOLD:
return "hold";
case DYNAMIC_TYPE_TRAVEL_ORIENTED:
return "travel-oriented";
case DYNAMIC_TYPE_HINGE:
return "hinge";
case DYNAMIC_TYPE_FAR_GRAB:
return "far-grab";
case DYNAMIC_TYPE_SLIDER:
return "slider";
case DYNAMIC_TYPE_BALL_SOCKET:
return "ball-socket";
case DYNAMIC_TYPE_CONE_TWIST:
return "cone-twist";
}
assert(false);
return "none";
}
glm::vec3 EntityDynamicInterface::extractVec3Argument(QString objectName, QVariantMap arguments,
QString argumentName, bool& ok, bool required) {
if (!arguments.contains(argumentName)) {
if (required) {
qCDebug(entities) << objectName << "requires argument:" << argumentName;
}
ok = false;
return glm::vec3(0.0f);
}
QVariant resultV = arguments[argumentName];
if (resultV.type() != (QVariant::Type) QMetaType::QVariantMap) {
qCDebug(entities) << objectName << "argument" << argumentName << "must be a map";
ok = false;
return glm::vec3(0.0f);
}
QVariantMap resultVM = resultV.toMap();
if (!resultVM.contains("x") || !resultVM.contains("y") || !resultVM.contains("z")) {
qCDebug(entities) << objectName << "argument" << argumentName << "must be a map with keys: x, y, z";
ok = false;
return glm::vec3(0.0f);
}
QVariant xV = resultVM["x"];
QVariant yV = resultVM["y"];
QVariant zV = resultVM["z"];
bool xOk = true;
bool yOk = true;
bool zOk = true;
float x = xV.toFloat(&xOk);
float y = yV.toFloat(&yOk);
float z = zV.toFloat(&zOk);
if (!xOk || !yOk || !zOk) {
qCDebug(entities) << objectName << "argument" << argumentName << "must be a map with keys: x, y, and z of type float.";
ok = false;
return glm::vec3(0.0f);
}
if (x != x || y != y || z != z) {
// at least one of the values is NaN
ok = false;
return glm::vec3(0.0f);
}
return glm::vec3(x, y, z);
}
glm::quat EntityDynamicInterface::extractQuatArgument(QString objectName, QVariantMap arguments,
QString argumentName, bool& ok, bool required) {
if (!arguments.contains(argumentName)) {
if (required) {
qCDebug(entities) << objectName << "requires argument:" << argumentName;
}
ok = false;
return glm::quat();
}
QVariant resultV = arguments[argumentName];
if (resultV.type() != (QVariant::Type) QMetaType::QVariantMap) {
qCDebug(entities) << objectName << "argument" << argumentName << "must be a map, not" << resultV.typeName();
ok = false;
return glm::quat();
}
QVariantMap resultVM = resultV.toMap();
if (!resultVM.contains("x") || !resultVM.contains("y") || !resultVM.contains("z") || !resultVM.contains("w")) {
qCDebug(entities) << objectName << "argument" << argumentName << "must be a map with keys: x, y, z, and w";
ok = false;
return glm::quat();
}
QVariant xV = resultVM["x"];
QVariant yV = resultVM["y"];
QVariant zV = resultVM["z"];
QVariant wV = resultVM["w"];
bool xOk = true;
bool yOk = true;
bool zOk = true;
bool wOk = true;
float x = xV.toFloat(&xOk);
float y = yV.toFloat(&yOk);
float z = zV.toFloat(&zOk);
float w = wV.toFloat(&wOk);
if (!xOk || !yOk || !zOk || !wOk) {
qCDebug(entities) << objectName << "argument" << argumentName
<< "must be a map with keys: x, y, z, and w of type float.";
ok = false;
return glm::quat();
}
if (x != x || y != y || z != z || w != w) {
// at least one of the components is NaN!
ok = false;
return glm::quat();
}
return glm::normalize(glm::quat(w, x, y, z));
}
float EntityDynamicInterface::extractFloatArgument(QString objectName, QVariantMap arguments,
QString argumentName, bool& ok, bool required) {
if (!arguments.contains(argumentName)) {
if (required) {
qCDebug(entities) << objectName << "requires argument:" << argumentName;
}
ok = false;
return 0.0f;
}
QVariant variant = arguments[argumentName];
bool variantOk = true;
float value = variant.toFloat(&variantOk);
if (!variantOk || std::isnan(value)) {
ok = false;
return 0.0f;
}
return value;
}
int EntityDynamicInterface::extractIntegerArgument(QString objectName, QVariantMap arguments,
QString argumentName, bool& ok, bool required) {
if (!arguments.contains(argumentName)) {
if (required) {
qCDebug(entities) << objectName << "requires argument:" << argumentName;
}
ok = false;
return 0.0f;
}
QVariant variant = arguments[argumentName];
bool variantOk = true;
int value = variant.toInt(&variantOk);
if (!variantOk) {
ok = false;
return 0;
}
return value;
}
QString EntityDynamicInterface::extractStringArgument(QString objectName, QVariantMap arguments,
QString argumentName, bool& ok, bool required) {
if (!arguments.contains(argumentName)) {
if (required) {
qCDebug(entities) << objectName << "requires argument:" << argumentName;
}
ok = false;
return "";
}
return arguments[argumentName].toString();
}
bool EntityDynamicInterface::extractBooleanArgument(QString objectName, QVariantMap arguments,
QString argumentName, bool& ok, bool required) {
if (!arguments.contains(argumentName)) {
if (required) {
qCDebug(entities) << objectName << "requires argument:" << argumentName;
}
ok = false;
return false;
}
return arguments[argumentName].toBool();
}
QDataStream& operator<<(QDataStream& stream, const EntityDynamicType& entityDynamicType) {
return stream << (quint16)entityDynamicType;
}
QDataStream& operator>>(QDataStream& stream, EntityDynamicType& entityDynamicType) {
quint16 dynamicTypeAsInt;
stream >> dynamicTypeAsInt;
entityDynamicType = (EntityDynamicType)dynamicTypeAsInt;
return stream;
}
QString serializedDynamicsToDebugString(QByteArray data) {
if (data.size() == 0) {
return QString();
}
QVector<QByteArray> serializedDynamics;
QDataStream serializedDynamicsStream(data);
serializedDynamicsStream >> serializedDynamics;
QString result;
foreach(QByteArray serializedDynamic, serializedDynamics) {
QDataStream serializedDynamicStream(serializedDynamic);
EntityDynamicType dynamicType;
QUuid dynamicID;
serializedDynamicStream >> dynamicType;
serializedDynamicStream >> dynamicID;
result += EntityDynamicInterface::dynamicTypeToString(dynamicType) + "-" + dynamicID.toString() + " ";
}
return result;
}
| 17,520 | 5,008 |
#include <string.h> // memcpy
#include "rx/core/memory/buddy_allocator.h"
#include "rx/core/concurrency/scope_lock.h"
#include "rx/core/hints/unlikely.h"
#include "rx/core/hints/likely.h"
#include "rx/core/assert.h"
namespace Rx::Memory {
// Each allocation in the heap is prefixed with this header.
struct alignas(Allocator::ALIGNMENT) Block {
Size size;
bool free;
};
// Returns the next block in the intrusive, flat linked-list structure.
static inline Block* next(Block* _block) {
return reinterpret_cast<Block*>(reinterpret_cast<Byte*>(_block) + _block->size);
}
// Returns size that is needed for |_size|.
static inline Size needed(Size _size) {
Size result = Allocator::ALIGNMENT; // Smallest allocation
// Storage for the block.
_size += sizeof(Block);
// Continually double result until |_size| fits.
while (_size > result) {
result <<= 1;
}
return result;
}
// Continually divides the block |block_| until it's the optimal size for
// an allocation of size |_size|.
static Block* divide(Block* block_, Size _size) {
while (block_->size > _size) {
// Split block into two halves, half-size each.
const auto size = block_->size >> 1;
block_->size = size;
block_ = next(block_);
block_->size = size;
block_->free = true;
}
return block_->size >= _size ? block_ : nullptr;
}
// Searches for a free block that matches the given size |_size| in the list
// defined by |_head| and |_tail|. When a block cannot be found which satisifies
// the size |_size| but there is a larger free block, this divides the free
// block into two halves of the same size until the block optimally fits the
// size |_size| in it. If there is no larger free block available, this returns
// nullptr.
//
// This function also merges adjacent free blocks as it searches to make larger,
// free blocks available during the search.
static Block* find_available(Block* _head, Block* _tail, Size _size) {
Block* region = _head;
Block* buddy = next(region);
Block* closest = nullptr;
// When at the end of the heap and the region is free.
if (buddy == _tail && region->free) {
// Split it into a block to satisfy the request leaving what is left over
// for any future allocations. This is the one edge case the general
// algorithm cannot cover.
return divide(region, _size);
}
// Find the closest minimum sized match within the heap.
Size closest_size = 0;
while (region < _tail && buddy < _tail) {
// When both the region and the buddy are free, merge those adjacent
// free blocks.
if (region->free && buddy->free && region->size == buddy->size) {
region->size <<= 1;
const Size region_size = region->size;
if (_size <= region_size && (!closest || region_size <= closest->size)) {
closest = region;
}
if ((region = next(buddy)) < _tail) {
buddy = next(region);
}
} else {
if (closest) {
closest_size = closest->size;
}
// Check the region block.
const Size region_size = region->size;
if (region->free && _size <= region_size
&& (!closest || region_size <= closest->size))
{
closest = region;
closest_size = region_size;
}
// Check the buddy block.
const Size buddy_size = buddy->size;
if (buddy->free && _size <= buddy_size
&& (!closest || buddy_size <= closest->size))
{
closest = buddy;
closest_size = buddy_size;
}
// The buddy has been split up into smaller blocks.
if (region_size > buddy_size) {
region = buddy;
buddy = next(buddy);
} else if ((region = next(buddy)) < _tail) {
// Skip the base and buddy region for the next iteration.
buddy = next(region);
}
}
}
if (closest) {
// Perfect match.
if (closest_size == _size) {
return closest;
}
// Split |current| in halves continually until it optimally fits |_size|.
return divide(closest, _size);
}
// Potentially out of memory.
return nullptr;
}
// Performs a single level merge of adjacent free blocks in the list given
// by |_head| and |_tail|.
static bool merge_free(Block* _head, Block* _tail) {
Block* region = _head;
Block* buddy = next(region);
bool modified = false;
while (region < _tail && buddy < _tail) {
// Both the region and buddy are free.
if (region->free && buddy->free && region->size == buddy->size) {
// Merge the blocks back into one, larger one.
region->size <<= 1;
if ((region = next(region)) < _tail) {
buddy = next(region);
}
modified = true;
} else if (region->size > buddy->size) {
// The buddy block has been split into smaller blocks.
region = buddy;
buddy = next(buddy);
} else if ((region = next(buddy)) < _tail) {
// Skip the base and buddy region for the next iteration.
buddy = next(region);
}
}
return modified;
}
BuddyAllocator::BuddyAllocator(Byte* _data, Size _size) {
// Ensure |_data| and |_size| are multiples of |ALIGNMENT|.
RX_ASSERT(reinterpret_cast<UintPtr>(_data) % ALIGNMENT == 0,
"_data not aligned on %zu-byte boundary", ALIGNMENT);
RX_ASSERT(_size % ALIGNMENT == 0,
"_size not a multiple of %zu", ALIGNMENT);
// Ensure |_size| is a power of two.
RX_ASSERT((_size & (_size - 1)) == 0, "_size not a power of two");
// Create the root block structure.
Block* head = reinterpret_cast<Block*>(_data);
head->size = _size;
head->free = true;
m_head = reinterpret_cast<void*>(head);
m_tail = reinterpret_cast<void*>(next(head));
}
Byte* BuddyAllocator::allocate(Size _size) {
Concurrency::ScopeLock lock{m_lock};
return allocate_unlocked(_size);
}
Byte* BuddyAllocator::reallocate(void* _data, Size _size) {
Concurrency::ScopeLock lock{m_lock};
return reallocate_unlocked(_data, _size);
}
void BuddyAllocator::deallocate(void* _data) {
Concurrency::ScopeLock lock{m_lock};
deallocate_unlocked(_data);
}
Byte* BuddyAllocator::allocate_unlocked(Size _size) {
const auto size = needed(_size);
const auto head = reinterpret_cast<Block*>(m_head);
const auto tail = reinterpret_cast<Block*>(m_tail);
auto find = find_available(head, tail, size);
if (RX_HINT_LIKELY(find)) {
find->free = false;
return reinterpret_cast<Byte*>(find + 1);
}
// Merge free blocks until they're all merged.
while (merge_free(head, tail)) {
;
}
// Search again for a free block.
if ((find = find_available(head, tail, size))) {
find->free = false;
return reinterpret_cast<Byte*>(find + 1);
}
// Out of memory.
return nullptr;
}
Byte* BuddyAllocator::reallocate_unlocked(void* _data, Size _size) {
if (RX_HINT_LIKELY(_data)) {
const auto region = reinterpret_cast<Block*>(_data) - 1;
const auto head = reinterpret_cast<Block*>(m_head);
const auto tail = reinterpret_cast<Block*>(m_tail);
RX_ASSERT(region >= head, "out of heap");
RX_ASSERT(region <= tail - 1, "out of heap");
// No need to resize.
if (region->size >= needed(_size)) {
return reinterpret_cast<Byte*>(_data);
}
// Create a new allocation.
auto resize = allocate_unlocked(_size);
if (RX_HINT_LIKELY(resize)) {
memcpy(resize, _data, region->size - sizeof *region);
deallocate_unlocked(_data);
return resize;
}
// Out of memory.
return nullptr;
}
return allocate_unlocked(_size);
}
void BuddyAllocator::deallocate_unlocked(void* _data) {
if (RX_HINT_LIKELY(_data)) {
const auto region = reinterpret_cast<Block*>(_data) - 1;
const auto head = reinterpret_cast<Block*>(m_head);
const auto tail = reinterpret_cast<Block*>(m_tail);
RX_ASSERT(region >= head, "out of heap");
RX_ASSERT(region <= tail - 1, "out of heap");
region->free = true;
}
}
} // namespace rx::memory
| 7,923 | 2,657 |
// Copyright 2014-2016 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "./publish_take.hpp"
#include "./templates.hpp"
bool using_introspection_c_typesupport(const char * typesupport_identifier)
{
return typesupport_identifier == rosidl_typesupport_introspection_c__identifier;
}
bool using_introspection_cpp_typesupport(const char * typesupport_identifier)
{
return typesupport_identifier ==
rosidl_typesupport_introspection_cpp::typesupport_identifier;
}
bool _publish(DDS_DynamicData * dynamic_data, const void * ros_message,
const void * untyped_members, const char * typesupport)
{
if (using_introspection_c_typesupport(typesupport)) {
return publish<rosidl_typesupport_introspection_c__MessageMembers>(
dynamic_data, ros_message, untyped_members);
} else if (using_introspection_cpp_typesupport(typesupport)) {
return publish<rosidl_typesupport_introspection_cpp::MessageMembers>(
dynamic_data, ros_message, untyped_members);
}
RMW_SET_ERROR_MSG("Unknown typesupport identifier")
return false;
}
bool _take(DDS_DynamicData * dynamic_data, void * ros_message,
const void * untyped_members, const char * typesupport)
{
if (using_introspection_c_typesupport(typesupport)) {
return take<rosidl_typesupport_introspection_c__MessageMembers>(
dynamic_data, ros_message, untyped_members);
} else if (using_introspection_cpp_typesupport(typesupport)) {
return take<rosidl_typesupport_introspection_cpp::MessageMembers>(
dynamic_data, ros_message, untyped_members);
}
RMW_SET_ERROR_MSG("Unknown typesupport identifier")
return false;
}
| 2,172 | 698 |
/*
* Copyright (C) 2018, Xilinx Inc - All rights reserved
* Xilinx SDAccel Media Accelerator API
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. A copy of the
* License is located 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 <fstream>
#include <stdexcept>
#include "xclbin.h"
#include "app/xmaerror.h"
#include "app/xmalogger.h"
#include "lib/xmaxclbin.h"
#include "core/common/config_reader.h"
#include "core/common/xclbin_parser.h"
#include "app/xma_utils.hpp"
#include "lib/xma_utils.hpp"
#define XMAAPI_MOD "xmaxclbin"
/* Private function */
static int get_xclbin_iplayout(const char *buffer, XmaXclbinInfo *xclbin_info);
static int get_xclbin_mem_topology(const char *buffer, XmaXclbinInfo *xclbin_info);
static int get_xclbin_connectivity(const char *buffer, XmaXclbinInfo *xclbin_info);
std::vector<char> xma_xclbin_file_open(const std::string& xclbin_name)
{
xma_logmsg(XMA_INFO_LOG, XMAAPI_MOD, "Loading %s ", xclbin_name.c_str());
std::ifstream infile(xclbin_name, std::ios::binary | std::ios::ate);
if (!infile) {
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Failed to open xclbin file");
throw std::runtime_error("Failed to open xclbin file");
}
std::streamsize xclbin_size = infile.tellg();
infile.seekg(0, std::ios::beg);
std::vector<char> xclbin_buffer;
try {
xclbin_buffer.reserve(xclbin_size);
} catch (const std::bad_alloc& ex) {
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Could not allocate buffer for file %s ", xclbin_name.c_str());
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Buffer allocation error: %s ", ex.what());
throw;
} catch (...) {
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Could not allocate buffer for xclbin file %s ", xclbin_name.c_str());
throw;
}
infile.read(xclbin_buffer.data(), xclbin_size);
if (infile.gcount() != xclbin_size) {
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Unable to read full xclbin file %s ", xclbin_name.c_str());
throw std::runtime_error("Unable to read full xclbin file");
}
return xclbin_buffer;
}
static int32_t kernel_max_channel_id(const ip_data* ip, std::string kernel_channels)
{
if (kernel_channels.empty())
return -1;
std::string knm = std::string(reinterpret_cast<const char*>(ip->m_name));
knm = knm.substr(0,knm.find(":"));
auto pos1 = kernel_channels.find("{"+knm+":");
if (pos1 == std::string::npos)
return -1;
auto pos2 = kernel_channels.find("}",pos1);
if (pos2 == std::string::npos || pos2 < pos1+knm.size()+2)
return -2;
auto ctxid_str = kernel_channels.substr(pos1+knm.size()+2,pos2);
auto ctxid = std::stoi(ctxid_str);
if (ctxid < 0 || ctxid > 31)
return -3;
return ctxid;
}
static int get_xclbin_iplayout(const char *buffer, XmaXclbinInfo *xclbin_info)
{
const axlf *xclbin = reinterpret_cast<const axlf *>(buffer);
const axlf_section_header *ip_hdr = xclbin::get_axlf_section(xclbin, IP_LAYOUT);
if (ip_hdr)
{
const char *data = &buffer[ip_hdr->m_sectionOffset];
const ip_layout *ipl = reinterpret_cast<const ip_layout *>(data);
xclbin_info->number_of_kernels = 0;
xclbin_info->number_of_hardware_kernels = 0;
std::string kernel_channels_info = xrt_core::config::get_kernel_channel_info();
xclbin_info->cu_addrs_sorted = xrt_core::xclbin::get_cus(ipl, false);
bool has_cuisr = xrt_core::xclbin::get_cuisr(xclbin);
if (!has_cuisr) {
xma_logmsg(XMA_WARNING_LOG, XMAAPI_MOD, "One or more CUs do not support interrupt. Use RTL Wizard or Vitis for xclbin creation ");
}
auto& xma_ip_layout = xclbin_info->ip_layout;
for (int i = 0; i < ipl->m_count; i++) {
if (ipl->m_ip_data[i].m_type != IP_KERNEL)
continue;
if (xma_ip_layout.size() == MAX_XILINX_KERNELS) {
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "XMA supports max of only %d kernels per device ", MAX_XILINX_KERNELS);
throw std::runtime_error("XMA supports max of only " + std::to_string(MAX_XILINX_KERNELS) + " kernels per device");
}
XmaIpLayout temp_ip_layout;
temp_ip_layout.base_addr = ipl->m_ip_data[i].m_base_address;
temp_ip_layout.kernel_name = std::string((char*)ipl->m_ip_data[i].m_name);
using xarg = xrt_core::xclbin::kernel_argument;
static constexpr size_t no_index = xarg::no_index;
auto args = xrt_core::xclbin::get_kernel_arguments(xclbin, temp_ip_layout.kernel_name);
//Note: args are sorted by index; Assuming that offset will increase with arg index
//This is fair assumption; v++ or HLS decides on these offset values
std::vector<xarg> args2;
std::copy_if(args.begin(), args.end(), std::back_inserter(args2),
[](const xarg& y){return y.index != no_index;});
temp_ip_layout.arg_start = -1;
temp_ip_layout.regmap_size = -1;
if (args2.size() > 0) {
temp_ip_layout.arg_start = args2[0].offset;
auto& last = args2.back();
temp_ip_layout.regmap_size = last.offset + last.size;
if (temp_ip_layout.arg_start < 0x10) {
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "kernel %s doesn't meet argument register map spec of HLS/RTL Wizard kernels ", temp_ip_layout.kernel_name.c_str());
throw std::runtime_error("kernel doesn't meet argument register map spec of HLS/RTL Wizard kernels");
}
} else {
std::string knm = temp_ip_layout.kernel_name.substr(0,temp_ip_layout.kernel_name.find(":"));
args = xrt_core::xclbin::get_kernel_arguments(xclbin, knm);
std::vector<xarg> args3;
std::copy_if(args.begin(), args.end(), std::back_inserter(args3),
[](const xarg& y){return y.index != no_index;});
if (args3.size() > 0) {
temp_ip_layout.arg_start = args3[0].offset;
auto& last = args3.back();
temp_ip_layout.regmap_size = last.offset + last.size;
if (temp_ip_layout.arg_start < 0x10) {
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "kernel %s doesn't meet argument register map spec of HLS/RTL Wizard kernels ", temp_ip_layout.kernel_name.c_str());
throw std::runtime_error("kernel doesn't meet argument register map spec of HLS/RTL Wizard kernels");
}
}
}
temp_ip_layout.kernel_channels = false;
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "index = %lu, kernel name = %s, base_addr = %lx ",
xma_ip_layout.size(), temp_ip_layout.kernel_name.c_str(), temp_ip_layout.base_addr);
if (temp_ip_layout.regmap_size > MAX_KERNEL_REGMAP_SIZE) {
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "kernel %s register map size exceeds max limit. regmap_size: %d, max regmap_size: %d . Will use only max regmap_size", temp_ip_layout.kernel_name.c_str(), temp_ip_layout.regmap_size, MAX_KERNEL_REGMAP_SIZE);
//DRM IPs have registers at high offset
temp_ip_layout.regmap_size = MAX_KERNEL_REGMAP_SIZE;
//throw std::runtime_error("kernel regmap exceed's max size");
}
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "%s:- arg_start: 0x%x, regmap_size: 0x%x", temp_ip_layout.kernel_name.c_str(), temp_ip_layout.arg_start, temp_ip_layout.regmap_size);
auto cu_data = xrt_core::xclbin::get_cus(ipl, temp_ip_layout.kernel_name);
if (cu_data.size() > 0) {
if (((cu_data[0]->properties & IP_CONTROL_MASK) >> IP_CONTROL_SHIFT) == AP_CTRL_CHAIN) {
int32_t max_channel_id = kernel_max_channel_id(cu_data[0], kernel_channels_info);
if (max_channel_id >= 0) {
xma_logmsg(XMA_INFO_LOG, XMAAPI_MOD, "kernel \"%s\" is a dataflow kernel. channel_id will be handled by XMA. host app and plugins should not use reserved channle_id registers. Max channel_id is: %d ", temp_ip_layout.kernel_name.c_str(), max_channel_id);
temp_ip_layout.kernel_channels = true;
temp_ip_layout.max_channel_id = (uint32_t)max_channel_id;
} else {
if (max_channel_id == -1) {
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "kernel \"%s\" is a dataflow kernel. Use kernel_channels xrt.ini setting to enable handling of channel_id by XMA. Treatng it as legacy dataflow kernel and channels to be managed by host app and plugins ", temp_ip_layout.kernel_name.c_str());
} else if (max_channel_id == -2) {
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "kernel \"%s\" is a dataflow kernel. xrt.ini kernel_channels setting has incorrect format. setting found is: %s ", temp_ip_layout.kernel_name.c_str(), kernel_channels_info.c_str());
throw std::runtime_error("Incorrect dataflow kernel ini setting");
} else if (max_channel_id == -3) {
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "kernel \"%s\" is a dataflow kernel. xrt.ini kernel_channels setting only supports channel_ids from 0 to 31. setting found is: %s ", temp_ip_layout.kernel_name.c_str(), kernel_channels_info.c_str());
throw std::runtime_error("Incorrect dataflow kernel ini setting");
}
}
} else {
xma_logmsg(XMA_INFO_LOG, XMAAPI_MOD, "kernel \"%s\" is a legacy kernel. Channels to be managed by host app and plugins ", temp_ip_layout.kernel_name.c_str());
}
} else {
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "No CU for kernel %s in xclbin", temp_ip_layout.kernel_name.c_str());
throw std::runtime_error("Unexpected error. CU not found in xclbin");
}
temp_ip_layout.soft_kernel = false;
xma_ip_layout.emplace_back(std::move(temp_ip_layout));
}
xclbin_info->number_of_hardware_kernels = xma_ip_layout.size();
if (xclbin_info->number_of_hardware_kernels != xclbin_info->cu_addrs_sorted.size()) {
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Num of hardware kernels on this device = %ud. But num of sorted kernels = %lu", xclbin_info->number_of_hardware_kernels, xclbin_info->cu_addrs_sorted.size());
throw std::runtime_error("Unable to get sorted kernel list");
}
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "Num of hardware kernels on this device = %ud ", xclbin_info->number_of_hardware_kernels);
uint32_t num_soft_kernels = 0;
//Handle soft kernels just like another hardware IP_Layout kernel
//soft kernels to follow hardware kernels. so soft kenrel index will start after hardware kernels
auto soft_kernels = xrt_core::xclbin::get_softkernels(xclbin);
for (auto& sk: soft_kernels) {
if (num_soft_kernels + sk.ninst > MAX_XILINX_SOFT_KERNELS) {
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "XMA supports max of only %d soft kernels per device ", MAX_XILINX_SOFT_KERNELS);
throw std::runtime_error("XMA supports max of only " + std::to_string(MAX_XILINX_SOFT_KERNELS) + " soft kernels per device");
}
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "soft kernel name = %s, version = %s, symbol name = %s, num of instances = %d ", sk.mpo_name.c_str(), sk.mpo_version.c_str(), sk.symbol_name.c_str(), sk.ninst);
XmaIpLayout temp_ip_layout;
std::string str_tmp1;
for (uint32_t i = 0; i < sk.ninst; i++) {
str_tmp1 = std::string(sk.mpo_name);
str_tmp1 += "_";
str_tmp1 += std::to_string(i);
temp_ip_layout.kernel_name = str_tmp1;
temp_ip_layout.soft_kernel = true;
temp_ip_layout.base_addr = 0;
temp_ip_layout.arg_start = -1;
temp_ip_layout.regmap_size = -1;
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "index = %lu, soft kernel name = %s ", xma_ip_layout.size(), temp_ip_layout.kernel_name.c_str());
xma_ip_layout.emplace_back(std::move(temp_ip_layout));
num_soft_kernels++;
}
}
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "Num of soft kernels on this device = %ud ", num_soft_kernels);
xclbin_info->number_of_kernels = xma_ip_layout.size();
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "Num of total kernels on this device = %ud ", xclbin_info->number_of_kernels);
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, " ");
const axlf_section_header *xml_hdr = xclbin::get_axlf_section(xclbin, EMBEDDED_METADATA);
if (xml_hdr) {
char *xml_data = const_cast<char*>(&buffer[xml_hdr->m_sectionOffset]);
uint64_t xml_size = xml_hdr->m_sectionSize;
if (xml_size > 0 && xml_size < 500000) {
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "XML MetaData is:");
xma_core::utils::streambuf xml_streambuf(xml_data, xml_size);
std::istream xml_stream(&xml_streambuf);
std::string line;
while(std::getline(xml_stream, line)) {
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "%s", line.c_str());
}
}
} else {
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "XML MetaData is missing");
}
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, " ");
const axlf_section_header *kv_hdr = xclbin::get_axlf_section(xclbin, KEYVALUE_METADATA);
if (kv_hdr) {
char *kv_data = const_cast<char*>(&buffer[kv_hdr->m_sectionOffset]);
uint64_t kv_size = kv_hdr->m_sectionSize;
if (kv_size > 0 && kv_size < 200000) {
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "Key-Value MetaData is:");
xma_core::utils::streambuf kv_streambuf(kv_data, kv_size);
std::istream kv_stream(&kv_streambuf);
std::string line;
while(std::getline(kv_stream, line)) {
uint32_t lsize = line.size();
uint32_t pos = 0;
while (pos < lsize) {
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "%s", line.substr(pos, MAX_KERNEL_NAME).c_str());
pos += MAX_KERNEL_NAME;
}
}
}
} else {
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "Key-Value Data is not present in xclbin");
}
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, " ");
}
else
{
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Could not find IP_LAYOUT in xclbin ip_hdr=%p ", ip_hdr);
throw std::runtime_error("Could not find IP_LAYOUT in xclbin");
}
uuid_copy(xclbin_info->uuid, xclbin->m_header.uuid);
return XMA_SUCCESS;
}
static int get_xclbin_mem_topology(const char *buffer, XmaXclbinInfo *xclbin_info)
{
const axlf *xclbin = reinterpret_cast<const axlf *>(buffer);
const axlf_section_header *mem_hdr = xrt_core::xclbin::get_axlf_section(xclbin, MEM_TOPOLOGY);
if (!mem_hdr) {
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Could not find MEM TOPOLOGY in xclbin ");
throw std::runtime_error("Could not find MEM TOPOLOGY in xclbin file");
}
const char *data3 = &buffer[mem_hdr->m_sectionOffset];
auto mem_topo1 = reinterpret_cast<const mem_topology *>(data3);
auto mem_topo2 = const_cast<mem_topology*>(mem_topo1);
xclbin_info->has_mem_groups = false;
const axlf_section_header *mem_grp_hdr = xrt_core::xclbin::get_axlf_section(xclbin, ASK_GROUP_TOPOLOGY);
if (mem_grp_hdr) {
const char *data2 = &buffer[mem_grp_hdr->m_sectionOffset];
auto mem_grp_topo = reinterpret_cast<const mem_topology *>(data2);
if (mem_grp_topo->m_count > mem_topo1->m_count) {
xclbin_info->has_mem_groups = true;
mem_topo2 = const_cast<mem_topology*>(mem_grp_topo);
}
}
auto mem_topo = reinterpret_cast<const mem_topology *>(mem_topo2);
auto& xma_mem_topology = xclbin_info->mem_topology;
xclbin_info->number_of_mem_banks = mem_topo->m_count;
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "MEM TOPOLOGY - %ud banks ",xclbin_info->number_of_mem_banks);
if (xclbin_info->number_of_mem_banks > MAX_DDR_MAP) {
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "XMA supports max of only %d mem banks ", MAX_DDR_MAP);
throw std::runtime_error("XMA supports max of only " + std::to_string(MAX_DDR_MAP) + " mem banks");
}
for (int i = 0; i < mem_topo->m_count; i++) {
XmaMemTopology temp_mem_topology;
temp_mem_topology.m_type = mem_topo->m_mem_data[i].m_type;
temp_mem_topology.m_used = mem_topo->m_mem_data[i].m_used;
temp_mem_topology.m_size = mem_topo->m_mem_data[i].m_size;
temp_mem_topology.m_base_address = mem_topo->m_mem_data[i].m_base_address;
//m_tag is 16 chars
auto tmp_ptr = mem_topo->m_mem_data[i].m_tag;
temp_mem_topology.m_tag = {tmp_ptr, std::find(tmp_ptr, tmp_ptr+16, '\0')};//magic 16 from xclbin.h
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "index=%d, tag=%s, type = %ud, used = %ud, size = %lx, base = %lx ",
i,temp_mem_topology.m_tag.c_str(), temp_mem_topology.m_type, temp_mem_topology.m_used,
temp_mem_topology.m_size, temp_mem_topology.m_base_address);
xma_mem_topology.emplace_back(std::move(temp_mem_topology));
}
return XMA_SUCCESS;
}
static int get_xclbin_connectivity(const char *buffer, XmaXclbinInfo *xclbin_info)
{
const axlf *xclbin = reinterpret_cast<const axlf *>(buffer);
const axlf_section_header *ip_hdr = xrt_core::xclbin::get_axlf_section(xclbin, ASK_GROUP_CONNECTIVITY);
if (ip_hdr)
{
const char *data = &buffer[ip_hdr->m_sectionOffset];
const connectivity *axlf_conn = reinterpret_cast<const connectivity *>(data);
auto& xma_connectivity = xclbin_info->connectivity;
xclbin_info->number_of_connections = axlf_conn->m_count;
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "CONNECTIVITY - %d connections ",xclbin_info->number_of_connections);
for (int i = 0; i < axlf_conn->m_count; i++)
{
XmaAXLFConnectivity temp_conn;
temp_conn.arg_index = axlf_conn->m_connection[i].arg_index;
temp_conn.m_ip_layout_index = axlf_conn->m_connection[i].m_ip_layout_index;
temp_conn.mem_data_index = axlf_conn->m_connection[i].mem_data_index;
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "index = %d, arg_idx = %d, ip_idx = %d, mem_idx = %d ",
i, temp_conn.arg_index, temp_conn.m_ip_layout_index,
temp_conn.mem_data_index);
xma_connectivity.emplace_back(std::move(temp_conn));
}
}
else
{
xma_logmsg(XMA_ERROR_LOG, XMAAPI_MOD, "Could not find CONNECTIVITY in xclbin ip_hdr=%p ", ip_hdr);
throw std::runtime_error("Could not find CONNECTIVITY in xclbin file");
}
return XMA_SUCCESS;
}
int xma_xclbin_info_get(const char *buffer, XmaXclbinInfo *info)
{
get_xclbin_mem_topology(buffer, info);
get_xclbin_connectivity(buffer, info);
get_xclbin_iplayout(buffer, info);
memset(info->ip_ddr_mapping, 0, sizeof(info->ip_ddr_mapping));
uint64_t tmp_ddr_map = 0;
for(uint32_t c = 0; c < info->number_of_connections; c++)
{
auto& xma_conn = info->connectivity[c];
tmp_ddr_map = 1;
tmp_ddr_map = tmp_ddr_map << (xma_conn.mem_data_index);
info->ip_ddr_mapping[xma_conn.m_ip_layout_index] |= tmp_ddr_map;
}
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "CU DDR connections bitmap:");
for(uint32_t i = 0; i < info->number_of_hardware_kernels; i++)
{
xma_logmsg(XMA_DEBUG_LOG, XMAAPI_MOD, "\t%s - 0x%016llx ",info->ip_layout[i].kernel_name.c_str(), (unsigned long long)info->ip_ddr_mapping[i]);
}
return XMA_SUCCESS;
}
int xma_xclbin_map2ddr(uint64_t bit_map, int32_t* ddr_bank, bool has_mem_grps)
{
//64 bits based on MAX_DDR_MAP = 64
int ddr_bank_idx = 0;
if (!has_mem_grps) {
while (bit_map != 0) {
if (bit_map & 1) {
*ddr_bank = ddr_bank_idx;
return XMA_SUCCESS;
}
ddr_bank_idx++;
bit_map = bit_map >> 1;
}
} else {//For Memory Groups use last group as default memory group; For HBM groups
ddr_bank_idx = 63;
uint64_t tmp_int = 1ULL << 63;
while (bit_map != 0) {
if (bit_map & tmp_int) {
*ddr_bank = ddr_bank_idx;
return XMA_SUCCESS;
}
ddr_bank_idx--;
bit_map = bit_map << 1;
}
}
*ddr_bank = -1;
return XMA_ERROR;
}
| 21,660 | 7,890 |
#include "graph.h"
#include <algorithm>
#include <assert.h>
#include "store.h"
#include "ntcoding.h"
#include "seed_filter.h"
#include "tbb/scalable_allocator.h"
std::atomic<uint64_t> seeder_body::num_seed_hits(0);
std::atomic<uint64_t> seeder_body::num_seeds(0);
std::atomic<uint64_t> seeder_body::num_hsps(0);
std::atomic<uint32_t> seeder_body::total_xdrop(0);
std::atomic<uint32_t> seeder_body::num_seeded_regions(0);
bool sort_hsp(segmentPair x, segmentPair y){
if(x.query_start < y.query_start)
return true;
else if(x.query_start == y.query_start){
if(x.len < y.len)
return true;
else
return false;
}
return false;
}
printer_input seeder_body::operator()(seeder_input input) {
auto &payload = get<0>(input);
size_t token = get<1>(input);
auto &block_data = get<0>(payload);
auto &interval_data = get<1>(payload);
size_t block_start = block_data.start;
uint32_t block_len = block_data.len;
int block_index = block_data.index;
uint32_t start_pos = interval_data.start;
uint32_t end_pos = interval_data.end;
uint32_t ref_start = interval_data.ref_start;
uint32_t ref_end = interval_data.ref_end;
uint32_t num_invoked = interval_data.num_invoked;
uint32_t num_intervals = interval_data.num_intervals;
uint32_t start_pos_rc = block_len - 1 - end_pos;
uint32_t end_pos_rc = block_len - 1 - start_pos;
size_t rc_block_start = cfg.seq_len - 1 - block_start - (block_len - 1);
uint64_t kmer_index;
uint64_t transition_index;
uint64_t seed_offset;
std::vector<segmentPair> total_hsps;
total_hsps.clear();
uint8_t* int_count;
int_count = (uint8_t*) scalable_calloc(block_len, sizeof(uint8_t));
std::vector<Segment> total_intervals;
total_intervals.clear();
int32_t start;
int32_t end;
uint32_t old_num_hsps = 0;
uint32_t new_num_hsps = 0;
fprintf (stderr, "Chromosome block %u interval %u/%u (%lu:%lu) with ref (%u:%u) rc (%lu:%lu)\n", block_index, num_invoked, num_intervals, block_start+start_pos, block_start+end_pos, ref_start, ref_end, rc_block_start+start_pos_rc, rc_block_start+end_pos_rc);
for (uint32_t i = start_pos; i < end_pos; i += cfg.wga_chunk_size) {
//chunk limit positions
start = i;
end = std::min(start + cfg.wga_chunk_size, end_pos);
if(cfg.strand == "plus" || cfg.strand == "both"){
std::vector<uint64_t> seed_offset_vector;
seed_offset_vector.clear();
//start to end position in the chunk
for (uint32_t j = start; j < end; j++) {
kmer_index = GetKmerIndexAtPos(seq_DRAM->buffer, block_start+j, cfg.seed.size);
if (kmer_index != ((uint32_t) 1 << 31)) {
seed_offset = (kmer_index << 32) + j;
seed_offset_vector.push_back(seed_offset);
if (cfg.seed.transition) {
for (int t=0; t < cfg.seed.kmer_size; t++) {
if (IsTransitionAtPos(t) == 1) {
transition_index = (kmer_index ^ (TRANSITION_MASK << (2*t)));
seed_offset = (transition_index << 32) + j;
seed_offset_vector.push_back(seed_offset);
}
}
}
}
}
if(seed_offset_vector.size() > 0){
seeder_body::num_seeds += seed_offset_vector.size();
std::vector<segmentPair> anchors = g_SeedAndFilter(seed_offset_vector, false, ref_start, ref_end);
seeder_body::num_seed_hits += anchors[0].score;
if(anchors.size() > 1){
total_hsps.insert(total_hsps.end(), anchors.begin()+1, anchors.end());
seeder_body::num_hsps += anchors.size()-1;
}
}
}
if(cfg.strand == "minus" || cfg.strand == "both"){
//chunk limit positions
start = block_len - 1 - end;
end = std::min(start + cfg.wga_chunk_size, end_pos_rc);
std::vector<uint64_t> seed_offset_vector;
seed_offset_vector.clear();
for (uint32_t j = start; j < end; j++) {
kmer_index = GetKmerIndexAtPos(seq_rc_DRAM->buffer, (rc_block_start+j), cfg.seed.size);
if (kmer_index != ((uint32_t) 1 << 31)) {
seed_offset = (kmer_index << 32) + j;
seed_offset_vector.push_back(seed_offset);
if (cfg.seed.transition) {
for (int t=0; t < cfg.seed.kmer_size; t++) {
if (IsTransitionAtPos(t) == 1) {
transition_index = (kmer_index ^ (TRANSITION_MASK << (2*t)));
seed_offset = (transition_index << 32) + j;
seed_offset_vector.push_back(seed_offset);
}
}
}
}
}
if(seed_offset_vector.size() > 0){
seeder_body::num_seeds += seed_offset_vector.size();
std::vector<segmentPair> anchors = g_SeedAndFilter(seed_offset_vector, true, ref_start, ref_end);
seeder_body::num_seed_hits += anchors[0].score;
if(anchors.size() > 1){
total_hsps.insert(total_hsps.end(), anchors.rbegin(), anchors.rend()-1);
seeder_body::num_hsps += anchors.size()-1;
}
}
}
if(total_hsps.size() > 0){
std::sort(total_hsps.begin(), total_hsps.end(), sort_hsp);
for (auto hsp: total_hsps) {
for(int j = hsp.query_start; j < (hsp.query_start + hsp.len); j++){
int_count[j]++;
}
}
total_hsps.clear();
}
}
int run = 0;
int query_start = 0;
int len = 0;
for(int i = 0; i < block_len; i++){
if(int_count[i] >= cfg.M){
if(run == 0){
run = 1;
query_start = i;
}
len++;
}
else{
if(run == 1){
run = 0;
Segment s;
s.query_start = query_start;
s.len = len;
total_intervals.push_back(s);
}
query_start = 0;
len = 0;
}
}
scalable_free(int_count);
seeder_body::num_seeded_regions += 1;
seeder_body::total_xdrop += 1;
return printer_input(printer_payload(block_data, num_invoked, total_intervals), token);
}
| 6,801 | 2,349 |
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "ngraph/op/reduce_logical_and.hpp"
#include <ngraph/validation_util.hpp>
#include "itt.hpp"
#include "ngraph/log.hpp"
#include "ngraph/op/util/evaluate_helpers.hpp"
#include "ngraph/runtime/host_tensor.hpp"
#include "ngraph/runtime/reference/logical_reduction.hpp"
using namespace ngraph;
using namespace std;
OPENVINO_RTTI_DEFINITION(op::v1::ReduceLogicalAnd, "ReduceLogicalAnd", 1, util::LogicalReductionKeepDims);
op::v1::ReduceLogicalAnd::ReduceLogicalAnd(const Output<Node>& data,
const Output<Node>& reduction_axes,
const bool keep_dims)
: LogicalReductionKeepDims(data, reduction_axes, keep_dims) {
constructor_validate_and_infer_types();
}
shared_ptr<Node> op::v1::ReduceLogicalAnd::clone_with_new_inputs(const OutputVector& new_args) const {
NGRAPH_OP_SCOPE(v1_ReduceLogicalAnd_clone_with_new_inputs);
check_new_args_count(this, new_args);
return make_shared<op::v1::ReduceLogicalAnd>(new_args.at(0), new_args.at(1), get_keep_dims());
}
namespace reduce_and {
bool evaluate_reduce_logical_and(const HostTensorPtr& data,
const HostTensorPtr& out,
const AxisSet& reduction_axes,
bool keep_dims) {
out->set_shape(reduce(data->get_shape(), reduction_axes, keep_dims));
try {
runtime::reference::reduce_logical_and(data->get_data_ptr<char>(),
out->get_data_ptr<char>(),
data->get_shape(),
reduction_axes);
return true;
} catch (const ngraph_error& e) {
NGRAPH_WARN << e.what();
return false;
}
}
} // namespace reduce_and
bool op::v1::ReduceLogicalAnd::evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs) const {
NGRAPH_OP_SCOPE(v1_ReduceLogicalAnd_evaluate);
NGRAPH_CHECK(validate_host_tensor_vector(inputs, 2));
NGRAPH_CHECK(validate_host_tensor_vector(outputs, 1));
const auto& data = inputs[0];
const auto& axes = inputs[1];
const auto& out = outputs[0];
if (data->get_element_type() != element::boolean || !axes->get_element_type().is_integral_number()) {
return false;
}
const auto reduction_axes =
get_normalized_axes_from_tensor(axes, data->get_partial_shape().rank(), get_friendly_name());
return reduce_and::evaluate_reduce_logical_and(data, out, reduction_axes, get_keep_dims());
}
bool op::v1::ReduceLogicalAnd::has_evaluate() const {
NGRAPH_OP_SCOPE(v1_ReduceLogicalAnd_has_evaluate);
return get_input_element_type(0) == element::boolean && get_input_element_type(1).is_integral_number();
}
| 2,895 | 981 |
// Given a string, your task is to count how many palindromic substrings in
// this string.
// The substrings with different start indexes or end indexes are counted as
// different substrings even they consist of same characters.
// Example 1:
// Input: "abc"
// Output: 3
// Explanation: Three palindromic strings: "a", "b", "c".
// Example 2:
// Input: "aaa"
// Output: 6
// Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
// Note:
// The input string length won't exceed 1000.
// Manacher’s Algorithm
// https://articles.leetcode.com/longest-palindromic-substring-part-ii/
// https://www.felix021.com/blog/read.php?2040
class Solution {
string prepare(const string &s) {
stringstream Ts("^");
for (auto &&c : s)
Ts << '#' << c;
if (!s.empty())
Ts << '#';
Ts << '$';
return Ts.str();
}
public:
int countSubstrings(string s) {
string T = prepare(s); // transformed string
vector<int> P(T.size()); // longest palindrome
int C = 0, R = 0; // center, right
for (int i = 1; i < T.size() - 1; ++i) {
P[i] = R > i ? min(R - i, P[2 * C - i]) : 0;
while (T[i + P[i] + 1] == T[i - P[i] - 1])
++P[i];
if (i + P[i] > R) {
C = i;
R = i + P[i];
}
}
int ret = 0;
for (auto &&pl : P)
ret += (pl + 1) / 2;
return ret;
}
};
// method 2, extend center
class Solution {
public:
int countSubstrings(string S) {
int n = S.size();
int ret = 0, l, r;
for (int i = 0; i < n; ++i) {
l = r = i;
while (l >= 0 && r < n && S[l--] == S[r++])
++ret;
l = i, r = i + 1;
while (l >= 0 && r < n && S[l--] == S[r++])
++ret;
}
return ret;
}
};
// method 3, dp, TODO | 1,967 | 714 |
/**
* author: etohirse
* created: 26.12.2020 15:54:25
**/
#include <fstream>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
std::ifstream fin("beyond_the_wall.in");
std::ofstream fout("beyond_the_wall.out");
const int mxn = 4e4;
std::pair<int, int> av[mxn];
int main() {
int n, q;
fin >> n >> q;
for (int i = 0; i < n; ++i) {
fin >> av[i].first >> av[i].second;
}
while (q--) {
int a, b, nr = 0;
long long ans;
fin >> a >> b;
for (int i = 0; i < n; ++i) {
ans = a * av[i].first - av[i].second + b;
nr += (ans > 0);
}
fout << nr << '\n';
}
return 0;
}
| 640 | 297 |
// Copyright 2018 U.C. Berkeley RISE Lab
//
// 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 "yaml-cpp/yaml.h"
#include "causal_cache_handlers.hpp"
#include "causal_cache_utils.hpp"
ZmqUtil zmq_util;
ZmqUtilInterface* kZmqUtil = &zmq_util;
void run(KvsAsyncClientInterface* client, Address ip, unsigned thread_id) {
string log_file = "causal_cache_log_" + std::to_string(thread_id) + ".txt";
string log_name = "causal_cache_log_" + std::to_string(thread_id);
auto log = spdlog::basic_logger_mt(log_name, log_file, true);
log->flush_on(spdlog::level::info);
zmq::context_t* context = client->get_context();
SocketCache pushers(context, ZMQ_PUSH);
// keep track of keys that this causal cache is responsible for
set<Key> key_set;
StoreType unmerged_store;
InPreparationType in_preparation;
StoreType causal_cut_store;
VersionStoreType version_store;
map<Key, set<Key>> to_fetch_map;
map<Key, std::unordered_map<VectorClock, set<Key>, VectorClockHash>>
cover_map;
map<Key, set<Address>> single_callback_map;
map<Address, PendingClientMetadata> pending_single_metadata;
map<Address, PendingClientMetadata> pending_cross_metadata;
// mapping from client id to a set of response address of GET request
map<string, set<Address>> client_id_to_address_map;
// mapping from request id to response address of PUT request
map<string, Address> request_id_to_address_map;
CausalCacheThread cct = CausalCacheThread(ip, thread_id);
// TODO: can we find a way to make the thread classes uniform across
// languages? or unify the python and cpp implementations; actually, mostly
// just the user thread stuff, I think.
zmq::socket_t get_puller(*context, ZMQ_PULL);
get_puller.bind(cct.causal_cache_get_bind_address());
zmq::socket_t put_puller(*context, ZMQ_PULL);
put_puller.bind(cct.causal_cache_put_bind_address());
zmq::socket_t update_puller(*context, ZMQ_PULL);
update_puller.bind(cct.causal_cache_update_bind_address());
zmq::socket_t version_gc_puller(*context, ZMQ_PULL);
version_gc_puller.bind(cct.causal_cache_version_gc_bind_address());
zmq::socket_t versioned_key_request_puller(*context, ZMQ_PULL);
versioned_key_request_puller.bind(
cct.causal_cache_versioned_key_request_bind_address());
zmq::socket_t versioned_key_response_puller(*context, ZMQ_PULL);
versioned_key_response_puller.bind(
cct.causal_cache_versioned_key_response_bind_address());
vector<zmq::pollitem_t> pollitems = {
{static_cast<void*>(get_puller), 0, ZMQ_POLLIN, 0},
{static_cast<void*>(put_puller), 0, ZMQ_POLLIN, 0},
{static_cast<void*>(update_puller), 0, ZMQ_POLLIN, 0},
{static_cast<void*>(version_gc_puller), 0, ZMQ_POLLIN, 0},
{static_cast<void*>(versioned_key_request_puller), 0, ZMQ_POLLIN, 0},
{static_cast<void*>(versioned_key_response_puller), 0, ZMQ_POLLIN, 0},
};
auto report_start = std::chrono::system_clock::now();
auto report_end = std::chrono::system_clock::now();
auto migrate_start = std::chrono::system_clock::now();
auto migrate_end = std::chrono::system_clock::now();
while (true) {
kZmqUtil->poll(0, &pollitems);
// handle a GET request
if (pollitems[0].revents & ZMQ_POLLIN) {
string serialized = kZmqUtil->recv_string(&get_puller);
get_request_handler(serialized, key_set, unmerged_store, in_preparation,
causal_cut_store, version_store, single_callback_map,
pending_single_metadata, pending_cross_metadata,
to_fetch_map, cover_map, pushers, client, log, cct,
client_id_to_address_map);
}
// handle a PUT request
if (pollitems[1].revents & ZMQ_POLLIN) {
string serialized = kZmqUtil->recv_string(&put_puller);
put_request_handler(serialized, unmerged_store, causal_cut_store,
version_store, request_id_to_address_map, client,
log);
}
// handle updates received from the KVS
if (pollitems[2].revents & ZMQ_POLLIN) {
string serialized = kZmqUtil->recv_string(&update_puller);
KeyRequest updates;
updates.ParseFromString(serialized);
for (const KeyTuple& tuple : updates.tuples()) {
Key key = tuple.key();
// if we are no longer caching this key, then we simply ignore updates
// for it because we received the update based on outdated information
if (key_set.find(key) == key_set.end()) {
continue;
}
auto lattice = std::make_shared<CrossCausalLattice<SetLattice<string>>>(
to_cross_causal_payload(deserialize_cross_causal(tuple.payload())));
process_response(key, lattice, unmerged_store, in_preparation,
causal_cut_store, version_store, single_callback_map,
pending_single_metadata, pending_cross_metadata,
to_fetch_map, cover_map, pushers, client, log, cct,
client_id_to_address_map);
}
}
// handle version GC request
if (pollitems[3].revents & ZMQ_POLLIN) {
// assume this string is the client id
string serialized = kZmqUtil->recv_string(&version_gc_puller);
version_store.erase(serialized);
}
// handle versioned key request
if (pollitems[4].revents & ZMQ_POLLIN) {
string serialized = kZmqUtil->recv_string(&versioned_key_request_puller);
versioned_key_request_handler(serialized, version_store, pushers, log,
kZmqUtil);
}
// handle versioned key response
if (pollitems[5].revents & ZMQ_POLLIN) {
string serialized = kZmqUtil->recv_string(&versioned_key_response_puller);
versioned_key_response_handler(
serialized, causal_cut_store, version_store, pending_cross_metadata,
client_id_to_address_map, cct, pushers, kZmqUtil, log);
}
vector<KeyResponse> responses = client->receive_async(kZmqUtil);
for (const auto& response : responses) {
kvs_response_handler(response, unmerged_store, in_preparation,
causal_cut_store, version_store, single_callback_map,
pending_single_metadata, pending_cross_metadata,
to_fetch_map, cover_map, pushers, client, log, cct,
client_id_to_address_map, request_id_to_address_map);
}
// collect and store internal statistics
report_end = std::chrono::system_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::seconds>(
report_end - report_start)
.count();
// update KVS with information about which keys this node is currently
// caching; we only do this periodically because we are okay with receiving
// potentially stale updates
if (duration >= kCausalCacheReportThreshold) {
KeySet set;
for (const auto& pair : unmerged_store) {
set.add_keys(pair.first);
}
string serialized;
set.SerializeToString(&serialized);
LWWPairLattice<string> val(TimestampValuePair<string>(
generate_timestamp(thread_id), serialized));
Key key = get_user_metadata_key(ip, UserMetadataType::cache_ip);
client->put_async(key, serialize(val), LatticeType::LWW);
report_start = std::chrono::system_clock::now();
}
migrate_end = std::chrono::system_clock::now();
duration = std::chrono::duration_cast<std::chrono::seconds>(migrate_end -
migrate_start)
.count();
// check if any key in unmerged_store is newer and migrate
if (duration >= kMigrateThreshold) {
periodic_migration_handler(
unmerged_store, in_preparation, causal_cut_store, version_store,
pending_cross_metadata, to_fetch_map, cover_map, pushers, client, cct,
client_id_to_address_map, log);
migrate_start = std::chrono::system_clock::now();
}
// TODO: check if cache size is exceeding (threshold x capacity) and evict.
}
}
int main(int argc, char* argv[]) {
if (argc > 1) {
std::cerr << "Usage: " << argv[0] << "" << std::endl;
return 1;
}
// read the YAML conf
YAML::Node conf = YAML::LoadFile("conf/kvs-config.yml");
unsigned kRoutingThreadCount = conf["threads"]["routing"].as<unsigned>();
YAML::Node user = conf["user"];
Address ip = user["ip"].as<Address>();
vector<Address> routing_ips;
if (YAML::Node elb = user["routing-elb"]) {
routing_ips.push_back(elb.as<Address>());
} else {
YAML::Node routing = user["routing"];
for (const YAML::Node& node : routing) {
routing_ips.push_back(node.as<Address>());
}
}
vector<UserRoutingThread> threads;
for (Address addr : routing_ips) {
for (unsigned i = 0; i < kRoutingThreadCount; i++) {
threads.push_back(UserRoutingThread(addr, i));
}
}
KvsAsyncClient cl(threads, ip, 0, 10000);
KvsAsyncClientInterface* client = &cl;
run(client, ip, 0);
} | 9,657 | 3,184 |
/*
Copyright (c) 2006, Michael Kazhdan and Matthew Bolitho
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 Johns Hopkins University 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 "PoissonRecon.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#ifdef _WIN32
#include <Windows.h>
#include <Psapi.h>
#endif // _WIN32
#include "MyTime.h"
#include "MarchingCubes.h"
#include "Octree.h"
#include "SparseMatrix.h"
#include "CmdLineParser.h"
#include "PPolynomial.h"
#include "Ply.h"
#include "MemoryUsage.h"
#ifdef _OPENMP
#include "omp.h"
#endif // _OPENMP
void DumpOutput( const char* format , ... );
#include "MultiGridOctreeData.h"
void DumpOutput2( std::vector< char* >& comments , const char* format , ... );
#define DEFAULT_FULL_DEPTH 5
#define XSTR(x) STR(x)
#define STR(x) #x
#if DEFAULT_FULL_DEPTH
#pragma message ( "[WARNING] Setting default full depth to " XSTR(DEFAULT_FULL_DEPTH) )
#endif // DEFAULT_FULL_DEPTH
#include <stdarg.h>
#include <iostream>
char* outputFile=NULL;
int echoStdout=0;
void DumpOutput( const char* format , ... )
{
if( outputFile )
{
FILE* fp = fopen( outputFile , "a" );
va_list args;
va_start( args , format );
vfprintf( fp , format , args );
fclose( fp );
va_end( args );
}
if( echoStdout )
{
va_list args;
va_start( args , format );
vprintf( format , args );
va_end( args );
}
}
void DumpOutput2( std::vector< char* >& comments , const char* format , ... )
{
if( outputFile )
{
FILE* fp = fopen( outputFile , "a" );
va_list args;
va_start( args , format );
vfprintf( fp , format , args );
fclose( fp );
va_end( args );
}
if( echoStdout )
{
va_list args;
va_start( args , format );
vprintf( format , args );
va_end( args );
}
comments.push_back( new char[1024] );
char* str = comments.back();
va_list args;
va_start( args , format );
vsprintf( str , format , args );
va_end( args );
if( str[strlen(str)-1]=='\n' ) str[strlen(str)-1] = 0;
}
cmdLineString
In( "in" ) ,
Out( "out" ) ,
VoxelGrid( "voxel" ) ,
XForm( "xForm" );
cmdLineReadable
#ifdef _WIN32
Performance( "performance" ) ,
#endif // _WIN32
Complete( "complete" ) ,
ShowResidual( "showResidual" ) ,
NoComments( "noComments" ) ,
PolygonMesh( "polygonMesh" ) ,
Confidence( "confidence" ) ,
NormalWeights( "nWeights" ) ,
NonManifold( "nonManifold" ) ,
ASCII( "ascii" ) ,
Density( "density" ) ,
Verbose( "verbose" ) ,
Double( "double" );
cmdLineInt
Depth( "depth" , 8 ) ,
CGDepth( "cgDepth" , 0 ) ,
KernelDepth( "kernelDepth" ) ,
AdaptiveExponent( "adaptiveExp" , 1 ) ,
Iters( "iters" , 8 ) ,
VoxelDepth( "voxelDepth" , -1 ) ,
FullDepth( "fullDepth" , DEFAULT_FULL_DEPTH ) ,
MinDepth( "minDepth" , 0 ) ,
MaxSolveDepth( "maxSolveDepth" ) ,
BoundaryType( "boundary" , 1 ) ,
Threads( "threads" , omp_get_num_procs() );
cmdLineFloat
Color( "color" , 16.f ) ,
SamplesPerNode( "samplesPerNode" , 1.5f ) ,
Scale( "scale" , 1.1f ) ,
CSSolverAccuracy( "cgAccuracy" , float(1e-3) ) ,
PointWeight( "pointWeight" , 4.f );
cmdLineReadable* params[] =
{
&In , &Depth , &Out , &XForm ,
&Scale , &Verbose , &CSSolverAccuracy , &NoComments , &Double ,
&KernelDepth , &SamplesPerNode , &Confidence , &NormalWeights , &NonManifold , &PolygonMesh , &ASCII , &ShowResidual , &VoxelDepth ,
&PointWeight , &VoxelGrid , &Threads , &MaxSolveDepth ,
&AdaptiveExponent , &BoundaryType ,
&Density ,
&FullDepth ,
&MinDepth ,
&CGDepth , &Iters ,
&Complete ,
&Color ,
#ifdef _WIN32
&Performance ,
#endif // _WIN32
};
void ShowUsage(char *ex)
{
printf( "Usage: %s\n" , ex );
printf( "\t --%s <input points>\n" , In.name );
printf( "\t[--%s <ouput triangle mesh>]\n" , Out.name );
printf( "\t[--%s <ouput voxel grid>]\n" , VoxelGrid.name );
printf( "\t[--%s <maximum reconstruction depth>=%d]\n" , Depth.name , Depth.value );
printf( "\t\t Running at depth d corresponds to solving on a 2^d x 2^d x 2^d\n" );
printf( "\t\t voxel grid.\n" );
printf( "\t[--%s <full depth>=%d]\n" , FullDepth.name , FullDepth.value );
printf( "\t\t This flag specifies the depth up to which the octree should be complete.\n" );
printf( "\t[--%s <depth at which to extract the voxel grid>=<%s>]\n" , VoxelDepth.name , Depth.name );
printf( "\t[--%s <conjugate-gradients depth>=%d]\n" , CGDepth.name , CGDepth.value );
printf( "\t\t The depth up to which a conjugate-gradients solver should be used.\n");
printf( "\t[--%s <scale factor>=%f]\n" , Scale.name , Scale.value );
printf( "\t\t Specifies the factor of the bounding cube that the input\n" );
printf( "\t\t samples should fit into.\n" );
printf( "\t[--%s <minimum number of samples per node>=%f]\n" , SamplesPerNode.name, SamplesPerNode.value );
printf( "\t\t This parameter specifies the minimum number of points that\n" );
printf( "\t\t should fall within an octree node.\n" );
printf( "\t[--%s <interpolation weight>=%f]\n" , PointWeight.name , PointWeight.value );
printf( "\t\t This value specifies the weight that point interpolation constraints are\n" );
printf( "\t\t given when defining the (screened) Poisson system.\n" );
printf( "\t[--%s <iterations>=%d]\n" , Iters.name , Iters.value );
printf( "\t\t This flag specifies the (maximum if CG) number of solver iterations.\n" );
printf( "\t[--%s <pull factor>]\n" , Color.name );
printf( "\t\t This flag specifies the pull factor for color interpolation\n" );
#ifdef _OPENMP
printf( "\t[--%s <num threads>=%d]\n" , Threads.name , Threads.value );
printf( "\t\t This parameter specifies the number of threads across which\n" );
printf( "\t\t the solver should be parallelized.\n" );
#endif // _OPENMP
printf( "\t[--%s]\n" , Confidence.name );
printf( "\t\t If this flag is enabled, the size of a sample's normals is\n" );
printf( "\t\t used as a confidence value, affecting the sample's\n" );
printf( "\t\t constribution to the reconstruction process.\n" );
printf( "\t[--%s]\n" , NormalWeights.name );
printf( "\t\t If this flag is enabled, the size of a sample's normals is\n" );
printf( "\t\t used as to modulate the interpolation weight.\n" );
#if 0
printf( "\t[--%s]\n" , NonManifold.name );
printf( "\t\t If this flag is enabled, the isosurface extraction does not add\n" );
printf( "\t\t a planar polygon's barycenter in order to ensure that the output\n" );
printf( "\t\t mesh is manifold.\n" );
#endif
printf( "\t[--%s]\n" , PolygonMesh.name);
printf( "\t\t If this flag is enabled, the isosurface extraction returns polygons\n" );
printf( "\t\t rather than triangles.\n" );
#if 0
printf( "\t[--%s <minimum depth>=%d]\n" , MinDepth.name , MinDepth.value );
printf( "\t\t This flag specifies the coarsest depth at which the system is to be solved.\n" );
printf( "\t[--%s <cg solver accuracy>=%g]\n" , CSSolverAccuracy.name , CSSolverAccuracy.value );
printf( "\t\t This flag specifies the accuracy cut-off to be used for CG.\n" );
printf( "\t[--%s <adaptive weighting exponent>=%d]\n", AdaptiveExponent.name , AdaptiveExponent.value );
printf( "\t\t This flag specifies the exponent scale for the adaptive weighting.\n" );
#ifdef _WIN32
printf( "\t[--%s]\n" , Performance.name );
printf( "\t\t If this flag is enabled, the running time and peak memory usage\n" );
printf( "\t\t is output after the reconstruction.\n" );
#endif // _WIN32
#endif
printf( "\t[--%s]\n" , Density.name );
printf( "\t\t If this flag is enabled, the sampling density is written out with the vertices.\n" );
#if 0
printf( "\t[--%s]\n" , ASCII.name );
printf( "\t\t If this flag is enabled, the output file is written out in ASCII format.\n" );
printf( "\t[--%s]\n" , NoComments.name );
printf( "\t\t If this flag is enabled, the output file will not include comments.\n" );
#endif
printf( "\t[--%s]\n" , Double.name );
printf( "\t\t If this flag is enabled, the reconstruction will be performed with double-precision floats.\n" );
printf( "\t[--%s]\n" , Verbose.name );
printf( "\t\t If this flag is enabled, the progress of the reconstructor will be output to STDOUT.\n" );
}
Point3D< unsigned char > ReadASCIIColor( FILE* fp )
{
Point3D< unsigned char > c;
if( fscanf( fp , " %c %c %c " , &c[0] , &c[1] , &c[2] )!=3 ) fprintf( stderr , "[ERROR] Failed to read color\n" ) , exit( 0 );
return c;
}
PlyProperty PlyColorProperties[]=
{
{ "r" , PLY_UCHAR , PLY_UCHAR , int( offsetof( Point3D< unsigned char > , coords[0] ) ) , 0 , 0 , 0 , 0 } ,
{ "g" , PLY_UCHAR , PLY_UCHAR , int( offsetof( Point3D< unsigned char > , coords[1] ) ) , 0 , 0 , 0 , 0 } ,
{ "b" , PLY_UCHAR , PLY_UCHAR , int( offsetof( Point3D< unsigned char > , coords[2] ) ) , 0 , 0 , 0 , 0 } ,
{ "red" , PLY_UCHAR , PLY_UCHAR , int( offsetof( Point3D< unsigned char > , coords[0] ) ) , 0 , 0 , 0 , 0 } ,
{ "green" , PLY_UCHAR , PLY_UCHAR , int( offsetof( Point3D< unsigned char > , coords[1] ) ) , 0 , 0 , 0 , 0 } ,
{ "blue" , PLY_UCHAR , PLY_UCHAR , int( offsetof( Point3D< unsigned char > , coords[2] ) ) , 0 , 0 , 0 , 0 }
};
bool ValidPlyColorProperties( const bool* props ){ return ( props[0] || props[3] ) && ( props[1] || props[4] ) && ( props[2] || props[5] ); }
template< class Real , class Vertex >
int Execute( int argc , char* argv[] )
{
Reset< Real >();
int paramNum = sizeof(params)/sizeof(cmdLineReadable*);
std::vector< char* > comments;
if( Verbose.set ) echoStdout=1;
XForm4x4< Real > xForm , iXForm;
if( XForm.set )
{
FILE* fp = fopen( XForm.value , "r" );
if( !fp )
{
fprintf( stderr , "[WARNING] Could not read x-form from: %s\n" , XForm.value );
xForm = XForm4x4< Real >::Identity();
}
else
{
for( int i=0 ; i<4 ; i++ ) for( int j=0 ; j<4 ; j++ )
{
float f;
if( fscanf( fp , " %f " , &f )!=1 ) fprintf( stderr , "[ERROR] Execute: Failed to read xform\n" ) , exit( 0 );
xForm(i,j) = (Real)f;
}
fclose( fp );
}
}
else xForm = XForm4x4< Real >::Identity();
iXForm = xForm.inverse();
DumpOutput2( comments , "Running Screened Poisson Reconstruction (Version 7.0)\n" );
char str[1024];
for( int i=0 ; i<paramNum ; i++ )
if( params[i]->set )
{
params[i]->writeValue( str );
if( strlen( str ) ) DumpOutput2( comments , "\t--%s %s\n" , params[i]->name , str );
else DumpOutput2( comments , "\t--%s\n" , params[i]->name );
}
double t;
double tt=Time();
Real isoValue = 0;
Octree< Real > tree;
tree.threads = Threads.value;
if( !In.set )
{
ShowUsage(argv[0]);
return 0;
}
if( !MaxSolveDepth.set ) MaxSolveDepth.value = Depth.value;
OctNode< TreeNodeData >::SetAllocator( MEMORY_ALLOCATOR_BLOCK_SIZE );
t=Time();
int kernelDepth = KernelDepth.set ? KernelDepth.value : Depth.value-2;
if( kernelDepth>Depth.value )
{
fprintf( stderr,"[ERROR] %s can't be greater than %s: %d <= %d\n" , KernelDepth.name , Depth.name , KernelDepth.value , Depth.value );
return EXIT_FAILURE;
}
double maxMemoryUsage;
t=Time() , tree.maxMemoryUsage=0;
typename Octree< Real >::template SparseNodeData< typename Octree< Real >::PointData >* pointInfo = new typename Octree< Real >::template SparseNodeData< typename Octree< Real >::PointData >();
typename Octree< Real >::template SparseNodeData< Point3D< Real > >* normalInfo = new typename Octree< Real >::template SparseNodeData< Point3D< Real > >();
std::vector< Real >* kernelDensityWeights = new std::vector< Real >();
std::vector< Real >* centerWeights = new std::vector< Real >();
int pointCount;
typedef typename Octree< Real >::template ProjectiveData< Point3D< Real > > ProjectiveColor;
typename Octree< Real >::template SparseNodeData< ProjectiveColor > colorData;
char* ext = GetFileExtension( In.value );
if( Color.set && Color.value>0 )
{
OrientedPointStreamWithData< float , Point3D< unsigned char > >* pointStream;
if ( !strcasecmp( ext , "bnpts" ) ) pointStream = new BinaryOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value );
else if( !strcasecmp( ext , "ply" ) ) pointStream = new PLYOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value , PlyColorProperties , 6 , ValidPlyColorProperties );
else pointStream = new ASCIIOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value , ReadASCIIColor );
pointCount = tree.template SetTree< float >( pointStream , MinDepth.value , Depth.value , FullDepth.value , kernelDepth , Real(SamplesPerNode.value) , Scale.value , Confidence.set , NormalWeights.set , PointWeight.value , AdaptiveExponent.value , *kernelDensityWeights , *pointInfo , *normalInfo , *centerWeights , colorData , xForm , BoundaryType.value , Complete.set );
delete pointStream;
for( const OctNode< TreeNodeData >* n = tree.tree.nextNode() ; n!=NULL ; n=tree.tree.nextNode( n ) )
{
int idx = colorData.index( n );
if( idx>=0 ) colorData.data[idx] *= (Real)pow( Color.value , n->depth() );
}
}
else
{
OrientedPointStream< float >* pointStream;
if ( !strcasecmp( ext , "bnpts" ) ) pointStream = new BinaryOrientedPointStream< float >( In.value );
else if( !strcasecmp( ext , "ply" ) ) pointStream = new PLYOrientedPointStream< float >( In.value );
else pointStream = new ASCIIOrientedPointStream< float >( In.value );
pointCount = tree.template SetTree< float >( pointStream , MinDepth.value
, Depth.value , FullDepth.value , kernelDepth , Real(SamplesPerNode.value)
, Scale.value , Confidence.set , NormalWeights.set , PointWeight.value
, AdaptiveExponent.value , *kernelDensityWeights , *pointInfo , *normalInfo
, *centerWeights , xForm , BoundaryType.value , Complete.set );
delete pointStream;
}
delete[] ext;
if( !Density.set ) delete kernelDensityWeights , kernelDensityWeights = NULL;
DumpOutput2( comments , "# Tree set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
DumpOutput( "Input Points: %d\n" , pointCount );
DumpOutput( "Leaves/Nodes: %d/%d\n" , tree.tree.leaves() , tree.tree.nodes() );
DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) );
maxMemoryUsage = tree.maxMemoryUsage;
t=Time() , tree.maxMemoryUsage=0;
Pointer( Real ) constraints = tree.SetLaplacianConstraints( *normalInfo );
delete normalInfo;
DumpOutput2( comments , "# Constraints set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage())/(1<<20) );
maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );
t=Time() , tree.maxMemoryUsage=0;
Pointer( Real ) solution = tree.SolveSystem( *pointInfo , constraints , ShowResidual.set , Iters.value , MaxSolveDepth.value , CGDepth.value , CSSolverAccuracy.value );
delete pointInfo;
FreePointer( constraints );
DumpOutput2( comments , "# Linear system solved in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) );
maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );
CoredFileMeshData< Vertex > mesh;
if( Verbose.set ) tree.maxMemoryUsage=0;
t=Time();
isoValue = tree.GetIsoValue( solution , *centerWeights );
delete centerWeights;
DumpOutput( "Got average in: %f\n" , Time()-t );
DumpOutput( "Iso-Value: %e\n" , isoValue );
Real scale = tree.GetScale();
// std::cout<<"iso value: "<<isoValue<<std::endl;
// std::cout<<"scale: "<<scale<<std::endl;
Point3D<Real> center = tree.GetCenter();
// std::cout<<"center: "<<center[0]<<", "<<center[1]<<", "<<center[2]<<std::endl;
if( VoxelGrid.set )
{
double t = Time();
FILE* fp = fopen( VoxelGrid.value , "wb" );
if( !fp ) fprintf( stderr , "Failed to open voxel file for writing: %s\n" , VoxelGrid.value );
else
{
int res = 0;
Pointer( Real ) values = tree.Evaluate( ( ConstPointer( Real ) )solution , res , isoValue , VoxelDepth.value );
fwrite(&res , sizeof(int) , 1 , fp );
fwrite(&scale, sizeof(float), 1, fp);
fwrite(¢er, sizeof(float), 3, fp);
// std::cout<<"res: "<<res<<std::endl;
// for( int i=0 ; i<res*res*res ; i++ ) {
// std::cout << float( values[i] )<<" ";
// }
// std::cout<<std::endl;
if( sizeof(Real)==sizeof(float) ) fwrite( values , sizeof(float) , res*res*res , fp );
else
{
float *fValues = new float[res*res*res];
for( int i=0 ; i<res*res*res ; i++ ){
fValues[i] = float( values[i] );
}
fwrite( fValues , sizeof(float) , res*res*res , fp );
delete[] fValues;
}
fclose( fp );
DeletePointer( values );
}
DumpOutput( "Got voxel grid in: %f\n" , Time()-t );
}
if( Out.set )
{
t = Time() , tree.maxMemoryUsage = 0;
tree.GetMCIsoSurface( kernelDensityWeights ? GetPointer( *kernelDensityWeights ) : NullPointer( Real ) , Color.set ? &colorData : NULL , solution , isoValue , mesh , true , !NonManifold.set , PolygonMesh.set );
if( PolygonMesh.set ) DumpOutput2( comments , "# Got polygons in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
else DumpOutput2( comments , "# Got triangles in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );
DumpOutput2( comments , "# Total Solve: %9.1f (s), %9.1f (MB)\n" , Time()-tt , maxMemoryUsage );
if( NoComments.set )
{
if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII , NULL , 0 , iXForm );
else PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , NULL , 0 , iXForm );
}
else
{
if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII , &comments[0] , (int)comments.size() , iXForm );
else PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , &comments[0] , (int)comments.size() , iXForm );
}
DumpOutput( "Vertices / Polygons: %d / %d\n" , mesh.outOfCorePointCount()+mesh.inCorePoints.size() , mesh.polygonCount() );
}
FreePointer( solution );
return 1;
}
#ifdef _WIN32
inline double to_seconds( const FILETIME& ft )
{
const double low_to_sec=100e-9; // 100 nanoseconds
const double high_to_sec=low_to_sec*4294967296.0;
return ft.dwLowDateTime*low_to_sec+ft.dwHighDateTime*high_to_sec;
}
#endif // _WIN32
#if 0
int poissonRecon( const char* input_file_name, const char * output_filename)
{
#if defined(WIN32) && defined(MAX_MEMORY_GB)
if( MAX_MEMORY_GB>0 )
{
SIZE_T peakMemory = 1;
peakMemory <<= 30;
peakMemory *= MAX_MEMORY_GB;
printf( "Limiting memory usage to %.2f GB\n" , float( peakMemory>>30 ) );
HANDLE h = CreateJobObject( NULL , NULL );
AssignProcessToJobObject( h , GetCurrentProcess() );
JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_JOB_MEMORY;
jeli.JobMemoryLimit = peakMemory;
if( !SetInformationJobObject( h , JobObjectExtendedLimitInformation , &jeli , sizeof( jeli ) ) )
fprintf( stderr , "Failed to set memory limit\n" );
}
#endif // defined(WIN32) && defined(MAX_MEMORY_GB)
typedef float Real;
typedef PlyValueVertex< float > Vertex;
Verbose.set= false;
In.set = true;
In.value = const_cast<char*>(input_file_name);
Out.set = true;
Out.value = const_cast<char*>(output_filename);
Density.set =true;
Depth.set = true;
Depth.value = 6;
Verbose.set = true;
Reset< Real >();
int paramNum = sizeof(params)/sizeof(cmdLineReadable*);
std::vector< char* > comments;
if( Verbose.set ) echoStdout=1;
XForm4x4< Real > xForm , iXForm;
xForm = XForm4x4< Real >::Identity();
iXForm = xForm.inverse();
double t;
double tt=Time();
Real isoValue = 0;
Octree< Real > tree;
tree.threads = Threads.value;
if( !In.set )
{
//ShowUsage(argv[0]);
return 0;
}
if( !MaxSolveDepth.set ) MaxSolveDepth.value = Depth.value;
OctNode< TreeNodeData >::SetAllocator( MEMORY_ALLOCATOR_BLOCK_SIZE );
t=Time();
int kernelDepth = KernelDepth.set ? KernelDepth.value : Depth.value-2;
if( kernelDepth>Depth.value )
{
fprintf( stderr,"[ERROR] %s can't be greater than %s: %d <= %d\n" , KernelDepth.name , Depth.name , KernelDepth.value , Depth.value );
return EXIT_FAILURE;
}
double maxMemoryUsage;
t=Time() , tree.maxMemoryUsage=0;
typename Octree< Real >::template SparseNodeData< typename Octree< Real >::PointData >* pointInfo = new typename Octree< Real >::template SparseNodeData< typename Octree< Real >::PointData >();
typename Octree< Real >::template SparseNodeData< Point3D< Real > >* normalInfo = new typename Octree< Real >::template SparseNodeData< Point3D< Real > >();
std::vector< Real >* kernelDensityWeights = new std::vector< Real >();
std::vector< Real >* centerWeights = new std::vector< Real >();
int pointCount;
typedef typename Octree< Real >::template ProjectiveData< Point3D< Real > > ProjectiveColor;
typename Octree< Real >::template SparseNodeData< ProjectiveColor > colorData;
char* ext = GetFileExtension( In.value );
if( Color.set && Color.value>0 )
{
OrientedPointStreamWithData< float , Point3D< unsigned char > >* pointStream;
if ( !strcasecmp( ext , "bnpts" ) ) pointStream = new BinaryOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value );
else if( !strcasecmp( ext , "ply" ) ) pointStream = new PLYOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value , PlyColorProperties , 6 , ValidPlyColorProperties );
else pointStream = new ASCIIOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value , ReadASCIIColor );
pointCount = tree.template SetTree< float >( pointStream , MinDepth.value , Depth.value , FullDepth.value , kernelDepth , Real(SamplesPerNode.value) , Scale.value , Confidence.set , NormalWeights.set , PointWeight.value , AdaptiveExponent.value , *kernelDensityWeights , *pointInfo , *normalInfo , *centerWeights , colorData , xForm , BoundaryType.value , Complete.set );
delete pointStream;
for( const OctNode< TreeNodeData >* n = tree.tree.nextNode() ; n!=NULL ; n=tree.tree.nextNode( n ) )
{
int idx = colorData.index( n );
if( idx>=0 ) colorData.data[idx] *= (Real)pow( Color.value , n->depth() );
}
}
else
{
OrientedPointStream< float >* pointStream;
if ( !strcasecmp( ext , "bnpts" ) ) pointStream = new BinaryOrientedPointStream< float >( In.value );
else if( !strcasecmp( ext , "ply" ) ) pointStream = new PLYOrientedPointStream< float >( In.value );
else pointStream = new ASCIIOrientedPointStream< float >( In.value );
pointCount = tree.template SetTree< float >( pointStream , MinDepth.value
, Depth.value , FullDepth.value , kernelDepth , Real(SamplesPerNode.value)
, Scale.value , Confidence.set , NormalWeights.set , PointWeight.value
, AdaptiveExponent.value , *kernelDensityWeights , *pointInfo , *normalInfo
, *centerWeights , xForm , BoundaryType.value , Complete.set );
delete pointStream;
}
delete[] ext;
if( !Density.set ) delete kernelDensityWeights , kernelDensityWeights = NULL;
DumpOutput2( comments , "# Tree set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
DumpOutput( "Input Points: %d\n" , pointCount );
DumpOutput( "Leaves/Nodes: %d/%d\n" , tree.tree.leaves() , tree.tree.nodes() );
DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) );
maxMemoryUsage = tree.maxMemoryUsage;
t=Time() , tree.maxMemoryUsage=0;
Pointer( Real ) constraints = tree.SetLaplacianConstraints( *normalInfo );
delete normalInfo;
DumpOutput2( comments , "# Constraints set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage())/(1<<20) );
maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );
t=Time() , tree.maxMemoryUsage=0;
Pointer( Real ) solution = tree.SolveSystem( *pointInfo , constraints , ShowResidual.set , Iters.value , MaxSolveDepth.value , CGDepth.value , CSSolverAccuracy.value );
delete pointInfo;
FreePointer( constraints );
DumpOutput2( comments , "# Linear system solved in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) );
maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );
CoredFileMeshData< Vertex > mesh;
if( Verbose.set ) tree.maxMemoryUsage=0;
t=Time();
isoValue = tree.GetIsoValue( solution , *centerWeights );
delete centerWeights;
DumpOutput( "Got average in: %f\n" , Time()-t );
DumpOutput( "Iso-Value: %e\n" , isoValue );
Real scale = tree.GetScale();
std::cout<<"iso value: "<<isoValue<<std::endl;
std::cout<<"scale: "<<scale<<std::endl;
Point3D<Real> center = tree.GetCenter();
std::cout<<"center: "<<center[0]<<", "<<center[1]<<", "<<center[2]<<std::endl;
if( VoxelGrid.set )
{
double t = Time();
FILE* fp = fopen( VoxelGrid.value , "wb" );
if( !fp ) fprintf( stderr , "Failed to open voxel file for writing: %s\n" , VoxelGrid.value );
else
{
int res = 0;
Pointer( Real ) values = tree.Evaluate( ( ConstPointer( Real ) )solution , res , isoValue , VoxelDepth.value );
fwrite(&res , sizeof(int) , 1 , fp );
fwrite(&scale, sizeof(float), 1, fp);
fwrite(¢er, sizeof(float), 3, fp);
// std::cout<<"res: "<<res<<std::endl;
// for( int i=0 ; i<res*res*res ; i++ ) {
// std::cout << float( values[i] )<<" ";
// }
// std::cout<<std::endl;
if( sizeof(Real)==sizeof(float) ) fwrite( values , sizeof(float) , res*res*res , fp );
else
{
float *fValues = new float[res*res*res];
for( int i=0 ; i<res*res*res ; i++ ){
fValues[i] = float( values[i] );
}
fwrite( fValues , sizeof(float) , res*res*res , fp );
delete[] fValues;
}
fclose( fp );
DeletePointer( values );
}
DumpOutput( "Got voxel grid in: %f\n" , Time()-t );
}
if( Out.set )
{
// t = Time() , tree.maxMemoryUsage = 0;
// tree.GetMCIsoSurface( kernelDensityWeights ? GetPointer( *kernelDensityWeights ) : NullPointer( Real ) , Color.set ? &colorData : NULL , solution , isoValue , mesh , true , !NonManifold.set , PolygonMesh.set );
// if( PolygonMesh.set ) DumpOutput2( comments , "# Got polygons in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
// else DumpOutput2( comments , "# Got triangles in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
// maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );
// DumpOutput2( comments , "# Total Solve: %9.1f (s), %9.1f (MB)\n" , Time()-tt , maxMemoryUsage );
//
// if( NoComments.set )
// {
// if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII , NULL , 0 , iXForm );
// else PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , NULL , 0 , iXForm );
// }
// else
// {
// if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII , &comments[0] , (int)comments.size() , iXForm );
// else PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , &comments[0] , (int)comments.size() , iXForm );
// }
// DumpOutput( "Vertices / Polygons: %d / %d\n" , mesh.outOfCorePointCount()+mesh.inCorePoints.size() , mesh.polygonCount() );
}
FreePointer( solution );
#ifdef _WIN32
if( Performance.set )
{
HANDLE cur_thread=GetCurrentThread();
FILETIME tcreat, texit, tkernel, tuser;
if( GetThreadTimes( cur_thread , &tcreat , &texit , &tkernel , &tuser ) )
printf( "Time (Wall/User/Kernel): %.2f / %.2f / %.2f\n" , Time()-t , to_seconds( tuser ) , to_seconds( tkernel ) );
else printf( "Time: %.2f\n" , Time()-t );
HANDLE h = GetCurrentProcess();
PROCESS_MEMORY_COUNTERS pmc;
if( GetProcessMemoryInfo( h , &pmc , sizeof(pmc) ) ) printf( "Peak Memory (MB): %d\n" , pmc.PeakWorkingSetSize>>20 );
}
#endif // _WIN32
return EXIT_SUCCESS;
}
#endif
int poissonRecon( int argc , char**argv)
{
#if defined(WIN32) && defined(MAX_MEMORY_GB)
if( MAX_MEMORY_GB>0 )
{
SIZE_T peakMemory = 1;
peakMemory <<= 30;
peakMemory *= MAX_MEMORY_GB;
printf( "Limiting memory usage to %.2f GB\n" , float( peakMemory>>30 ) );
HANDLE h = CreateJobObject( NULL , NULL );
AssignProcessToJobObject( h , GetCurrentProcess() );
JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 };
jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_JOB_MEMORY;
jeli.JobMemoryLimit = peakMemory;
if( !SetInformationJobObject( h , JobObjectExtendedLimitInformation , &jeli , sizeof( jeli ) ) )
fprintf( stderr , "Failed to set memory limit\n" );
}
#endif // defined(WIN32) && defined(MAX_MEMORY_GB)
double t = Time();
cmdLineParse( argc-1 , &argv[1] , sizeof(params)/sizeof(cmdLineReadable*) , params , 1 );
if( Density.set )
if( Color.set )
if( Double.set ) Execute< double , PlyColorAndValueVertex< float > >( argc , argv );
else Execute< float , PlyColorAndValueVertex< float > >( argc , argv );
else
if( Double.set ) Execute< double , PlyValueVertex< float > >( argc , argv );
else Execute< float , PlyValueVertex< float > >( argc , argv );//
else
if( Color.set )
if( Double.set ) Execute< double , PlyColorVertex< float > >( argc , argv );
else Execute< float , PlyColorVertex< float > >( argc , argv );
else
if( Double.set ) Execute< double , PlyVertex< float > >( argc , argv );
else Execute< float , PlyVertex< float > >( argc , argv );
#ifdef _WIN32
if( Performance.set )
{
HANDLE cur_thread=GetCurrentThread();
FILETIME tcreat, texit, tkernel, tuser;
if( GetThreadTimes( cur_thread , &tcreat , &texit , &tkernel , &tuser ) )
printf( "Time (Wall/User/Kernel): %.2f / %.2f / %.2f\n" , Time()-t , to_seconds( tuser ) , to_seconds( tkernel ) );
else printf( "Time: %.2f\n" , Time()-t );
HANDLE h = GetCurrentProcess();
PROCESS_MEMORY_COUNTERS pmc;
if( GetProcessMemoryInfo( h , &pmc , sizeof(pmc) ) ) printf( "Peak Memory (MB): %d\n" , pmc.PeakWorkingSetSize>>20 );
}
#endif // _WIN32
return EXIT_SUCCESS;
}
int poisson(const char *input_file_name, const char *output_filename, int depth)
{
typedef float Real;
typedef PlyValueVertex< float > Vertex;
In.set = true;
In.value=new char[strlen(input_file_name)+1];
stpcpy(In.value, input_file_name);
Out.set = true;
Out.value=new char[strlen(output_filename)+1];
stpcpy(Out.value, output_filename);
Density.set = false; // there is no need to trimmer surface in the surgical guide generation stage
Depth.set = true;
Depth.value = depth;
Verbose.set = true;
ASCII.set=true;
Threads.value = 8;
Reset< Real >();
int paramNum = sizeof(params)/sizeof(cmdLineReadable*);
std::vector< char* > comments;
if( Verbose.set ) echoStdout=1;
XForm4x4< Real > xForm , iXForm;
xForm = XForm4x4< Real >::Identity();
iXForm = xForm.inverse();
DumpOutput2( comments , "Running Screened Poisson Reconstruction (Version 7.0)\n" );
double t;
double tt=Time();
Real isoValue = 0;
Octree< Real > tree;
tree.threads = Threads.value;
if( !In.set )
{
//ShowUsage(argv[0]);
return 0;
}
if( !MaxSolveDepth.set ) MaxSolveDepth.value = Depth.value;
OctNode< TreeNodeData >::SetAllocator( MEMORY_ALLOCATOR_BLOCK_SIZE );
t=Time();
int kernelDepth = KernelDepth.set ? KernelDepth.value : Depth.value-2;
if( kernelDepth>Depth.value )
{
fprintf( stderr,"[ERROR] %s can't be greater than %s: %d <= %d\n" , KernelDepth.name , Depth.name , KernelDepth.value , Depth.value );
return EXIT_FAILURE;
}
double maxMemoryUsage;
t=Time() , tree.maxMemoryUsage=0;
typename Octree< Real >::template SparseNodeData< typename Octree< Real >::PointData >* pointInfo = new typename Octree< Real >::template SparseNodeData< typename Octree< Real >::PointData >();
typename Octree< Real >::template SparseNodeData< Point3D< Real > >* normalInfo = new typename Octree< Real >::template SparseNodeData< Point3D< Real > >();
std::vector< Real >* kernelDensityWeights = new std::vector< Real >();
std::vector< Real >* centerWeights = new std::vector< Real >();
int pointCount;
typedef typename Octree< Real >::template ProjectiveData< Point3D< Real > > ProjectiveColor;
typename Octree< Real >::template SparseNodeData< ProjectiveColor > colorData;
char* ext = GetFileExtension( In.value );
if( Color.set && Color.value>0 )
{
OrientedPointStreamWithData< float , Point3D< unsigned char > >* pointStream;
if ( !strcasecmp( ext , "bnpts" ) ) pointStream = new BinaryOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value );
else if( !strcasecmp( ext , "ply" ) ) pointStream = new PLYOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value , PlyColorProperties , 6 , ValidPlyColorProperties );
else pointStream = new ASCIIOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value , ReadASCIIColor );
pointCount = tree.template SetTree< float >( pointStream , MinDepth.value , Depth.value , FullDepth.value , kernelDepth , Real(SamplesPerNode.value) , Scale.value , Confidence.set , NormalWeights.set , PointWeight.value , AdaptiveExponent.value , *kernelDensityWeights , *pointInfo , *normalInfo , *centerWeights , colorData , xForm , BoundaryType.value , Complete.set );
delete pointStream;
for( const OctNode< TreeNodeData >* n = tree.tree.nextNode() ; n!=NULL ; n=tree.tree.nextNode( n ) )
{
int idx = colorData.index( n );
if( idx>=0 ) colorData.data[idx] *= (Real)pow( Color.value , n->depth() );
}
}
else
{
OrientedPointStream< float >* pointStream;
if ( !strcasecmp( ext , "bnpts" ) ) pointStream = new BinaryOrientedPointStream< float >( In.value );
else if( !strcasecmp( ext , "ply" ) ) pointStream = new PLYOrientedPointStream< float >( In.value );
else pointStream = new ASCIIOrientedPointStream< float >( In.value );
pointCount = tree.template SetTree< float >( pointStream , MinDepth.value
, Depth.value , FullDepth.value , kernelDepth , Real(SamplesPerNode.value)
, Scale.value , Confidence.set , NormalWeights.set , PointWeight.value
, AdaptiveExponent.value , *kernelDensityWeights , *pointInfo , *normalInfo
, *centerWeights , xForm , BoundaryType.value , Complete.set );
delete pointStream;
}
delete[] ext;
if( !Density.set ) delete kernelDensityWeights , kernelDensityWeights = NULL;
DumpOutput2( comments , "# Tree set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
DumpOutput( "Input Points: %d\n" , pointCount );
DumpOutput( "Leaves/Nodes: %d/%d\n" , tree.tree.leaves() , tree.tree.nodes() );
DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) );
maxMemoryUsage = tree.maxMemoryUsage;
t=Time() , tree.maxMemoryUsage=0;
Pointer( Real ) constraints = tree.SetLaplacianConstraints( *normalInfo );
delete normalInfo;
DumpOutput2( comments , "# Constraints set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage())/(1<<20) );
maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );
t=Time() , tree.maxMemoryUsage=0;
Pointer( Real ) solution = tree.SolveSystem( *pointInfo , constraints , ShowResidual.set , Iters.value , MaxSolveDepth.value , CGDepth.value , CSSolverAccuracy.value );
delete pointInfo;
FreePointer( constraints );
DumpOutput2( comments , "# Linear system solved in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) );
maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );
CoredFileMeshData< Vertex > mesh;
if( Verbose.set ) tree.maxMemoryUsage=0;
t=Time();
isoValue = tree.GetIsoValue( solution , *centerWeights );
delete centerWeights;
DumpOutput( "Got average in: %f\n" , Time()-t );
DumpOutput( "Iso-Value: %e\n" , isoValue );
Real scale = tree.GetScale();
//std::cout<<"iso value: "<<isoValue<<std::endl;
//std::cout<<"scale: "<<scale<<std::endl;
Point3D<Real> center = tree.GetCenter();
//std::cout<<"center: "<<center[0]<<", "<<center[1]<<", "<<center[2]<<std::endl;
if( VoxelGrid.set )
{
double t = Time();
FILE* fp = fopen( VoxelGrid.value , "wb" );
if( !fp ) fprintf( stderr , "Failed to open voxel file for writing: %s\n" , VoxelGrid.value );
else
{
int res = 0;
Pointer( Real ) values = tree.Evaluate( ( ConstPointer( Real ) )solution , res , isoValue , VoxelDepth.value );
fwrite(&res , sizeof(int) , 1 , fp );
fwrite(&scale, sizeof(float), 1, fp);
fwrite(¢er, sizeof(float), 3, fp);
// std::cout<<"res: "<<res<<std::endl;
// for( int i=0 ; i<res*res*res ; i++ ) {
// std::cout << float( values[i] )<<" ";
// }
// std::cout<<std::endl;
if( sizeof(Real)==sizeof(float) ) fwrite( values , sizeof(float) , res*res*res , fp );
else
{
float *fValues = new float[res*res*res];
for( int i=0 ; i<res*res*res ; i++ ){
fValues[i] = float( values[i] );
}
fwrite( fValues , sizeof(float) , res*res*res , fp );
delete[] fValues;
}
fclose( fp );
DeletePointer( values );
}
DumpOutput( "Got voxel grid in: %f\n" , Time()-t );
}
if( Out.set )
{
t = Time() , tree.maxMemoryUsage = 0;
tree.GetMCIsoSurface( kernelDensityWeights ? GetPointer( *kernelDensityWeights ) : NullPointer( Real ) , Color.set ? &colorData : NULL , solution , isoValue , mesh , true , !NonManifold.set , PolygonMesh.set );
if( PolygonMesh.set ) DumpOutput2( comments , "# Got polygons in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
else DumpOutput2( comments , "# Got triangles in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage );
maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage );
DumpOutput2( comments , "# Total Solve: %9.1f (s), %9.1f (MB)\n" , Time()-tt , maxMemoryUsage );
if( NoComments.set )
{
if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII , NULL , 0 , iXForm );
else PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , NULL , 0 , iXForm );
}
else
{
if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII , &comments[0] , (int)comments.size() , iXForm );
else PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , &comments[0] , (int)comments.size() , iXForm );
}
DumpOutput( "Vertices / Polygons: %d / %d\n" , mesh.outOfCorePointCount()+mesh.inCorePoints.size() , mesh.polygonCount() );
}
FreePointer( solution );
} | 40,020 | 15,601 |
/*
* 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.
*/
/**
* @author Intel, Konstantin M. Anisimov, Igor V. Chebykin
*
*/
#include "IpfType.h"
namespace Jitrino {
namespace IPF {
bool ipfLogIsOn = false;
bool ipfVerifyIsOn = true;
bool ipfConstantFolding = true;
//============================================================================//
// IpfType
//============================================================================//
int16 IpfType::getSize(DataKind dataKind) {
switch(dataKind) {
case DATA_BASE : return 8;
case DATA_MPTR : return 8;
case DATA_I8 : return 1;
case DATA_U8 : return 1;
case DATA_I16 : return 2;
case DATA_U16 : return 2;
case DATA_I32 : return 4;
case DATA_U32 : return 4;
case DATA_I64 : return 8;
case DATA_U64 : return 8;
case DATA_S : return 4;
case DATA_D : return 8;
case DATA_F : return 16;
case DATA_P : return 1;
case DATA_B : return 8;
case DATA_IMM : return 8;
case DATA_CONST_REF : return 8;
case DATA_NODE_REF : return 8;
case DATA_METHOD_REF : return 8;
case DATA_SWITCH_REF : return 8;
case DATA_INVALID : break;
}
IPF_ERR << " unexpected dataKind " << dataKind << endl;
return 0;
}
//----------------------------------------------------------------------------------------//
bool IpfType::isReg(OpndKind opndKind) {
switch(opndKind) {
case OPND_G_REG :
case OPND_F_REG :
case OPND_P_REG :
case OPND_B_REG :
case OPND_A_REG :
case OPND_IP_REG :
case OPND_UM_REG : return true;
case OPND_IMM : return false;
case OPND_INVALID : break;
}
IPF_ERR << " unexpected opndKind " << opndKind << endl;
return 0;
}
//----------------------------------------------------------------------------------------//
bool IpfType::isGReg(OpndKind opndKind) {
switch(opndKind) {
case OPND_G_REG : return true;
case OPND_F_REG :
case OPND_P_REG :
case OPND_B_REG :
case OPND_A_REG :
case OPND_IP_REG :
case OPND_UM_REG :
case OPND_IMM : return false;
case OPND_INVALID : break;
}
IPF_ERR << " unexpected opndKind " << opndKind << endl;
return 0;
}
//----------------------------------------------------------------------------------------//
bool IpfType::isFReg(OpndKind opndKind) {
switch(opndKind) {
case OPND_G_REG : return false;
case OPND_F_REG : return true;
case OPND_P_REG :
case OPND_B_REG :
case OPND_A_REG :
case OPND_IP_REG :
case OPND_UM_REG :
case OPND_IMM : return false;
case OPND_INVALID : break;
}
IPF_ERR << " unexpected opndKind " << opndKind << endl;
return 0;
}
//----------------------------------------------------------------------------------------//
bool IpfType::isImm(OpndKind opndKind) {
switch(opndKind) {
case OPND_G_REG :
case OPND_F_REG :
case OPND_P_REG :
case OPND_B_REG :
case OPND_A_REG :
case OPND_IP_REG :
case OPND_UM_REG : return false;
case OPND_IMM : return true;
case OPND_INVALID : break;
}
IPF_ERR << " unexpected opndKind " << opndKind << endl;
return 0;
}
//----------------------------------------------------------------------------------------//
bool IpfType::isSigned(DataKind dataKind) {
switch(dataKind) {
case DATA_I8 :
case DATA_I16 :
case DATA_I32 :
case DATA_I64 :
case DATA_S :
case DATA_D :
case DATA_F : return true;
default : return false;;
}
}
//----------------------------------------------------------------------------------------//
bool IpfType::isFloating(DataKind dataKind) {
switch(dataKind) {
case DATA_S :
case DATA_D :
case DATA_F : return true;
default : return false;;
}
}
} // IPF
} // Jitrino
| 5,247 | 1,655 |
// Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <pup.h>
#include "Domain/BoundaryConditions/BoundaryCondition.hpp"
namespace NewtonianEuler {
/// \brief Boundary conditions for the Newtonian Euler hydrodynamics system
namespace BoundaryConditions {
/// \brief The base class off of which all boundary conditions must inherit
template <size_t Dim>
class BoundaryCondition : public domain::BoundaryConditions::BoundaryCondition {
public:
BoundaryCondition() = default;
BoundaryCondition(BoundaryCondition&&) = default;
BoundaryCondition& operator=(BoundaryCondition&&) = default;
BoundaryCondition(const BoundaryCondition&) = default;
BoundaryCondition& operator=(const BoundaryCondition&) = default;
~BoundaryCondition() override = default;
explicit BoundaryCondition(CkMigrateMessage* msg);
void pup(PUP::er& p) override;
};
} // namespace BoundaryConditions
} // namespace NewtonianEuler
| 957 | 280 |
#include <QtWidgets>
#include "IsosurfaceWidget.hpp"
#include "SpinWidget.hpp"
IsosurfaceWidget::IsosurfaceWidget(std::shared_ptr<State> state, SpinWidget *spinWidget, int i)
{
this->state = state;
this->spinWidget = spinWidget;
setAttribute(Qt::WA_DeleteOnClose);
// Setup User Interface
this->setupUi(this);
// Create renderer pointer
this->m_renderer = std::make_shared<VFRendering::IsosurfaceRenderer>(*spinWidget->view(), *spinWidget->vectorfield());
// Defaults
this->setShowIsosurface(true);
this->setIsovalue(0);
this->setIsocomponent(2);
this->setDrawShadows(false);
if (i == 1) {
this->setIsovalue(0.96);
this->setIsocomponent(0);
this->setDrawShadows(false);
}
if (i == 2) {
this->setIsovalue(-0.96);
this->setIsocomponent(0);
this->setDrawShadows(false);
}
// Read values
auto isovalue = this->isovalue();
horizontalSlider_isovalue->setRange(0, 100);
horizontalSlider_isovalue->setValue((int)(isovalue + 1 * 50));
int component = this->isocomponent();
if (component == 0) this->radioButton_isosurface_x->setChecked(true);
else if (component == 1) this->radioButton_isosurface_y->setChecked(true);
else if (component == 2) this->radioButton_isosurface_z->setChecked(true);
// Add this isosurface to the SpinWidget
this->spinWidget->addIsosurface(m_renderer);
// Connect Slots
this->setupSlots();
// Input validation
QRegularExpression re("[+|-]?[\\d]*[\\.]?[\\d]*");
this->number_validator = new QRegularExpressionValidator(re);
this->setupInputValidators();
}
bool IsosurfaceWidget::showIsosurface()
{
return this->m_show_isosurface;
}
void IsosurfaceWidget::setShowIsosurface(bool show)
{
this->m_show_isosurface = show;
QTimer::singleShot(1, this->spinWidget, SLOT(update()));
}
float IsosurfaceWidget::isovalue()
{
return this->m_isovalue;
}
void IsosurfaceWidget::setIsovalue(float value)
{
this->m_isovalue = value;
m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::ISOVALUE>(m_isovalue);
QTimer::singleShot(1, this->spinWidget, SLOT(update()));
}
int IsosurfaceWidget::isocomponent()
{
return this->m_isocomponent;
}
void IsosurfaceWidget::setIsocomponent(int component)
{
this->m_isocomponent = component;
if (this->m_isocomponent == 0)
{
m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::VALUE_FUNCTION>([](const glm::vec3& position, const glm::vec3& direction) -> VFRendering::IsosurfaceRenderer::isovalue_type {
(void)position;
return direction.x;
});
}
else if (this->m_isocomponent == 1)
{
m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::VALUE_FUNCTION>([](const glm::vec3& position, const glm::vec3& direction) -> VFRendering::IsosurfaceRenderer::isovalue_type {
(void)position;
return direction.y;
});
}
else if (this->m_isocomponent == 2)
{
m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::VALUE_FUNCTION>([](const glm::vec3& position, const glm::vec3& direction) -> VFRendering::IsosurfaceRenderer::isovalue_type {
(void)position;
return direction.z;
});
}
QTimer::singleShot(1, this->spinWidget, SLOT(update()));
}
bool IsosurfaceWidget::drawShadows()
{
return this->m_draw_shadows;
}
void IsosurfaceWidget::setDrawShadows(bool show)
{
this->m_draw_shadows = show;
if (this->m_draw_shadows)
{
m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::LIGHTING_IMPLEMENTATION>(
"uniform vec3 uLightPosition;"
"float lighting(vec3 position, vec3 normal)"
"{"
" vec3 lightDirection = -normalize(uLightPosition-position);"
" float diffuse = 0.7*max(0.0, dot(normal, lightDirection));"
" float ambient = 0.2;"
" return diffuse+ambient;"
"}");
}
else
{
m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::LIGHTING_IMPLEMENTATION>(
"float lighting(vec3 position, vec3 normal) { return 1.0; }");
}
QTimer::singleShot(1, this->spinWidget, SLOT(update()));
}
void IsosurfaceWidget::setupSlots()
{
connect(horizontalSlider_isovalue, SIGNAL(valueChanged(int)), this, SLOT(slot_setIsovalue_slider()));
connect(lineEdit_isovalue, SIGNAL(returnPressed()), this, SLOT(slot_setIsovalue_lineedit()));
connect(radioButton_isosurface_x, SIGNAL(toggled(bool)), this, SLOT(slot_setIsocomponent()));
connect(radioButton_isosurface_y, SIGNAL(toggled(bool)), this, SLOT(slot_setIsocomponent()));
connect(radioButton_isosurface_z, SIGNAL(toggled(bool)), this, SLOT(slot_setIsocomponent()));
connect(checkBox_invert_lighting, SIGNAL(stateChanged(int)), this, SLOT(slot_setTriangleNormal()));
connect(pushButton_remove, SIGNAL(clicked()), this, SLOT(close()));
}
void IsosurfaceWidget::slot_setIsovalue_slider()
{
float isovalue = horizontalSlider_isovalue->value() / 50.0f - 1.0f;
this->lineEdit_isovalue->setText(QString::number(isovalue));
this->setIsovalue(isovalue);
}
void IsosurfaceWidget::slot_setIsovalue_lineedit()
{
float isovalue = this->lineEdit_isovalue->text().toFloat();
this->horizontalSlider_isovalue->setValue((int)(isovalue * 50 + 50));
this->setIsovalue(isovalue);
}
void IsosurfaceWidget::slot_setIsocomponent()
{
if (this->radioButton_isosurface_x->isChecked())
{
this->setIsocomponent(0);
}
else if (this->radioButton_isosurface_y->isChecked())
{
this->setIsocomponent(1);
}
else if (this->radioButton_isosurface_z->isChecked())
{
this->setIsocomponent(2);
}
}
void IsosurfaceWidget::slot_setTriangleNormal()
{
m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::FLIP_NORMALS>(this->checkBox_invert_lighting->isChecked());
QTimer::singleShot(1, this->spinWidget, SLOT(update()));
}
void IsosurfaceWidget::setupInputValidators()
{
// Isovalue
this->lineEdit_isovalue->setValidator(this->number_validator);
}
void IsosurfaceWidget::closeEvent(QCloseEvent *event)
{
// Remove this isosurface from the SpinWidget
this->spinWidget->removeIsosurface(m_renderer);
// Notify others that this widget was closed
emit closedSignal();
// Close
event->accept();
} | 6,487 | 2,278 |
#include "SentryThreadMetadataCache.hpp"
#if SENTRY_TARGET_PROFILING_SUPPORTED
# include "SentryStackBounds.hpp"
# include "SentryThreadHandle.hpp"
# include <algorithm>
# include <string>
# include <vector>
namespace {
bool
isSentryOwnedThreadName(const std::string &name)
{
return name.rfind("io.sentry", 0) == 0;
}
constexpr std::size_t kMaxThreadNameLength = 100;
} // namespace
namespace sentry {
namespace profiling {
ThreadMetadata
ThreadMetadataCache::metadataForThread(const ThreadHandle &thread)
{
const auto handle = thread.nativeHandle();
const auto it = std::find_if(cache_.cbegin(), cache_.cend(),
[handle](const ThreadHandleMetadataPair &pair) { return pair.handle == handle; });
if (it == cache_.cend()) {
ThreadMetadata metadata;
metadata.threadID = ThreadHandle::tidFromNativeHandle(handle);
metadata.priority = thread.priority();
// If getting the priority fails (via pthread_getschedparam()), that
// means the rest of this is probably going to fail too.
if (metadata.priority != -1) {
auto threadName = thread.name();
if (isSentryOwnedThreadName(threadName)) {
// Don't collect backtraces for Sentry-owned threads.
metadata.priority = 0;
metadata.threadID = 0;
cache_.push_back({ handle, metadata });
return metadata;
}
if (threadName.size() > kMaxThreadNameLength) {
threadName.resize(kMaxThreadNameLength);
}
metadata.name = threadName;
}
cache_.push_back({ handle, metadata });
return metadata;
} else {
return (*it).metadata;
}
}
} // namespace profiling
} // namespace sentry
#endif
| 1,946 | 529 |
#pragma once
#include "JsonModelTypes.hpp"
#include <fstream>
namespace ReliveAPI {
// Reads the root fields to read the version/game type (we need to know this so we can create a game specific reader/do an upgrade of the json).
class JsonMapRootInfoReader final
{
public:
void Read(const std::string& fileName);
MapRootInfo mMapRootInfo;
};
void readFileContentsIntoString(std::string& target, std::ifstream& ifs);
std::string& getStaticStringBuffer();
} // namespace ReliveAPI
| 491 | 144 |
#include <catch2/catch.hpp>
#include <iomanip>
#include <cannon/math/rootfinding.hpp>
#include <cannon/math/nearly_equal.hpp>
#include <cannon/log/registry.hpp>
using namespace cannon::math;
using namespace cannon::log;
TEST_CASE("Rootfinding", "[math]") {
double r = bisection_method([](double x){
return x * x - 10;
}, -10, 0);
log_info(std::setprecision(15), r);
REQUIRE(nearly_equal(r, -std::sqrt(10)));
r = bisection_method([](double x){
return x * x - 10;
}, 0, 10);
log_info(std::setprecision(15), r);
REQUIRE(nearly_equal(r, std::sqrt(10)));
r = regula_falsi([](double x){
return x * x - 10;
}, -10, 0);
log_info(std::setprecision(15), r);
REQUIRE(nearly_equal(r, -std::sqrt(10)));
r = regula_falsi([](double x){
return x * x - 10;
}, 0, 10);
log_info(std::setprecision(15), r);
REQUIRE(nearly_equal(r, std::sqrt(10)));
r = newton_method([](double x) { return x * x - 10; },
[](double x) { return 2 * x; }, -10);
log_info(std::setprecision(15), r);
REQUIRE(nearly_equal(r, -std::sqrt(10)));
}
| 1,107 | 483 |
/* This file is part of the Pangolin Project.
* http://github.com/stevenlovegrove/Pangolin
*
* Copyright (c) Andrey Mnatsakanov
*
* 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 "window.hpp"
#include <pangolin/display/window.h>
namespace py_pangolin {
class PyWindowInterface: public pangolin::WindowInterface{
public:
using pangolin::WindowInterface::WindowInterface;
void ToggleFullscreen() override {
PYBIND11_OVERLOAD_PURE(
void,
pangolin::WindowInterface,
ToggleFullscreen);
}
void Move(int x, int y) override {
PYBIND11_OVERLOAD_PURE(
void,
pangolin::WindowInterface,
Move,
x,
y);
}
void Resize(unsigned int w, unsigned int h) override {
PYBIND11_OVERLOAD_PURE(
void,
pangolin::WindowInterface,
Resize,
w,
h);
}
void MakeCurrent() override {
PYBIND11_OVERLOAD_PURE(
void,
pangolin::WindowInterface,
MakeCurrent);
}
void RemoveCurrent() override {
PYBIND11_OVERLOAD_PURE(
void,
pangolin::WindowInterface,
RemoveCurrent);
}
void ProcessEvents() override {
PYBIND11_OVERLOAD_PURE(
void,
pangolin::WindowInterface,
ProcessEvents);
}
void SwapBuffers() override {
PYBIND11_OVERLOAD_PURE(
void,
pangolin::WindowInterface,
SwapBuffers);
}
};
void bind_window(pybind11::module &m) {
pybind11::class_<pangolin::WindowInterface, PyWindowInterface > windows_interface(m, "WindowsInterface");
windows_interface
.def(pybind11::init<>())
.def("ToggleFullscreen", &pangolin::WindowInterface::ToggleFullscreen)
.def("Move", &pangolin::WindowInterface::Move)
.def("Resize", &pangolin::WindowInterface::Resize)
.def("MakeCurrent", &pangolin::WindowInterface::MakeCurrent)
.def("ProcessEvents", &pangolin::WindowInterface::ProcessEvents)
.def("SwapBuffers", &pangolin::WindowInterface::SwapBuffers);
}
}
| 3,646 | 1,045 |
#include "qmlhighlighter.h"
#include <QColor>
void QMLHighlighter::highlightBlock(const QString &text)
{
QTextCharFormat keywordFormat;
keywordFormat.setForeground(QColor("#d7ffaf")); // Identifier
QTextCharFormat typeFormat;
typeFormat.setForeground(QColor("#afffff")); // Type
QTextCharFormat commentFormat;
commentFormat.setForeground(QColor("#8a8a8a")); // Comment
QTextCharFormat numericConstantFormat;
numericConstantFormat.setForeground(QColor("#ffffd7")); // Constant
QTextCharFormat stringConstantFormat;
stringConstantFormat.setForeground(QColor("#ffffd7"));
QRegExp type("\\b[A-Z][A-Za-z]+\\b");
QRegExp numericConstant("[0-9]+\\.?[0-9]*");
QRegExp stringConstant("['\"].*['\"]");//Not multiline strings, but they're rare
QRegExp lineComment("//[^\n]*");
QRegExp startComment("/\\*");
QRegExp endComment("\\*/");
applyBasicHighlight(text, type, typeFormat);
applyBasicHighlight(text, numericConstant, numericConstantFormat);
applyBasicHighlight(text, stringConstant, stringConstantFormat);
applyBasicHighlight(text, lineComment, commentFormat);
setCurrentBlockState(0);
int startIndex = 0;
if (previousBlockState() != 1)
startIndex = text.indexOf(startComment);
while (startIndex >= 0) {
int endIndex = text.indexOf(endComment, startIndex);
int commentLength;
if (endIndex == -1) {
setCurrentBlockState(1);
commentLength = text.length() - startIndex;
} else {
commentLength = endIndex - startIndex
+ endComment.matchedLength();
}
setFormat(startIndex, commentLength, commentFormat);
startIndex = text.indexOf(startComment,
startIndex + commentLength);
}
}
void QMLHighlighter::applyBasicHighlight(const QString &text, QRegExp &re, QTextCharFormat &format)
{
int index = text.indexOf(re);
while (index >= 0) {
int length = re.matchedLength();
setFormat(index, length, format);
index = text.indexOf(re, index + length);
}
}
| 2,112 | 642 |
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "muddle_logging_name.hpp"
#include "peer_list.hpp"
#include "router.hpp"
#include "core/logging.hpp"
#include <algorithm>
#include <cstddef>
#include <string>
#include <utility>
static constexpr std::size_t MAX_LOG2_BACKOFF = 11; // 2048
static constexpr char const *BASE_NAME = "MuddlePeers";
namespace fetch {
namespace muddle {
PeerConnectionList::PeerConnectionList(NetworkId const &network)
: name_{GenerateLoggingName(BASE_NAME, network)}
{}
void PeerConnectionList::SetStatusCallback(StatusCallback callback)
{
status_callback_ = std::move(callback);
}
bool PeerConnectionList::AddPersistentPeer(Uri const &peer)
{
FETCH_LOCK(lock_);
auto const result = persistent_peers_.emplace(peer);
return result.second;
}
void PeerConnectionList::RemovePersistentPeer(Uri const &peer)
{
FETCH_LOCK(lock_);
persistent_peers_.erase(peer);
}
void PeerConnectionList::RemovePersistentPeer(Handle handle)
{
FETCH_LOCK(lock_);
for (auto &peer_connection : peer_connections_)
{
if (peer_connection.second->handle() == handle)
{
persistent_peers_.erase(peer_connection.first);
break;
}
}
}
std::size_t PeerConnectionList::GetNumPeers() const
{
FETCH_LOCK(lock_);
return persistent_peers_.size();
}
void PeerConnectionList::AddConnection(Uri const &peer, ConnectionPtr const &conn)
{
FETCH_LOCK(lock_);
// update the metadata
auto &metadata = peer_metadata_[peer];
metadata.connected = false;
++metadata.attempts;
peer_connections_[peer] = conn;
}
PeerConnectionList::PeerMap PeerConnectionList::GetCurrentPeers() const
{
FETCH_LOCK(lock_);
return peer_connections_;
}
PeerConnectionList::PeerSet PeerConnectionList::GetPersistentPeers() const
{
FETCH_LOCK(lock_);
return persistent_peers_;
}
bool PeerConnectionList::GetMetadataForPeer(Uri const &peer, PeerMetadata &metadata) const
{
bool success{false};
FETCH_LOCK(lock_);
auto it = peer_metadata_.find(peer);
if (it != peer_metadata_.end())
{
metadata = it->second;
success = true;
}
return success;
}
PeerConnectionList::ConnectionState PeerConnectionList::GetStateForPeer(Uri const &peer) const
{
FETCH_LOCK(lock_);
auto metadataiter = peer_metadata_.find(peer);
if (metadataiter == peer_metadata_.end())
{
return ConnectionState::UNKNOWN;
}
auto const &metadata = metadataiter->second;
if (metadata.connected)
{
return ConnectionState::CONNECTED;
}
if (ReadyForRetry(metadata))
{
return ConnectionState::TRYING;
}
return ConnectionState(int(ConnectionState::BACKOFF) + metadata.consecutive_failures);
}
void PeerConnectionList::OnConnectionEstablished(Uri const &peer)
{
Handle connection_handle = 0;
// update the connection metadata
{
FETCH_LOCK(lock_);
auto it = peer_connections_.find(peer);
if (it != peer_connections_.end())
{
connection_handle = it->second->handle();
}
auto &metadata = peer_metadata_[peer];
++metadata.successes;
metadata.connected = true;
metadata.consecutive_failures = 0;
}
// send an identity message
if ((connection_handle != 0u) && status_callback_)
{
status_callback_(peer, connection_handle, ConnectionState::CONNECTED);
}
FETCH_LOG_INFO(logging_name_, "Connection to ", peer.uri(),
" established (conn: ", connection_handle, ")");
}
void PeerConnectionList::RemoveConnection(Uri const &peer)
{
FETCH_LOCK(lock_);
// remove the active connection
peer_connections_.erase(peer);
// update the metadata
auto mt_it = peer_metadata_.find(peer);
if (mt_it != peer_metadata_.end())
{
auto &metadata = mt_it->second;
++metadata.consecutive_failures;
++metadata.total_failures;
metadata.connected = false;
metadata.last_failed_connection = Clock::now();
}
}
void PeerConnectionList::RemoveConnection(Handle handle)
{
FETCH_LOCK(lock_);
for (auto it = peer_connections_.begin(); it != peer_connections_.end(); ++it)
{
if (it->second->handle() == handle)
{
FETCH_LOG_DEBUG(logging_name_, "Connection to ", it->first.uri(), " lost");
auto metadata = peer_metadata_.find(it->first);
if (metadata != peer_metadata_.end())
{
metadata->second.connected = false;
}
peer_connections_.erase(it);
break;
}
}
}
void PeerConnectionList::Disconnect(Uri const &peer)
{
FETCH_LOCK(lock_);
if (peer_metadata_.erase(peer) != 0u)
{
peer_connections_.erase(peer);
}
FETCH_LOG_DEBUG(logging_name_, "Connection to ", peer.uri(), " shut down");
}
void PeerConnectionList::DisconnectAll()
{
FETCH_LOCK(lock_);
peer_connections_.clear();
persistent_peers_.clear();
}
bool PeerConnectionList::ReadyForRetry(PeerMetadata const &metadata) const
{
std::size_t const log2_backoff = std::min(metadata.consecutive_failures, MAX_LOG2_BACKOFF);
Timepoint const backoff_deadline =
metadata.last_failed_connection + std::chrono::seconds{1u << log2_backoff};
return (Clock::now() >= backoff_deadline);
}
PeerConnectionList::PeerList PeerConnectionList::GetPeersToConnectTo() const
{
PeerList peers;
FETCH_LOCK(lock_);
// determine which of the persistent peers are no longer active
for (auto const &peer : persistent_peers_)
{
bool const inactive = peer_connections_.find(peer) == peer_connections_.end();
if (inactive)
{
auto it = peer_metadata_.find(peer);
// determine if this is an initial connection, or if we should try and apply some
// type of backoff.
bool const is_first_connection = it == peer_metadata_.end();
if (is_first_connection)
{
// on a first attempt, a connection attempt should always be made
peers.push_back(peer);
}
else
{
// lookup the connection metadata
auto const &metadata = it->second;
// determine if this connection should be connected again
if (ReadyForRetry(metadata))
{
peers.push_back(peer);
}
}
}
}
return peers;
}
} // namespace muddle
} // namespace fetch
| 6,922 | 2,259 |
//
// Created by yaoyao.sun on 2019-05-18.
// Copyright (c) 2019 Horizon Robotics. All rights reserved.
//
#include <iostream>
#include "bpu_predict/bpu_predict.h"
int TestHBCCInfo(int argc, char **argv) {
const char *model_file_path = "./models/faceMultitask.hbm";
const char *bpu_config = "./configs/bpu_config.json";
BPUHandle bpu_handle;
int ret = BPU_loadModel(model_file_path, &bpu_handle, bpu_config);
if (ret != 0) {
std::cout << "here load bpu model failed: "
<< BPU_getLastError(bpu_handle) << std::endl;
return 1;
}
const char **model_names;
int model_num;
ret = BPU_getModelNameList(bpu_handle, &model_names, &model_num);
if (ret != 0) {
std::cout << "here get name list failed: "
<< BPU_getLastError(bpu_handle) << std::endl;
return 1;
}
for (int i = 0; i < model_num; i++) {
std::cout << "model name:" << model_names[i] << std::endl;
}
return 0;
}
| 944 | 380 |
#include<bits/stdc++.h>
using namespace std;
/*
NAME : DIPU BISWAS
JUST CSE 2019 - 2020
PROBLEM CODE : 510A
LINK : https://codeforces.com/problemset/problem/510/A
*/
int main()
{
int m, n, i = 0, j = 0, k = 2;
cin >> m >> n;
for(i = 0; i < m; i++){
if(i % 2 == 0)
for(j = 0; j < n; j++)
cout << '#';
else if(i % 2 == 1 && k % 2 == 0){
for(j = 0; j < n; j++)
if(j == n - 1)
cout << '#';
else
cout << '.';
k++;
}
else if(i % 2 == 1 && k % 2 == 1)
{
k--;
for(j = 0; j < n; j++)
if(j == 0)
cout << '#';
else
cout << '.';
}
cout << endl;
}
return 0;
}
| 896 | 339 |
#include <libsystem/Result.h>
#include "kernel/node/Handle.h"
#include "kernel/node/Pipe.h"
#define PIPE_BUFFER_SIZE 4096
static bool pipe_can_read(FsPipe *node, FsHandle *handle)
{
__unused(handle);
// FIXME: make this atomic or something...
return !ringbuffer_is_empty(node->buffer) || !node->writers;
}
static bool pipe_can_write(FsPipe *node, FsHandle *handle)
{
__unused(handle);
// FIXME: make this atomic or something...
return !ringbuffer_is_full(node->buffer) || !node->readers;
}
static Result pipe_read(FsPipe *node, FsHandle *handle, void *buffer, size_t size, size_t *read)
{
__unused(handle);
if (!node->writers)
{
return ERR_STREAM_CLOSED;
}
*read = ringbuffer_read(node->buffer, (char *)buffer, size);
return SUCCESS;
}
static Result pipe_write(FsPipe *node, FsHandle *handle, const void *buffer, size_t size, size_t *written)
{
__unused(handle);
if (!node->readers)
{
return ERR_STREAM_CLOSED;
}
*written = ringbuffer_write(node->buffer, (const char *)buffer, size);
return SUCCESS;
}
static size_t pipe_size(FsPipe *node, FsHandle *handle)
{
__unused(node);
__unused(handle);
return PIPE_BUFFER_SIZE;
}
static void pipe_destroy(FsPipe *node)
{
ringbuffer_destroy(node->buffer);
}
FsNode *fspipe_create()
{
FsPipe *pipe = __create(FsPipe);
fsnode_init(pipe, FILE_TYPE_PIPE);
pipe->can_read = (FsNodeCanReadCallback)pipe_can_read;
pipe->can_write = (FsNodeCanWriteCallback)pipe_can_write;
pipe->read = (FsNodeReadCallback)pipe_read;
pipe->write = (FsNodeWriteCallback)pipe_write;
pipe->size = (FsNodeSizeCallback)pipe_size;
pipe->destroy = (FsNodeDestroyCallback)pipe_destroy;
pipe->buffer = ringbuffer_create(PIPE_BUFFER_SIZE);
return (FsNode *)pipe;
}
| 1,837 | 696 |
#include "pattern_fire.h"
void Pattern_Fire::init() {
clearLEDs();
FastLED.setBrightness(BRIGHTNESS_MAX);
}
void Pattern_Fire::loop() {
uint16_t brightness = max((float) BRIGHTNESS_MAX * (((float) (1024 - analogRead(PIN_POT))) / 1024.0), 5);
FastLED.setBrightness(brightness);
for (int i = 1; i < NUM_LEDS_TOTAL - 1; i++) {
if (leds[i].r == 0) { // This point has not yet been initialized
leds[i] = CRGB(random8(100, 255), random8(0, 50), 0);
} else { // Standard fire algorithm
x = ((leds[i-1].r - leds[i].r) - (leds[i + 1].r - leds[i].r)) / 4;
leds[i].r = x + random8(100, 255);
leds[i].g = random8(0, 20);
leds[i].b = 0;
}
}
FastLED.show();
delay(31);
}
| 750 | 338 |
#include<iostream.h>
#include<math.h>
void main()
{
const int iPrimeCount=169;
const int iPrimeNum[iPrimeCount]={1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103
,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211
,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331
,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449
,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587
,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709
,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853
,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991
,997};
int iN,iC,iLimit,iLow,iHigh,i;
while(cin>>iN>>iC)
{
for(i=0;i<iPrimeCount;i++)
{
if(i==iPrimeCount-1)
iLimit=i;
else if(iPrimeNum[i+1]>iN)
{
iLimit=i;
break;
}
}
if(iC>iLimit/2+1)
{
iLow=0;
iHigh=iLimit;
}
else
{
iLow=iLimit/2-iC+1;
iHigh=iLimit/2+iC-1+iLimit%2;
}
cout<<iN<<" "<<iC<<":";
for(i=iLow;i<=iHigh;i++)
cout<<" "<<iPrimeNum[i];
cout<<"\n\n";
}
} | 1,253 | 1,028 |
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/vm/jit/fixup.h"
#include "hphp/vixl/a64/simulator-a64.h"
#include "hphp/runtime/vm/jit/abi-arm.h"
#include "hphp/runtime/vm/jit/mc-generator.h"
#include "hphp/runtime/vm/jit/translator-inline.h"
#include "hphp/util/data-block.h"
namespace HPHP {
namespace JIT {
bool
FixupMap::getFrameRegs(const ActRec* ar, const ActRec* prevAr,
VMRegs* outVMRegs) const {
CTCA tca = (CTCA)ar->m_savedRip;
// Non-obvious off-by-one fun: if the *return address* points into the TC,
// then the frame we were running on in the TC is actually the previous
// frame.
ar = (const ActRec*)ar->m_savedRbp;
auto* ent = m_fixups.find(tca);
if (!ent) return false;
if (ent->isIndirect()) {
// Note: if indirect fixups happen frequently enough, we could
// just compare savedRip to be less than some threshold where
// stubs in a.code stop.
assert(prevAr);
auto pRealRip = ent->indirect.returnIpDisp +
uintptr_t(prevAr->m_savedRbp);
ent = m_fixups.find(*reinterpret_cast<CTCA*>(pRealRip));
assert(ent && !ent->isIndirect());
}
regsFromActRec(tca, ar, ent->fixup, outVMRegs);
return true;
}
void
FixupMap::recordSyncPoint(CodeAddress frontier, Offset pcOff, Offset spOff) {
m_pendingFixups.push_back(PendingFixup(frontier, Fixup(pcOff, spOff)));
}
void
FixupMap::recordIndirectFixup(CodeAddress frontier, int dwordsPushed) {
recordIndirectFixup(frontier, IndirectFixup((2 + dwordsPushed) * 8));
}
namespace {
bool isVMFrame(const ExecutionContext* ec, const ActRec* ar) {
// If this assert is failing, you may have forgotten a sync point somewhere
assert(ar);
bool ret = uintptr_t(ar) - s_stackLimit >= s_stackSize;
assert(!ret ||
(ar >= ec->m_stack.getStackLowAddress() &&
ar < ec->m_stack.getStackHighAddress()) ||
(ar->m_func->validate(), ar->inGenerator()));
return ret;
}
}
void
FixupMap::fixupWork(ExecutionContext* ec, ActRec* rbp) const {
assert(RuntimeOption::EvalJit);
TRACE(1, "fixup(begin):\n");
auto* nextRbp = rbp;
rbp = 0;
do {
auto* prevRbp = rbp;
rbp = nextRbp;
assert(rbp && "Missing fixup for native call");
nextRbp = reinterpret_cast<ActRec*>(rbp->m_savedRbp);
TRACE(2, "considering frame %p, %p\n", rbp, (void*)rbp->m_savedRip);
if (isVMFrame(ec, nextRbp)) {
TRACE(2, "fixup checking vm frame %s\n",
nextRbp->m_func->name()->data());
VMRegs regs;
if (getFrameRegs(rbp, prevRbp, ®s)) {
TRACE(2, "fixup(end): func %s fp %p sp %p pc %p\n",
regs.m_fp->m_func->name()->data(),
regs.m_fp, regs.m_sp, regs.m_pc);
ec->m_fp = const_cast<ActRec*>(regs.m_fp);
ec->m_pc = reinterpret_cast<PC>(regs.m_pc);
vmsp() = regs.m_sp;
return;
}
}
} while (rbp && rbp != nextRbp);
// OK, we've exhausted the entire actRec chain. We are only
// invoking ::fixup() from contexts that were known to be called out
// of the TC, so this cannot happen.
always_assert(false);
}
void
FixupMap::fixupWorkSimulated(ExecutionContext* ec) const {
TRACE(1, "fixup(begin):\n");
auto isVMFrame = [] (ActRec* ar, const vixl::Simulator* sim) {
// If this assert is failing, you may have forgotten a sync point somewhere
assert(ar);
bool ret =
uintptr_t(ar) - s_stackLimit >= s_stackSize &&
!sim->is_on_stack(ar);
assert(!ret ||
(ar >= g_context->m_stack.getStackLowAddress() &&
ar < g_context->m_stack.getStackHighAddress()) ||
ar->inGenerator());
return ret;
};
// For each nested simulator (corresponding to nested VM invocations), look at
// its PC to find a potential fixup key.
//
// Callstack walking is necessary, because we may get called from a
// uniqueStub.
for (int i = ec->m_activeSims.size() - 1; i >= 0; --i) {
auto const* sim = ec->m_activeSims[i];
auto* rbp = reinterpret_cast<ActRec*>(sim->xreg(JIT::ARM::rVmFp.code()));
auto tca = reinterpret_cast<TCA>(sim->pc());
TRACE(2, "considering frame %p, %p\n", rbp, tca);
while (rbp && !isVMFrame(rbp, sim)) {
tca = reinterpret_cast<TCA>(rbp->m_savedRip);
rbp = reinterpret_cast<ActRec*>(rbp->m_savedRbp);
}
if (!rbp) continue;
auto* ent = m_fixups.find(tca);
if (!ent) {
continue;
}
if (ent->isIndirect()) {
not_implemented();
}
VMRegs regs;
regsFromActRec(tca, rbp, ent->fixup, ®s);
TRACE(2, "fixup(end): func %s fp %p sp %p pc %p\b",
regs.m_fp->m_func->name()->data(),
regs.m_fp, regs.m_sp, regs.m_pc);
ec->m_fp = const_cast<ActRec*>(regs.m_fp);
ec->m_pc = reinterpret_cast<PC>(regs.m_pc);
vmsp() = regs.m_sp;
return;
}
// This shouldn't be reached.
always_assert(false);
}
void
FixupMap::fixup(ExecutionContext* ec) const {
if (RuntimeOption::EvalSimulateARM) {
// Walking the C++ stack doesn't work in simulation mode. Fortunately, the
// execution context has a stack of simulators, which we consult instead.
fixupWorkSimulated(ec);
} else {
// Start looking for fixup entries at the current (C++) frame. This
// will walk the frames upward until we find a TC frame.
DECLARE_FRAME_POINTER(framePtr);
fixupWork(ec, framePtr);
}
}
void
FixupMap::processPendingFixups() {
for (uint i = 0; i < m_pendingFixups.size(); i++) {
TCA tca = m_pendingFixups[i].m_tca;
assert(mcg->isValidCodeAddress(tca));
recordFixup(tca, m_pendingFixups[i].m_fixup);
}
m_pendingFixups.clear();
}
/* This is somewhat hacky. It decides which helpers/builtins should
* use eager vmreganchor based on profile information. Using eager
* vmreganchor for all helper calls is a perf regression. */
bool
FixupMap::eagerRecord(const Func* func) {
const char* list[] = {
"func_get_args",
"get_called_class",
"func_num_args",
"array_filter",
"array_map",
"hphp_func_slice_args",
};
for (int i = 0; i < sizeof(list)/sizeof(list[0]); i++) {
if (!strcmp(func->name()->data(), list[i])) {
return true;
}
}
if (func->cls() && !strcmp(func->cls()->name()->data(), "WaitHandle")
&& !strcmp(func->name()->data(), "join")) {
return true;
}
return false;
}
} // HPHP::JIT
} // HPHP
| 7,309 | 2,634 |
/** \file RadShockPosn.cc
* \author Jonathan Mackey
*
* This file reads in a series of fits files, which are assumed to be outputs
* of radiative shock simulations in 1D or 2D. For each file it determines
* the position of the shock in the x-direction, in the 1st y-column, and
* writes the (time,position) pair to a tab delimited text file. The first line
* of the file should contain info about the simulation that the data is from.
*
* This is explicitly serial code, so if there are parallel outputs to multiple
* files this code won't work.
*
* Compile with:\n
* g++ -Wall -DSERIAL RadShockPosn.cc ../testing/global.cc ../testing/uniformGrid.cc ../testing/dataio.cc -lreadline -lcfitsio
*
* Run with (example):\n
* ./a.out v140.txt ../results/RadShock2D_n128x32_v140_n10_T1e4 0 50
*
* */
#include "fitsio.h"
using namespace std;
#include "../testing/global.h"
#include "../testing/uniformGrid.h"
#include "../testing/dataio.h"
int main(int argc, char **argv)
{
// Get two input files and one output file from cmd-line args.
if (argc!=5) {
cerr << "Error: must call with 4 arguments...\n";
cerr << "RadShockPosn: <executable> <OutfileName> <file-base> <FirstOutput> <OutputFreq>\n";
rep.error("Bad number of Args",argc);
}
string outfile = argv[1];
string infilebase = argv[2];
int startct = atoi(argv[3]);
int opfreq = atoi(argv[4]);
if (isnan(startct) || isnan(opfreq) || opfreq==0) rep.error("Bad ints in args",opfreq);
cout <<"reading from first file "<<infilebase<<"."<<startct<<".fits\n";
cout <<"Writing shock position to file "<<outfile<<"\n";
cout <<"**********************************************\n";
class DataIOFits dataio;
class file_status fs;
// First we need to open the first file in the list, and get the grid dimensions,
// so we can set it up once and use it for all the infiles.
string infile;
ostringstream temp; temp.str("");
temp << infilebase <<"."<<startct <<".fits";
infile=temp.str();
cout <<"Initially reading from file "<<infile<<endl;
int err=0;
if (!fs.file_exists(infile)) rep.error("First file not found!",infile);
err = dataio.ReadHeader(infile);
if (err) rep.error("read header went bad",err);
// check dimensionality is ok.
if (SimPM.ndim!=1 && SimPM.ndim!=2)
rep.error("need 1D or 2D sim for rad.shock test",SimPM.ndim);
// Now the header should contain the sim dimensionality, number of vars,
// size of box, so we can use these to set up the grid.
cout <<"(UniformFV::setup_grid) Setting up grid...\n";
grid = new UniformGrid (SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Xmin, SimPM.Xmax, SimPM.NG);
if (grid==0) rep.error("(IntUniformFV::setup_grid) Couldn't assign data!", grid);
cout <<"(setup_grid) Done. g="<<grid<<"\n";
// Set up and open outfile
if (fs.file_exists(outfile)) cout <<"WARNING:: file exists, I am overwriting a text file.\n";
ofstream outf(outfile.c_str());
if(!outf.is_open()) rep.error("couldn't open outfile",outfile);
outf.setf( ios_base::scientific );
outf.precision(6);
outf << "# Radiative Shock Test Problem outputs. First file: "<<infile<<endl;
outf << "# Columns are time and shock position, and should be in cgs units (s,cm).\n\n";
int count = startct; double refvel=0.0;
// Need to loop this over all timesteps, incrementing 'start' by 'step' each time
// until there are no more files to analyse (note the last one might get left out).
do {
cout <<"Reading from file "<<infile<<endl;
// read data onto grid.
err += dataio.ReadHeader(infile);
err += dataio.ReadData(infile);
if (err) rep.error("read data went bad for file",err);
// get first point, and move to XP end of grid.
cell *c = grid->FirstPt();
do {c=grid->NextPt(c,XP);} while (grid->NextPt(c,XP) !=0);
cell *c2 = grid->NextPt(c,XN); if (!c2) {rep.error("Lost on grid",c2); grid->PrintCell(c);}
refvel = c->P[VX];
// find the shock position by locating where VX first changes by >10%
while ( fabs(fabs(c2->P[VX]/refvel)-1.0) <= 0.3) {
c = c2;
c2 = grid->NextPt(c2,XN);
if (!c2) { cout <<"no shock found!\n"; c2=c; break; }
}
// Write (x_sh,t_sim) to file.
outf <<SimPM.simtime<<"\t"<<c2->x[XX]<<"\n";
// increment filename
count += opfreq;
temp.str("");
temp << infilebase <<"."<< count <<".fits"; infile=temp.str();
} while (fs.file_exists(infile));
// loop over all timesteps.
cout <<"\n***************************************************\n";
cout <<"couldn't find file "<<infile<<" for step "<<count<<"... assuming i'm finished!\n";
outf.close();
delete grid; grid=0;
return 0;
}
| 4,708 | 1,706 |
// GENERATED BY `scripts/gen-visitor-templates.py`; DO NOT MODIFY.
// Memory node implementation.
// @PENGUINLIONG
#pragma once
#include "node/reg.hpp"
typedef Reference<struct MemoryPatternCapture> MemoryPatternCaptureRef;
typedef Reference<struct MemoryFunctionVariable> MemoryFunctionVariableRef;
typedef Reference<struct MemoryIterationVariable> MemoryIterationVariableRef;
typedef Reference<struct MemoryUniformBuffer> MemoryUniformBufferRef;
typedef Reference<struct MemoryStorageBuffer> MemoryStorageBufferRef;
typedef Reference<struct MemorySampledImage> MemorySampledImageRef;
typedef Reference<struct MemoryStorageImage> MemoryStorageImageRef;
struct MemoryPatternCapture : public Memory {
static const MemoryClass CLS = L_MEMORY_CLASS_PATTERN_CAPTURE;
MemoryRef captured;
inline MemoryPatternCapture(
const TypeRef& ty,
const std::vector<ExprRef>& ac,
const MemoryRef& captured
) : Memory(L_MEMORY_CLASS_PATTERN_CAPTURE, ty, ac), captured(captured) {
liong::assert(captured != nullptr);
}
inline MemoryPatternCapture(const TypeRef& ty, const std::vector<ExprRef>& ac) : Memory(L_MEMORY_CLASS_PATTERN_CAPTURE, ty, ac) {}
virtual bool structured_eq(MemoryRef b_) const override final {
if (!b_->is<MemoryPatternCapture>()) { return false; }
const auto& b2_ = b_->as<MemoryPatternCapture>();
if (!ty->structured_eq(b2_.ty)) { return false; }
if (ac.size() != b2_.ac.size()) { return false; }
for (size_t i = 0; i < ac.size(); ++i) {
if (!ac.at(i)->structured_eq(b2_.ac.at(i))) { return false; }
}
if (!captured->structured_eq(b2_.captured)) { return false; }
return true;
}
virtual void collect_children(NodeDrain* drain) const override final {
drain->push(ty);
for (const auto& x : ac) { drain->push(x); }
drain->push(captured);
}
};
struct MemoryFunctionVariable : public Memory {
static const MemoryClass CLS = L_MEMORY_CLASS_FUNCTION_VARIABLE;
std::shared_ptr<uint8_t> handle;
inline MemoryFunctionVariable(
const TypeRef& ty,
const std::vector<ExprRef>& ac,
std::shared_ptr<uint8_t> handle
) : Memory(L_MEMORY_CLASS_FUNCTION_VARIABLE, ty, ac), handle(handle) {
}
virtual bool structured_eq(MemoryRef b_) const override final {
if (!b_->is<MemoryFunctionVariable>()) { return false; }
const auto& b2_ = b_->as<MemoryFunctionVariable>();
if (!ty->structured_eq(b2_.ty)) { return false; }
if (ac.size() != b2_.ac.size()) { return false; }
for (size_t i = 0; i < ac.size(); ++i) {
if (!ac.at(i)->structured_eq(b2_.ac.at(i))) { return false; }
}
if (handle != b2_.handle) { return false; }
return true;
}
virtual void collect_children(NodeDrain* drain) const override final {
drain->push(ty);
for (const auto& x : ac) { drain->push(x); }
}
};
struct MemoryIterationVariable : public Memory {
static const MemoryClass CLS = L_MEMORY_CLASS_ITERATION_VARIABLE;
ExprRef begin;
ExprRef end;
ExprRef stride;
inline MemoryIterationVariable(
const TypeRef& ty,
const std::vector<ExprRef>& ac,
const ExprRef& begin,
const ExprRef& end,
const ExprRef& stride
) : Memory(L_MEMORY_CLASS_ITERATION_VARIABLE, ty, ac), begin(begin), end(end), stride(stride) {
liong::assert(begin != nullptr);
liong::assert(end != nullptr);
liong::assert(stride != nullptr);
}
virtual bool structured_eq(MemoryRef b_) const override final {
if (!b_->is<MemoryIterationVariable>()) { return false; }
const auto& b2_ = b_->as<MemoryIterationVariable>();
if (!ty->structured_eq(b2_.ty)) { return false; }
if (ac.size() != b2_.ac.size()) { return false; }
for (size_t i = 0; i < ac.size(); ++i) {
if (!ac.at(i)->structured_eq(b2_.ac.at(i))) { return false; }
}
if (!begin->structured_eq(b2_.begin)) { return false; }
if (!end->structured_eq(b2_.end)) { return false; }
if (!stride->structured_eq(b2_.stride)) { return false; }
return true;
}
virtual void collect_children(NodeDrain* drain) const override final {
drain->push(ty);
for (const auto& x : ac) { drain->push(x); }
drain->push(begin);
drain->push(end);
drain->push(stride);
}
};
struct MemoryUniformBuffer : public Memory {
static const MemoryClass CLS = L_MEMORY_CLASS_UNIFORM_BUFFER;
uint32_t binding;
uint32_t set;
inline MemoryUniformBuffer(
const TypeRef& ty,
const std::vector<ExprRef>& ac,
uint32_t binding,
uint32_t set
) : Memory(L_MEMORY_CLASS_UNIFORM_BUFFER, ty, ac), binding(binding), set(set) {
}
virtual bool structured_eq(MemoryRef b_) const override final {
if (!b_->is<MemoryUniformBuffer>()) { return false; }
const auto& b2_ = b_->as<MemoryUniformBuffer>();
if (!ty->structured_eq(b2_.ty)) { return false; }
if (ac.size() != b2_.ac.size()) { return false; }
for (size_t i = 0; i < ac.size(); ++i) {
if (!ac.at(i)->structured_eq(b2_.ac.at(i))) { return false; }
}
if (binding != b2_.binding) { return false; }
if (set != b2_.set) { return false; }
return true;
}
virtual void collect_children(NodeDrain* drain) const override final {
drain->push(ty);
for (const auto& x : ac) { drain->push(x); }
}
};
struct MemoryStorageBuffer : public Memory {
static const MemoryClass CLS = L_MEMORY_CLASS_STORAGE_BUFFER;
uint32_t binding;
uint32_t set;
inline MemoryStorageBuffer(
const TypeRef& ty,
const std::vector<ExprRef>& ac,
uint32_t binding,
uint32_t set
) : Memory(L_MEMORY_CLASS_STORAGE_BUFFER, ty, ac), binding(binding), set(set) {
}
virtual bool structured_eq(MemoryRef b_) const override final {
if (!b_->is<MemoryStorageBuffer>()) { return false; }
const auto& b2_ = b_->as<MemoryStorageBuffer>();
if (!ty->structured_eq(b2_.ty)) { return false; }
if (ac.size() != b2_.ac.size()) { return false; }
for (size_t i = 0; i < ac.size(); ++i) {
if (!ac.at(i)->structured_eq(b2_.ac.at(i))) { return false; }
}
if (binding != b2_.binding) { return false; }
if (set != b2_.set) { return false; }
return true;
}
virtual void collect_children(NodeDrain* drain) const override final {
drain->push(ty);
for (const auto& x : ac) { drain->push(x); }
}
};
struct MemorySampledImage : public Memory {
static const MemoryClass CLS = L_MEMORY_CLASS_SAMPLED_IMAGE;
uint32_t binding;
uint32_t set;
inline MemorySampledImage(
const TypeRef& ty,
const std::vector<ExprRef>& ac,
uint32_t binding,
uint32_t set
) : Memory(L_MEMORY_CLASS_SAMPLED_IMAGE, ty, ac), binding(binding), set(set) {
}
virtual bool structured_eq(MemoryRef b_) const override final {
if (!b_->is<MemorySampledImage>()) { return false; }
const auto& b2_ = b_->as<MemorySampledImage>();
if (!ty->structured_eq(b2_.ty)) { return false; }
if (ac.size() != b2_.ac.size()) { return false; }
for (size_t i = 0; i < ac.size(); ++i) {
if (!ac.at(i)->structured_eq(b2_.ac.at(i))) { return false; }
}
if (binding != b2_.binding) { return false; }
if (set != b2_.set) { return false; }
return true;
}
virtual void collect_children(NodeDrain* drain) const override final {
drain->push(ty);
for (const auto& x : ac) { drain->push(x); }
}
};
struct MemoryStorageImage : public Memory {
static const MemoryClass CLS = L_MEMORY_CLASS_STORAGE_IMAGE;
uint32_t binding;
uint32_t set;
inline MemoryStorageImage(
const TypeRef& ty,
const std::vector<ExprRef>& ac,
uint32_t binding,
uint32_t set
) : Memory(L_MEMORY_CLASS_STORAGE_IMAGE, ty, ac), binding(binding), set(set) {
}
virtual bool structured_eq(MemoryRef b_) const override final {
if (!b_->is<MemoryStorageImage>()) { return false; }
const auto& b2_ = b_->as<MemoryStorageImage>();
if (!ty->structured_eq(b2_.ty)) { return false; }
if (ac.size() != b2_.ac.size()) { return false; }
for (size_t i = 0; i < ac.size(); ++i) {
if (!ac.at(i)->structured_eq(b2_.ac.at(i))) { return false; }
}
if (binding != b2_.binding) { return false; }
if (set != b2_.set) { return false; }
return true;
}
virtual void collect_children(NodeDrain* drain) const override final {
drain->push(ty);
for (const auto& x : ac) { drain->push(x); }
}
};
| 8,307 | 2,996 |
// -*- C++ -*-
// Copyright (C) 2005, 2006, 2009 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, 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
// General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
/**
* @file binomial_heap_base_.hpp
* Contains an implementation class for a base of binomial heaps.
*/
#ifndef PB_DS_BINOMIAL_HEAP_BASE_HPP
#define PB_DS_BINOMIAL_HEAP_BASE_HPP
/*
* Binomial heap base.
* Vuillemin J is the mastah.
* Modified from CLRS.
*/
#include <debug/debug.h>
#include <ext/pb_ds/detail/cond_dealtor.hpp>
#include <ext/pb_ds/detail/type_utils.hpp>
#include <ext/pb_ds/detail/left_child_next_sibling_heap_/left_child_next_sibling_heap_.hpp>
#include <ext/pb_ds/detail/left_child_next_sibling_heap_/null_metadata.hpp>
namespace __gnu_pbds
{
namespace detail
{
#define PB_DS_CLASS_T_DEC \
template<typename Value_Type, class Cmp_Fn, class Allocator>
#define PB_DS_CLASS_C_DEC \
binomial_heap_base_<Value_Type, Cmp_Fn, Allocator>
#ifdef _GLIBCXX_DEBUG
#define PB_DS_BASE_C_DEC \
left_child_next_sibling_heap_<Value_Type, Cmp_Fn, \
typename Allocator::size_type, \
Allocator, false>
#else
#define PB_DS_BASE_C_DEC \
left_child_next_sibling_heap_<Value_Type, Cmp_Fn, \
typename Allocator::size_type, Allocator>
#endif
/**
* class description = "8y|\|0|\/|i41 h34p 74813">
**/
template<typename Value_Type, class Cmp_Fn, class Allocator>
class binomial_heap_base_ : public PB_DS_BASE_C_DEC
{
private:
typedef PB_DS_BASE_C_DEC base_type;
protected:
typedef typename base_type::node node;
typedef typename base_type::node_pointer node_pointer;
typedef typename base_type::const_node_pointer const_node_pointer;
public:
typedef typename Allocator::size_type size_type;
typedef typename Allocator::difference_type difference_type;
typedef Value_Type value_type;
typedef
typename Allocator::template rebind<
value_type>::other::pointer
pointer;
typedef
typename Allocator::template rebind<
value_type>::other::const_pointer
const_pointer;
typedef
typename Allocator::template rebind<
value_type>::other::reference
reference;
typedef
typename Allocator::template rebind<
value_type>::other::const_reference
const_reference;
typedef
typename PB_DS_BASE_C_DEC::const_point_iterator
const_point_iterator;
typedef typename PB_DS_BASE_C_DEC::point_iterator point_iterator;
typedef typename PB_DS_BASE_C_DEC::const_iterator const_iterator;
typedef typename PB_DS_BASE_C_DEC::iterator iterator;
typedef Cmp_Fn cmp_fn;
typedef Allocator allocator_type;
public:
inline point_iterator
push(const_reference r_val);
void
modify(point_iterator it, const_reference r_new_val);
inline const_reference
top() const;
void
pop();
void
erase(point_iterator it);
inline void
clear();
template<typename Pred>
size_type
erase_if(Pred pred);
template<typename Pred>
void
split(Pred pred, PB_DS_CLASS_C_DEC& other);
void
join(PB_DS_CLASS_C_DEC& other);
protected:
binomial_heap_base_();
binomial_heap_base_(const Cmp_Fn& r_cmp_fn);
binomial_heap_base_(const PB_DS_CLASS_C_DEC& other);
void
swap(PB_DS_CLASS_C_DEC& other);
~binomial_heap_base_();
template<typename It>
void
copy_from_range(It first_it, It last_it);
inline void
find_max();
#ifdef _GLIBCXX_DEBUG
void
assert_valid(bool strictly_binomial) const;
void
assert_max() const;
#endif
private:
inline node_pointer
fix(node_pointer p_nd) const;
inline void
insert_node(node_pointer p_nd);
inline void
remove_parentless_node(node_pointer p_nd);
inline node_pointer
join(node_pointer p_lhs, node_pointer p_rhs) const;
#ifdef _GLIBCXX_DEBUG
void
assert_node_consistent(const_node_pointer, bool, bool) const;
#endif
protected:
node_pointer m_p_max;
};
#include <ext/pb_ds/detail/binomial_heap_base_/constructors_destructor_fn_imps.hpp>
#include <ext/pb_ds/detail/binomial_heap_base_/debug_fn_imps.hpp>
#include <ext/pb_ds/detail/binomial_heap_base_/find_fn_imps.hpp>
#include <ext/pb_ds/detail/binomial_heap_base_/insert_fn_imps.hpp>
#include <ext/pb_ds/detail/binomial_heap_base_/erase_fn_imps.hpp>
#include <ext/pb_ds/detail/binomial_heap_base_/split_join_fn_imps.hpp>
#undef PB_DS_CLASS_C_DEC
#undef PB_DS_CLASS_T_DEC
#undef PB_DS_BASE_C_DEC
} // namespace detail
} // namespace __gnu_pbds
#endif
| 6,158 | 2,160 |
#include "VehicleDirector.h"
#include <iostream>
namespace core {
VehicleDirector::VehicleDirector() {
m_builder = nullptr;
}
void VehicleDirector::ChangeBuilder(VehicleBuilder* builder) {
m_builder = builder;
}
void VehicleDirector::Make(AxleNum type) {
if (m_builder == nullptr) throw "Builder is nullptr!";
m_builder->Reset();
switch (type)
{
case TwoAxle:
std::cout << "TwoAxle" << std::endl;
m_builder->SetName("Two axle truck");
m_builder->AddAxle();
m_builder->AddAxle();
break;
case ThreeAxle:
std::cout << "ThreeAxle" << std::endl;
m_builder->SetName("Three axle truck");
m_builder->AddAxle();
m_builder->AddAxle();
m_builder->AddAxle();
break;
case FourAxle:
m_builder->SetName("Four axle truck");
m_builder->AddAxle();
m_builder->AddAxle();
m_builder->AddAxle();
m_builder->AddAxle();
break;
default:
throw "Does not support type the given type!";
break;
}
}
} | 1,243 | 389 |
//
// Copyright (c) 2017-2020 the rbfx project.
//
// 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.
//
#ifdef WIN32
#include <windows.h>
#endif
#include <Urho3D/Engine/EngineDefs.h>
#include <Urho3D/Engine/EngineEvents.h>
#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Core/WorkQueue.h>
#include <Urho3D/Graphics/Graphics.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/Resource/JSONArchive.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/SystemUI/SystemUI.h>
#include <Urho3D/SystemUI/Console.h>
#include <Urho3D/SystemUI/DebugHud.h>
#include <Urho3D/LibraryInfo.h>
#include <Urho3D/Core/CommandLine.h>
#include <Urho3D/Audio/Sound.h>
#include <Toolbox/ToolboxAPI.h>
#include <Toolbox/SystemUI/Widgets.h>
#include <IconFontCppHeaders/IconsFontAwesome5.h>
#include <nativefiledialog/nfd.h>
#include "Editor.h"
#include "EditorEvents.h"
#include "EditorIconCache.h"
#include "Tabs/Scene/SceneTab.h"
#include "Tabs/Scene/EditorSceneSettings.h"
#include "Tabs/UI/UITab.h"
#include "Tabs/InspectorTab.h"
#include "Tabs/HierarchyTab.h"
#include "Tabs/ConsoleTab.h"
#include "Tabs/ResourceTab.h"
#include "Tabs/PreviewTab.h"
#include "Pipeline/Asset.h"
#include "Pipeline/Commands/CookScene.h"
#include "Pipeline/Commands/BuildAssets.h"
#include "Pipeline/Importers/ModelImporter.h"
#include "Pipeline/Importers/SceneConverter.h"
#include "Pipeline/Importers/TextureImporter.h"
#if URHO3D_PLUGINS
# include "Plugins/PluginManager.h"
# include "Plugins/ModulePlugin.h"
#endif
#include "Plugins/ScriptBundlePlugin.h"
#include "Inspector/AssetInspector.h"
#include "Inspector/MaterialInspector.h"
#include "Inspector/ModelInspector.h"
#include "Inspector/NodeInspector.h"
#include "Inspector/ComponentInspector.h"
#include "Inspector/SerializableInspector.h"
#include "Inspector/SoundInspector.h"
#include "Inspector/UIElementInspector.h"
#include "Tabs/ProfilerTab.h"
#include "EditorUndo.h"
namespace Urho3D
{
namespace
{
const auto&& DEFAULT_TAB_TYPES = {
InspectorTab::GetTypeStatic(),
HierarchyTab::GetTypeStatic(),
ResourceTab::GetTypeStatic(),
ConsoleTab::GetTypeStatic(),
PreviewTab::GetTypeStatic(),
SceneTab::GetTypeStatic(),
ProfilerTab::GetTypeStatic()
};
}
Editor::Editor(Context* context)
: Application(context)
{
}
void Editor::Setup()
{
context_->RegisterSubsystem(this, Editor::GetTypeStatic());
#ifdef _WIN32
// Required until SDL supports hdpi on windows
if (HMODULE hLibrary = LoadLibraryA("Shcore.dll"))
{
typedef HRESULT(WINAPI*SetProcessDpiAwarenessType)(size_t value);
if (auto fn = GetProcAddress(hLibrary, "SetProcessDpiAwareness"))
((SetProcessDpiAwarenessType)fn)(2); // PROCESS_PER_MONITOR_DPI_AWARE
FreeLibrary(hLibrary);
}
#endif
// Discover resource prefix path by looking for CoreData and going up.
for (coreResourcePrefixPath_ = context_->GetFileSystem()->GetProgramDir();;
coreResourcePrefixPath_ = GetParentPath(coreResourcePrefixPath_))
{
if (context_->GetFileSystem()->DirExists(coreResourcePrefixPath_ + "CoreData"))
break;
else
{
#if WIN32
if (coreResourcePrefixPath_.length() <= 3) // Root path of any drive
#else
if (coreResourcePrefixPath_ == "/") // Filesystem root
#endif
{
URHO3D_LOGERROR("Prefix path not found, unable to continue. Prefix path must contain all of your data "
"directories (including CoreData).");
engine_->Exit();
}
}
}
engineParameters_[EP_WINDOW_TITLE] = GetTypeName();
engineParameters_[EP_HEADLESS] = false;
engineParameters_[EP_FULL_SCREEN] = false;
engineParameters_[EP_LOG_LEVEL] = LOG_DEBUG;
engineParameters_[EP_WINDOW_RESIZABLE] = true;
engineParameters_[EP_AUTOLOAD_PATHS] = "";
engineParameters_[EP_RESOURCE_PATHS] = "CoreData;EditorData";
engineParameters_[EP_RESOURCE_PREFIX_PATHS] = coreResourcePrefixPath_;
engineParameters_[EP_WINDOW_MAXIMIZE] = true;
engineParameters_[EP_ENGINE_AUTO_LOAD_SCRIPTS] = false;
#if URHO3D_SYSTEMUI_VIEWPORTS
engineParameters_[EP_HIGH_DPI] = true;
engineParameters_[EP_SYSTEMUI_FLAGS] = ImGuiConfigFlags_ViewportsEnable | ImGuiConfigFlags_DpiEnableScaleViewports;
#else
engineParameters_[EP_HIGH_DPI] = false;
#endif
// Load editor settings
{
auto* fs = context_->GetFileSystem();
ea::string editorSettingsDir = fs->GetAppPreferencesDir("rbfx", "Editor");
if (!fs->DirExists(editorSettingsDir))
fs->CreateDir(editorSettingsDir);
ea::string editorSettingsFile = editorSettingsDir + "Editor.json";
if (fs->FileExists(editorSettingsFile))
{
JSONFile file(context_);
if (file.LoadFile(editorSettingsFile))
{
JSONInputArchive archive(&file);
if (!Serialize(archive))
URHO3D_LOGERROR("Loading of editor settings failed.");
engineParameters_[EP_WINDOW_WIDTH] = windowSize_.x_;
engineParameters_[EP_WINDOW_HEIGHT] = windowSize_.y_;
engineParameters_[EP_WINDOW_POSITION_X] = windowPos_.x_;
engineParameters_[EP_WINDOW_POSITION_Y] = windowPos_.y_;
}
}
}
context_->GetLog()->SetLogFormat("[%H:%M:%S] [%l] [%n] : %v");
SetRandomSeed(Time::GetTimeSinceEpoch());
// Register factories
context_->RegisterFactory<EditorIconCache>();
context_->RegisterFactory<SceneTab>();
context_->RegisterFactory<UITab>();
context_->RegisterFactory<ConsoleTab>();
context_->RegisterFactory<HierarchyTab>();
context_->RegisterFactory<InspectorTab>();
context_->RegisterFactory<ResourceTab>();
context_->RegisterFactory<PreviewTab>();
context_->RegisterFactory<ProfilerTab>();
// Inspectors.
inspectors_.push_back(SharedPtr(new AssetInspector(context_)));
inspectors_.push_back(SharedPtr(new ModelInspector(context_)));
inspectors_.push_back(SharedPtr(new MaterialInspector(context_)));
inspectors_.push_back(SharedPtr(new SoundInspector(context_)));
inspectors_.push_back(SharedPtr(new NodeInspector(context_)));
inspectors_.push_back(SharedPtr(new ComponentInspector(context_)));
inspectors_.push_back(SharedPtr(new UIElementInspector(context_)));
// FIXME: If user registers their own inspector later then SerializableInspector would no longer come in last.
inspectors_.push_back(SharedPtr(new SerializableInspector(context_)));
#if URHO3D_PLUGINS
RegisterPluginsLibrary(context_);
#endif
RegisterToolboxTypes(context_);
EditorSceneSettings::RegisterObject(context_);
context_->RegisterFactory<SerializableInspector>();
// Importers
ModelImporter::RegisterObject(context_);
SceneConverter::RegisterObject(context_);
TextureImporter::RegisterObject(context_);
Asset::RegisterObject(context_);
// Define custom command line parameters here
auto& cmd = GetCommandLineParser();
cmd.add_option("project", defaultProjectPath_, "Project to open or create on startup.")->set_custom_option("dir");
// Subcommands
RegisterSubcommand<CookScene>();
RegisterSubcommand<BuildAssets>();
keyBindings_.Bind(ActionType::OpenProject, this, &Editor::OpenOrCreateProject);
keyBindings_.Bind(ActionType::Exit, this, &Editor::OnExitHotkeyPressed);
}
void Editor::Start()
{
// Execute specified subcommand and exit.
for (SharedPtr<SubCommand>& cmd : subCommands_)
{
if (GetCommandLineParser().got_subcommand(cmd->GetTypeName().c_str()))
{
context_->GetLog()->SetLogFormat("%v");
ExecuteSubcommand(cmd);
engine_->Exit();
return;
}
}
// Continue with normal editor initialization
context_->RegisterSubsystem(new SceneManager(context_));
context_->RegisterSubsystem(new EditorIconCache(context_));
context_->GetInput()->SetMouseMode(MM_ABSOLUTE);
context_->GetInput()->SetMouseVisible(true);
context_->GetCache()->SetAutoReloadResources(true);
engine_->SetAutoExit(false);
SubscribeToEvent(E_UPDATE, [this](StringHash, VariantMap& args) { OnUpdate(args); });
// Creates console but makes sure it's UI is not rendered. Console rendering is done manually in editor.
auto* console = engine_->CreateConsole();
console->SetAutoVisibleOnError(false);
context_->GetFileSystem()->SetExecuteConsoleCommands(false);
SubscribeToEvent(E_CONSOLECOMMAND, [this](StringHash, VariantMap& args) { OnConsoleCommand(args); });
console->RefreshInterpreters();
SubscribeToEvent(E_ENDFRAME, [this](StringHash, VariantMap&) { OnEndFrame(); });
SubscribeToEvent(E_EXITREQUESTED, [this](StringHash, VariantMap&) { OnExitRequested(); });
SubscribeToEvent(E_EDITORPROJECTSERIALIZE, [this](StringHash, VariantMap&) { UpdateWindowTitle(); });
SubscribeToEvent(E_CONSOLEURICLICK, [this](StringHash, VariantMap& args) { OnConsoleUriClick(args); });
SubscribeToEvent(E_EDITORSELECTIONCHANGED, &Editor::OnSelectionChanged);
SetupSystemUI();
if (!defaultProjectPath_.empty())
{
ui::GetIO().IniFilename = nullptr; // Avoid creating imgui.ini in some cases
OpenProject(defaultProjectPath_);
}
// Hud will be rendered manually.
context_->GetEngine()->CreateDebugHud()->SetMode(DEBUGHUD_SHOW_NONE);
}
void Editor::ExecuteSubcommand(SubCommand* cmd)
{
if (!defaultProjectPath_.empty())
{
project_ = new Project(context_);
context_->RegisterSubsystem(project_);
if (!project_->LoadProject(defaultProjectPath_))
{
URHO3D_LOGERRORF("Loading project '%s' failed.", pendingOpenProject_.c_str());
exitCode_ = EXIT_FAILURE;
engine_->Exit();
return;
}
}
cmd->Execute();
}
void Editor::Stop()
{
// Save editor settings
if (!engine_->IsHeadless())
{
// Save window geometry
auto* graphics = GetSubsystem<Graphics>();
windowPos_ = graphics->GetWindowPosition();
windowSize_ = graphics->GetSize();
auto* fs = context_->GetFileSystem();
ea::string editorSettingsDir = fs->GetAppPreferencesDir("rbfx", "Editor");
if (!fs->DirExists(editorSettingsDir))
fs->CreateDir(editorSettingsDir);
JSONFile json(context_);
JSONOutputArchive archive(&json);
if (Serialize(archive))
{
if (!json.SaveFile(editorSettingsDir + "Editor.json"))
URHO3D_LOGERROR("Saving of editor settings failed.");
}
else
URHO3D_LOGERROR("Serializing of editor settings failed.");
}
context_->GetWorkQueue()->Complete(0);
if (auto* manager = GetSubsystem<SceneManager>())
manager->UnloadAll();
CloseProject();
context_->RemoveSubsystem<WorkQueue>(); // Prevents deadlock when unloading plugin AppDomain in managed host.
context_->RemoveSubsystem<Editor>();
}
void Editor::OnUpdate(VariantMap& args)
{
ImGuiWindowFlags flags = ImGuiWindowFlags_MenuBar;
flags |= ImGuiWindowFlags_NoDocking;
ImGuiViewport* viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->Pos);
ImGui::SetNextWindowSize(viewport->Size);
ImGui::SetNextWindowViewport(viewport->ID);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
ImGui::Begin("DockSpace", nullptr, flags);
ImGui::PopStyleVar();
RenderMenuBar();
RenderSettingsWindow();
bool hasModified = false;
if (project_.NotNull())
{
dockspaceId_ = ui::GetID("Root");
ui::DockSpace(dockspaceId_);
auto tabsCopy = tabs_;
for (auto& tab : tabsCopy)
{
if (tab->RenderWindow())
{
// Only active window may override another active window
if (activeTab_ != tab && tab->IsActive())
{
activeTab_ = tab;
tab->OnFocused();
}
hasModified |= tab->IsModified();
}
else if (!tab->IsUtility())
// Content tabs get closed permanently
tabs_.erase(tabs_.find(tab));
}
if (!activeTab_.Expired())
{
activeTab_->OnActiveUpdate();
}
if (loadDefaultLayout_ && project_)
{
loadDefaultLayout_ = false;
LoadDefaultLayout();
}
}
else
{
// Render start page
auto& style = ui::GetStyle();
auto* lists = ui::GetWindowDrawList();
ImRect rect{ui::GetWindowContentRegionMin(), ui::GetWindowContentRegionMax()};
ImVec2 tileSize{200, 200};
ui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2{10, 10});
ui::SetCursorPos(rect.GetCenter() - ImVec2{tileSize.x * 1.5f + 10, tileSize.y * 1.5f + 10});
ui::BeginGroup();
struct State
{
explicit State(Editor* editor)
{
FileSystem *fs = editor->GetContext()->GetFileSystem();
StringVector& recents = editor->recentProjects_;
snapshots_.resize(recents.size());
for (int i = 0; i < recents.size();)
{
const ea::string& projectPath = recents[i];
ea::string snapshotFile = AddTrailingSlash(projectPath) + ".snapshot.png";
if (fs->FileExists(snapshotFile))
{
Image img(editor->context_);
if (img.LoadFile(snapshotFile))
{
SharedPtr<Texture2D> texture(editor->context_->CreateObject<Texture2D>());
texture->SetData(&img);
snapshots_[i] = texture;
}
}
++i;
}
}
ea::vector<SharedPtr<Texture2D>> snapshots_;
};
auto* state = ui::GetUIState<State>(this);
const StringVector& recents = recentProjects_;
int index = 0;
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 3; col++, index++)
{
SharedPtr<Texture2D> snapshot;
if (state->snapshots_.size() > index)
snapshot = state->snapshots_[index];
if (recents.size() <= index || (row == 2 && col == 2)) // Last tile never shows a project.
{
if (ui::Button("Open/Create Project", tileSize))
OpenOrCreateProject();
}
else
{
const ea::string& projectPath = recents[index];
if (snapshot.NotNull())
{
if (ui::ImageButton(snapshot.Get(), tileSize - style.ItemInnerSpacing * 2))
OpenProject(projectPath);
}
else
{
if (ui::Button(recents[index].c_str(), tileSize))
OpenProject(projectPath);
}
if (ui::IsItemHovered())
ui::SetTooltip("%s", projectPath.c_str());
}
ui::SameLine();
}
ui::NewLine();
}
ui::EndGroup();
ui::PopStyleVar();
}
ui::End();
ImGui::PopStyleVar();
// Dialog for a warning when application is being closed with unsaved resources.
if (exiting_)
{
if (!context_->GetWorkQueue()->IsCompleted(0))
{
ui::OpenPopup("Completing Tasks");
if (ui::BeginPopupModal("Completing Tasks", nullptr, ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_Popup))
{
ui::TextUnformatted("Some tasks are in progress and are being completed. Please wait.");
static float totalIncomplete = context_->GetWorkQueue()->GetNumIncomplete(0);
ui::ProgressBar(100.f / totalIncomplete * Min(totalIncomplete - (float)context_->GetWorkQueue()->GetNumIncomplete(0), totalIncomplete));
ui::EndPopup();
}
}
else if (hasModified)
{
ui::OpenPopup("Save All?");
if (ui::BeginPopupModal("Save All?", nullptr, ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoResize |
ImGuiWindowFlags_NoMove | ImGuiWindowFlags_Popup))
{
ui::TextUnformatted("You have unsaved resources. Save them before exiting?");
if (ui::Button(ICON_FA_SAVE " Save & Close"))
{
for (auto& tab : tabs_)
{
if (tab->IsModified())
tab->SaveResource();
}
ui::CloseCurrentPopup();
}
ui::SameLine();
if (ui::Button(ICON_FA_EXCLAMATION_TRIANGLE " Close without saving"))
{
engine_->Exit();
}
ui::SetHelpTooltip(ICON_FA_EXCLAMATION_TRIANGLE " All unsaved changes will be lost!", KEY_UNKNOWN);
ui::SameLine();
if (ui::Button(ICON_FA_TIMES " Cancel"))
{
exiting_ = false;
ui::CloseCurrentPopup();
}
ui::EndPopup();
}
}
else
{
context_->GetWorkQueue()->Complete(0);
if (project_.NotNull())
{
project_->SaveProject();
CloseProject();
}
engine_->Exit();
}
}
}
Tab* Editor::CreateTab(StringHash type)
{
SharedPtr<Tab> tab(DynamicCast<Tab>(context_->CreateObject(type)));
tabs_.push_back(tab);
return tab.Get();
}
StringVector Editor::GetObjectsByCategory(const ea::string& category)
{
StringVector result;
const auto& factories = context_->GetObjectFactories();
auto it = context_->GetObjectCategories().find(category);
if (it != context_->GetObjectCategories().end())
{
for (const StringHash& type : it->second)
{
auto jt = factories.find(type);
if (jt != factories.end())
result.push_back(jt->second->GetTypeName());
}
}
return result;
}
void Editor::OnConsoleCommand(VariantMap& args)
{
using namespace ConsoleCommand;
if (args[P_COMMAND].GetString() == "revision")
URHO3D_LOGINFOF("Engine revision: %s", GetRevision());
}
void Editor::OnEndFrame()
{
// Opening a new project must be done at the point when SystemUI is not in use. End of the frame is a good
// candidate. This subsystem will be recreated.
if (!pendingOpenProject_.empty())
{
CloseProject();
// Reset SystemUI so that imgui loads it's config proper.
context_->RemoveSubsystem<SystemUI>();
#if URHO3D_SYSTEMUI_VIEWPORTS
unsigned flags = ImGuiConfigFlags_ViewportsEnable | ImGuiConfigFlags_DpiEnableScaleViewports;
#else
unsigned flags = 0;
#endif
context_->RegisterSubsystem(new SystemUI(context_, flags));
SetupSystemUI();
project_ = new Project(context_);
context_->RegisterSubsystem(project_);
bool loaded = project_->LoadProject(pendingOpenProject_);
// SystemUI has to be started after loading project, because project sets custom settings file path. Starting
// subsystem reads this file and loads settings.
if (loaded)
{
auto* fs = context_->GetFileSystem();
loadDefaultLayout_ = project_->NeeDefaultUIPlacement();
StringVector& recents = recentProjects_;
// Remove latest project if it was already opened or any projects that no longer exists.
for (auto it = recents.begin(); it != recents.end();)
{
if (*it == pendingOpenProject_ || !fs->DirExists(*it))
it = recents.erase(it);
else
++it;
}
// Latest project goes to front
recents.insert(recents.begin(), pendingOpenProject_);
// Limit recents list size
if (recents.size() > 10)
recents.resize(10);
}
else
{
CloseProject();
URHO3D_LOGERROR("Loading project failed.");
}
pendingOpenProject_.clear();
}
}
void Editor::OnExitRequested()
{
if (auto* preview = GetTab<PreviewTab>())
{
if (preview->GetSceneSimulationStatus() != SCENE_SIMULATION_STOPPED)
preview->Stop();
}
exiting_ = true;
}
void Editor::OnExitHotkeyPressed()
{
if (!exiting_)
OnExitRequested();
}
void Editor::CreateDefaultTabs()
{
for (StringHash type : DEFAULT_TAB_TYPES)
context_->RemoveSubsystem(type);
tabs_.clear();
for (StringHash type : DEFAULT_TAB_TYPES)
{
SharedPtr<Tab> tab;
tab.StaticCast(context_->CreateObject(type));
tabs_.push_back(tab);
}
}
void Editor::LoadDefaultLayout()
{
CreateDefaultTabs();
auto* inspector = GetTab<InspectorTab>();
auto* hierarchy = GetTab<HierarchyTab>();
auto* resources = GetTab<ResourceTab>();
auto* console = GetTab<ConsoleTab>();
auto* preview = GetTab<PreviewTab>();
auto* scene = GetTab<SceneTab>();
auto* profiler = GetTab<ProfilerTab>();
profiler->SetOpen(false);
ImGui::DockBuilderRemoveNode(dockspaceId_);
ImGui::DockBuilderAddNode(dockspaceId_, 0);
ImGui::DockBuilderSetNodeSize(dockspaceId_, ui::GetMainViewport()->Size);
ImGuiID dock_main_id = dockspaceId_;
ImGuiID dockHierarchy = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Left, 0.20f, nullptr, &dock_main_id);
ImGuiID dockResources = ImGui::DockBuilderSplitNode(dockHierarchy, ImGuiDir_Down, 0.40f, nullptr, &dockHierarchy);
ImGuiID dockInspector = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Right, 0.30f, nullptr, &dock_main_id);
ImGuiID dockLog = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Down, 0.30f, nullptr, &dock_main_id);
ImGui::DockBuilderDockWindow(hierarchy->GetUniqueTitle().c_str(), dockHierarchy);
ImGui::DockBuilderDockWindow(resources->GetUniqueTitle().c_str(), dockResources);
ImGui::DockBuilderDockWindow(console->GetUniqueTitle().c_str(), dockLog);
ImGui::DockBuilderDockWindow(profiler->GetUniqueTitle().c_str(), dockLog);
ImGui::DockBuilderDockWindow(scene->GetUniqueTitle().c_str(), dock_main_id);
ImGui::DockBuilderDockWindow(preview->GetUniqueTitle().c_str(), dock_main_id);
ImGui::DockBuilderDockWindow(inspector->GetUniqueTitle().c_str(), dockInspector);
ImGui::DockBuilderFinish(dockspaceId_);
scene->Activate();
}
void Editor::OpenProject(const ea::string& projectPath)
{
pendingOpenProject_ = AddTrailingSlash(projectPath);
}
void Editor::CloseProject()
{
SendEvent(E_EDITORPROJECTCLOSING);
context_->RemoveSubsystem<Project>();
for (StringHash type : DEFAULT_TAB_TYPES)
context_->RemoveSubsystem(type);
tabs_.clear();
project_.Reset();
}
Tab* Editor::GetTabByName(const ea::string& uniqueName)
{
for (auto& tab : tabs_)
{
if (tab->GetUniqueName() == uniqueName)
return tab.Get();
}
return nullptr;
}
Tab* Editor::GetTabByResource(const ea::string& resourceName)
{
for (auto& tab : tabs_)
{
auto resource = DynamicCast<BaseResourceTab>(tab);
if (resource && resource->GetResourceName() == resourceName)
return resource.Get();
}
return nullptr;
}
Tab* Editor::GetTab(StringHash type)
{
for (auto& tab : tabs_)
{
if (tab->GetType() == type)
return tab.Get();
}
return nullptr;
}
void Editor::SetupSystemUI()
{
static ImWchar fontAwesomeIconRanges[] = {ICON_MIN_FA, ICON_MAX_FA, 0};
static ImWchar notoSansRanges[] = {0x20, 0x52f, 0x1ab0, 0x2189, 0x2c60, 0x2e44, 0xa640, 0xab65, 0};
static ImWchar notoMonoRanges[] = {0x20, 0x513, 0x1e00, 0x1f4d, 0};
SystemUI* systemUI = GetSubsystem<SystemUI>();
systemUI->ApplyStyleDefault(true, 1.0f);
systemUI->AddFont("Fonts/NotoSans-Regular.ttf", notoSansRanges, 16.f);
systemUI->AddFont("Fonts/" FONT_ICON_FILE_NAME_FAS, fontAwesomeIconRanges, 14.f, true);
monoFont_ = systemUI->AddFont("Fonts/NotoMono-Regular.ttf", notoMonoRanges, 14.f);
systemUI->AddFont("Fonts/" FONT_ICON_FILE_NAME_FAS, fontAwesomeIconRanges, 12.f, true);
ui::GetStyle().WindowRounding = 3;
// Disable imgui saving ui settings on it's own. These should be serialized to project file.
auto& io = ui::GetIO();
#if URHO3D_SYSTEMUI_VIEWPORTS
io.ConfigViewportsNoAutoMerge = true;
#endif
io.IniFilename = nullptr;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable | ImGuiConfigFlags_NavEnableKeyboard;
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors;
io.ConfigWindowsResizeFromEdges = true;
// TODO: Make configurable.
auto& style = ImGui::GetStyle();
style.FrameBorderSize = 0;
style.WindowBorderSize = 1;
style.ItemSpacing = {4, 4};
ImVec4* colors = ImGui::GetStyle().Colors;
colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
colors[ImGuiCol_WindowBg] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
colors[ImGuiCol_ChildBg] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
colors[ImGuiCol_PopupBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);
colors[ImGuiCol_Border] = ImVec4(0.24f, 0.24f, 0.24f, 1.00f);
colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_FrameBg] = ImVec4(0.26f, 0.26f, 0.26f, 1.00f);
colors[ImGuiCol_FrameBgHovered] = ImVec4(0.32f, 0.32f, 0.32f, 1.00f);
colors[ImGuiCol_FrameBgActive] = ImVec4(0.37f, 0.37f, 0.37f, 1.00f);
colors[ImGuiCol_TitleBg] = ImVec4(0.12f, 0.12f, 0.12f, 1.00f);
colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f);
colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);
colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.00f);
colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f);
colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f);
colors[ImGuiCol_CheckMark] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f);
colors[ImGuiCol_SliderGrab] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f);
colors[ImGuiCol_SliderGrabActive] = ImVec4(0.56f, 0.56f, 0.56f, 1.00f);
colors[ImGuiCol_Button] = ImVec4(0.27f, 0.27f, 0.27f, 1.00f);
colors[ImGuiCol_ButtonHovered] = ImVec4(0.34f, 0.34f, 0.34f, 1.00f);
colors[ImGuiCol_ButtonActive] = ImVec4(0.38f, 0.38f, 0.38f, 1.00f);
colors[ImGuiCol_Header] = ImVec4(0.35f, 0.35f, 0.35f, 1.00f);
colors[ImGuiCol_HeaderHovered] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f);
colors[ImGuiCol_HeaderActive] = ImVec4(0.44f, 0.44f, 0.44f, 1.00f);
colors[ImGuiCol_Separator] = ImVec4(0.24f, 0.24f, 0.24f, 1.00f);
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.34f, 0.34f, 0.34f, 1.00f);
colors[ImGuiCol_ResizeGrip] = ImVec4(0.24f, 0.24f, 0.24f, 1.00f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.37f, 0.37f, 0.37f, 1.00f);
colors[ImGuiCol_Tab] = ImVec4(0.26f, 0.26f, 0.26f, 0.40f);
colors[ImGuiCol_TabHovered] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_TabActive] = ImVec4(0.28f, 0.28f, 0.28f, 1.00f);
colors[ImGuiCol_TabUnfocused] = ImVec4(0.17f, 0.17f, 0.17f, 1.00f);
colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.26f, 0.26f, 0.26f, 1.00f);
colors[ImGuiCol_DockingPreview] = ImVec4(0.55f, 0.55f, 0.55f, 1.00f);
colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f);
colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f);
colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f);
colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
colors[ImGuiCol_NavHighlight] = ImVec4(0.78f, 0.88f, 1.00f, 1.00f);
colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f);
colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.44f, 0.44f, 0.44f, 0.35f);
ImGuiSettingsHandler handler;
handler.TypeName = "Project";
handler.TypeHash = ImHashStr(handler.TypeName, 0, 0);
handler.ReadOpenFn = [](ImGuiContext* context, ImGuiSettingsHandler* handler, const char* name) -> void*
{
return (void*) name;
};
handler.ReadLineFn = [](ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
{
auto* systemUI = ui::GetSystemUI();
auto* editor = systemUI->GetSubsystem<Editor>();
const char* name = static_cast<const char*>(entry);
if (strcmp(name, "Window") == 0)
editor->CreateDefaultTabs();
else
{
Tab* tab = editor->GetTabByName(name);
if (tab == nullptr)
{
StringVector parts = ea::string(name).split('#');
tab = editor->CreateTab(parts.front());
}
tab->OnLoadUISettings(name, line);
}
};
handler.WriteAllFn = [](ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
auto* systemUI = ui::GetSystemUI();
auto* editor = systemUI->GetSubsystem<Editor>();
buf->appendf("[Project][Window]\n");
// Save tabs
for (auto& tab : editor->GetContentTabs())
tab->OnSaveUISettings(buf);
};
ui::GetCurrentContext()->SettingsHandlers.push_back(handler);
}
void Editor::UpdateWindowTitle(const ea::string& resourcePath)
{
if (context_->GetEngine()->IsHeadless())
return;
auto* project = GetSubsystem<Project>();
ea::string title;
if (project == nullptr)
title = "Editor";
else
{
ea::string projectName = GetFileName(RemoveTrailingSlash(project->GetProjectPath()));
title = ToString("Editor | %s", projectName.c_str());
if (!resourcePath.empty())
title += ToString(" | %s", GetFileName(resourcePath).c_str());
}
context_->GetGraphics()->SetWindowTitle(title);
}
template<typename T>
void Editor::RegisterSubcommand()
{
T::RegisterObject(context_);
SharedPtr<T> cmd(context_->CreateObject<T>());
subCommands_.push_back(DynamicCast<SubCommand>(cmd));
if (CLI::App* subCommand = GetCommandLineParser().add_subcommand(T::GetTypeNameStatic().c_str()))
cmd->RegisterCommandLine(*subCommand);
else
URHO3D_LOGERROR("Sub-command '{}' was not registered due to user error.", T::GetTypeNameStatic());
}
void Editor::OpenOrCreateProject()
{
nfdchar_t* projectDir = nullptr;
if (NFD_PickFolder("", &projectDir) == NFD_OKAY)
{
OpenProject(projectDir);
NFD_FreePath(projectDir);
}
}
#if URHO3D_STATIC && URHO3D_PLUGINS
bool Editor::RegisterPlugin(PluginApplication* plugin)
{
return project_->GetPlugins()->RegisterPlugin(plugin);
}
#endif
void Editor::OnConsoleUriClick(VariantMap& args)
{
using namespace ConsoleUriClick;
if (ui::IsMouseClicked(MOUSEB_LEFT))
{
const ea::string& protocol = args[P_PROTOCOL].GetString();
const ea::string& address = args[P_ADDRESS].GetString();
if (protocol == "res")
context_->GetFileSystem()->SystemOpen(context_->GetCache()->GetResourceFileName(address));
}
}
void Editor::OnSelectionChanged(StringHash, VariantMap& args)
{
using namespace EditorSelectionChanged;
auto tab = static_cast<Tab*>(args[P_TAB].GetPtr());
auto undo = GetSubsystem<UndoStack>();
ByteVector newSelection = tab->SerializeSelection();
if (tab == selectionTab_)
{
if (newSelection == selectionBuffer_)
return;
}
else
{
if (!selectionTab_.Expired())
selectionTab_->ClearSelection();
}
undo->Add<UndoSetSelection>(selectionTab_, selectionBuffer_, tab, newSelection);
selectionTab_ = tab;
selectionBuffer_ = newSelection;
}
}
| 35,058 | 11,831 |
#pragma once
#define PIPE_LOGGING | 34 | 15 |
/////////////////////////////////////////////////////////////////////////////
// Copyright (c) Electronic Arts Inc. All rights reserved.
/////////////////////////////////////////////////////////////////////////////
#include "EASTLTest.h"
#include "TestMap.h"
#include "TestSet.h"
#include <EASTL/hash_set.h>
#include <EASTL/hash_map.h>
#include <EASTL/unordered_set.h>
#include <EASTL/unordered_map.h>
#include <EASTL/map.h>
#include <EASTL/string.h>
#include <EASTL/algorithm.h>
#include <EASTL/vector.h>
#include <EASTL/unique_ptr.h>
EA_DISABLE_ALL_VC_WARNINGS()
#include <string.h>
EA_RESTORE_ALL_VC_WARNINGS()
using namespace eastl;
namespace eastl
{
template <>
struct hash<Align32>
{
size_t operator()(const Align32& a32) const
{ return static_cast<size_t>(a32.mX); }
};
// extension to hash an eastl::pair
template <typename T1, typename T2>
struct hash<pair<T1, T2>>
{
size_t operator()(const pair<T1, T2>& c) const
{
return static_cast<size_t>(hash<T1>()(c.first) ^ hash<T2>()(c.second));
}
};
}
// For regression code below.
class HashRegressionA { public: int x; };
class HashRegressionB { public: int y; };
// For regression code below.
struct Struct {
char8_t name[128];
};
// For regression code below.
template<class HashType>
struct HashTest
{
template<typename... Args>
auto operator()(Args&&... args)
{
return eastl::hash<HashType>{}(eastl::forward<Args>(args)...);
}
};
// What we are doing here is creating a special case of a hashtable where the key compare
// function is not the same as the value operator==. 99% of the time when you create a
// hashtable the key compare (predicate) is simply key_equal or something else that's
// identical to operator== for the hashtable value type. But for some tests we want
// to exercise the case that these aren't different. A result of this difference is that
// you can lookup an element in a hash table and the returned value is not == to the
// value you looked up, because it succeeds the key compare but not operator==.
struct HashtableValue
{
HashtableValue(eastl_size_t d = 0, eastl_size_t e = 0) : mData(d), mExtra(e){}
void Set(eastl_size_t d, eastl_size_t e = 0) { mData = d; mExtra = e; }
eastl_size_t mData;
eastl_size_t mExtra;
};
bool operator==(const HashtableValue& htv1, const HashtableValue& htv2)
{
return (htv1.mData == htv2.mData) && (htv1.mExtra == htv2.mExtra); // Fully compare the HashTableValue.
}
struct HashtableValuePredicate
{
bool operator()(const HashtableValue& htv1, const HashtableValue& htv2) const
{ return (htv1.mData == htv2.mData); } // Compare just the mData portion of HashTableValue.
};
struct HashtableValueHash
{
size_t operator()(const HashtableValue& htv) const
{ return static_cast<size_t>(htv.mData); }
};
// Explicit Template instantiations.
// These tell the compiler to compile all the functions for the given class.
template class eastl::hashtable<int,
eastl::pair<const int, int>,
eastl::allocator,
eastl::use_first<eastl::pair<const int, int>>,
eastl::equal_to<int>,
eastl::hash<int>,
mod_range_hashing,
default_ranged_hash,
prime_rehash_policy,
true, // bCacheHashCode
true, // bMutableIterators
true // bUniqueKeys
>;
template class eastl::hashtable<int,
eastl::pair<const int, int>,
eastl::allocator,
eastl::use_first<eastl::pair<const int, int>>,
eastl::equal_to<int>,
eastl::hash<int>,
mod_range_hashing,
default_ranged_hash,
prime_rehash_policy,
false, // bCacheHashCode
true, // bMutableIterators
true // bUniqueKeys
>;
// TODO(rparolin): known compiler error, we should fix this.
// template class eastl::hashtable<int,
// eastl::pair<const int, int>,
// eastl::allocator,
// eastl::use_first<eastl::pair<const int, int>>,
// eastl::equal_to<int>,
// eastl::hash<int>,
// mod_range_hashing,
// default_ranged_hash,
// prime_rehash_policy,
// false, // bCacheHashCode
// true, // bMutableIterators
// false // bUniqueKeys
// >;
// Note these will only compile non-inherited functions. We provide explicit
// template instantiations for the hashtable base class above to get compiler
// coverage of those inherited hashtable functions.
template class eastl::hash_set<int>;
template class eastl::hash_multiset<int>;
template class eastl::hash_map<int, int>;
template class eastl::hash_multimap<int, int>;
template class eastl::hash_set<Align32>;
template class eastl::hash_multiset<Align32>;
template class eastl::hash_map<Align32, Align32>;
template class eastl::hash_multimap<Align32, Align32>;
// validate static assumptions about hashtable core types
typedef eastl::hash_node<int, false> HashNode1;
typedef eastl::hash_node<int, true> HashNode2;
static_assert(eastl::is_default_constructible<HashNode1>::value, "hash_node static error");
static_assert(eastl::is_default_constructible<HashNode2>::value, "hash_node static error");
static_assert(eastl::is_copy_constructible<HashNode1>::value, "hash_node static error");
static_assert(eastl::is_copy_constructible<HashNode2>::value, "hash_node static error");
static_assert(eastl::is_move_constructible<HashNode1>::value, "hash_node static error");
static_assert(eastl::is_move_constructible<HashNode2>::value, "hash_node static error");
// A custom hash function that has a high number of collisions is used to ensure many keys share the same hash value.
struct colliding_hash
{
size_t operator()(const int& val) const
{ return static_cast<size_t>(val % 3); }
};
int TestHash()
{
int nErrorCount = 0;
{ // Test declarations
hash_set<int> hashSet;
hash_multiset<int> hashMultiSet;
hash_map<int, int> hashMap;
hash_multimap<int, int> hashMultiMap;
hash_set<int> hashSet2(hashSet);
EATEST_VERIFY(hashSet2.size() == hashSet.size());
EATEST_VERIFY(hashSet2 == hashSet);
hash_multiset<int> hashMultiSet2(hashMultiSet);
EATEST_VERIFY(hashMultiSet2.size() == hashMultiSet.size());
EATEST_VERIFY(hashMultiSet2 == hashMultiSet);
hash_map<int, int> hashMap2(hashMap);
EATEST_VERIFY(hashMap2.size() == hashMap.size());
EATEST_VERIFY(hashMap2 == hashMap);
hash_multimap<int, int> hashMultiMap2(hashMultiMap);
EATEST_VERIFY(hashMultiMap2.size() == hashMultiMap.size());
EATEST_VERIFY(hashMultiMap2 == hashMultiMap);
// allocator_type& get_allocator();
// void set_allocator(const allocator_type& allocator);
hash_set<int>::allocator_type& allocator = hashSet.get_allocator();
hashSet.set_allocator(EASTLAllocatorType());
hashSet.set_allocator(allocator);
// To do: Try to find something better to test here.
// const key_equal& key_eq() const;
// key_equal& key_eq();
hash_set<int> hs;
const hash_set<int> hsc;
const hash_set<int>::key_equal& ke = hsc.key_eq();
hs.key_eq() = ke;
// const char* get_name() const;
// void set_name(const char* pName);
#if EASTL_NAME_ENABLED
hashMap.get_allocator().set_name("test");
const char* pName = hashMap.get_allocator().get_name();
EATEST_VERIFY(equal(pName, pName + 5, "test"));
#endif
}
{
hash_set<int> hashSet;
// Clear a newly constructed, already empty container.
hashSet.clear(true);
EATEST_VERIFY(hashSet.validate());
EATEST_VERIFY(hashSet.size() == 0);
EATEST_VERIFY(hashSet.bucket_count() == 1);
for(int i = 0; i < 100; ++i)
hashSet.insert(i);
EATEST_VERIFY(hashSet.validate());
EATEST_VERIFY(hashSet.size() == 100);
hashSet.clear(true);
EATEST_VERIFY(hashSet.validate());
EATEST_VERIFY(hashSet.size() == 0);
EATEST_VERIFY(hashSet.bucket_count() == 1);
for(int i = 0; i < 100; ++i)
hashSet.insert(i);
EATEST_VERIFY(hashSet.validate());
EATEST_VERIFY(hashSet.size() == 100);
hashSet.clear(true);
EATEST_VERIFY(hashSet.validate());
EATEST_VERIFY(hashSet.size() == 0);
EATEST_VERIFY(hashSet.bucket_count() == 1);
}
{ // Test hash_set
// size_type size() const
// bool empty() const
// insert_return_type insert(const value_type& value);
// insert_return_type insert(const value_type& value, hash_code_t c, node_type* pNodeNew = NULL);
// iterator insert(const_iterator, const value_type& value);
// iterator find(const key_type& k);
// const_iterator find(const key_type& k) const;
// size_type count(const key_type& k) const;
typedef hash_set<int> HashSetInt;
HashSetInt hashSet;
const HashSetInt::size_type kCount = 10000;
EATEST_VERIFY(hashSet.empty());
EATEST_VERIFY(hashSet.size() == 0);
EATEST_VERIFY(hashSet.count(0) == 0);
for(int i = 0; i < (int)kCount; i++)
hashSet.insert(i);
EATEST_VERIFY(!hashSet.empty());
EATEST_VERIFY(hashSet.size() == kCount);
EATEST_VERIFY(hashSet.count(0) == 1);
for(HashSetInt::iterator it = hashSet.begin(); it != hashSet.end(); ++it)
{
int value = *it;
EATEST_VERIFY(value < (int)kCount);
}
for(int i = 0; i < (int)kCount * 2; i++)
{
HashSetInt::iterator it = hashSet.find(i);
if(i < (int)kCount)
EATEST_VERIFY(it != hashSet.end());
else
EATEST_VERIFY(it == hashSet.end());
}
// insert_return_type insert(const value_type& value, hash_code_t c, node_type* pNodeNew = NULL);
HashSetInt::node_type* pNode = hashSet.allocate_uninitialized_node();
HashSetInt::insert_return_type r = hashSet.insert(eastl::hash<int>()(999999), pNode, 999999);
EATEST_VERIFY(r.second == true);
pNode = hashSet.allocate_uninitialized_node();
r = hashSet.insert(eastl::hash<int>()(999999), pNode, 999999);
EATEST_VERIFY(r.second == false);
hashSet.free_uninitialized_node(pNode);
hashSet.erase(999999);
// iterator begin();
// const_iterator begin() const;
// iterator end();
// const_iterator end() const;
int* const pIntArray = new int[kCount];
memset(pIntArray, 0, kCount * sizeof(int)); // We want to make sure each element is present only once.
int nCount = 0;
for(HashSetInt::iterator it = hashSet.begin(); it != hashSet.end(); ++it, ++nCount)
{
int i = *it;
EATEST_VERIFY((i >= 0) && (i < (int)kCount) && (pIntArray[i] == 0));
pIntArray[i] = 1;
}
EATEST_VERIFY(nCount == (int)kCount);
delete[] pIntArray;
}
{
// size_type bucket_count() const
// size_type bucket_size(size_type n) const
// float load_factor() const
// float get_max_load_factor() const;
// void set_max_load_factor(float fMaxLoadFactor);
// void rehash(size_type n);
// const RehashPolicy& rehash_policy() const
// void rehash_policy(const RehashPolicy& rehashPolicy);
typedef hash_set<int> HashSetInt;
HashSetInt hashSet;
float fLoadFactor = hashSet.load_factor();
EATEST_VERIFY(fLoadFactor == 0.f);
hashSet.set_max_load_factor(65536.f * 512.f);
float fMaxLoadFactor = hashSet.get_max_load_factor();
EATEST_VERIFY(fMaxLoadFactor == (65536.f * 512.f));
hashSet.rehash(20);
HashSetInt::size_type n = hashSet.bucket_count();
EATEST_VERIFY((n >= 20) && (n < 25));
for(int i = 0; i < 100000; i++)
hashSet.insert(i); // This also tests for high loading.
HashSetInt::size_type n2 = hashSet.bucket_count();
EATEST_VERIFY(n2 == n); // Verify no rehashing has occured, due to our high load factor.
n = hashSet.bucket_size(0);
EATEST_VERIFY(n >= ((hashSet.size() / hashSet.bucket_count()) / 2)); // It will be some high value. We divide by 2 to give it some slop.
EATEST_VERIFY(hashSet.validate());
hash_set<int>::rehash_policy_type rp = hashSet.rehash_policy();
rp.mfGrowthFactor = 1.5f;
hashSet.rehash_policy(rp);
EATEST_VERIFY(hashSet.validate());
// local_iterator begin(size_type n);
// local_iterator end(size_type n);
// const_local_iterator begin(size_type n) const;
// const_local_iterator end(size_type n) const;
HashSetInt::size_type b = hashSet.bucket_count() - 1;
hash<int> IntHash;
for(HashSetInt::const_local_iterator cli = hashSet.begin(b); cli != hashSet.end(b); ++cli)
{
int v = *cli;
EATEST_VERIFY((IntHash(v) % hashSet.bucket_count()) == b);
}
// clear();
hashSet.clear();
EATEST_VERIFY(hashSet.validate());
EATEST_VERIFY(hashSet.empty());
EATEST_VERIFY(hashSet.size() == 0);
EATEST_VERIFY(hashSet.count(0) == 0);
hashSet.clear(true);
EATEST_VERIFY(hashSet.validate());
EATEST_VERIFY(hashSet.bucket_count() == 1);
}
{
// void reserve(size_type nElementCount);
nErrorCount += HashContainerReserveTest<hash_set<int>>()();
nErrorCount += HashContainerReserveTest<hash_multiset<int>>()();
nErrorCount += HashContainerReserveTest<hash_map<int, int>>()();
nErrorCount += HashContainerReserveTest<hash_multimap<int, int>>()();
}
{ // Test hash_set with cached hash code.
// insert_return_type insert(const value_type& value) ;
// iterator find(const key_type& k);
// const_iterator find(const key_type& k) const;
typedef hash_set<int, hash<int>, equal_to<int>, EASTLAllocatorType, true> HashSetIntC;
HashSetIntC hashSet;
const int kCount = 10000;
for(int i = 0; i < kCount; i++)
hashSet.insert(i);
for(HashSetIntC::iterator it = hashSet.begin(); it != hashSet.end(); ++it)
{
int value = *it;
EATEST_VERIFY(value < kCount);
}
for(int i = 0; i < kCount * 2; i++)
{
HashSetIntC::iterator it = hashSet.find(i);
if(i < kCount)
EATEST_VERIFY(it != hashSet.end());
else
EATEST_VERIFY(it == hashSet.end());
}
}
{
// ENABLE_IF_HASHCODE_U32(HashCodeT, iterator) find_by_hash(HashCodeT c)
// ENABLE_IF_HASHCODE_U32(HashCodeT, const_iterator) find_by_hash(HashCodeT c) const
{
// NOTE(rparolin):
// these overloads of find_by_hash contains a static assert that forces a compiler error in the event it is
// used with a hashtable configured to not cache the hash value in the node.
}
// iterator find_by_hash(const key_type& k, hash_code_t c)
// const_iterator find_by_hash(const key_type& k, hash_code_t c) const
#ifdef EA_COMPILER_CPP14_ENABLED
{
auto FindByHashTest = [&nErrorCount](auto& hashSet)
{
const int kCount = 10000;
for(int i = 0; i < kCount; i++)
hashSet.insert(i);
for(int i = 0; i < kCount * 2; i++)
{
auto it = hashSet.find_by_hash(i, i);
if(i < kCount)
EATEST_VERIFY(it != hashSet.end());
else
EATEST_VERIFY(it == hashSet.end());
}
};
{
typedef hash_set<int, hash<int>, equal_to<int>, EASTLAllocatorType, true> HashSetIntC;
HashSetIntC hashSetC;
FindByHashTest(hashSetC);
typedef hash_set<int, hash<int>, equal_to<int>, EASTLAllocatorType, false> HashSetInt;
HashSetInt hashSet;
FindByHashTest(hashSet);
}
}
#endif
}
{
// hash_set(const allocator_type& allocator);
// hashtable& operator=(const this_type& x);
// bool validate() const;
hash_set<int> hashSet1(EASTLAllocatorType("hash_set name"));
hash_set<int> hashSet2(hashSet1);
for(int i = 0; i < 10; i++)
{
hashSet1.insert(i);
hashSet2.insert(i);
}
hashSet1 = hashSet2;
EATEST_VERIFY(hashSet1.validate());
EATEST_VERIFY(hashSet2.validate());
}
{
// hash_set(size_type nBucketCount, const Hash& hashFunction = Hash(), const Predicate& predicate = Predicate(), const allocator_type& allocator);
// hashtable(const hashtable& x);
// hashtable& operator=(const this_type& x);
// void swap(this_type& x);
// bool validate() const;
{
hash_set<int> hashSet3(0);
hash_set<int> hashSet4(1);
hash_set<int> hashSet5(2);
hash_set<int> hashSet6(3);
hash_set<int> hashSet7(4);
hashSet4 = hashSet3;
hashSet6 = hashSet5;
hashSet3 = hashSet7;
for(int i = 0; i < 10; i++)
{
hashSet3.insert(i);
hashSet4.insert(i);
hashSet5.insert(i);
hashSet6.insert(i);
hashSet7.insert(i);
}
hashSet4 = hashSet3;
hashSet6 = hashSet5;
hashSet3 = hashSet7;
EATEST_VERIFY(hashSet3.validate());
EATEST_VERIFY(hashSet4.validate());
EATEST_VERIFY(hashSet5.validate());
EATEST_VERIFY(hashSet6.validate());
EATEST_VERIFY(hashSet7.validate());
swap(hashSet4, hashSet3);
swap(hashSet6, hashSet5);
swap(hashSet3, hashSet7);
EATEST_VERIFY(hashSet3.validate());
EATEST_VERIFY(hashSet4.validate());
EATEST_VERIFY(hashSet5.validate());
EATEST_VERIFY(hashSet6.validate());
EATEST_VERIFY(hashSet7.validate());
hash_set<int> hashSet8(hashSet6);
hash_set<int> hashSet9(hashSet7);
hash_set<int> hashSet10(hashSet8);
EATEST_VERIFY(hashSet8.validate());
EATEST_VERIFY(hashSet9.validate());
EATEST_VERIFY(hashSet10.validate());
}
// test hashtable::swap using different allocator instances
{
typedef hash_set<int, eastl::hash<int>, eastl::equal_to<int>, InstanceAllocator> HS;
HS hashSet1(InstanceAllocator("hash_set1 name", 111));
HS hashSet2(InstanceAllocator("hash_set2 name", 222));
for(int i = 0; i < 10; i++)
{
hashSet1.insert(i);
hashSet2.insert(i+10);
}
hashSet2.swap(hashSet1);
EATEST_VERIFY(hashSet1.validate());
EATEST_VERIFY(hashSet2.validate());
EATEST_VERIFY(hashSet1.get_allocator().mInstanceId == 222);
EATEST_VERIFY(hashSet2.get_allocator().mInstanceId == 111);
EATEST_VERIFY(eastl::all_of(eastl::begin(hashSet2), eastl::end(hashSet2), [](int i) { return i < 10; }));
EATEST_VERIFY(eastl::all_of(eastl::begin(hashSet1), eastl::end(hashSet1), [](int i) { return i >= 10; }));
}
}
{
// hash_set(InputIterator first, InputIterator last, size_type nBucketCount = 8, const Hash& hashFunction = Hash(), const Predicate& predicate = Predicate(), const allocator_type& allocator);
// bool validate() const;
vector<int> intArray;
for(int i = 0; i < 1000; i++)
intArray.push_back(i);
hash_set<int> hashSet1(intArray.begin(), intArray.end(), 0);
hash_set<int> hashSet2(intArray.begin(), intArray.end(), 1);
hash_set<int> hashSet3(intArray.begin(), intArray.end(), 2);
hash_set<int> hashSet4(intArray.begin(), intArray.end(), 3);
EATEST_VERIFY(hashSet1.validate());
EATEST_VERIFY(hashSet2.validate());
EATEST_VERIFY(hashSet3.validate());
EATEST_VERIFY(hashSet4.validate());
// bool validate_iterator(const_iterator i) const;
hash_set<int>::iterator it;
int result = hashSet1.validate_iterator(it);
EATEST_VERIFY(result == isf_none);
it = hashSet1.begin();
result = hashSet2.validate_iterator(it);
EATEST_VERIFY(result == isf_none);
result = hashSet1.validate_iterator(it);
EATEST_VERIFY(result == (isf_valid | isf_current | isf_can_dereference));
it = hashSet1.end();
result = hashSet1.validate_iterator(it);
EATEST_VERIFY(result == (isf_valid | isf_current));
// void reset_lose_memory();
hashSet1.reset_lose_memory();
hashSet1 = hashSet2;
EATEST_VERIFY(hashSet1.validate());
EATEST_VERIFY(hashSet2.validate());
hashSet3.reset_lose_memory();
hashSet4 = hashSet3;
EATEST_VERIFY(hashSet3.validate());
EATEST_VERIFY(hashSet4.validate());
hashSet2.reset_lose_memory();
hashSet3.reset_lose_memory();
swap(hashSet2, hashSet3);
EATEST_VERIFY(hashSet3.validate());
EATEST_VERIFY(hashSet4.validate());
hashSet2 = hashSet3;
EATEST_VERIFY(hashSet2.validate());
}
{
// void insert(InputIterator first, InputIterator last);
vector<int> intArray1;
vector<int> intArray2;
for(int i = 0; i < 1000; i++)
{
intArray1.push_back(i + 0);
intArray2.push_back(i + 500);
}
hash_set<int> hashSet1(intArray1.begin(), intArray1.end());
hashSet1.insert(intArray2.begin(), intArray2.end());
EATEST_VERIFY(hashSet1.validate());
hash_set<int> hashSet2;
hashSet2.insert(intArray1.begin(), intArray1.end());
hashSet2.insert(intArray2.begin(), intArray2.end());
EATEST_VERIFY(hashSet2.validate());
EATEST_VERIFY(hashSet1 == hashSet2);
// insert_return_type insert(const_iterator, const value_type& value)
for(int j = 0; j < 1000; j++)
hashSet1.insert(hashSet1.begin(), j);
insert_iterator< hash_set<int> > ii(hashSet1, hashSet1.begin());
for(int j = 0; j < 1000; j++)
*ii++ = j;
}
{
// C++11 emplace and related functionality
nErrorCount += TestMapCpp11<eastl::hash_map<int, TestObject>>();
nErrorCount += TestMapCpp11<eastl::unordered_map<int, TestObject>>();
nErrorCount += TestSetCpp11<eastl::hash_set<TestObject>>();
nErrorCount += TestSetCpp11<eastl::unordered_set<TestObject>>();
nErrorCount += TestMultimapCpp11<eastl::hash_multimap<int, TestObject>>();
nErrorCount += TestMultimapCpp11<eastl::unordered_multimap<int, TestObject>>();
nErrorCount += TestMultisetCpp11<eastl::hash_multiset<TestObject>>();
nErrorCount += TestMultisetCpp11<eastl::unordered_multiset<TestObject>>();
nErrorCount += TestMapCpp11NonCopyable<eastl::hash_map<int, NonCopyable>>();
nErrorCount += TestMapCpp11NonCopyable<eastl::unordered_map<int, NonCopyable>>();
}
{
// C++17 try_emplace and related functionality
nErrorCount += TestMapCpp17<eastl::hash_map<int, TestObject>>();
nErrorCount += TestMapCpp17<eastl::unordered_map<int, TestObject>>();
}
{
// initializer_list support.
// hash_set(std::initializer_list<value_type> ilist, size_type nBucketCount = 0, const Hash& hashFunction = Hash(),
// const Predicate& predicate = Predicate(), const allocator_type& allocator = EASTL_HASH_SET_DEFAULT_ALLOCATOR)
// this_type& operator=(std::initializer_list<value_type> ilist);
// void insert(std::initializer_list<value_type> ilist);
hash_set<int> intHashSet = { 12, 13, 14 };
EATEST_VERIFY(intHashSet.size() == 3);
EATEST_VERIFY(intHashSet.find(12) != intHashSet.end());
EATEST_VERIFY(intHashSet.find(13) != intHashSet.end());
EATEST_VERIFY(intHashSet.find(14) != intHashSet.end());
intHashSet = { 22, 23, 24 };
EATEST_VERIFY(intHashSet.size() == 3);
EATEST_VERIFY(intHashSet.find(22) != intHashSet.end());
EATEST_VERIFY(intHashSet.find(23) != intHashSet.end());
EATEST_VERIFY(intHashSet.find(24) != intHashSet.end());
intHashSet.insert({ 42, 43, 44 });
EATEST_VERIFY(intHashSet.size() == 6);
EATEST_VERIFY(intHashSet.find(42) != intHashSet.end());
EATEST_VERIFY(intHashSet.find(43) != intHashSet.end());
EATEST_VERIFY(intHashSet.find(44) != intHashSet.end());
}
{
// eastl::pair<iterator, iterator> equal_range(const key_type& k);
// eastl::pair<const_iterator, const_iterator> equal_range(const key_type& k) const;
// const_iterator erase(const_iterator, const_iterator);
// size_type erase(const key_type&);
// To do.
}
{ // hash_set erase_if
hash_set<int> m = {0, 1, 2, 3, 4};
eastl::erase_if(m, [](auto i) { return i % 2 == 0; });
VERIFY((m == hash_set<int>{1, 3}));
}
{ // hash_multiset erase_if
hash_multiset<int> m = {0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 4};
eastl::erase_if(m, [](auto i) { return i % 2 == 0; });
VERIFY((m == hash_multiset<int>{1, 1, 1, 3}));
}
{ // Test hash_map
// insert_return_type insert(const value_type& value);
// insert_return_type insert(const key_type& key);
// iterator find(const key_type& k);
// const_iterator find(const key_type& k) const;
typedef hash_map<int, int> HashMapIntInt;
HashMapIntInt hashMap;
const int kCount = 10000;
for(int i = 0; i < kCount; i++)
{
HashMapIntInt::value_type vt(i, i);
hashMap.insert(vt);
}
const HashMapIntInt const_hashMap = hashMap; // creating a const version to test for const correctness
for(auto& e : hashMap)
{
int k = e.first;
int v = e.second;
EATEST_VERIFY(k < kCount);
EATEST_VERIFY(v == k);
EATEST_VERIFY(hashMap.at(k) == k);
EATEST_VERIFY(const_hashMap.at(k) == k);
hashMap.at(k) = k << 4;
}
for(auto& e : hashMap)
{
int k = e.first;
int v = e.second;
EATEST_VERIFY(k < kCount);
EATEST_VERIFY(v == (k << 4));
}
for(int i = 0; i < kCount * 2; i++)
{
HashMapIntInt::iterator it = hashMap.find(i);
if(i < kCount)
{
EATEST_VERIFY(it != hashMap.end());
int k = (*it).first;
int v = (*it).second;
EATEST_VERIFY(v == (k << 4));
}
else
EATEST_VERIFY(it == hashMap.end());
}
for(int i = 0; i < kCount; i++)
{
int v = hashMap.at(i);
EATEST_VERIFY(v == (i << 4));
}
#if EASTL_EXCEPTIONS_ENABLED
try
{
hashMap.at(kCount);
EASTL_ASSERT_MSG(false, "at accessor did not throw out_of_range exception");
}
catch(const std::out_of_range) { }
catch(const std::exception& e)
{
string e_msg(e.what());
string msg = "wrong exception with message \"" + e_msg + "\" thrown";
EASTL_ASSERT_MSG(false, msg.c_str());
}
#endif
HashMapIntInt::insert_return_type result = hashMap.insert(88888);
EATEST_VERIFY(result.second == true);
result = hashMap.insert(88888);
EATEST_VERIFY(result.second == false);
result.first->second = 0;
// const_iterator erase(const_iterator);
size_t nExpectedSize = hashMap.size();
HashMapIntInt::iterator it50 = hashMap.find(50);
EATEST_VERIFY(it50 != hashMap.end());
HashMapIntInt::iterator itNext = hashMap.erase(it50);
nExpectedSize--;
EATEST_VERIFY(itNext != hashMap.end()); // Strictly speaking, this isn't guaranteed to be so. But statistically it is very likely. We'll fix this if it becomes a problem.
EATEST_VERIFY(hashMap.size() == nExpectedSize);
HashMapIntInt::size_type n = hashMap.erase(10);
nExpectedSize--;
EATEST_VERIFY(n == 1);
EATEST_VERIFY(hashMap.size() == nExpectedSize);
HashMapIntInt::iterator it60 = hashMap.find(60);
EATEST_VERIFY(itNext != hashMap.end());
HashMapIntInt::iterator it60Incremented(it60);
for(int i = 0; (i < 5) && (it60Incremented != hashMap.end()); ++i)
{
++it60Incremented;
--nExpectedSize;
}
hashMap.erase(it60, it60Incremented);
EATEST_VERIFY(hashMap.size() == nExpectedSize);
// insert_return_type insert(const value_type& value, hash_code_t c, node_type* pNodeNew = NULL);
HashMapIntInt::node_type* pNode = hashMap.allocate_uninitialized_node();
HashMapIntInt::insert_return_type r = hashMap.insert(eastl::hash<int>()(999999), pNode, HashMapIntInt::value_type(999999, 999999));
EATEST_VERIFY(r.second == true);
pNode = hashMap.allocate_uninitialized_node();
r = hashMap.insert(eastl::hash<int>()(999999), pNode, HashMapIntInt::value_type(999999, 999999));
EATEST_VERIFY(r.second == false);
hashMap.free_uninitialized_node(pNode);
hashMap.erase(999999);
// mapped_type& operator[](const key_type& key)
// hash_map is unique among the map/set containers in having this function.
hashMap.clear();
int x = hashMap[0]; // A default-constructed int (i.e. 0) should be returned.
EATEST_VERIFY(x == 0);
hashMap[1] = 1;
x = hashMap[1];
EATEST_VERIFY(x == 1); // Verify that the value we assigned is returned and a default-constructed value is not returned.
hashMap[0] = 10; // Overwrite our previous 0 with 10.
hashMap[1] = 11;
x = hashMap[0];
EATEST_VERIFY(x == 10); // Verify the value is as expected.
x = hashMap[1];
EATEST_VERIFY(x == 11);
}
{ // Test hash_map
// Aligned objects should be CustomAllocator instead of the default, because the
// EASTL default might be unable to do aligned allocations, but CustomAllocator always can.
hash_map<Align32, int, eastl::hash<Align32>, eastl::equal_to<Align32>, CustomAllocator> hashMap;
const int kCount = 10000;
for(int i = 0; i < kCount; i++)
{
Align32 a32(i); // GCC 2.x doesn't like the Align32 object being created in the ctor below.
hash_map<Align32, int>::value_type vt(a32, i);
hashMap.insert(vt);
}
for(hash_map<Align32, int>::iterator it = hashMap.begin(); it != hashMap.end(); ++it)
{
const Align32& k = (*it).first;
int v = (*it).second;
EATEST_VERIFY(k.mX < 10000);
EATEST_VERIFY(v == k.mX);
}
for(int i = 0; i < kCount * 2; i++)
{
hash_map<Align32, int>::iterator it = hashMap.find(Align32(i));
if(i < kCount)
{
EATEST_VERIFY(it != hashMap.end());
const Align32& k = (*it).first;
int v = (*it).second;
EATEST_VERIFY(v == k.mX);
}
else
EATEST_VERIFY(it == hashMap.end());
}
}
{ // hash_map erase_if
hash_map<int, int> m = {{0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}};
eastl::erase_if(m, [](auto p) { return p.first % 2 == 0; });
VERIFY((m == hash_map<int, int>{{1, 1}, {3, 3}}));
}
{ // hash_multimap erase_if
hash_multimap<int, int> m = {{0, 0}, {0, 0}, {0, 0}, {0, 0}, {1, 1}, {2, 2},
{2, 2}, {2, 2}, {2, 2}, {3, 3}, {3, 3}, {4, 4}};
eastl::erase_if(m, [](auto p) { return p.first % 2 == 0; });
VERIFY((m == hash_multimap<int, int>{{1, 1}, {3, 3}, {3, 3}}));
}
{
// template <typename U, typename UHash, typename BinaryPredicate>
// iterator find_as(const U& u, UHash uhash, BinaryPredicate predicate);
// template <typename U, typename UHash, typename BinaryPredicate>
// const_iterator find_as(const U& u, UHash uhash, BinaryPredicate predicate) const;
// template <typename U>
// iterator find_as(const U& u);
// template <typename U>
// const_iterator find_as(const U& u) const;
typedef hash_set<string> HashSetString;
HashSetString hashSet;
const int kCount = 100;
for(int i = 0; i < kCount; i++)
{
string::CtorSprintf cs; // GCC 2.x doesn't like this value being created in the ctor below.
string s(cs, "%d", i);
hashSet.insert(s);
}
for(int i = 0; i < kCount * 2; i++)
{
char pString[32];
sprintf(pString, "%d", i);
HashSetString::iterator it = hashSet.find_as(pString);
if(i < kCount)
EATEST_VERIFY(it != hashSet.end());
else
EATEST_VERIFY(it == hashSet.end());
it = hashSet.find_as(pString, hash<const char*>(), equal_to_2<string, const char*>());
if(i < kCount)
EATEST_VERIFY(it != hashSet.end());
else
EATEST_VERIFY(it == hashSet.end());
string::CtorSprintf cs;
string s(cs, "%d", i);
it = hashSet.find_as(s);
if (i < kCount)
EATEST_VERIFY(it != hashSet.end());
else
EATEST_VERIFY(it == hashSet.end());
}
}
{
// Test const containers.
const hash_set<int> constHashSet;
hash_set<int>::const_iterator i = constHashSet.begin();
hash_set<int>::const_iterator i3 = i;
hash_set<int>::iterator i2;
i3 = i2;
EATEST_VERIFY(i3 == i2);
//const std::tr1::unordered_set<int> constUSet;
//std::tr1::unordered_set<int>::const_iterator i = constUSet.begin();
//*i = 0;
}
{
// global operator ==, !=
EASTLTest_Rand rng(EA::UnitTest::GetRandSeed());
const eastl_size_t kIterationCount = 100;
const eastl_size_t kDataRange = 50;
{
typedef hash_set<HashtableValue, HashtableValueHash, HashtableValuePredicate> HashSet;
HashtableValue value;
HashSet h1;
HashSet h2;
EATEST_VERIFY(h1 == h2);
for(eastl_size_t i = 0; i < kIterationCount; i++)
{
value.mData = rng.RandLimit(kDataRange);
h1.insert(value); // Leave value.mExtra as 0.
}
EATEST_VERIFY(h1 != h2);
h2 = h1;
EATEST_VERIFY(h1 == h2);
// Test the case of the containers being the same size but having a single different value, despite that it's key compare yields equal.
HashSet h2Saved(h2);
HashSet::iterator it = h2.find(value);
HashtableValue valueModified(value.mData, 1);
h2.erase(it);
h2.insert(valueModified);
EATEST_VERIFY(h1 != h2);
h2 = h2Saved;
// Test the case of the containers being the same size but having a single different key.
h2Saved = h2;
h2.erase(h2.find(value));
h2.insert(kDataRange); // Insert something that could not have been in h2.
EATEST_VERIFY(h1 != h2);
h2 = h2Saved;
h1.erase(h1.find(value)); // Erase from h1 whatever the last value was.
EATEST_VERIFY(h1 != h2);
}
{
typedef hash_multiset<HashtableValue, HashtableValueHash, HashtableValuePredicate> HashSet;
HashtableValue value;
HashSet h1;
HashSet h2;
EATEST_VERIFY(h1 == h2);
for(eastl_size_t i = 0; i < kIterationCount; i++)
{
value.mData = rng.RandLimit(kDataRange);
h1.insert(value); // Leave value.mExtra as 0.
}
EATEST_VERIFY(h1 != h2);
h2 = h1;
EATEST_VERIFY(h1 == h2);
// Test the case of the containers being the same size but having a single different value, despite that it's key compare yields equal.
HashSet h2Saved(h2);
HashSet::iterator it = h2.find(value);
HashtableValue valueModified(value.mData, 1);
h2.erase(it);
h2.insert(valueModified);
EATEST_VERIFY(h1 != h2);
h2 = h2Saved;
// Test the case of the containers being the same size but having a single different key.
h2Saved = h2;
h2.erase(h2.find(value));
h2.insert(kDataRange); // Insert something that could not have been in h2.
EATEST_VERIFY(h1 != h2);
h2 = h2Saved;
h1.erase(h1.find(value)); // Erase from h1 whatever the last value was.
EATEST_VERIFY(h1 != h2);
}
{
// For simplicity we duplicate the HashtableValue::mData member as the hash map key.
typedef hash_map<eastl_size_t, HashtableValue, HashtableValueHash, HashtableValuePredicate> HashMap;
HashtableValue value;
HashMap h1;
HashMap h2;
EATEST_VERIFY(h1 == h2);
for(eastl_size_t i = 0; i < kIterationCount; i++)
{
value.mData = rng.RandLimit(kDataRange);
h1.insert(HashMap::value_type(value.mData, value)); // Leave value.mExtra as 0.
}
EATEST_VERIFY(h1 != h2);
h2 = h1;
EATEST_VERIFY(h1 == h2);
// Test the case of the containers being the same size but having a single different value, despite that it's key compare yields equal.
HashMap h2Saved(h2);
HashMap::iterator it = h2.find(value.mData); // We are using value.mData as the key as well, so we can do a find via it.
HashtableValue valueModified(value.mData, 1);
h2.erase(it);
h2.insert(HashMap::value_type(valueModified.mData, valueModified));
EATEST_VERIFY(h1 != h2);
h2 = h2Saved;
// Test the case of the containers being the same size but having a single different key.
h2Saved = h2;
h2.erase(h2.find(value.mData));
h2.insert(HashMap::value_type(kDataRange, HashtableValue(kDataRange))); // Insert something that could not have been in h2.
EATEST_VERIFY(h1 != h2);
h2 = h2Saved;
h1.erase(h1.find(value.mData)); // Erase from h1 whatever the last value was.
EATEST_VERIFY(h1 != h2);
}
{
// For simplicity we duplicate the HashtableValue::mData member as the hash map key.
typedef hash_multimap<eastl_size_t, HashtableValue, HashtableValueHash, HashtableValuePredicate> HashMap;
HashtableValue value;
HashMap h1;
HashMap h2;
EATEST_VERIFY(h1 == h2);
for(eastl_size_t i = 0; i < kIterationCount; i++)
{
value.mData = rng.RandLimit(kDataRange);
h1.insert(HashMap::value_type(value.mData, value)); // Leave value.mExtra as 0.
}
EATEST_VERIFY(h1 != h2);
h2 = h1;
EATEST_VERIFY(h1 == h2);
// Test the case of the containers being the same size but having a single different value, despite that it's key compare yields equal.
HashMap h2Saved(h2);
HashMap::iterator it = h2.find(value.mData); // We are using value.mData as the key as well, so we can do a find via it.
HashtableValue valueModified(value.mData, 1);
h2.erase(it);
h2.insert(HashMap::value_type(valueModified.mData, valueModified));
EATEST_VERIFY(h1 != h2);
h2 = h2Saved;
// Test the case of the containers being the same size but having a single different key.
h2Saved = h2;
h2.erase(h2.find(value.mData));
h2.insert(HashMap::value_type(kDataRange, HashtableValue(kDataRange))); // Insert something that could not have been in h2.
EATEST_VERIFY(h1 != h2);
h2 = h2Saved;
h1.erase(h1.find(value.mData)); // Erase from h1 whatever the last value was.
EATEST_VERIFY(h1 != h2);
}
}
{
typedef eastl::hash_multiset<int> HashMultisetInt;
HashMultisetInt hashMultiSet;
// insert_return_type insert(const value_type& value, hash_code_t c, node_type* pNodeNew = NULL);
HashMultisetInt::node_type* pNode = hashMultiSet.allocate_uninitialized_node();
HashMultisetInt::iterator it1 = hashMultiSet.insert(eastl::hash<int>()(999999), pNode, 999999);
EATEST_VERIFY(it1 != hashMultiSet.end());
pNode = hashMultiSet.allocate_uninitialized_node();
HashMultisetInt::iterator it2 = hashMultiSet.insert(eastl::hash<int>()(999999), pNode, 999999);
EATEST_VERIFY(it2 != hashMultiSet.end() && it2 != it1);
}
{
// Regression of compiler warning reported by Jeff Litz/Godfather regarding
// strict aliasing (EASTL 1.09.01) December 2007).
typedef eastl::hash_multimap<uint32_t, uint32_t*> Map;
Map* pMap = new Map;
delete pMap;
}
{
// Regression of user-reported crash.
eastl::hash_map<int, eastl::string*>* _hmTextureList;
_hmTextureList = new eastl::hash_map<int, eastl::string*>();
eastl::string* a = NULL;
(*_hmTextureList)[0] = a;
delete _hmTextureList;
}
{
// Regression of user-reported Android compiler error.
typedef eastl::hash_multimap<HashRegressionA*, HashRegressionB> HMM;
HMM m_hash;
// Section 1
for (HMM::iterator it = m_hash.begin(); it != m_hash.end(); it++)
it->second.y = 1;
// Section 2
HashRegressionA* pA = NULL;
eastl::pair<HMM::iterator, HMM::iterator> pair = m_hash.equal_range(pA);
(void)pair;
}
{
// Regression of user-reported GCC 4.8 compile failure.
typedef eastl::hash_map<int64_t, Struct> AuditByBlazeIdMap;
AuditByBlazeIdMap auditBlazeIds;
AuditByBlazeIdMap tempAuditBlazeIds;
auditBlazeIds.swap(tempAuditBlazeIds); // This line was generating an unexpected compiler failure.
EATEST_VERIFY(auditBlazeIds.empty() && tempAuditBlazeIds.empty());
}
{
// This test is designed to designed to use the find_range_by_hash method to walk over all keys in a hash bucket (located by a hash value).
// Use the 'colliding_hash' hash function to intentionally create lots of collisions in a predictable way.
typedef hash_map<int, int, colliding_hash> HM;
HM hashMap;
// Add some numbers to the hashMap.
for(int i=0; i<90; i++)
{
hashMap[i] = i;
}
// Try to find a hash value that doesn't exist
{
eastl::pair<HM::iterator, HM::iterator> i = hashMap.find_range_by_hash(1000);
EATEST_VERIFY(i.first == hashMap.end());
EATEST_VERIFY(i.second == hashMap.end());
}
{
int iterations = 0;
for(eastl::pair<HM::iterator, HM::iterator> i = hashMap.find_range_by_hash(1); i.first != i.second; i.first++)
{
int nodeValue = i.first.get_node()->mValue.first;
EATEST_VERIFY(nodeValue % 3 == 1); // Verify the hash of the node matches the expected value
iterations++;
}
EATEST_VERIFY(iterations == 30);
}
{
const HM &constHashMap = hashMap;
int iterations = 0;
for(eastl::pair<HM::const_iterator, HM::const_iterator> i = constHashMap.find_range_by_hash(1); i.first != i.second; i.first++)
{
int nodeValue = i.first.get_node()->mValue.first;
EATEST_VERIFY(nodeValue % 3 == 1); // Verify the hash of the node matches the expected value
iterations++;
}
EATEST_VERIFY(iterations == 30);
}
}
// test hashtable holding move-only types
#if !defined(EA_COMPILER_MSVC_2013)
{
struct Movable
{
Movable() {}
Movable(Movable&&) = default;
Movable& operator=(Movable&&) = default;
Movable(const Movable&) = delete;
Movable& operator=(const Movable&) = delete;
bool operator==(Movable) const { return true; }
struct Hash
{
size_t operator()(Movable) const { return 0; }
};
};
eastl::unordered_set<Movable, Movable::Hash> a, b;
swap(a,b);
}
#endif
{
// hashtable(this_type&& x);
// hashtable(this_type&& x, const allocator_type& allocator);
// this_type& operator=(this_type&& x);
// template <class... Args>
// insert_return_type emplace(Args&&... args);
// template <class... Args>
// iterator emplace_hint(const_iterator position, Args&&... args);
// template <class P> // Requires that "value_type is constructible from forward<P>(otherValue)."
// insert_return_type insert(P&& otherValue);
// iterator insert(const_iterator hint, value_type&& value);
// Regression of user reported compiler error in hashtable sfinae mechanism
{
TestObject::Reset();
eastl::hash_set<TestObject> toSet;
toSet.emplace(3, 4, 5);
}
}
{
// initializer_list support.
// hash_map(std::initializer_list<value_type> ilist, size_type nBucketCount = 0, const Hash& hashFunction = Hash(),
// const Predicate& predicate = Predicate(), const allocator_type& allocator = EASTL_HASH_MAP_DEFAULT_ALLOCATOR)
// this_type& operator=(std::initializer_list<value_type> ilist);
// void insert(std::initializer_list<value_type> ilist);
// VS2013 has a known issue when dealing with std::initializer_lists
// https://connect.microsoft.com/VisualStudio/feedback/details/792355/compiler-confused-about-whether-to-use-a-initializer-list-assignment-operator
#if !defined(EA_COMPILER_NO_INITIALIZER_LISTS) && !(defined(_MSC_VER) && _MSC_VER == 1800)
hash_map<int, double> intHashMap = { {12,12.0}, {13,13.0}, {14,14.0} };
EATEST_VERIFY(intHashMap.size() == 3);
EATEST_VERIFY(intHashMap.find(12) != intHashMap.end());
EATEST_VERIFY(intHashMap.find(13) != intHashMap.end());
EATEST_VERIFY(intHashMap.find(14) != intHashMap.end());
intHashMap = { {22,22.0}, {23,23.0}, {24,24.0} };
EATEST_VERIFY(intHashMap.size() == 3);
EATEST_VERIFY(intHashMap.find(22) != intHashMap.end());
EATEST_VERIFY(intHashMap.find(23) != intHashMap.end());
EATEST_VERIFY(intHashMap.find(24) != intHashMap.end());
intHashMap.insert({ {42,42.0}, {43,43.0}, {44,44.0} });
EATEST_VERIFY(intHashMap.size() == 6);
EATEST_VERIFY(intHashMap.find(42) != intHashMap.end());
EATEST_VERIFY(intHashMap.find(43) != intHashMap.end());
EATEST_VERIFY(intHashMap.find(44) != intHashMap.end());
#endif
}
// Can't use move semantics with hash_map::operator[]
//
// GCC has a bug with overloading rvalue and lvalue function templates.
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54425
//
// error: 'eastl::pair<T1, T2>::pair(T1&&) [with T1 = const int&; T2 = const int&]' cannot be overloaded
// error: with 'eastl::pair<T1, T2>::pair(const T1&) [with T1 = const int&; T2 = const int&]'
#if !defined(EA_COMPILER_GNUC)
{
EA_DISABLE_VC_WARNING(4626)
struct Key
{
Key() {}
Key(Key&&) {}
Key(const Key&&) {}
bool operator==(const Key&) const { return true; }
private:
Key(const Key&) {}
};
EA_RESTORE_VC_WARNING()
struct Hash
{
std::size_t operator()(const Key&) const { return 0; }
};
Key key1, key2;
eastl::hash_map<Key, int, Hash> hm;
hm[eastl::move(key1)] = 12345;
EATEST_VERIFY(hm[eastl::move(key2)] == 12345);
}
#endif
{
using AllocatorType = CountingAllocator;
using String = eastl::basic_string<char8_t, AllocatorType>;
using StringStringMap = eastl::map<String, String, eastl::equal_to<String>, AllocatorType>;
using StringStringHashMap = eastl::hash_map<String, String, eastl::string_hash<String>, eastl::equal_to<String>, AllocatorType>;
AllocatorType::resetCount();
{
StringStringHashMap myMap(5); // construct map with 5 buckets, so we don't rehash on insert
String key("mykey01234567890000000000000000000000000000");
String value("myvalue01234567890000000000000000000000000000");
AllocatorType::resetCount();
myMap.insert(eastl::make_pair(eastl::move(key), eastl::move(value)));
EATEST_VERIFY(AllocatorType::getTotalAllocationCount() == 1);
}
{
StringStringHashMap myMap(5); // construct map with 5 buckets, so we don't rehash on insert
String key("mykey01234567890000000000000000000000000000");
String value("myvalue01234567890000000000000000000000000000");
AllocatorType::resetCount();
myMap.emplace(eastl::move(key), eastl::move(value));
EATEST_VERIFY(AllocatorType::getTotalAllocationCount() == 1);
}
{
StringStringMap myMap;
String key("mykey01234567890000000000000000000000000000");
String value("myvalue01234567890000000000000000000000000000");
AllocatorType::resetCount();
myMap.insert(eastl::make_pair(eastl::move(key), eastl::move(value)));
EATEST_VERIFY(AllocatorType::getTotalAllocationCount() == 1);
}
{
StringStringMap myMap;
String key("mykey01234567890000000000000000000000000000");
String value("myvalue01234567890000000000000000000000000000");
AllocatorType::resetCount();
myMap.emplace(eastl::move(key), eastl::move(value));
EATEST_VERIFY(AllocatorType::getTotalAllocationCount() == 1);
}
}
{
struct name_equals
{
bool operator()(const eastl::pair<int, const char*>& a, const eastl::pair<int, const char*>& b) const
{
if (a.first != b.first)
return false;
return strcmp(a.second, b.second) == 0;
}
};
{
int n = 42;
const char* pCStrName = "electronic arts";
eastl::hash_map<eastl::pair<int, const char*>, bool, eastl::hash<eastl::pair<int, const char*>>, name_equals, eastl::allocator> m_TempNames;
m_TempNames[eastl::make_pair(n, pCStrName)] = true;
auto isFound = (m_TempNames.find(eastl::make_pair(n, pCStrName)) != m_TempNames.end());
VERIFY(isFound);
}
}
{ // User reported regression for code changes limiting hash code generated for non-arithmetic types.
{ VERIFY(HashTest<char>{}('a') == size_t('a')); }
{ VERIFY(HashTest<int>{}(42) == 42); }
{ VERIFY(HashTest<unsigned>{}(42) == 42); }
{ VERIFY(HashTest<signed>{}(42) == 42); }
{ VERIFY(HashTest<short>{}(short(42)) == 42); }
{ VERIFY(HashTest<unsigned short>{}((unsigned short)42) == 42); }
{ VERIFY(HashTest<int>{}(42) == 42); }
{ VERIFY(HashTest<unsigned int>{}(42) == 42); }
{ VERIFY(HashTest<long int>{}(42) == 42); }
{ VERIFY(HashTest<unsigned long int>{}(42) == 42); }
{ VERIFY(HashTest<long long int>{}(42) == 42); }
{ VERIFY(HashTest<unsigned long long int>{}(42) == 42); }
#if defined(EA_HAVE_INT128) && EA_HAVE_INT128
{ VERIFY(HashTest<uint128_t>{}(UINT128_C(0, 42)) == 42); }
#endif
}
return nErrorCount;
}
| 46,853 | 20,060 |
/*
*/
/*
* File: PythonFitness.cpp
* Author: virgolin
*
* Created on May 31, 2019, 12:25 PM
*/
#include "GPGOMEA/Fitness/PythonFitness.h"
using namespace std;
using namespace arma;
namespace py = boost::python;
namespace np = boost::python::numpy;
PythonFitness::PythonFitness() {
Py_Initialize();
np::initialize();
PyRun_SimpleString("import sys; sys.path.insert(0,'./')");
}
void PythonFitness::SetPythonCallableFunction(std::string filename, std::string function_name) {
try {
py::object module = py::import(py::str(filename));
callable_python_function = py::object(module.attr(py::str(function_name)));
} catch (boost::python::error_already_set const &) {
std::string err = "PythonFitness::SetPythonCallableFunction error: perhaps misspelled names in pyprobdef?\n" + filename + " " + function_name;
throw std::runtime_error(err);
}
}
double_t PythonFitness::ComputeFitness(Node* n, bool use_caching) {
evaluations++;
vec out = n->GetOutput(this->TrainX, use_caching);
np::ndarray npout = Utils::ToNumpyArray(out);
//cout << py::str(callable_python_function) << endl;
py::object pyresult = callable_python_function(npout);
double_t fit = py::extract<double_t>(pyresult);
if (std::isnan(fit)) {
fit = arma::datum::inf;
}
n->cached_fitness = fit;
return fit;
}
| 1,393 | 493 |
/*
GLM header include directives. Please use GLM 0.9.9.3 or greater for known
results. Previous versions of GLM are not guaranteed to work correctly.
*/
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <glm/mat4x4.hpp>
#include <glm/gtc/matrix_transform.hpp>
/*
libnoise header include directives. libnoise is used to generate coherent
noise for generating procedural planets.
*/
#include <noise/noise.h>
/*
noiseutils header include directives. noiseutils is used as a utility library
on top of libnoise.
*/
#include "noiseutils.h"
/*
GLAD header include directives. GLAD is used to load OpenGL 3.3 Core
functions.
*/
#include "glad.h"
/*
SDL header include directives. Please use SDL 2.0.9 or greater for known
results. Previous versions of SDL are not guaranteed to work correctly.
*/
#include <SDL2/SDL.h>
/*
Standard header include directives.
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <tuple>
/*
A std::tuple<int, int, int> is used to represent a triangle defined by indices
in a list of vertices.
*/
typedef std::tuple<int, int, int> triangle_indices;
/*
Add a vertex to a std::vector<glm::vec3> while ensuring that the vertex lies
on the unit sphere.
*/
int add_vertex(std::vector<glm::vec3>& vector, glm::vec3 vertex)
{
vector.push_back(vertex / glm::length(vertex));
return vector.size() - 1;
}
/*
Return the index of a vertex in the middle of p_1 and p_2.
*/
int get_middle_point(std::vector<glm::vec3>& vector, int p_1, int p_2)
{
glm::vec3 pt_1 = vector[p_1];
glm::vec3 pt_2 = vector[p_2];
glm::vec3 pt_middle = (pt_1 + pt_2) / 2.0f;
int i = add_vertex(vector, pt_middle);
return i;
}
/*
Create an icosphere with the given amount of subdivisions.
*/
std::vector<glm::vec3> create_icosphere(int subdivisions = 8)
{
// Generate the icosphere's vertices.
std::vector<glm::vec3> icosphere_vertices;
// Generate the 12 vertices of an icosahedron.
float t = (1.0f + sqrt(5.0f)) / 2.0f;
add_vertex(icosphere_vertices, glm::vec3(-1.0f, t, 0.0f));
add_vertex(icosphere_vertices, glm::vec3( 1.0f, t, 0.0f));
add_vertex(icosphere_vertices, glm::vec3(-1.0f, -t, 0.0f));
add_vertex(icosphere_vertices, glm::vec3( 1.0f, -t, 0.0f));
add_vertex(icosphere_vertices, glm::vec3(0.0f, -1.0f, t));
add_vertex(icosphere_vertices, glm::vec3(0.0f, 1.0f, t));
add_vertex(icosphere_vertices, glm::vec3(0.0f, -1.0f, -t));
add_vertex(icosphere_vertices, glm::vec3(0.0f, 1.0f, -t));
add_vertex(icosphere_vertices, glm::vec3( t, 0.0f, -1.0f));
add_vertex(icosphere_vertices, glm::vec3( t, 0.0f, 1.0f));
add_vertex(icosphere_vertices, glm::vec3(-t, 0.0f, -1.0f));
add_vertex(icosphere_vertices, glm::vec3(-t, 0.0f, 1.0f));
// Generate the 20 faces of an icosahedron.
std::vector<triangle_indices> icosphere_indices;
icosphere_indices.push_back(triangle_indices(0x0, 0xB, 0x5));
icosphere_indices.push_back(triangle_indices(0x0, 0x5, 0x1));
icosphere_indices.push_back(triangle_indices(0x0, 0x1, 0x7));
icosphere_indices.push_back(triangle_indices(0x0, 0x7, 0xA));
icosphere_indices.push_back(triangle_indices(0x0, 0xA, 0xB));
icosphere_indices.push_back(triangle_indices(0x1, 0x5, 0x9));
icosphere_indices.push_back(triangle_indices(0x5, 0xB, 0x4));
icosphere_indices.push_back(triangle_indices(0xB, 0xA, 0x2));
icosphere_indices.push_back(triangle_indices(0xA, 0x7, 0x6));
icosphere_indices.push_back(triangle_indices(0x7, 0x1, 0x8));
icosphere_indices.push_back(triangle_indices(0x3, 0x9, 0x4));
icosphere_indices.push_back(triangle_indices(0x3, 0x4, 0x2));
icosphere_indices.push_back(triangle_indices(0x3, 0x2, 0x6));
icosphere_indices.push_back(triangle_indices(0x3, 0x6, 0x8));
icosphere_indices.push_back(triangle_indices(0x3, 0x8, 0x9));
icosphere_indices.push_back(triangle_indices(0x4, 0x9, 0x5));
icosphere_indices.push_back(triangle_indices(0x2, 0x4, 0xB));
icosphere_indices.push_back(triangle_indices(0x6, 0x2, 0xA));
icosphere_indices.push_back(triangle_indices(0x8, 0x6, 0x7));
icosphere_indices.push_back(triangle_indices(0x9, 0x8, 0x1));
// Subdivide the icosphere.
for (int i = 0; i < subdivisions; i++)
{
// Generate a temporary mesh to hold the result of the next
// subdivision.
std::vector<triangle_indices> new_icosphere_indices;
// Subdivide each triangle in the current mesh.
for (int j = 0; j < icosphere_indices.size(); j++)
{
triangle_indices tri = icosphere_indices[j];
int a = get_middle_point(icosphere_vertices, std::get<0>(tri), std::get<1>(tri));
int b = get_middle_point(icosphere_vertices, std::get<1>(tri), std::get<2>(tri));
int c = get_middle_point(icosphere_vertices, std::get<2>(tri), std::get<0>(tri));
// Add the 4 new triangles to the temporary mesh.
new_icosphere_indices.push_back(triangle_indices(std::get<0>(tri), a, c));
new_icosphere_indices.push_back(triangle_indices(std::get<1>(tri), b, a));
new_icosphere_indices.push_back(triangle_indices(std::get<2>(tri), c, b));
new_icosphere_indices.push_back(triangle_indices(a, b, c));
}
// Replace the current mesh with the temporary mesh.
icosphere_indices = new_icosphere_indices;
}
// Convert the icosphere's structured triangle_indices vector to a list of
// ordered vertices.
std::vector<glm::vec3> icosphere_mesh;
for (int i = 0; i < icosphere_indices.size(); i++)
{
icosphere_mesh.push_back(icosphere_vertices[std::get<0>(icosphere_indices[i])]);
icosphere_mesh.push_back(icosphere_vertices[std::get<1>(icosphere_indices[i])]);
icosphere_mesh.push_back(icosphere_vertices[std::get<2>(icosphere_indices[i])]);
}
// Return the icosphere's mesh.
return icosphere_mesh;
};
/*
Load a shader program from two files.
*/
GLuint load_shader_program
(
std::string shader_path_0,
std::string shader_path_1,
GLenum shader_type_0,
GLenum shader_type_1
)
{
// Open shader_path_0 and shader_path_1 as input file streams.
std::ifstream shader_file_0(shader_path_0);
std::ifstream shader_file_1(shader_path_1);
if (!shader_file_0.is_open())
{
std::cout << "Could not open file \"" << shader_path_0 << "\"." << std::endl;
exit(EXIT_FAILURE);
}
else if (!shader_file_1.is_open())
{
std::cout << "Could not open file \"" << shader_path_1 << "\"." << std::endl;
exit(EXIT_FAILURE);
}
// Load the text context of shader_path_0 and shader_path_1 into
// shader_buffer_0 and shader_buffer_1.
std::stringstream shader_buffer_0;
std::stringstream shader_buffer_1;
shader_buffer_0 << shader_file_0.rdbuf() << "\0";
shader_buffer_1 << shader_file_1.rdbuf() << "\0";
// Convert shader_buffer_0 and shader_buffer_1 from std::stringstream to
// std::string, and then to const GLchar* (const char*).
std::string shader_text_0 = shader_buffer_0.str();
std::string shader_text_1 = shader_buffer_1.str();
const GLchar* shader_data_0 = shader_text_0.c_str();
const GLchar* shader_data_1 = shader_text_1.c_str();
// Create shader_0 and shader_1 with the types shader_type_0 and
// shader_type_1, then source them with shader_data_0 and shader_data_1.
GLuint shader_0 = glCreateShader(shader_type_0);
GLuint shader_1 = glCreateShader(shader_type_1);
glShaderSource(shader_0, 1, &shader_data_0, NULL);
glShaderSource(shader_1, 1, &shader_data_1, NULL);
// Compile shader_0 and shader_1.
glCompileShader(shader_0);
glCompileShader(shader_1);
// Check if shader_0 or shader_1 failed compilation. If so, print out the
// error message provided by OpenGL.
GLint success_0 = 0;
GLint success_1 = 0;
GLchar crash_information_0[16 * 1024];
GLchar crash_information_1[16 * 1024];
glGetShaderiv(shader_0, GL_COMPILE_STATUS, &success_0);
glGetShaderiv(shader_1, GL_COMPILE_STATUS, &success_1);
if (!success_0)
{
std::cout << "Could not compile shader loaded from \"" << shader_path_0 << "\"." << std::endl;
glGetShaderInfoLog(shader_0, 16 * 1024, NULL, crash_information_0);
std::cout << crash_information_0;
exit(EXIT_FAILURE);
}
else if (!success_1)
{
std::cout << "Could not compile shader loaded from \"" << shader_path_1 << "\"." << std::endl;
glGetShaderInfoLog(shader_1, 16 * 1024, NULL, crash_information_1);
std::cout << crash_information_1;
exit(EXIT_FAILURE);
}
// Create an empty shader program.
GLuint shader_program = glCreateProgram();
// Attach shader_0 and shader_1 to shader_program, and then link
// shader_program.
glAttachShader(shader_program, shader_0);
glAttachShader(shader_program, shader_1);
glLinkProgram(shader_program);
// Check if shader_program failed linkage. If so, print out the error
// message provied by OpenGL.
GLint success_program = 0;
glGetProgramiv(shader_program, GL_LINK_STATUS, &success_program);
if (!success_program)
{
std::cout << "Could not link shader program loaded from \"" << shader_path_0 << "\" and \"" << shader_path_1 << "\"." << std::endl;
GLchar crash_information_program[16 * 1024];
glGetProgramInfoLog(shader_program, 16 * 1024, NULL, crash_information_program);
std::cout << crash_information_program;
exit(EXIT_FAILURE);
}
// Delete shader_0 and shader_1, then return shader_program.
glDeleteShader(shader_0);
glDeleteShader(shader_1);
return shader_program;
}
/*
Entry point.
*/
int main(int argc, char** argv)
{
// Initialize SDL.
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
std::cout << "Could not initialize SDL." << std::endl;
return EXIT_FAILURE;
}
// Create a SDL_Window*.
int sdl_x_res = 960;
int sdl_y_res = 960;
SDL_Window* sdl_window = SDL_CreateWindow
(
"SDL 2.0 with OpenGL 3.3 Core",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
sdl_x_res,
sdl_y_res,
SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL
);
// Make sure the SDL_Window* was created successfully.
if (!sdl_window)
{
std::cout << "Could not create a SDL_Window*." << std::endl;
return EXIT_FAILURE;
}
// Request OpenGL 3.3 Core.
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
// Create a SDL_GLContext.
SDL_GLContext gl_context = SDL_GL_CreateContext(sdl_window);
// Make sure the SDL_GLContext was created successfully.
if (!gl_context)
{
std::cout << "Could not create a SDL_GLContext." << std::endl;
return EXIT_FAILURE;
}
// Load all OpenGL 3.3 Core functions using GLAD.
if (!gladLoadGLLoader(SDL_GL_GetProcAddress))
{
std::cout << "Could not load OpenGL 3.3 Core functions using GLAD." << std::endl;
return EXIT_FAILURE;
}
// Make sure the OpenGL version that was loaded by GLAD is greater than or
// equal to OpenGL 3.3.
if (GLVersion.major * 10 + GLVersion.minor < 33)
{
std::cout << "Could not load OpenGL 3.3 Core functions using GLAD." << std::endl;
return EXIT_FAILURE;
}
// Create and initialize a noise::module::Perlin. This noise module will
// dictate the general shape of the islands on the planet.
noise::module::Perlin noise_1;
{
// Set the seed to the current time, so that the output noise will be
// slightly different every time.
noise_1.SetSeed(time(NULL));
// Set the octave count to 16 for a high level of detail.
noise_1.SetOctaveCount(16);
// Set the frequency to 2.0f to make the noise more random and less
// coherent.
noise_1.SetFrequency(2.0f);
}
// Create and initialize a noise::module::RidgedMulti. This noise module
// will create round basins and sharp mountain ranges.
noise::module::RidgedMulti noise_2;
{
// Set the seed to the current time, so that the output noise will be
// slightly different every time.
noise_2.SetSeed(time(NULL));
// Set the octave count to 16 for a high level of detail.
noise_2.SetOctaveCount(16);
// Set the frequency to 2.0f to make the noise more random and less
// coherent.
noise_2.SetFrequency(1.0f);
}
// Create a gradient to define the color of points on the planet based on
// the point's elevation.
noise::utils::GradientColor color_map;
color_map.Clear();
color_map.AddGradientPoint(0.0f - 1.0000f, noise::utils::Color(0x00, 0x00, 0x80, 0xFF));
color_map.AddGradientPoint(0.0f - 0.2500f, noise::utils::Color(0x00, 0x00, 0xFF, 0xFF));
color_map.AddGradientPoint(0.0f + 0.0000f, noise::utils::Color(0x00, 0x80, 0xFF, 0xFF));
color_map.AddGradientPoint(0.0f + 0.0625f, noise::utils::Color(0xF0, 0xF0, 0x40, 0xFF));
color_map.AddGradientPoint(0.0f + 0.1250f, noise::utils::Color(0x20, 0xA0, 0x00, 0xFF));
color_map.AddGradientPoint(0.0f + 0.3750f, noise::utils::Color(0xE0, 0xE0, 0x00, 0xFF));
color_map.AddGradientPoint(0.0f + 0.7500f, noise::utils::Color(0x80, 0x80, 0x80, 0xFF));
color_map.AddGradientPoint(0.0f + 1.0000f, noise::utils::Color(0xFF, 0xFF, 0xFF, 0xFF));
// Generate the base icosphere.
std::vector<glm::vec3> icosphere_managed_vertices = create_icosphere(8);
// Allocate space to hold the vertex data of the icosphere.
float* icosphere_vertices = (float*)malloc(icosphere_managed_vertices.size() * (9 * sizeof(float)));
// Perturb the terrain using the noise modules by iterating through each
// triangle rather than each vertex. This is done to make it easy to
// calculate triangle normals.
for (int i = 0; i < icosphere_managed_vertices.size(); i += 3)
{
// Create an array to hold the noise values at the three vertices of
// the current triangle.
float noise_map[3];
for (int j = 0; j < 3; j++)
{
// Get the current vertex.
glm::vec3 vertex = icosphere_managed_vertices[i + j];
// Get the noise value at the current vertex.
float actual_noise_value = noise_1.GetValue(vertex.x, vertex.y, vertex.z) * (noise_2.GetValue(vertex.x, vertex.y, vertex.z) + 0.2f);
// Clamp the noise value to create smooth, flat water.
float noise_value = std::max(0.0f, actual_noise_value);
noise_map[j] = actual_noise_value;
// Perturb the current vertex by the noise value.
icosphere_managed_vertices[i + j] = vertex * (1.0f + noise_value * 0.075f);
}
// Calculate the triangle's normal.
glm::vec3 edge_1 = icosphere_managed_vertices[i + 1] - icosphere_managed_vertices[i];
glm::vec3 edge_2 = icosphere_managed_vertices[i + 2] - icosphere_managed_vertices[i];
glm::vec3 normal = glm::normalize(glm::cross(edge_1, edge_2));
float nx = normal.x;
float ny = normal.y;
float nz = normal.z;
// Generate the vertex data.
for (int j = 0; j < 3; j++)
{
utils::Color color = color_map.GetColor(noise_map[j]);
// Write the position of the current vertex.
icosphere_vertices[(i + j) * 9 + 0] = icosphere_managed_vertices[i + j].x;
icosphere_vertices[(i + j) * 9 + 1] = icosphere_managed_vertices[i + j].y;
icosphere_vertices[(i + j) * 9 + 2] = icosphere_managed_vertices[i + j].z;
// Write the color of the current vertex.
icosphere_vertices[(i + j) * 9 + 3] = color.red / 255.0f;
icosphere_vertices[(i + j) * 9 + 4] = color.green / 255.0f;
icosphere_vertices[(i + j) * 9 + 5] = color.blue / 255.0f;
// Write the surface normal of the current vertex.
icosphere_vertices[(i + j) * 9 + 6] = nx;
icosphere_vertices[(i + j) * 9 + 7] = ny;
icosphere_vertices[(i + j) * 9 + 8] = nz;
}
}
// Generate a VAO and a VBO for the icosphere.
GLuint icosphere_vao;
GLuint icosphere_vbo;
glGenVertexArrays(1, &icosphere_vao);
glGenBuffers(1, &icosphere_vbo);
// Bind the VAO and the VBO of the icosphere to the current state.
glBindVertexArray(icosphere_vao);
glBindBuffer(GL_ARRAY_BUFFER, icosphere_vbo);
// Upload the icosphere data to the VBO.
glBufferData(GL_ARRAY_BUFFER, icosphere_managed_vertices.size() * (10 * sizeof(float)), icosphere_vertices, GL_STATIC_DRAW);
// Enable the required vertex attribute pointers.
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)(0 * sizeof(float)));
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)(3 * sizeof(float)));
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)(6 * sizeof(float)));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
// Unbind the VAO and the VBO of the icosphere from the current state.
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// Load the default shader program.
GLuint default_shader_program = load_shader_program("default_vertex.glsl", "default_fragment.glsl", GL_VERTEX_SHADER, GL_FRAGMENT_SHADER);
// Define variables to hold the state of the mouse and the application's
// state.
int sdl_mouse_x = 0;
int sdl_mouse_y = 0;
bool sdl_mouse_l = false;
bool sdl_mouse_r = false;
bool sdl_running = true;
// Enter the main loop.
while (sdl_running)
{
// Refresh the window's size.
SDL_GetWindowSize(sdl_window, &sdl_x_res, &sdl_y_res);
// Poll and handle events.
SDL_Event e;
while (SDL_PollEvent(&e))
{
if (e.type == SDL_QUIT)
{
// The application was quit.
sdl_running = false;
}
else if (e.type == SDL_MOUSEMOTION)
{
// The mouse moved.
sdl_mouse_x = e.motion.x;
sdl_mouse_y = e.motion.y;
}
else if (e.type == SDL_MOUSEBUTTONDOWN)
{
// A mouse button was pressed.
if (e.button.button == SDL_BUTTON_LEFT)
{
sdl_mouse_l = true;
}
else if (e.button.button == SDL_BUTTON_RIGHT)
{
sdl_mouse_r = true;
}
}
else if (e.type == SDL_MOUSEBUTTONUP)
{
// A mouse button was released.
if (e.button.button == SDL_BUTTON_LEFT)
{
sdl_mouse_l = false;
}
else if (e.button.button == SDL_BUTTON_RIGHT)
{
sdl_mouse_r = false;
}
}
else if (e.type == SDL_KEYDOWN)
{
// A key was pressed.
SDL_Keycode key = e.key.keysym.sym;
if (key == SDLK_ESCAPE)
{
// Quit the application.
sdl_running = false;
}
}
}
// Clear the screen to black.
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
{
// Enable the default shader program.
glUseProgram(default_shader_program);
// Enable depth testing.
glEnable(GL_DEPTH_TEST);
// Enable backface culling.
glEnable(GL_CULL_FACE);
{
// Calculate the aspect ratio.
float aspect_ratio = (float)sdl_x_res / (float)sdl_y_res;
// Calculate the projection matrix.
glm::mat4 matrix_projection = glm::perspective(glm::radians(70.0f), aspect_ratio, 0.128f, 1024.0f);
// Calculate the view matrix.
glm::mat4 matrix_view = glm::mat4(1.0f);
// Rotate the view matrix.
matrix_view = glm::rotate(matrix_view, glm::radians(0.0f), glm::vec3(1.0f, 0.0f, 0.0f));
matrix_view = glm::rotate(matrix_view, glm::radians(0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
// Calculate the model matrix.
glm::mat4 matrix_model = glm::mat4(1.0f);
// Translate the model matrix.
matrix_model = glm::translate(matrix_model, glm::vec3(0.0f, 0.0f, 0.2f * -10.0f));
// Rotate the model matrix.
matrix_model = glm::rotate(matrix_model, glm::radians(SDL_GetTicks() / 100.0f), glm::vec3(1.0f, 0.0f, 0.0f));
matrix_model = glm::rotate(matrix_model, glm::radians(SDL_GetTicks() / 100.0f), glm::vec3(0.0f, 1.0f, 0.0f));
// Pass matrix_projection, matrix_view and matrix_model to the
// default_shader_program.
glUniformMatrix4fv(glGetUniformLocation(default_shader_program, "matrix_projection"), 1, GL_FALSE, &matrix_projection[0][0]);
glUniformMatrix4fv(glGetUniformLocation(default_shader_program, "matrix_view"), 1, GL_FALSE, &matrix_view[0][0]);
glUniformMatrix4fv(glGetUniformLocation(default_shader_program, "matrix_model"), 1, GL_FALSE, &matrix_model[0][0]);
}
// Bind the icosphere VAO to the current state.
glBindVertexArray(icosphere_vao);
// Set the polygon mode to render wireframes.
if (false)
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
}
// Draw the icosphere VAO as an array of triangles.
glDrawArrays(GL_TRIANGLES, 0, icosphere_managed_vertices.size());
// Unbind the icosphere VAO from the current state.
glBindVertexArray(0);
// Disable backface culling.
glDisable(GL_CULL_FACE);
// Disable depth testing.
glDisable(GL_DEPTH_TEST);
// Disable the default shader program.
glUseProgram(0);
}
// Swap the sdl_window's current buffer to display the contents of the
// back buffer to the screen.
SDL_GL_SwapWindow(sdl_window);
}
// Free the icosphere's vertices.
free(icosphere_vertices);
// Destroy the default shader program.
glDeleteProgram(default_shader_program);
// Destroy all SDL_GL resources.
SDL_GL_DeleteContext(gl_context);
// Destroy all SDL resources.
SDL_DestroyWindow(sdl_window);
// Quit SDL.
SDL_Quit();
// Exit successfully.
return EXIT_SUCCESS;
} | 20,900 | 9,081 |
/******************************************************************************\
Copyright (c) 2005-2019, Intel Corporation
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.
This sample was distributed or derived from the Intel's Media Samples package.
The original version of this sample may be obtained from https://software.intel.com/en-us/intel-media-server-studio
or https://software.intel.com/en-us/media-client-solutions-support.
\**********************************************************************************/
#include "mfx_samples_config.h"
#include "pipeline_user.h"
#include "sysmem_allocator.h"
#ifndef MFX_VERSION
#error MFX_VERSION not defined
#endif
mfxStatus CUserPipeline::InitRotateParam(sInputParams *pInParams)
{
MSDK_CHECK_POINTER(pInParams, MFX_ERR_NULL_PTR);
MSDK_ZERO_MEMORY(m_pluginVideoParams);
m_pluginVideoParams.AsyncDepth = pInParams->nAsyncDepth; // the maximum number of tasks that can be submitted before any task execution finishes
m_pluginVideoParams.vpp.In.FourCC = MFX_FOURCC_NV12;
m_pluginVideoParams.vpp.In.Width = m_pluginVideoParams.vpp.In.CropW = pInParams->nWidth;
m_pluginVideoParams.vpp.In.Height = m_pluginVideoParams.vpp.In.CropH = pInParams->nHeight;
m_pluginVideoParams.vpp.Out.FourCC = MFX_FOURCC_NV12;
m_pluginVideoParams.vpp.Out.Width = m_pluginVideoParams.vpp.Out.CropW = pInParams->nWidth;
m_pluginVideoParams.vpp.Out.Height = m_pluginVideoParams.vpp.Out.CropH = pInParams->nHeight;
if (pInParams->memType != SYSTEM_MEMORY)
m_pluginVideoParams.IOPattern = MFX_IOPATTERN_IN_VIDEO_MEMORY | MFX_IOPATTERN_OUT_VIDEO_MEMORY;
m_RotateParams.Angle = pInParams->nRotationAngle;
return MFX_ERR_NONE;
}
mfxStatus CUserPipeline::AllocFrames()
{
MSDK_CHECK_POINTER(m_pmfxENC, MFX_ERR_NOT_INITIALIZED);
mfxStatus sts = MFX_ERR_NONE;
mfxFrameAllocRequest EncRequest, RotateRequest;
mfxU16 nEncSurfNum = 0; // number of frames at encoder input (rotate output)
mfxU16 nRotateSurfNum = 0; // number of frames at rotate input
MSDK_ZERO_MEMORY(EncRequest);
sts = m_pmfxENC->QueryIOSurf(&m_mfxEncParams, &EncRequest);
MSDK_CHECK_STATUS(sts, "m_pmfxENC->QueryIOSurf failed");
if (EncRequest.NumFrameSuggested < m_mfxEncParams.AsyncDepth)
return MFX_ERR_MEMORY_ALLOC;
nEncSurfNum = EncRequest.NumFrameSuggested;
// The number of surfaces for plugin input - so that plugin can work at async depth = m_nAsyncDepth
nRotateSurfNum = MSDK_MAX(m_mfxEncParams.AsyncDepth, m_nMemBuffer);
// If surfaces are shared by 2 components, c1 and c2. NumSurf = c1_out + c2_in - AsyncDepth + 1
nEncSurfNum += nRotateSurfNum - m_mfxEncParams.AsyncDepth + 1;
// prepare allocation requests
EncRequest.NumFrameSuggested = EncRequest.NumFrameMin = nEncSurfNum;
RotateRequest.NumFrameSuggested = RotateRequest.NumFrameMin = nRotateSurfNum;
mfxU16 mem_type = MFX_MEMTYPE_EXTERNAL_FRAME;
mem_type |= (SYSTEM_MEMORY == m_memType) ?
(mfxU16)MFX_MEMTYPE_SYSTEM_MEMORY
:(mfxU16)MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET;
EncRequest.Type = RotateRequest.Type = mem_type;
EncRequest.Type |= MFX_MEMTYPE_FROM_ENCODE;
RotateRequest.Type |= MFX_MEMTYPE_FROM_VPPOUT; // THIS IS A WORKAROUND, NEED TO ADJUST ALLOCATOR
MSDK_MEMCPY_VAR(EncRequest.Info, &(m_mfxEncParams.mfx.FrameInfo), sizeof(mfxFrameInfo));
MSDK_MEMCPY_VAR(RotateRequest.Info, &(m_pluginVideoParams.vpp.In), sizeof(mfxFrameInfo));
// alloc frames for encoder input
sts = m_pMFXAllocator->Alloc(m_pMFXAllocator->pthis, &EncRequest, &m_EncResponse);
MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Alloc failed");
// alloc frames for rotate input
sts = m_pMFXAllocator->Alloc(m_pMFXAllocator->pthis, &(RotateRequest), &m_PluginResponse);
MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Alloc failed");
// prepare mfxFrameSurface1 array for components
m_pEncSurfaces = new mfxFrameSurface1 [nEncSurfNum];
MSDK_CHECK_POINTER(m_pEncSurfaces, MFX_ERR_MEMORY_ALLOC);
m_pPluginSurfaces = new mfxFrameSurface1 [nRotateSurfNum];
MSDK_CHECK_POINTER(m_pPluginSurfaces, MFX_ERR_MEMORY_ALLOC);
for (int i = 0; i < nEncSurfNum; i++)
{
MSDK_ZERO_MEMORY(m_pEncSurfaces[i]);
MSDK_MEMCPY_VAR(m_pEncSurfaces[i].Info, &(m_mfxEncParams.mfx.FrameInfo), sizeof(mfxFrameInfo));
if (SYSTEM_MEMORY != m_memType)
{
// external allocator used - provide just MemIds
m_pEncSurfaces[i].Data.MemId = m_EncResponse.mids[i];
}
else
{
sts = m_pMFXAllocator->Lock(m_pMFXAllocator->pthis, m_EncResponse.mids[i], &(m_pEncSurfaces[i].Data));
MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Lock failed");
}
}
for (int i = 0; i < nRotateSurfNum; i++)
{
MSDK_ZERO_MEMORY(m_pPluginSurfaces[i]);
MSDK_MEMCPY_VAR(m_pPluginSurfaces[i].Info, &(m_pluginVideoParams.vpp.In), sizeof(mfxFrameInfo));
if (SYSTEM_MEMORY != m_memType)
{
// external allocator used - provide just MemIds
m_pPluginSurfaces[i].Data.MemId = m_PluginResponse.mids[i];
}
else
{
sts = m_pMFXAllocator->Lock(m_pMFXAllocator->pthis, m_PluginResponse.mids[i], &(m_pPluginSurfaces[i].Data));
MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Lock failed");
}
}
return MFX_ERR_NONE;
}
void CUserPipeline::DeleteFrames()
{
MSDK_SAFE_DELETE_ARRAY(m_pPluginSurfaces);
CEncodingPipeline::DeleteFrames();
}
CUserPipeline::CUserPipeline() : CEncodingPipeline()
{
m_pPluginSurfaces = NULL;
m_PluginModule = NULL;
m_pusrPlugin = NULL;
MSDK_ZERO_MEMORY(m_PluginResponse);
MSDK_ZERO_MEMORY(m_pluginVideoParams);
MSDK_ZERO_MEMORY(m_RotateParams);
m_MVCflags = MVC_DISABLED;
}
CUserPipeline::~CUserPipeline()
{
Close();
}
mfxStatus CUserPipeline::Init(sInputParams *pParams)
{
MSDK_CHECK_POINTER(pParams, MFX_ERR_NULL_PTR);
mfxStatus sts = MFX_ERR_NONE;
m_PluginModule = msdk_so_load(pParams->strPluginDLLPath);
MSDK_CHECK_POINTER(m_PluginModule, MFX_ERR_NOT_FOUND);
PluginModuleTemplate::fncCreateGenericPlugin pCreateFunc = (PluginModuleTemplate::fncCreateGenericPlugin)msdk_so_get_addr(m_PluginModule, "mfxCreateGenericPlugin");
MSDK_CHECK_POINTER(pCreateFunc, MFX_ERR_NOT_FOUND);
m_pusrPlugin = (*pCreateFunc)();
MSDK_CHECK_POINTER(m_pusrPlugin, MFX_ERR_NOT_FOUND);
// prepare input file reader
sts = m_FileReader.Init(pParams->InputFiles,
pParams->FileInputFourCC );
MSDK_CHECK_STATUS(sts, "m_FileReader.Init failed");
// set memory type
m_memType = pParams->memType;
m_nMemBuffer = pParams->nMemBuf;
m_nTimeout = pParams->nTimeout;
m_bCutOutput = !pParams->bUncut;
// prepare output file writer
sts = InitFileWriters(pParams);
MSDK_CHECK_STATUS(sts, "InitFileWriters failed");
mfxIMPL impl = pParams->bUseHWLib ? MFX_IMPL_HARDWARE : MFX_IMPL_SOFTWARE;
// if d3d11 surfaces are used ask the library to run acceleration through D3D11
// feature may be unsupported due to OS or MSDK API version
if (D3D11_MEMORY == pParams->memType)
impl |= MFX_IMPL_VIA_D3D11;
mfxVersion min_version;
mfxVersion version; // real API version with which library is initialized
// we set version to 1.0 and later we will query actual version of the library which will got leaded
min_version.Major = 1;
min_version.Minor = 0;
// create a session for the second vpp and encode
sts = m_mfxSession.Init(impl, &min_version);
MSDK_CHECK_STATUS(sts, "m_mfxSession.Init failed");
sts = MFXQueryVersion(m_mfxSession , &version); // get real API version of the loaded library
MSDK_CHECK_STATUS(sts, "MFXQueryVersion failed");
if (CheckVersion(&version, MSDK_FEATURE_PLUGIN_API)) {
// we check if codec is distributed as a mediasdk plugin and load it if yes
// else if codec is not in the list of mediasdk plugins, we assume, that it is supported inside mediasdk library
// in case of HW library (-hw key) we will firstly try to load HW plugin
// in case of failure - we will try SW one
mfxIMPL impl2 = pParams->bUseHWLib ? MFX_IMPL_HARDWARE : MFX_IMPL_SOFTWARE;
if (AreGuidsEqual(MSDK_PLUGINGUID_NULL,pParams->pluginParams.pluginGuid))
{
pParams->pluginParams.pluginGuid = msdkGetPluginUID(impl2, MSDK_VENCODE, pParams->CodecId);
}
if (AreGuidsEqual(pParams->pluginParams.pluginGuid, MSDK_PLUGINGUID_NULL) && impl2 == MFX_IMPL_HARDWARE)
pParams->pluginParams.pluginGuid = msdkGetPluginUID(MFX_IMPL_SOFTWARE, MSDK_VENCODE, pParams->CodecId);
if (!AreGuidsEqual(pParams->pluginParams.pluginGuid, MSDK_PLUGINGUID_NULL))
{
m_pPlugin.reset(LoadPlugin(MFX_PLUGINTYPE_VIDEO_ENCODE, m_mfxSession, pParams->pluginParams.pluginGuid, 1));
if (m_pPlugin.get() == NULL) sts = MFX_ERR_UNSUPPORTED;
}
}
// create encoder
m_pmfxENC = new MFXVideoENCODE(m_mfxSession);
MSDK_CHECK_POINTER(m_pmfxENC, MFX_ERR_MEMORY_ALLOC);
sts = InitMfxEncParams(pParams);
MSDK_CHECK_STATUS(sts, "InitMfxEncParams failed");
sts = InitRotateParam(pParams);
MSDK_CHECK_STATUS(sts, "InitRotateParam failed");
// create and init frame allocator
sts = CreateAllocator();
MSDK_CHECK_STATUS(sts, "CreateAllocator failed");
sts = ResetMFXComponents(pParams);
MSDK_CHECK_STATUS(sts, "ResetMFXComponents failed");
// register plugin callbacks in Media SDK
mfxPlugin plg = make_mfx_plugin_adapter(m_pusrPlugin);
sts = MFXVideoUSER_Register(m_mfxSession, 0, &plg);
MSDK_CHECK_STATUS(sts, "MFXVideoUSER_Register failed");
// need to call Init after registration because mfxCore interface is needed
sts = m_pusrPlugin->Init(&m_pluginVideoParams);
MSDK_CHECK_STATUS(sts, "m_pusrPlugin->Init failed");
sts = m_pusrPlugin->SetAuxParams(&m_RotateParams, sizeof(m_RotateParams));
MSDK_CHECK_STATUS(sts, "m_pusrPlugin->SetAuxParams failed");
return MFX_ERR_NONE;
}
void CUserPipeline::Close()
{
MFXVideoUSER_Unregister(m_mfxSession, 0);
CEncodingPipeline::Close();
MSDK_SAFE_DELETE(m_pusrPlugin);
if (m_PluginModule)
{
msdk_so_free(m_PluginModule);
m_PluginModule = NULL;
}
}
mfxStatus CUserPipeline::ResetMFXComponents(sInputParams* pParams)
{
MSDK_CHECK_POINTER(pParams, MFX_ERR_NULL_PTR);
MSDK_CHECK_POINTER(m_pmfxENC, MFX_ERR_NOT_INITIALIZED);
mfxStatus sts = MFX_ERR_NONE;
sts = m_pmfxENC->Close();
MSDK_IGNORE_MFX_STS(sts, MFX_ERR_NOT_INITIALIZED);
MSDK_CHECK_STATUS(sts, "m_pmfxENC->Close failed");
// free allocated frames
DeleteFrames();
m_TaskPool.Close();
sts = AllocFrames();
MSDK_CHECK_STATUS(sts, "AllocFrames failed");
sts = m_pmfxENC->Init(&m_mfxEncParams);
MSDK_CHECK_STATUS(sts, "m_pmfxENC->Init failed");
mfxU32 nEncodedDataBufferSize = m_mfxEncParams.mfx.FrameInfo.Width * m_mfxEncParams.mfx.FrameInfo.Height * 4;
sts = m_TaskPool.Init(&m_mfxSession, m_FileWriters.first, m_mfxEncParams.AsyncDepth, nEncodedDataBufferSize, m_FileWriters.second);
MSDK_CHECK_STATUS(sts, "m_TaskPool.Init failed");
sts = FillBuffers();
MSDK_CHECK_STATUS(sts, "FillBuffers failed");
return MFX_ERR_NONE;
}
mfxStatus CUserPipeline::Run()
{
m_statOverall.StartTimeMeasurement();
MSDK_CHECK_POINTER(m_pmfxENC, MFX_ERR_NOT_INITIALIZED);
mfxStatus sts = MFX_ERR_NONE;
sTask *pCurrentTask = NULL; // a pointer to the current task
mfxU16 nEncSurfIdx = 0; // index of free surface for encoder input
mfxU16 nRotateSurfIdx = 0; // ~ for rotation plugin input
mfxSyncPoint RotateSyncPoint = NULL; // ~ with rotation plugin call
sts = MFX_ERR_NONE;
// main loop, preprocessing and encoding
while (MFX_ERR_NONE <= sts || MFX_ERR_MORE_DATA == sts)
{
// get a pointer to a free task (bit stream and sync point for encoder)
sts = GetFreeTask(&pCurrentTask);
MSDK_BREAK_ON_ERROR(sts);
if (m_nMemBuffer)
{
nRotateSurfIdx = m_nFramesRead % m_nMemBuffer;
}
else
{
nRotateSurfIdx = GetFreeSurface(m_pPluginSurfaces, m_PluginResponse.NumFrameActual);
}
MSDK_CHECK_ERROR(nRotateSurfIdx, MSDK_INVALID_SURF_IDX, MFX_ERR_MEMORY_ALLOC);
m_statFile.StartTimeMeasurement();
sts = LoadNextFrame(&m_pPluginSurfaces[nRotateSurfIdx]);
m_statFile.StopTimeMeasurement();
if ( (MFX_ERR_MORE_DATA == sts) && !m_bTimeOutExceed)
continue;
MSDK_BREAK_ON_ERROR(sts);
nEncSurfIdx = GetFreeSurface(m_pEncSurfaces, m_EncResponse.NumFrameActual);
MSDK_CHECK_ERROR(nEncSurfIdx, MSDK_INVALID_SURF_IDX, MFX_ERR_MEMORY_ALLOC);
// rotation
for(;;)
{
mfxHDL h1, h2;
h1 = &m_pPluginSurfaces[nRotateSurfIdx];
h2 = &m_pEncSurfaces[nEncSurfIdx];
sts = MFXVideoUSER_ProcessFrameAsync(m_mfxSession, &h1, 1, &h2, 1, &RotateSyncPoint);
if (MFX_WRN_DEVICE_BUSY == sts)
{
MSDK_SLEEP(1); // just wait and then repeat the same call
}
else
{
break;
}
}
MSDK_BREAK_ON_ERROR(sts);
// save the id of preceding rotate task which will produce input data for the encode task
if (RotateSyncPoint)
{
pCurrentTask->DependentVppTasks.push_back(RotateSyncPoint);
RotateSyncPoint = NULL;
}
for (;;)
{
InsertIDR(pCurrentTask->encCtrl, m_bInsertIDR);
m_bInsertIDR = false;
sts = m_pmfxENC->EncodeFrameAsync(&pCurrentTask->encCtrl, &m_pEncSurfaces[nEncSurfIdx], &pCurrentTask->mfxBS, &pCurrentTask->EncSyncP);
if (MFX_ERR_NONE < sts && !pCurrentTask->EncSyncP) // repeat the call if warning and no output
{
if (MFX_WRN_DEVICE_BUSY == sts)
MSDK_SLEEP(1); // wait if device is busy
}
else if (MFX_ERR_NONE < sts && pCurrentTask->EncSyncP)
{
sts = MFX_ERR_NONE; // ignore warnings if output is available
break;
}
else if (MFX_ERR_NOT_ENOUGH_BUFFER == sts)
{
sts = AllocateSufficientBuffer(pCurrentTask->mfxBS);
MSDK_CHECK_STATUS(sts, "AllocateSufficientBuffer failed");
}
else
{
break;
}
}
}
// means that the input file has ended, need to go to buffering loops
MSDK_IGNORE_MFX_STS(sts, MFX_ERR_MORE_DATA);
// exit in case of other errors
MSDK_CHECK_STATUS(sts, "m_pmfENC->EncodeFrameAsync failed");
// rotate plugin doesn't buffer frames
// loop to get buffered frames from encoder
while (MFX_ERR_NONE <= sts)
{
// get a free task (bit stream and sync point for encoder)
sts = GetFreeTask(&pCurrentTask);
MSDK_BREAK_ON_ERROR(sts);
for (;;)
{
InsertIDR(pCurrentTask->encCtrl, m_bInsertIDR);
m_bInsertIDR = false;
sts = m_pmfxENC->EncodeFrameAsync(&pCurrentTask->encCtrl, NULL, &pCurrentTask->mfxBS, &pCurrentTask->EncSyncP);
if (MFX_ERR_NONE < sts && !pCurrentTask->EncSyncP) // repeat the call if warning and no output
{
if (MFX_WRN_DEVICE_BUSY == sts)
MSDK_SLEEP(1); // wait if device is busy
}
else if (MFX_ERR_NONE < sts && pCurrentTask->EncSyncP)
{
sts = MFX_ERR_NONE; // ignore warnings if output is available
break;
}
else if (MFX_ERR_NOT_ENOUGH_BUFFER == sts)
{
sts = AllocateSufficientBuffer(pCurrentTask->mfxBS);
MSDK_CHECK_STATUS(sts, "AllocateSufficientBuffer failed");
}
else
{
break;
}
}
MSDK_BREAK_ON_ERROR(sts);
}
// MFX_ERR_MORE_DATA is the correct status to exit buffering loop with
// indicates that there are no more buffered frames
MSDK_IGNORE_MFX_STS(sts, MFX_ERR_MORE_DATA);
// exit in case of other errors
MSDK_CHECK_STATUS(sts, "m_pmfxENC->EncodeFrameAsync failed");
// synchronize all tasks that are left in task pool
while (MFX_ERR_NONE == sts)
{
sts = m_TaskPool.SynchronizeFirstTask();
}
// MFX_ERR_NOT_FOUND is the correct status to exit the loop with,
// EncodeFrameAsync and SyncOperation don't return this status
MSDK_IGNORE_MFX_STS(sts, MFX_ERR_NOT_FOUND);
// report any errors that occurred in asynchronous part
MSDK_CHECK_STATUS(sts, "m_TaskPool.SynchronizeFirstTask failed");
m_statOverall.StopTimeMeasurement();
return sts;
}
mfxStatus CUserPipeline::FillBuffers()
{
if (m_nMemBuffer)
{
for (mfxU32 i = 0; i < m_nMemBuffer; i++)
{
mfxFrameSurface1* surface = &m_pPluginSurfaces[i];
mfxStatus sts = m_pMFXAllocator->Lock(m_pMFXAllocator->pthis, surface->Data.MemId, &surface->Data);
MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Lock failed");
sts = m_FileReader.LoadNextFrame(surface);
MSDK_CHECK_STATUS(sts, "m_FileReader.LoadNextFrame failed");
sts = m_pMFXAllocator->Unlock(m_pMFXAllocator->pthis, surface->Data.MemId, &surface->Data);
MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Unlock failed");
}
}
return MFX_ERR_NONE;
}
void CUserPipeline::PrintInfo()
{
msdk_printf(MSDK_STRING("\nPipeline with rotation plugin"));
msdk_printf(MSDK_STRING("\nNOTE: Some of command line options may have been ignored as non-supported for this pipeline. For details see readme-encode.rtf.\n\n"));
CEncodingPipeline::PrintInfo();
}
| 19,548 | 7,111 |
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma
// de Barcelona (UAB).
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
#include "test.h"
#include <carla/Buffer.h>
#include <carla/BufferPool.h>
#include <array>
#include <list>
#include <set>
#include <string>
#include <vector>
using namespace util::buffer;
TEST(buffer, compile) {
carla::Buffer buffer;
{ std::array<boost::asio::const_buffer, 3u> s; buffer.copy_from(s); }
{ std::array<boost::asio::mutable_buffer, 3u> s; buffer.copy_from(s); }
{ std::vector<boost::asio::const_buffer> s; buffer.copy_from(s); }
{ std::vector<boost::asio::mutable_buffer> s; buffer.copy_from(s); }
{ std::list<boost::asio::const_buffer> s; buffer.copy_from(s); }
{ std::list<boost::asio::mutable_buffer> s; buffer.copy_from(s); }
{ std::set<boost::asio::const_buffer> s; buffer.copy_from(s); }
{ std::set<boost::asio::mutable_buffer> s; buffer.copy_from(s); }
{ boost::asio::const_buffer v; buffer.copy_from(v); }
{ boost::asio::mutable_buffer v; buffer.copy_from(v); }
{ int v[3u]; buffer.copy_from(v); }
{ std::vector<int> v; buffer.copy_from(v); }
{ std::string v; buffer.copy_from(v); }
{ std::wstring v; buffer.copy_from(v); }
{ struct C { int x = 0; } v[3u]; buffer.copy_from(v); }
{ struct C { int x = 0; }; std::array<C, 3u> v; buffer.copy_from(v); }
{ struct C { int x = 0; }; std::vector<C> v; buffer.copy_from(v); }
}
TEST(buffer, copy_buffer_sequence) {
constexpr auto number_of_buffers = 15u;
const std::string str = "WXdI<x->+<If$ua>$pu1AUBmS]?_PT{3z$B7L(E|?$]";
std::string message;
std::array<Buffer, number_of_buffers> buffers;
std::array<boost::asio::const_buffer, number_of_buffers> sequence;
for (auto i = 0u; i < number_of_buffers; ++i) {
message += str;
buffers[i].copy_from(str);
sequence[i] = buffers[i].buffer();
}
auto result = Buffer(sequence);
ASSERT_EQ(result.size(), message.size());
auto result_str = as_string(result);
ASSERT_EQ(result_str, message);
}
TEST(buffer, to_from_string) {
const std::string str = "The quick brown fox jumps over the lazy dog";
Buffer buffer(str);
ASSERT_EQ(buffer.size(), str.size());
const std::string result = as_string(buffer);
ASSERT_EQ(result, str);
}
TEST(buffer, to_from_vector) {
constexpr auto size = 1000u;
using T = size_t;
std::vector<T> v;
v.reserve(size);
for (auto i = 0u; i < size; ++i) {
v.emplace_back(i);
}
Buffer buffer(v);
ASSERT_EQ(buffer.size(), sizeof(T) * size);
auto begin = reinterpret_cast<const T *>(buffer.data());
std::vector<T> result(begin, begin + size);
ASSERT_EQ(result, v);
}
TEST(buffer, copy) {
auto msg = make_random(1024u);
auto cpy = make_empty();
cpy->copy_from(*msg);
ASSERT_EQ(msg->size(), cpy->size());
ASSERT_EQ(*cpy, *msg);
}
TEST(buffer, copy_with_offset) {
const char str0[] = "Hello";
const char str1[] = "buffer!";
Buffer buffer;
auto offset = sizeof(str0);
buffer.copy_from(
offset,
reinterpret_cast<const unsigned char *>(&str1),
std::strlen(str1));
std::memcpy(buffer.data(), str0, std::strlen(str0));
buffer[std::strlen(str0)] = ' ';
auto str = std::string(str0) + " " + str1;
ASSERT_EQ(buffer.size(), str.size());
ASSERT_EQ(as_string(buffer), str.c_str());
}
TEST(buffer, memcpy) {
auto msg = make_random(1024u);
auto cpy = make_empty(msg->size());
ASSERT_EQ(msg->size(), cpy->size());
auto buffer = cpy->buffer();
std::memcpy(buffer.data(), msg->data(), buffer.size());
ASSERT_EQ(*cpy, *msg);
}
#ifndef LIBCARLA_NO_EXCEPTIONS
TEST(buffer, message_too_big) {
ASSERT_THROW(Buffer(4294967296ul), std::invalid_argument);
Buffer buf;
ASSERT_THROW(buf.reset(4294967296ul), std::invalid_argument);
}
#endif // LIBCARLA_NO_EXCEPTIONS
TEST(buffer, buffer_pool) {
const std::string str = "Hello buffer!";
auto pool = std::make_shared<carla::BufferPool>();
{
auto buff = pool->Pop();
buff.copy_from(str);
}
auto buff1 = pool->Pop();
ASSERT_EQ(as_string(buff1), str);
auto buff2 = pool->Pop();
ASSERT_NE(as_string(buff2), str);
// Now delete the pool to test the weak reference inside the buffers.
pool.reset();
}
| 4,272 | 1,704 |
#include "stdafx.h"
#include "CppUnitTest.h"
#include"..\ManagerEmployeeSystem\Manager.cpp"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace ManagerEmployeeSystemUnitTest
{
TEST_CLASS(ManagerUnitTest)
{
public:
TEST_METHOD(ManagerUnitTest_parseManager)
{
string manEmp = "a->b,c,d.b->e,f.";
Manager manager;
list<string>managerList = manager.parseManager(manEmp);
string expected = "b";
managerList.pop_front();
Assert::AreEqual(expected, managerList.front());
}
};
} | 526 | 199 |
// Copyright 2021 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/updater/test/integration_tests_impl.h"
#include <cstdlib>
#include <memory>
#include <string>
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/files/scoped_temp_dir.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/memory/scoped_refptr.h"
#include "base/numerics/checked_math.h"
#include "base/path_service.h"
#include "base/process/launch.h"
#include "base/process/process.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/strings/stringprintf.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/post_task.h"
#include "base/task/single_thread_task_runner_thread_mode.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/test/bind.h"
#include "base/test/test_timeouts.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "base/time/time.h"
#include "base/values.h"
#include "base/version.h"
#include "build/build_config.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/updater/constants.h"
#include "chrome/updater/persisted_data.h"
#include "chrome/updater/prefs.h"
#include "chrome/updater/registration_data.h"
#include "chrome/updater/service_proxy_factory.h"
#include "chrome/updater/test/server.h"
#include "chrome/updater/update_service.h"
#include "chrome/updater/updater_scope.h"
#include "chrome/updater/updater_version.h"
#include "chrome/updater/util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/re2/src/re2/re2.h"
namespace updater {
namespace test {
namespace {
#if defined(OS_MAC)
constexpr char kDoNothingCRXName[] = "updater_qualification_app_dmg.crx";
constexpr char kDoNothingCRXRun[] = "updater_qualification_app_dmg.dmg";
constexpr char kDoNothingCRXHash[] =
"c9eeadf63732f3259e2ad1cead6298f90a3ef4b601b1ba1cbb0f37b6112a632c";
#elif defined(OS_WIN)
constexpr char kDoNothingCRXName[] = "updater_qualification_app_exe.crx";
constexpr char kDoNothingCRXRun[] = "qualification_app.exe";
constexpr char kDoNothingCRXHash[] =
"0705f7eedb0427810db76dfc072c8cbc302fbeb9b2c56fa0de3752ed8d6f9164";
#elif defined(OS_LINUX)
constexpr char kDoNothingCRXName[] = "updater_qualification_app.crx";
constexpr char kDoNothingCRXRun[] = "qualification_app";
constexpr char kDoNothingCRXHash[] = "";
#endif
std::string GetUpdateResponse(const std::string& app_id,
const std::string& codebase,
const base::Version& version) {
return base::StringPrintf(
")]}'\n"
R"({"response":{)"
R"( "protocol":"3.1",)"
R"( "app":[)"
R"( {)"
R"( "appid":"%s",)"
R"( "status":"ok",)"
R"( "updatecheck":{)"
R"( "status":"ok",)"
R"( "urls":{"url":[{"codebase":"%s"}]},)"
R"( "manifest":{)"
R"( "version":"%s",)"
R"( "run":"%s",)"
R"( "packages":{)"
R"( "package":[)"
R"( {"name":"%s","hash_sha256":"%s"})"
R"( ])"
R"( })"
R"( })"
R"( })"
R"( })"
R"( ])"
R"(}})",
app_id.c_str(), codebase.c_str(), version.GetString().c_str(),
kDoNothingCRXRun, kDoNothingCRXName, kDoNothingCRXHash);
}
} // namespace
int CountDirectoryFiles(const base::FilePath& dir) {
base::FileEnumerator it(dir, false, base::FileEnumerator::FILES);
int res = 0;
for (base::FilePath name = it.Next(); !name.empty(); name = it.Next())
++res;
return res;
}
void RegisterApp(UpdaterScope scope, const std::string& app_id) {
scoped_refptr<UpdateService> update_service = CreateUpdateServiceProxy(scope);
RegistrationRequest registration;
registration.app_id = app_id;
registration.version = base::Version("0.1");
base::RunLoop loop;
update_service->RegisterApp(
registration, base::BindOnce(base::BindLambdaForTesting(
[&loop](const RegistrationResponse& response) {
EXPECT_EQ(response.status_code, 0);
loop.Quit();
})));
loop.Run();
}
void ExpectVersionActive(UpdaterScope scope, const std::string& version) {
scoped_refptr<GlobalPrefs> prefs = CreateGlobalPrefs(scope);
ASSERT_NE(prefs, nullptr) << "Failed to acquire GlobalPrefs.";
EXPECT_EQ(prefs->GetActiveVersion(), version);
}
void ExpectVersionNotActive(UpdaterScope scope, const std::string& version) {
scoped_refptr<GlobalPrefs> prefs = CreateGlobalPrefs(scope);
ASSERT_NE(prefs, nullptr) << "Failed to acquire GlobalPrefs.";
EXPECT_NE(prefs->GetActiveVersion(), version);
}
void PrintLog(UpdaterScope scope) {
std::string contents;
absl::optional<base::FilePath> path = GetDataDirPath(scope);
EXPECT_TRUE(path);
if (path &&
base::ReadFileToString(path->AppendASCII("updater.log"), &contents)) {
VLOG(0) << "Contents of updater.log:";
VLOG(0) << contents;
VLOG(0) << "End contents of updater.log.";
} else {
VLOG(0) << "Failed to read updater.log file.";
}
}
const testing::TestInfo* GetTestInfo() {
return testing::UnitTest::GetInstance()->current_test_info();
}
base::FilePath GetLogDestinationDir() {
// Fetch path to ${ISOLATED_OUTDIR} env var.
// ResultDB reads logs and test artifacts info from there.
const char* var = std::getenv("ISOLATED_OUTDIR");
return var ? base::FilePath::FromUTF8Unsafe(var) : base::FilePath();
}
void CopyLog(const base::FilePath& src_dir) {
// TODO(crbug.com/1159189): copy other test artifacts.
base::FilePath dest_dir = GetLogDestinationDir();
if (!dest_dir.empty() && base::PathExists(dest_dir) &&
base::PathExists(src_dir)) {
base::FilePath test_name_path = dest_dir.AppendASCII(base::StrCat(
{GetTestInfo()->test_suite_name(), ".", GetTestInfo()->name()}));
EXPECT_TRUE(base::CreateDirectory(test_name_path));
base::FilePath dest_file_path = test_name_path.AppendASCII("updater.log");
base::FilePath log_path = src_dir.AppendASCII("updater.log");
VLOG(0) << "Copying updater.log file. From: " << log_path
<< ". To: " << dest_file_path;
EXPECT_TRUE(base::CopyFile(log_path, dest_file_path));
}
}
void RunWake(UpdaterScope scope, int expected_exit_code) {
const absl::optional<base::FilePath> installed_executable_path =
GetInstalledExecutablePath(scope);
ASSERT_TRUE(installed_executable_path);
EXPECT_TRUE(base::PathExists(*installed_executable_path));
base::CommandLine command_line(*installed_executable_path);
command_line.AppendSwitch(kWakeSwitch);
command_line.AppendSwitch(kEnableLoggingSwitch);
command_line.AppendSwitchASCII(kLoggingModuleSwitch,
kLoggingModuleSwitchValue);
int exit_code = -1;
ASSERT_TRUE(Run(scope, command_line, &exit_code));
EXPECT_EQ(exit_code, expected_exit_code);
}
void Update(UpdaterScope scope, const std::string& app_id) {
scoped_refptr<UpdateService> update_service = CreateUpdateServiceProxy(scope);
base::RunLoop loop;
update_service->Update(
app_id, UpdateService::Priority::kForeground,
UpdateService::PolicySameVersionUpdate::kNotAllowed, base::DoNothing(),
base::BindOnce(base::BindLambdaForTesting(
[&loop](UpdateService::Result result_unused) { loop.Quit(); })));
loop.Run();
}
void UpdateAll(UpdaterScope scope) {
scoped_refptr<UpdateService> update_service = CreateUpdateServiceProxy(scope);
base::RunLoop loop;
update_service->UpdateAll(
base::DoNothing(),
base::BindOnce(base::BindLambdaForTesting(
[&loop](UpdateService::Result result_unused) { loop.Quit(); })));
loop.Run();
}
void SetupFakeUpdaterPrefs(UpdaterScope scope, const base::Version& version) {
scoped_refptr<GlobalPrefs> global_prefs = CreateGlobalPrefs(scope);
ASSERT_TRUE(global_prefs) << "No global prefs.";
global_prefs->SetActiveVersion(version.GetString());
global_prefs->SetSwapping(false);
PrefsCommitPendingWrites(global_prefs->GetPrefService());
ASSERT_EQ(version.GetString(), global_prefs->GetActiveVersion());
}
void SetupFakeUpdaterInstallFolder(UpdaterScope scope,
const base::Version& version) {
const absl::optional<base::FilePath> folder_path =
GetFakeUpdaterInstallFolderPath(scope, version);
ASSERT_TRUE(folder_path);
ASSERT_TRUE(base::CreateDirectory(*folder_path));
}
void SetupFakeUpdater(UpdaterScope scope, const base::Version& version) {
SetupFakeUpdaterPrefs(scope, version);
SetupFakeUpdaterInstallFolder(scope, version);
}
void SetupFakeUpdaterVersion(UpdaterScope scope, int offset) {
ASSERT_NE(offset, 0);
std::vector<uint32_t> components =
base::Version(kUpdaterVersion).components();
base::CheckedNumeric<uint32_t> new_version = components[0];
new_version += offset;
ASSERT_TRUE(new_version.AssignIfValid(&components[0]));
SetupFakeUpdater(scope, base::Version(std::move(components)));
}
void SetupFakeUpdaterLowerVersion(UpdaterScope scope) {
SetupFakeUpdaterVersion(scope, -1);
}
void SetupFakeUpdaterHigherVersion(UpdaterScope scope) {
SetupFakeUpdaterVersion(scope, 1);
}
void SetExistenceCheckerPath(UpdaterScope scope,
const std::string& app_id,
const base::FilePath& path) {
scoped_refptr<GlobalPrefs> global_prefs = CreateGlobalPrefs(scope);
base::MakeRefCounted<PersistedData>(global_prefs->GetPrefService())
->SetExistenceCheckerPath(app_id, path);
PrefsCommitPendingWrites(global_prefs->GetPrefService());
}
void SetServerStarts(UpdaterScope scope, int value) {
scoped_refptr<GlobalPrefs> global_prefs = CreateGlobalPrefs(scope);
for (int i = 0; i <= value; ++i) {
global_prefs->CountServerStarts();
}
PrefsCommitPendingWrites(global_prefs->GetPrefService());
}
void ExpectAppUnregisteredExistenceCheckerPath(UpdaterScope scope,
const std::string& app_id) {
scoped_refptr<GlobalPrefs> global_prefs = CreateGlobalPrefs(scope);
auto persisted_data =
base::MakeRefCounted<PersistedData>(global_prefs->GetPrefService());
EXPECT_EQ(base::FilePath(FILE_PATH_LITERAL("")).value(),
persisted_data->GetExistenceCheckerPath(app_id).value());
}
void ExpectAppVersion(UpdaterScope scope,
const std::string& app_id,
const base::Version& version) {
const base::Version app_version =
base::MakeRefCounted<PersistedData>(
CreateGlobalPrefs(scope)->GetPrefService())
->GetProductVersion(app_id);
EXPECT_TRUE(app_version.IsValid() && version == app_version);
}
bool Run(UpdaterScope scope, base::CommandLine command_line, int* exit_code) {
base::ScopedAllowBaseSyncPrimitivesForTesting allow_wait_process;
command_line.AppendSwitch(kEnableLoggingSwitch);
command_line.AppendSwitchASCII(kLoggingModuleSwitch,
kLoggingModuleSwitchValue);
if (scope == UpdaterScope::kSystem) {
command_line.AppendSwitch(kSystemSwitch);
command_line = MakeElevated(command_line);
}
VLOG(0) << " Run command: " << command_line.GetCommandLineString();
base::Process process = base::LaunchProcess(command_line, {});
if (!process.IsValid())
return false;
// TODO(crbug.com/1096654): Get the timeout from TestTimeouts.
return process.WaitForExitWithTimeout(base::Seconds(45), exit_code);
}
void SleepFor(int seconds) {
VLOG(2) << "Sleeping " << seconds << " seconds...";
base::WaitableEvent sleep(base::WaitableEvent::ResetPolicy::MANUAL,
base::WaitableEvent::InitialState::NOT_SIGNALED);
base::ThreadPool::PostDelayedTask(
FROM_HERE, {base::MayBlock()},
base::BindOnce(&base::WaitableEvent::Signal, base::Unretained(&sleep)),
base::Seconds(seconds));
sleep.Wait();
VLOG(2) << "Sleep complete.";
}
bool WaitFor(base::RepeatingCallback<bool()> predicate) {
base::TimeTicks deadline =
base::TimeTicks::Now() + TestTimeouts::action_max_timeout();
while (base::TimeTicks::Now() < deadline) {
if (predicate.Run())
return true;
base::PlatformThread::Sleep(base::Milliseconds(200));
}
return false;
}
bool RequestMatcherRegex(const std::string& request_body_regex,
const std::string& request_body) {
if (!re2::RE2::PartialMatch(request_body, request_body_regex)) {
ADD_FAILURE() << "Request with body: " << request_body
<< " did not match expected regex " << request_body_regex;
return false;
}
return true;
}
void ExpectUpdateSequence(UpdaterScope scope,
ScopedServer* test_server,
const std::string& app_id,
const base::Version& from_version,
const base::Version& to_version) {
auto request_matcher_scope =
base::BindLambdaForTesting([scope](const std::string& request_body) {
const bool is_match = [&scope, &request_body]() {
const absl::optional<base::Value> doc =
base::JSONReader::Read(request_body);
if (!doc || !doc->is_dict())
return false;
const base::Value* object_request = doc->FindKey("request");
if (!object_request || !object_request->is_dict())
return false;
const base::Value* value_ismachine =
object_request->FindKey("ismachine");
if (!value_ismachine || !value_ismachine->is_bool())
return false;
switch (scope) {
case UpdaterScope::kSystem:
return value_ismachine->GetBool();
case UpdaterScope::kUser:
return !value_ismachine->GetBool();
}
}();
if (!is_match) {
ADD_FAILURE() << R"(Request does not match "ismachine": )"
<< request_body;
}
return is_match;
});
// First request: update check.
test_server->ExpectOnce(
{base::BindRepeating(
RequestMatcherRegex,
base::StringPrintf(R"(.*"appid":"%s".*)", app_id.c_str())),
request_matcher_scope},
GetUpdateResponse(app_id, test_server->base_url().spec(), to_version));
// Second request: update download.
base::FilePath test_data_path;
ASSERT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &test_data_path));
base::FilePath crx_path = test_data_path.Append(FILE_PATH_LITERAL("updater"))
.AppendASCII(kDoNothingCRXName);
ASSERT_TRUE(base::PathExists(crx_path));
std::string crx_bytes;
base::ReadFileToString(crx_path, &crx_bytes);
test_server->ExpectOnce({base::BindRepeating(RequestMatcherRegex, "")},
crx_bytes);
// Third request: event ping.
test_server->ExpectOnce(
{base::BindRepeating(
RequestMatcherRegex,
base::StringPrintf(R"(.*"eventresult":1,"eventtype":3,)"
R"("nextversion":"%s","previousversion":"%s".*)",
to_version.GetString().c_str(),
from_version.GetString().c_str())),
request_matcher_scope},
")]}'\n");
}
// Runs multiple cycles of instantiating the update service, calling
// `GetVersion()`, then releasing the service interface.
void StressUpdateService(UpdaterScope scope) {
base::RunLoop loop;
// Number of times to run the cycle of instantiating the service.
int n = 10;
// Delay in milliseconds between successive cycles.
const int kDelayBetweenLoopsMS = 0;
// Runs on the main sequence.
auto loop_closure = [&]() {
if (--n)
return false;
loop.Quit();
return true;
};
// Creates a task runner, and runs the service instance on it.
using LoopClosure = decltype(loop_closure);
auto stress_runner = [scope, loop_closure]() {
// `task_runner` is always bound on the main sequence.
struct Local {
static void GetVersion(
UpdaterScope scope,
scoped_refptr<base::SequencedTaskRunner> task_runner,
LoopClosure loop_closure) {
auto service_task_runner =
base::ThreadPool::CreateSingleThreadTaskRunner(
{}, base::SingleThreadTaskRunnerThreadMode::DEDICATED);
service_task_runner->PostDelayedTask(
FROM_HERE,
base::BindLambdaForTesting([scope, task_runner, loop_closure]() {
auto update_service = CreateUpdateServiceProxy(scope);
update_service->GetVersion(
base::BindOnce(GetVersionCallback, scope, update_service,
task_runner, loop_closure));
}),
base::Milliseconds(kDelayBetweenLoopsMS));
}
static void GetVersionCallback(
UpdaterScope scope,
scoped_refptr<UpdateService> /*update_service*/,
scoped_refptr<base::SequencedTaskRunner> task_runner,
LoopClosure loop_closure,
const base::Version& version) {
EXPECT_EQ(version, base::Version(kUpdaterVersion));
task_runner->PostTask(
FROM_HERE,
base::BindLambdaForTesting([scope, task_runner, loop_closure]() {
if (loop_closure()) {
return;
}
GetVersion(scope, task_runner, loop_closure);
}));
}
};
Local::GetVersion(scope, base::SequencedTaskRunnerHandle::Get(),
loop_closure);
};
stress_runner();
loop.Run();
}
void CallServiceUpdate(UpdaterScope updater_scope,
const std::string& app_id,
bool same_version_update_allowed) {
UpdateService::PolicySameVersionUpdate policy_same_version_update =
same_version_update_allowed
? UpdateService::PolicySameVersionUpdate::kAllowed
: UpdateService::PolicySameVersionUpdate::kNotAllowed;
scoped_refptr<UpdateService> service_proxy =
CreateUpdateServiceProxy(updater_scope);
base::RunLoop loop;
service_proxy->Update(
app_id, UpdateService::Priority::kForeground, policy_same_version_update,
base::BindLambdaForTesting([](const UpdateService::UpdateState&) {}),
base::BindLambdaForTesting([&](UpdateService::Result result) {
EXPECT_EQ(result, UpdateService::Result::kSuccess);
loop.Quit();
}));
loop.Run();
}
} // namespace test
} // namespace updater
| 18,869 | 6,161 |
#include<Core/hash.hpp>
#include<gtest/gtest.h>
#include<gmock/gmock.h>
using namespace core;
TEST(HashInt, DoneAtCompile){
static_assert(hashInt(1234) != 1234, "Not evaluted at compileTime");
}
TEST(Hash, IsItSalty){
EXPECT_NE(hashInt(1234 ), hashInt(1234,1));
EXPECT_NE(hashInt(1234,1), hashInt(1234,2));
EXPECT_NE(hashInt(1234 ), hashInt(1234,2));
EXPECT_NE(hashConstStr("foo" ), hashConstStr("foo",1));
EXPECT_NE(hashConstStr("foo",1), hashConstStr("foo",2));
EXPECT_NE(hashConstStr("foo" ), hashConstStr("foo",2));
}
TEST(HashString, TakesCorrectInputs){
const char* cc = "foo";
std::string ss = "bar";
EXPECT_NE(hashConstStr(cc), hashStdStr(ss));
EXPECT_NE(hashConstStr("baz"), hashStdStr(ss));
EXPECT_NE(hashConstStr(cc), hashConstStr("baz"));
}
TEST(HashString, DoneAtCompile){
static_assert(hashConstStr("foo") == 193491849, "Not evaluated at compileTime");
}
| 933 | 397 |
#define __STDC_FORMAT_MACROS 1
#include "BldDetector.hh"
#include <bitset>
#include <chrono>
#include <iostream>
#include <memory>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include "DataDriver.h"
#include "RunInfoDef.hh"
#include "psdaq/service/kwargs.hh"
#include "psdaq/service/EbDgram.hh"
#include "xtcdata/xtc/DescData.hh"
#include "xtcdata/xtc/ShapesData.hh"
#include "xtcdata/xtc/NamesLookup.hh"
#include "psdaq/eb/TebContributor.hh"
#include "psalg/utils/SysLog.hh"
#include <getopt.h>
#include <Python.h>
#include <inttypes.h>
#include <poll.h>
using json = nlohmann::json;
using logging = psalg::SysLog;
namespace Drp {
static const XtcData::Name::DataType xtype[] = {
XtcData::Name::UINT8 , // pvBoolean
XtcData::Name::INT8 , // pvByte
XtcData::Name::INT16, // pvShort
XtcData::Name::INT32 , // pvInt
XtcData::Name::INT64 , // pvLong
XtcData::Name::UINT8 , // pvUByte
XtcData::Name::UINT16, // pvUShort
XtcData::Name::UINT32, // pvUInt
XtcData::Name::UINT64, // pvULong
XtcData::Name::FLOAT , // pvFloat
XtcData::Name::DOUBLE, // pvDouble
XtcData::Name::CHARSTR, // pvString
};
BldPVA::BldPVA(std::string det,
unsigned interface) : _interface(interface)
{
//
// Parse '+' separated list of detName, detType, detId
//
size_t p1 = det.find('+',0);
if (p1 == std::string::npos) {
}
size_t p2 = det.find('+',p1+1);
if (p2 == std::string::npos) {
}
_detName = det.substr( 0, p1).c_str();
_detType = det.substr(p1+1,p2-p1-1).c_str();
_detId = det.substr(p2+1).c_str();
std::string sname(_detId);
_pvaAddr = std::make_shared<Pds_Epics::PVBase>((sname+":ADDR" ).c_str());
_pvaPort = std::make_shared<Pds_Epics::PVBase>((sname+":PORT" ).c_str());
_pvaPayload = std::make_shared<BldDescriptor> ((sname+":PAYLOAD").c_str());
logging::info("BldPVA::BldPVA looking up multicast parameters for %s/%s from %s",
_detName.c_str(), _detType.c_str(), _detId.c_str());
}
BldPVA::~BldPVA()
{
}
//
// LCLS-I Style
//
BldFactory::BldFactory(const char* name,
unsigned interface) :
_alg ("raw", 2, 0, 0)
{
logging::debug("BldFactory::BldFactory %s", name);
if (strchr(name,':'))
name = strrchr(name,':')+1;
_detName = std::string(name);
_detType = std::string(name);
_detId = std::string(name);
_pvaPayload = 0;
unsigned payloadSize = 0;
unsigned mcaddr = 0;
unsigned mcport = 10148; // 12148, eventually
uint64_t tscorr = 0x259e9d80ULL << 32;
//
// Make static configuration of BLD :(
//
if (strncmp("ebeam",name,5)==0) {
if (name[5]=='h') {
mcaddr = 0xefff1800;
}
else {
mcaddr = 0xefff1900;
}
tscorr = 0;
_alg = XtcData::Alg("raw", 2, 0, 0);
_varDef.NameVec.push_back(XtcData::Name("damageMask" , XtcData::Name::UINT32));
_varDef.NameVec.push_back(XtcData::Name("ebeamCharge" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamL3Energy" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamLTUPosX" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamLTUPosY" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamLUTAngX" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamLTUAngY" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamPkCurrBC2" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamEnergyBC2" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamPkCurrBC1" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamEnergyBC1" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamUndPosX" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamUndPosY" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamUndAngX" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamUndAngY" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamXTCAVAmpl" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamXTCAVPhase" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamDumpCharge" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamPhotonEnergy", XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamLTU250" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ebeamLTU450" , XtcData::Name::DOUBLE));
payloadSize = 164;
}
else if (strncmp("pcav",name,4)==0) {
if (name[4]=='h') {
mcaddr = 0xefff1801;
}
else {
mcaddr = 0xefff1901;
}
_alg = XtcData::Alg("raw", 2, 0, 0);
_varDef.NameVec.push_back(XtcData::Name("fitTime1" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("fitTime2" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("charge1" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("charge2" , XtcData::Name::DOUBLE));
payloadSize = 32;
}
else if (strncmp("gmd",name,3)==0) {
mcaddr = 0xefff1902;
_alg = XtcData::Alg("raw", 2, 1, 0);
_varDef.NameVec.push_back(XtcData::Name("energy" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("xpos" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ypos" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("avgIntensity", XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("rmsElectronSum", XtcData::Name::INT64));
_varDef.NameVec.push_back(XtcData::Name("electron1BkgNoiseAvg", XtcData::Name::INT16));
_varDef.NameVec.push_back(XtcData::Name("electron2BkgNoiseAvg", XtcData::Name::INT16));
payloadSize = 44;
}
else if (strcmp("xgmd",name)==0) {
mcaddr = 0xefff1903;
_alg = XtcData::Alg("raw", 2, 1, 0);
_varDef.NameVec.push_back(XtcData::Name("energy" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("xpos" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("ypos" , XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("avgIntensity", XtcData::Name::DOUBLE));
_varDef.NameVec.push_back(XtcData::Name("rmsElectronSum", XtcData::Name::INT64));
_varDef.NameVec.push_back(XtcData::Name("electron1BkgNoiseAvg", XtcData::Name::INT16));
_varDef.NameVec.push_back(XtcData::Name("electron2BkgNoiseAvg", XtcData::Name::INT16));
payloadSize = 44;
}
else {
throw std::string("BLD name ")+name+" not recognized";
}
_handler = std::make_shared<Bld>(mcaddr, mcport, interface, Bld::DgramTimestampPos, Bld::DgramHeaderSize, payloadSize,
tscorr);
}
//
// LCLS-II Style
//
BldFactory::BldFactory(const BldPVA& pva) :
_detName (pva._detName),
_detType (pva._detType),
_detId (pva._detId),
_alg ("raw", 2, 0, 0),
_pvaPayload (pva._pvaPayload)
{
while(1) {
if (pva._pvaAddr ->ready() &&
pva._pvaPort ->ready() &&
pva._pvaPayload->ready())
break;
usleep(10000);
}
unsigned mcaddr = pva._pvaAddr->getScalarAs<unsigned>();
unsigned mcport = pva._pvaPort->getScalarAs<unsigned>();
unsigned payloadSize = 0;
_varDef = pva._pvaPayload->get(payloadSize);
if (_detType == "hpsex" ||
_detType == "hpscp" ||
_detType == "hpscpb") {
_alg = XtcData::Alg("raw", 2, 0, 0);
// validate _varDef against version here
}
else {
throw std::string("BLD type ")+_detType+" not recognized";
}
_handler = std::make_shared<Bld>(mcaddr, mcport, pva._interface, Bld::TimestampPos, Bld::HeaderSize, payloadSize);
}
BldFactory::BldFactory(const BldFactory& o) :
_detName (o._detName),
_detType (o._detType),
_detId (o._detId),
_alg (o._alg),
_pvaPayload (o._pvaPayload)
{
logging::error("BldFactory copy ctor called");
}
BldFactory::~BldFactory()
{
}
Bld& BldFactory::handler()
{
return *_handler;
}
XtcData::NameIndex BldFactory::addToXtc (XtcData::Xtc& xtc,
const XtcData::NamesId& namesId)
{
XtcData::Names& bldNames = *new(xtc) XtcData::Names(_detName.c_str(), _alg,
_detType.c_str(), _detId.c_str(), namesId);
bldNames.add(xtc, _varDef);
return XtcData::NameIndex(bldNames);
}
unsigned interfaceAddress(const std::string& interface)
{
int fd = socket(AF_INET, SOCK_DGRAM, 0);
struct ifreq ifr;
strcpy(ifr.ifr_name, interface.c_str());
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
logging::debug("%s", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));
return ntohl(*(unsigned*)&(ifr.ifr_addr.sa_data[2]));
}
BldDescriptor::~BldDescriptor()
{
logging::debug("~BldDescriptor");
}
XtcData::VarDef BldDescriptor::get(unsigned& payloadSize)
{
payloadSize = 0;
XtcData::VarDef vd;
const pvd::StructureConstPtr& structure = _strct->getStructure();
if (!structure) {
logging::error("BLD with no payload. Is FieldMask empty?");
throw std::string("BLD with no payload. Is FieldMask empty?");
}
const pvd::StringArray& names = structure->getFieldNames();
const pvd::FieldConstPtrArray& fields = structure->getFields();
for (unsigned i=0; i<fields.size(); i++) {
switch (fields[i]->getType()) {
case pvd::scalar: {
const pvd::Scalar* scalar = static_cast<const pvd::Scalar*>(fields[i].get());
XtcData::Name::DataType type = xtype[scalar->getScalarType()];
vd.NameVec.push_back(XtcData::Name(names[i].c_str(), type));
payloadSize += XtcData::Name::get_element_size(type);
break;
}
default: {
throw std::string("PV type ")+pvd::TypeFunc::name(fields[i]->getType())+
" for field "+names[i]+" not supported";
break;
}
}
}
std::string fnames("fields: ");
for(auto & elem: vd.NameVec)
fnames += std::string(elem.name()) + "[" + elem.str_type() + "],";
logging::debug("%s",fnames.c_str());
return vd;
}
#define HANDLE_ERR(str) { \
perror(str); \
throw std::string(str); }
Bld::Bld(unsigned mcaddr,
unsigned port,
unsigned interface,
unsigned timestampPos,
unsigned headerSize,
unsigned payloadSize,
uint64_t timestampCorr) :
m_timestampPos(timestampPos), m_headerSize(headerSize), m_payloadSize(payloadSize),
m_bufferSize(0), m_position(0), m_buffer(Bld::MTU), m_payload(m_buffer.data()),
m_timestampCorr(timestampCorr)
{
logging::debug("Bld listening for %x.%d with payload size %u",mcaddr,port,payloadSize);
m_sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (m_sockfd < 0)
HANDLE_ERR("Open socket");
{ unsigned skbSize = 0x1000000;
if (setsockopt(m_sockfd, SOL_SOCKET, SO_RCVBUF, &skbSize, sizeof(skbSize)) == -1)
HANDLE_ERR("set so_rcvbuf");
}
struct sockaddr_in saddr;
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = htonl(mcaddr);
saddr.sin_port = htons(port);
memset(saddr.sin_zero, 0, sizeof(saddr.sin_zero));
if (bind(m_sockfd, (sockaddr*)&saddr, sizeof(saddr)) < 0)
HANDLE_ERR("bind");
int y = 1;
if (setsockopt(m_sockfd, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(y)) == -1)
HANDLE_ERR("set reuseaddr");
ip_mreq ipmreq;
bzero(&ipmreq, sizeof(ipmreq));
ipmreq.imr_multiaddr.s_addr = htonl(mcaddr);
ipmreq.imr_interface.s_addr = htonl(interface);
if (setsockopt(m_sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
&ipmreq, sizeof(ipmreq)) == -1)
HANDLE_ERR("mcast join");
}
Bld::Bld(const Bld& o) :
m_timestampPos(o.m_timestampPos),
m_headerSize (o.m_headerSize),
m_payloadSize (o.m_payloadSize),
m_sockfd (o.m_sockfd)
{
logging::error("Bld copy ctor called");
}
Bld::~Bld()
{
close(m_sockfd);
}
/*
memory layout for bld packet
header:
uint64_t pulseId
uint64_t timeStamp
uint32_t id;
uint8_t payload[]
following events []
uint32_t pulseIdOffset
uint8_t payload[]
*/
uint64_t Bld::next()
{
uint64_t timestamp(0L);
// get new multicast if buffer is empty
if ((m_position + m_payloadSize + 4) > m_bufferSize) {
m_bufferSize = recv(m_sockfd, m_buffer.data(), Bld::MTU, 0);
timestamp = headerTimestamp();
m_payload = &m_buffer[m_headerSize];
m_position = m_headerSize + m_payloadSize;
}
else {
uint32_t timestampOffset = *reinterpret_cast<uint32_t*>(m_buffer.data() + m_position)&0xfffff;
timestamp = headerTimestamp() + timestampOffset;
m_payload = &m_buffer[m_position + 4];
m_position += 4 + m_payloadSize;
}
logging::debug("BLD timestamp %16llx",timestamp);
return timestamp;
}
class BldDetector : public XpmDetector
{
public:
BldDetector(Parameters& para, DrpBase& drp) : XpmDetector(¶, &drp.pool) {}
void event(XtcData::Dgram& dgram, PGPEvent* event) override {}
};
Pgp::Pgp(Parameters& para, DrpBase& drp, Detector* det) :
m_para(para), m_drp(drp), m_det(det),
m_config(0), m_terminate(false), m_running(false),
m_available(0), m_current(0), m_lastComplete(0), m_next(0)
{
m_nodeId = det->nodeId;
uint8_t mask[DMA_MASK_SIZE];
dmaInitMaskBytes(mask);
for (unsigned i=0; i<PGP_MAX_LANES; i++) {
if (para.laneMask & (1 << i)) {
logging::info("setting lane %d", i);
dmaAddMaskBytes((uint8_t*)mask, dmaDest(i, 0));
}
}
dmaSetMaskBytes(m_drp.pool.fd(), mask);
}
Pds::EbDgram* Pgp::_handle(uint32_t& current, uint64_t& bytes)
{
int32_t size = dmaRet[m_current];
uint32_t index = dmaIndex[m_current];
uint32_t lane = (dest[m_current] >> 8) & 7;
bytes += size;
if (unsigned(size) > m_drp.pool.dmaSize()) {
logging::critical("DMA overflowed buffer: %d vs %d", size, m_drp.pool.dmaSize());
throw "DMA overflowed buffer";
}
const uint32_t* data = (uint32_t*)m_drp.pool.dmaBuffers[index];
uint32_t evtCounter = data[5] & 0xffffff;
const unsigned bufferMask = m_drp.pool.nbuffers() - 1;
current = evtCounter & (m_drp.pool.nbuffers() - 1);
PGPEvent* event = &m_drp.pool.pgpEvents[current];
DmaBuffer* buffer = &event->buffers[lane];
buffer->size = size;
buffer->index = index;
event->mask |= (1 << lane);
logging::debug("PGPReader lane %d size %d hdr %016lx.%016lx.%08x",
lane, size,
reinterpret_cast<const uint64_t*>(data)[0],
reinterpret_cast<const uint64_t*>(data)[1],
reinterpret_cast<const uint32_t*>(data)[4]);
const Pds::TimingHeader* timingHeader = reinterpret_cast<const Pds::TimingHeader*>(data);
if (timingHeader->error()) {
logging::error("Timing header error bit is set");
}
XtcData::TransitionId::Value transitionId = timingHeader->service();
if (transitionId != XtcData::TransitionId::L1Accept) {
if (transitionId != XtcData::TransitionId::SlowUpdate) {
logging::info("PGPReader saw %s @ %u.%09u (%014lx)",
XtcData::TransitionId::name(transitionId),
timingHeader->time.seconds(), timingHeader->time.nanoseconds(),
timingHeader->pulseId());
}
else {
logging::debug("PGPReader saw %s @ %u.%09u (%014lx)",
XtcData::TransitionId::name(transitionId),
timingHeader->time.seconds(), timingHeader->time.nanoseconds(),
timingHeader->pulseId());
}
if (transitionId == XtcData::TransitionId::BeginRun) {
m_lastComplete = 0; // EvtCounter reset
}
}
if (evtCounter != ((m_lastComplete + 1) & 0xffffff)) {
logging::critical("%sPGPReader: Jump in complete l1Count %u -> %u | difference %d, tid %s%s",
RED_ON, m_lastComplete, evtCounter, evtCounter - m_lastComplete, XtcData::TransitionId::name(transitionId), RED_OFF);
logging::critical("data: %08x %08x %08x %08x %08x %08x",
data[0], data[1], data[2], data[3], data[4], data[5]);
logging::critical("lastTid %s", XtcData::TransitionId::name(m_lastTid));
logging::critical("lastData: %08x %08x %08x %08x %08x %08x",
m_lastData[0], m_lastData[1], m_lastData[2], m_lastData[3], m_lastData[4], m_lastData[5]);
throw "Jump in event counter";
for (unsigned e=m_lastComplete+1; e<evtCounter; e++) {
PGPEvent* brokenEvent = &m_drp.pool.pgpEvents[e & bufferMask];
logging::error("broken event: %08x", brokenEvent->mask);
brokenEvent->mask = 0;
}
}
m_lastComplete = evtCounter;
m_lastTid = transitionId;
memcpy(m_lastData, data, 24);
event->l3InpBuf = m_drp.tebContributor().allocate(*timingHeader, (void*)((uintptr_t)current));
// make new dgram in the pebble
// It must be an EbDgram in order to be able to send it to the MEB
Pds::EbDgram* dgram = new(m_drp.pool.pebble[current]) Pds::EbDgram(*timingHeader, XtcData::Src(m_nodeId), m_para.rogMask);
return dgram;
}
Pds::EbDgram* Pgp::next(uint32_t& evtIndex, uint64_t& bytes)
{
// get new buffers
if (m_current == m_available) {
m_current = 0;
m_available = dmaReadBulkIndex(m_drp.pool.fd(), MAX_RET_CNT_C, dmaRet, dmaIndex, NULL, NULL, dest);
if (m_available == 0)
return nullptr;
m_drp.pool.allocate(m_available);
}
Pds::EbDgram* dgram = _handle(evtIndex, bytes);
m_current++;
return dgram;
}
void Pgp::shutdown()
{
m_terminate.store(true, std::memory_order_release);
m_det->namesLookup().clear(); // erase all elements
}
void Pgp::worker(std::shared_ptr<Pds::MetricExporter> exporter)
{
// setup monitoring
uint64_t nevents = 0L;
std::map<std::string, std::string> labels{{"instrument", m_para.instrument},
{"partition", std::to_string(m_para.partition)},
{"detname", m_para.detName},
{"detseg", std::to_string(m_para.detSegment)},
{"alias", m_para.alias}};
exporter->add("drp_event_rate", labels, Pds::MetricType::Rate,
[&](){return nevents;});
uint64_t bytes = 0L;
exporter->add("drp_pgp_byte_rate", labels, Pds::MetricType::Rate,
[&](){return bytes;});
uint64_t nmissed = 0L;
exporter->add("bld_miss_count", labels, Pds::MetricType::Counter,
[&](){return nmissed;});
//
// Setup the multicast receivers
//
m_config.erase(m_config.begin(), m_config.end());
unsigned interface = interfaceAddress(m_para.kwargs["interface"]);
//
// Cache the BLD types that require lookup
//
std::vector<std::shared_ptr<BldPVA> > bldPva(0);
std::string s(m_para.detType);
logging::debug("Parsing %s",s.c_str());
for(size_t curr = 0, next = 0; next != std::string::npos; curr = next+1) {
next = s.find(',',curr+1);
size_t pvpos = s.find('+',curr+1);
logging::debug("(%d,%d,%d)",curr,pvpos,next);
if (next == std::string::npos) {
if (pvpos != std::string::npos)
bldPva.push_back(std::make_shared<BldPVA>(s.substr(curr,next),
interface));
else
m_config.push_back(std::make_shared<BldFactory>(s.substr(curr,next).c_str(),
interface));
}
else if (pvpos > curr && pvpos < next)
bldPva.push_back(std::make_shared<BldPVA>(s.substr(curr,next-curr),
interface));
else
m_config.push_back(std::make_shared<BldFactory>(s.substr(curr,next-curr).c_str(),
interface));
}
for(unsigned i=0; i<bldPva.size(); i++)
m_config.push_back(std::make_shared<BldFactory>(*bldPva[i].get()));
// Event builder variables
unsigned index;
Pds::EbDgram* dgram = 0;
uint64_t timestamp[m_config.size()];
memset(timestamp,0,sizeof(timestamp));
bool lMissing = false;
XtcData::NamesLookup& namesLookup = m_det->namesLookup();
// Poll
// this was 4ms, but EBeam bld timed out in rix intermittently,
// increased it to 50ms, but then we get deadtime running bld
// with no eventcode 136 @120Hz. 120Hz corresponds to 8ms, so try 7ms.
unsigned tmo = 7; // milliseconds
{
std::map<std::string,std::string>::iterator it = m_para.kwargs.find("timeout");
if (it != m_para.kwargs.end())
tmo = strtoul(it->second.c_str(),NULL,0);
}
unsigned nfds = m_config.size()+1;
pollfd pfd[nfds];
pfd[0].fd = m_drp.pool.fd();
pfd[0].events = POLLIN;
for(unsigned i=0; i<m_config.size(); i++) {
pfd[i+1].fd = m_config[i]->handler().fd();
pfd[i+1].events = POLL_IN;
}
m_terminate.store(false, std::memory_order_release);
while (true) {
if (m_terminate.load(std::memory_order_relaxed)) {
break;
}
int rval = poll(pfd, nfds, tmo);
if (rval < 0) { // error
}
/**
else if (rval == 0) { // timeout
// flush dgrams
if (pfd[0].events == 0) {
bool lMissed = false;
uint64_t ts = dgram->time.value();
for(unsigned i=0; i<m_config.size(); i++) {
if (timestamp[i] == ts) {
XtcData::NamesId namesId(m_nodeId, BldNamesIndex + i);
const Bld& bld = m_config[i]->handler();
XtcData::DescribedData desc(dgram->xtc, namesLookup, namesId);
memcpy(desc.data(), bld.payload(), bld.payloadSize());
desc.set_data_length(bld.payloadSize());
pfd[i+1].events = POLLIN;
}
else {
lMissed = true;
if (!lMissing)
logging::debug("Missed bld[%u]: pgp %016lx bld %016lx",
i, ts, timestamp[i]);
}
}
if (lMissed) {
lMissing = true;
dgram->xtc.damage.increase(XtcData::Damage::DroppedContribution);
}
else
lMissing = false;
logging::debug("poll tmo flush dgram %p extent %u dmg 0x%x",
dgram, dgram->xtc.extent, dgram->xtc.damage.value());
_sendToTeb(*dgram, index);
nevents++;
pfd[0].events = POLLIN;
}
for(unsigned i=0; i<m_config.size(); i++)
pfd[i+1].events = POLLIN;
}
**/
else {
logging::debug("poll rval[%d] pfd[0].events %u pfd[1].events %u dgram %p",
rval, pfd[0].events,pfd[1].events,dgram);
// handle pgp
if (pfd[0].revents == POLLIN) {
dgram = next(index, bytes);
pfd[0].events = 0;
}
// handle bld
for(unsigned i=0; i<m_config.size(); i++) {
if (pfd[i+1].revents == POLLIN) {
timestamp[i] = m_config[i]->handler().next();
pfd[i+1].events = 0;
}
}
if (dgram) {
bool lready = true;
uint64_t ts = dgram->time.value();
for(unsigned i=0; i<m_config.size(); i++) {
if (timestamp[i] < ts) {
pfd[i+1].events = POLLIN;
lready = false;
}
}
// Accept non-L1 transitions
if (dgram->service() != XtcData::TransitionId::L1Accept) {
// Allocate a transition dgram from the pool and initialize its header
Pds::EbDgram* trDgram = m_drp.pool.allocateTr();
memcpy((void*)trDgram, (const void*)dgram, sizeof(*dgram) - sizeof(dgram->xtc));
// copy the temporary xtc created on phase 1 of the transition
// into the real location
XtcData::Xtc& trXtc = m_det->transitionXtc();
memcpy((void*)&trDgram->xtc, (const void*)&trXtc, trXtc.extent);
PGPEvent* pgpEvent = &m_drp.pool.pgpEvents[index];
pgpEvent->transitionDgram = trDgram;
if (dgram->service() == XtcData::TransitionId::Configure) {
logging::info("BLD configure");
// Revisit: This is intended to be done by BldDetector::configure()
for(unsigned i=0; i<m_config.size(); i++) {
XtcData::NamesId namesId(m_nodeId, BldNamesIndex + i);
namesLookup[namesId] = m_config[i]->addToXtc(trDgram->xtc, namesId);
}
}
_sendToTeb(*dgram, index);
nevents++;
pfd[0].events = POLLIN;
dgram = 0;
}
// Accept L1 transitions
else if (lready or rval==0) {
bool lMissed = false;
for(unsigned i=0; i<m_config.size(); i++) {
if (timestamp[i] == ts) {
XtcData::NamesId namesId(m_nodeId, BldNamesIndex + i);
const Bld& bld = m_config[i]->handler();
XtcData::DescribedData desc(dgram->xtc, namesLookup, namesId);
memcpy(desc.data(), bld.payload(), bld.payloadSize());
desc.set_data_length(bld.payloadSize());
pfd[i+1].events = POLLIN;
}
else {
lMissed = true;
if (!lMissing)
logging::debug("Missed bld[%u]: pgp %016lx bld %016lx",
i, ts, timestamp[i]);
}
}
if (lMissed) {
lMissing = true;
dgram->xtc.damage.increase(XtcData::Damage::DroppedContribution);
}
else
lMissing = false;
_sendToTeb(*dgram, index);
nevents++;
pfd[0].events = POLLIN;
dgram = 0;
}
}
}
}
logging::info("Worker thread finished");
}
void Pgp::_sendToTeb(Pds::EbDgram& dgram, uint32_t index)
{
// Make sure the datagram didn't get too big
const size_t size = sizeof(dgram) + dgram.xtc.sizeofPayload();
const size_t maxSize = ((dgram.service() == XtcData::TransitionId::L1Accept) ||
(dgram.service() == XtcData::TransitionId::SlowUpdate))
? m_drp.pool.bufferSize()
: m_para.maxTrSize;
if (size > maxSize) {
logging::critical("%s Dgram of size %zd overflowed buffer of size %zd", XtcData::TransitionId::name(dgram.service()), size, maxSize);
throw "Dgram overflowed buffer";
}
PGPEvent* event = &m_drp.pool.pgpEvents[index];
if (event->l3InpBuf) { // else timed out
Pds::EbDgram* l3InpDg = new(event->l3InpBuf) Pds::EbDgram(dgram);
if (l3InpDg->isEvent()) {
if (m_drp.triggerPrimitive()) { // else this DRP doesn't provide input
m_drp.triggerPrimitive()->event(m_drp.pool, index, dgram.xtc, l3InpDg->xtc); // Produce
}
}
m_drp.tebContributor().process(l3InpDg);
}
}
BldApp::BldApp(Parameters& para) :
CollectionApp(para.collectionHost, para.partition, "drp", para.alias),
m_drp (para, context()),
m_para (para),
m_det (new BldDetector(m_para, m_drp)),
m_unconfigure(false)
{
Py_Initialize(); // for use by configuration
if (m_det == nullptr) {
logging::critical("Error !! Could not create Detector object for %s", m_para.detType.c_str());
throw "Could not create Detector object for " + m_para.detType;
}
if (m_para.outputDir.empty()) {
logging::info("output dir: n/a");
} else {
logging::info("output dir: %s", m_para.outputDir.c_str());
}
logging::info("Ready for transitions");
}
BldApp::~BldApp()
{
// Try to take things down gracefully when an exception takes us off the
// normal path so that the most chance is given for prints to show up
handleReset(json({}));
if (m_det) {
delete m_det;
}
Py_Finalize(); // for use by configuration
}
void BldApp::_disconnect()
{
m_drp.disconnect();
m_det->shutdown();
}
void BldApp::_unconfigure()
{
m_drp.unconfigure(); // TebContributor must be shut down before the worker
if (m_pgp) {
m_pgp->shutdown();
if (m_workerThread.joinable()) {
m_workerThread.join();
}
m_pgp.reset();
}
m_unconfigure = false;
}
json BldApp::connectionInfo()
{
std::string ip = m_para.kwargs.find("ep_domain") != m_para.kwargs.end()
? getNicIp(m_para.kwargs["ep_domain"])
: getNicIp(m_para.kwargs["forceEnet"] == "yes");
logging::debug("nic ip %s", ip.c_str());
json body = {{"connect_info", {{"nic_ip", ip}}}};
json info = m_det->connectionInfo();
body["connect_info"].update(info);
json bufInfo = m_drp.connectionInfo(ip);
body["connect_info"].update(bufInfo);
return body;
}
void BldApp::connectionShutdown()
{
m_drp.shutdown();
if (m_exporter) {
m_exporter.reset();
}
}
void BldApp::_error(const std::string& which, const nlohmann::json& msg, const std::string& errorMsg)
{
json body = json({});
body["err_info"] = errorMsg;
json answer = createMsg(which, msg["header"]["msg_id"], getId(), body);
reply(answer);
}
void BldApp::handleConnect(const nlohmann::json& msg)
{
std::string errorMsg = m_drp.connect(msg, getId());
if (!errorMsg.empty()) {
logging::error("Error in BldApp::handleConnect");
logging::error("%s", errorMsg.c_str());
_error("connect", msg, errorMsg);
return;
}
// Check for proper command-line parameters
std::map<std::string,std::string>::iterator it = m_para.kwargs.find("interface");
if (it == m_para.kwargs.end()) {
logging::error("Error in BldApp::handleConnect");
logging::error("No multicast interface specified");
_error("connect", msg, std::string("No multicast interface specified"));
return;
}
unsigned interface = interfaceAddress(it->second);
if (!interface) {
logging::error("Error in BldApp::handleConnect");
logging::error("Failed to lookup multicast interface %s",it->second.c_str());
_error("connect", msg, std::string("Failed to lookup multicast interface"));
return;
}
m_det->nodeId = m_drp.nodeId();
m_det->connect(msg, std::to_string(getId()));
json body = json({});
json answer = createMsg("connect", msg["header"]["msg_id"], getId(), body);
reply(answer);
}
void BldApp::handleDisconnect(const json& msg)
{
// Carry out the queued Unconfigure, if there was one
if (m_unconfigure) {
_unconfigure();
}
_disconnect();
json body = json({});
reply(createMsg("disconnect", msg["header"]["msg_id"], getId(), body));
}
void BldApp::handlePhase1(const json& msg)
{
std::string key = msg["header"]["key"];
logging::debug("handlePhase1 for %s in BldDetectorApp", key.c_str());
XtcData::Xtc& xtc = m_det->transitionXtc();
XtcData::TypeId tid(XtcData::TypeId::Parent, 0);
xtc.src = XtcData::Src(m_det->nodeId); // set the src field for the event builders
xtc.damage = 0;
xtc.contains = tid;
xtc.extent = sizeof(XtcData::Xtc);
json phase1Info{ "" };
if (msg.find("body") != msg.end()) {
if (msg["body"].find("phase1Info") != msg["body"].end()) {
phase1Info = msg["body"]["phase1Info"];
}
}
json body = json({});
if (key == "configure") {
if (m_unconfigure) {
_unconfigure();
}
std::string errorMsg = m_drp.configure(msg);
if (!errorMsg.empty()) {
errorMsg = "Phase 1 error: " + errorMsg;
logging::error("%s", errorMsg.c_str());
_error(key, msg, errorMsg);
return;
}
m_pgp = std::make_unique<Pgp>(m_para, m_drp, m_det);
if (m_exporter) m_exporter.reset();
m_exporter = std::make_shared<Pds::MetricExporter>();
if (m_drp.exposer()) {
m_drp.exposer()->RegisterCollectable(m_exporter);
}
std::string config_alias = msg["body"]["config_alias"];
unsigned error = m_det->configure(config_alias, xtc);
if (error) {
std::string errorMsg = "Phase 1 error in Detector::configure";
logging::error("%s", errorMsg.c_str());
_error(key, msg, errorMsg);
return;
}
m_workerThread = std::thread{&Pgp::worker, std::ref(*m_pgp), m_exporter};
m_drp.runInfoSupport(xtc, m_det->namesLookup());
}
else if (key == "unconfigure") {
// "Queue" unconfiguration until after phase 2 has completed
m_unconfigure = true;
}
else if (key == "beginrun") {
RunInfo runInfo;
std::string errorMsg = m_drp.beginrun(phase1Info, runInfo);
if (!errorMsg.empty()) {
logging::error("%s", errorMsg.c_str());
_error(key, msg, errorMsg);
return;
}
m_drp.runInfoData(xtc, m_det->namesLookup(), runInfo);
}
else if (key == "endrun") {
std::string errorMsg = m_drp.endrun(phase1Info);
if (!errorMsg.empty()) {
logging::error("%s", errorMsg.c_str());
_error(key, msg, errorMsg);
return;
}
}
json answer = createMsg(key, msg["header"]["msg_id"], getId(), body);
reply(answer);
}
void BldApp::handleReset(const nlohmann::json& msg)
{
unsubscribePartition(); // ZMQ_UNSUBSCRIBE
_unconfigure();
_disconnect();
connectionShutdown();
}
} // namespace Drp
int main(int argc, char* argv[])
{
Drp::Parameters para;
std::string kwargs_str;
int c;
while((c = getopt(argc, argv, "l:p:o:C:b:d:D:u:P:T::k:M:v")) != EOF) {
switch(c) {
case 'p':
para.partition = std::stoi(optarg);
break;
case 'l':
para.laneMask = strtoul(optarg,NULL,0);
break;
case 'o':
para.outputDir = optarg;
break;
case 'C':
para.collectionHost = optarg;
break;
case 'b':
para.detName = optarg;
break;
case 'd':
para.device = optarg;
break;
case 'D':
para.detType = optarg;
break;
case 'u':
para.alias = optarg;
break;
case 'P':
para.instrument = optarg;
break;
case 'k':
kwargs_str = kwargs_str.empty()
? optarg
: kwargs_str + ", " + optarg;
break;
case 'M':
para.prometheusDir = optarg;
break;
case 'v':
++para.verbose;
break;
default:
return 1;
}
}
switch (para.verbose) {
case 0: logging::init(para.instrument.c_str(), LOG_INFO); break;
default: logging::init(para.instrument.c_str(), LOG_DEBUG); break;
}
logging::info("logging configured");
if (optind < argc)
{
logging::error("Unrecognized argument:");
while (optind < argc)
logging::error(" %s ", argv[optind++]);
return 1;
}
if (para.instrument.empty()) {
logging::warning("-P: instrument name is missing");
}
// Check required parameters
if (para.partition == unsigned(-1)) {
logging::critical("-p: partition is mandatory");
return 1;
}
if (para.device.empty()) {
logging::critical("-d: device is mandatory");
return 1;
}
if (para.alias.empty()) {
logging::critical("-u: alias is mandatory");
return 1;
}
// Only one lane is supported by this DRP
if (std::bitset<PGP_MAX_LANES>(para.laneMask).count() != 1) {
logging::critical("-l: lane mask must have only 1 bit set");
return 1;
}
// Alias must be of form <detName>_<detSegment>
size_t found = para.alias.rfind('_');
if ((found == std::string::npos) || !isdigit(para.alias.back())) {
logging::critical("-u: alias must have _N suffix");
return 1;
}
para.detName = "bld"; //para.alias.substr(0, found);
para.detSegment = std::stoi(para.alias.substr(found+1, para.alias.size()));
get_kwargs(kwargs_str, para.kwargs);
for (const auto& kwargs : para.kwargs) {
if (kwargs.first == "forceEnet") continue;
if (kwargs.first == "ep_fabric") continue;
if (kwargs.first == "ep_domain") continue;
if (kwargs.first == "ep_provider") continue;
if (kwargs.first == "sim_length") continue; // XpmDetector
if (kwargs.first == "timebase") continue; // XpmDetector
if (kwargs.first == "pebbleBufSize") continue; // DrpBase
if (kwargs.first == "batching") continue; // DrpBase
if (kwargs.first == "directIO") continue; // DrpBase
if (kwargs.first == "interface") continue;
if (kwargs.first == "timeout") continue;
logging::critical("Unrecognized kwarg '%s=%s'\n",
kwargs.first.c_str(), kwargs.second.c_str());
return 1;
}
para.maxTrSize = 256 * 1024;
try {
Drp::BldApp app(para);
app.run();
return 0;
}
catch (std::exception& e) { logging::critical("%s", e.what()); }
catch (std::string& e) { logging::critical("%s", e.c_str()); }
catch (char const* e) { logging::critical("%s", e); }
catch (...) { logging::critical("Default exception"); }
return EXIT_FAILURE;
}
| 40,214 | 14,067 |
#include <bits/stdc++.h>
using namespace std;
int main()
{ int sum=1, s,x=1;
cout<<"Enter no. of terms";
cin>>s;
if (s<=1){cout<<s;}
else
{for (int i =2;i<=s;i++){ x=x*10;
x=x+i;
sum=sum+x;
}
cout<<sum;}
return 0;
} | 217 | 113 |
#include "stdafx.h"
#include <OdbcConnection.h>
#include <OdbcStatement.h>
#include <BoundDatumSet.h>
#include <QueryPreparedOperation.h>
namespace mssql
{
QueryPreparedOperation::QueryPreparedOperation(
const shared_ptr<OdbcConnection> &connection,
const size_t query_id, const u_int timeout,
const Local<Object> callback) :
OdbcOperation(connection, callback),
_timeout(timeout),
_output_param_count(0)
{
_statementId = static_cast<long>(query_id);
_params = make_shared<BoundDatumSet>();
}
bool QueryPreparedOperation::parameter_error_to_user_callback(const uint32_t param, const char* error) const
{
const nodeTypeFactory fact;
_params->clear();
stringstream full_error;
full_error << "IMNOD: [msnodesql] Parameter " << param + 1 << ": " << error;
auto err = fact.error(full_error);
const auto imn = fact.new_string("IMNOD");
err->Set(fact.new_string("sqlstate"), imn);
err->Set(fact.new_string("code"), fact.new_integer(-1));
Local<Value> args[1];
args[0] = err;
const auto argc = 1;
fact.scopedCallback(_callback, argc, args);
return false;
}
bool QueryPreparedOperation::bind_parameters(Local<Array> &node_params) const
{
const auto res = _params->bind(node_params);
if (!res)
{
parameter_error_to_user_callback(_params->first_error, _params->err);
}
return res;
}
bool QueryPreparedOperation::TryInvokeOdbc()
{
if (_statement == nullptr) return false;
return _statement->bind_fetch(_params);
}
Local<Value> QueryPreparedOperation::CreateCompletionArg()
{
return _statement->get_meta_value();
}
}
| 1,594 | 598 |
/***********************************************************
* FileName: Mapper.cpp
* Author: binss
* Create: 2015-11-06 11:24:22
* Description: No Description
***********************************************************/
#include "Mapper.h"
Mapper * Mapper::mapper = NULL;
Mapper * Mapper::GetInstance()
{
if(mapper == NULL)
{
mapper = new Mapper();
}
return mapper;
}
Mapper::Mapper():logger_("Mapper", DEBUG, true)
{
InitContentTypeMap();
InitViewMap();
InitReasonMap();
}
void Mapper::InitContentTypeMap()
{
// 0 - 9 chucked
content_type_map_[""] = 0;
content_type_map_["tml"] = 1;
// 10 - 19 fixed-length text file
content_type_map_[".js"] = 10;
content_type_map_["css"] = 11;
// 20 - 29 image
content_type_map_["png"] = 20;
content_type_map_["jpg"] = 21;
content_type_map_["gif"] = 22;
content_type_map_["ico"] = 23;
}
void Mapper::InitReasonMap()
{
// 0 - 9 chucked
reason_map_[200] = "200 OK";
reason_map_[304] = "304 Not Modified";
reason_map_[403] = "403 Forbidden";
reason_map_[404] = "404 Not Found";
reason_map_[500] = "500 Internal Server Error";
}
int Mapper::GetContentType(string file_type)
{
// 默认为0
return content_type_map_[file_type];
}
void Mapper::InitViewMap()
{
view_map_["/"] = main_page;
view_map_["/404/"] = error_404;
view_map_["/403/"] = error_403;
view_map_["/upload/"] = upload_page;
view_map_["/user/"] = user_page;
}
View Mapper::GetView(string target)
{
View view = view_map_[target];
if(NULL == view)
{
logger_<<"Can not find the view of the target["<<target<<"]"<<endl;
return view_map_["/404/"];
}
return view;
}
string & Mapper::GetReason(int code)
{
return reason_map_[code];
}
| 1,825 | 728 |
/*
==============================================================================
This is an automatically generated GUI class created by the Projucer!
Be careful when adding custom code to these files, as only the code within
the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded
and re-saved.
Created with Projucer version: 5.4.3
------------------------------------------------------------------------------
The Projucer is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
==============================================================================
*/
//[Headers] You can add your own extra header files here...
#include "Core.h"
//[/Headers]
#include "UiUndoRedo.h"
//[MiscUserDefs] You can add your own user definitions and misc code here...
//[/MiscUserDefs]
//==============================================================================
UiUndoRedo::UiUndoRedo (Component* parent, Core& core)
: mParent{parent}, mUndoManager{core.getUndoManager()}
{
//[Constructor_pre] You can add your own custom stuff here..
//[/Constructor_pre]
setName ("UiUndoRedo");
mButtonUndo.reset (new TextButton ("ButtonUndo"));
addAndMakeVisible (mButtonUndo.get());
mButtonUndo->setButtonText (TRANS("Undo"));
mButtonUndo->setColour (TextButton::buttonOnColourId, Colour (0xffa45c94));
mButtonRedo.reset (new TextButton ("ButtonRedo"));
addAndMakeVisible (mButtonRedo.get());
mButtonRedo->setButtonText (TRANS("Redo"));
mButtonRedo->setColour (TextButton::buttonOnColourId, Colour (0xffa45c94));
//[UserPreSize]
mButtonUndo->setEnabled(false);
mButtonRedo->setEnabled(false);
//[/UserPreSize]
setSize (600, 400);
//[Constructor] You can add your own custom stuff here..
mButtonUndo->onClick = [&] { mUndoManager.undo(); };
mButtonRedo->onClick = [&] { mUndoManager.redo(); };
startTimer (250);
//[/Constructor]
}
UiUndoRedo::~UiUndoRedo()
{
//[Destructor_pre]. You can add your own custom destruction code here..
//[/Destructor_pre]
mButtonUndo = nullptr;
mButtonRedo = nullptr;
//[Destructor]. You can add your own custom destruction code here..
//[/Destructor]
}
//==============================================================================
void UiUndoRedo::paint (Graphics& g)
{
//[UserPrePaint] Add your own custom painting code here..
//[/UserPrePaint]
{
float x = 0.0f, y = 0.0f, width = static_cast<float> (proportionOfWidth (1.0000f)), height = static_cast<float> (proportionOfHeight (1.0000f));
Colour fillColour = Colours::yellow;
Colour strokeColour = Colours::black;
//[UserPaintCustomArguments] Customize the painting arguments here..
//[/UserPaintCustomArguments]
g.setColour (fillColour);
g.fillRoundedRectangle (x, y, width, height, 20.000f);
g.setColour (strokeColour);
g.drawRoundedRectangle (x, y, width, height, 20.000f, 5.000f);
}
//[UserPaint] Add your own custom painting code here..
//[/UserPaint]
}
void UiUndoRedo::resized()
{
//[UserPreResize] Add your own custom resize code here..
//[/UserPreResize]
mButtonUndo->setBounds (proportionOfWidth (0.0391f), proportionOfHeight (0.2530f), proportionOfWidth (0.4104f), proportionOfHeight (0.5060f));
mButtonRedo->setBounds (proportionOfWidth (0.5570f), proportionOfHeight (0.2530f), proportionOfWidth (0.4104f), proportionOfHeight (0.5060f));
//[UserResized] Add your own custom resize handling here..
//[/UserResized]
}
//[MiscUserCode] You can add your own definitions of your custom methods or any other code here...
void UiUndoRedo::timerCallback()
{
mButtonUndo->setEnabled(mUndoManager.canUndo());
mButtonRedo->setEnabled(mUndoManager.canRedo());
}
//[/MiscUserCode]
//==============================================================================
#if 0
/* -- Projucer information section --
This is where the Projucer stores the metadata that describe this GUI layout, so
make changes in here at your peril!
BEGIN_JUCER_METADATA
<JUCER_COMPONENT documentType="Component" className="UiUndoRedo" componentName="UiUndoRedo"
parentClasses="public Component, public Timer" constructorParams="Component* parent, Core& core"
variableInitialisers="mParent{parent}, mUndoManager{core.getUndoManager()}"
snapPixels="8" snapActive="1" snapShown="1" overlayOpacity="0.330"
fixedSize="0" initialWidth="600" initialHeight="400">
<BACKGROUND backgroundColour="0">
<ROUNDRECT pos="0 0 100% 100%" cornerSize="20.0" fill="solid: ffffff00"
hasStroke="1" stroke="5, mitered, butt" strokeColour="solid: ff000000"/>
</BACKGROUND>
<TEXTBUTTON name="ButtonUndo" id="2905daae1318e8f9" memberName="mButtonUndo"
virtualName="" explicitFocusOrder="0" pos="3.867% 25.397% 40.884% 50.794%"
bgColOn="ffa45c94" buttonText="Undo" connectedEdges="0" needsCallback="0"
radioGroupId="0"/>
<TEXTBUTTON name="ButtonRedo" id="f80fc073aaa0b332" memberName="mButtonRedo"
virtualName="" explicitFocusOrder="0" pos="55.801% 25.397% 40.884% 50.794%"
bgColOn="ffa45c94" buttonText="Redo" connectedEdges="0" needsCallback="0"
radioGroupId="0"/>
</JUCER_COMPONENT>
END_JUCER_METADATA
*/
#endif
//[EndFile] You can add extra defines here...
//[/EndFile]
| 5,640 | 2,003 |
/*****************************************************************************************************************************
* Copyright 2020 Gabriel Gheorghe. All rights reserved.
* This code is licensed under the BSD 3-Clause "New" or "Revised" License
* License url: https://github.com/GabyForceQ/PolluxEngine/blob/master/LICENSE
*****************************************************************************************************************************/
#pragma once
#include "../../ASTNodeBase.hpp"
namespace Pollux::Lang
{
class ASTNodeIfStatement final : public ASTNodeBase
{
public:
ASTNodeIfStatement() noexcept;
void Accept(IASTNodeVisitor* pVisitor) override;
ASTNodeExpression* pExpression = nullptr;
ASTNodeScope* pIfScope = nullptr;
ASTNodeScope* pElseScope = nullptr;
bool bHasElseScope = false;
bool bComptimeEval = false;
AST_FRIENDS_BODY
};
} | 904 | 272 |
#include "Project.h"
#include <iostream>
static void printMat(const Eigen::Matrix4d& mat)
{
std::cout<<" matrix:"<<std::endl;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
std::cout<< mat(j,i)<<" ";
std::cout<<std::endl;
}
}
Project::Project()
{
}
//Project::Project(float angle ,float relationWH, float near, float far) : Scene(angle,relationWH,near,far)
//{
//}
void Project::Init()
{
unsigned int texIDs[3] = { 0 , 1, 2};
unsigned int slots[3] = { 0 , 1, 2 };
AddShader("shaders/pickingShader");
AddShader("shaders/cubemapShader");
AddShader("shaders/basicShaderTex");
AddShader("shaders/basicShader");
AddTexture("textures/plane.png",2);
AddTexture("textures/cubemaps/Daylight Box_", 3);
AddTexture("textures/grass.bmp", 2);
//AddTexture("../res/textures/Cat_bump.jpg", 2);
AddMaterial(texIDs,slots, 1);
AddMaterial(texIDs+1, slots+1, 1);
AddMaterial(texIDs + 2, slots + 2, 1);
AddShape(Cube, -2, TRIANGLES);
AddShape(zCylinder, -1, TRIANGLES);
AddShape(zCylinder, 1, TRIANGLES);
AddShape(zCylinder, 2, TRIANGLES);
AddShape(Axis, -1, LINES);
//AddShapeFromFile("../res/objs/Cat_v1.obj", -1, TRIANGLES);
SetShapeShader(1, 2);
SetShapeShader(2, 2);
SetShapeShader(3, 2);
SetShapeShader(4, 2);
SetShapeMaterial(1, 0);
SetShapeMaterial(2, 0);
SetShapeMaterial(3, 0);
SetShapeMaterial(4, 0);
SetShapeMaterial(0, 1);
selected_data_index = 0;
float cylinderLen = 1.6f;
float s = 60;
ShapeTransformation(scaleAll, s,0);
selected_data_index = 1;
data()->SetCenterOfRotation(Eigen::Vector3d(0, 0, -cylinderLen / 2.0));
ShapeTransformation(zTranslate, cylinderLen / 2.0, 1);
selected_data_index = 2;
ShapeTransformation(zTranslate, cylinderLen , 1);
data()->SetCenterOfRotation(Eigen::Vector3d(0, 0, -cylinderLen / 2.0));
selected_data_index = 3;
ShapeTransformation(zTranslate, cylinderLen, 1);
data()->SetCenterOfRotation(Eigen::Vector3d(0, 0, -cylinderLen / 2.0));
selected_data_index = 0;
SetShapeStatic(0);
//SetShapeViewport(6, 1);
// ReadPixel(); //uncomment when you are reading from the z-buffer
}
void Project::Update(const Eigen::Matrix4f& Proj, const Eigen::Matrix4f& View, const Eigen::Matrix4f& Model, unsigned int shaderIndx, unsigned int shapeIndx)
{
Shader *s = shaders[shaderIndx];
int r = ((shapeIndx+1) & 0x000000FF) >> 0;
int g = ((shapeIndx+1) & 0x0000FF00) >> 8;
int b = ((shapeIndx+1) & 0x00FF0000) >> 16;
s->Bind();
s->SetUniformMat4f("Proj", Proj);
s->SetUniformMat4f("View", View);
s->SetUniformMat4f("Model", Model);
if (data_list[shapeIndx]->GetMaterial() >= 0 && !materials.empty())
{
// materials[shapes[pickedShape]->GetMaterial()]->Bind(textures);
BindMaterial(s, data_list[shapeIndx]->GetMaterial());
}
if (shaderIndx == 0)
s->SetUniform4f("lightColor", r / 255.0f, g / 255.0f, b / 255.0f, 0.0f);
else
s->SetUniform4f("lightColor", 4/100.0f, 60 / 100.0f, 99 / 100.0f, 0.5f);
//textures[0]->Bind(0);
//s->SetUniform1i("sampler2", materials[shapes[pickedShape]->GetMaterial()]->GetSlot(1));
//s->SetUniform4f("lightDirection", 0.0f , 0.0f, -1.0f, 0.0f);
// if(shaderIndx == 0)
// s->SetUniform4f("lightColor",r/255.0f, g/255.0f, b/255.0f,1.0f);
// else
// s->SetUniform4f("lightColor",0.7f,0.8f,0.1f,1.0f);
s->Unbind();
}
void Project::WhenRotate()
{
}
void Project::WhenTranslate()
{
}
void Project::Animate() {
if(isActive)
{
if(selected_data_index > 0 )
data()->MyRotate(Eigen::Vector3d(0, 1, 0), 0.01);
}
}
void Project::ScaleAllShapes(float amt,int viewportIndx)
{
for (int i = 1; i < data_list.size(); i++)
{
if (data_list[i]->Is2Render(viewportIndx))
{
data_list[i]->MyScale(Eigen::Vector3d(amt, amt, amt));
}
}
}
Project::~Project(void)
{
}
| 3,752 | 1,748 |
// Copyright 2013 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/dbus/fake_shill_profile_client.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "base/stl_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/shill_property_changed_observer.h"
#include "chromeos/dbus/shill_service_client.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_path.h"
#include "dbus/values_util.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
namespace chromeos {
struct FakeShillProfileClient::ProfileProperties {
base::DictionaryValue entries; // Dictionary of Service Dictionaries
base::DictionaryValue properties; // Dictionary of Profile properties
};
namespace {
void PassDictionary(
const ShillProfileClient::DictionaryValueCallbackWithoutStatus& callback,
const base::DictionaryValue* dictionary) {
callback.Run(*dictionary);
}
} // namespace
FakeShillProfileClient::FakeShillProfileClient() {
}
FakeShillProfileClient::~FakeShillProfileClient() {
STLDeleteValues(&profiles_);
}
void FakeShillProfileClient::Init(dbus::Bus* bus) {
}
void FakeShillProfileClient::AddPropertyChangedObserver(
const dbus::ObjectPath& profile_path,
ShillPropertyChangedObserver* observer) {
}
void FakeShillProfileClient::RemovePropertyChangedObserver(
const dbus::ObjectPath& profile_path,
ShillPropertyChangedObserver* observer) {
}
void FakeShillProfileClient::GetProperties(
const dbus::ObjectPath& profile_path,
const DictionaryValueCallbackWithoutStatus& callback,
const ErrorCallback& error_callback) {
ProfileProperties* profile = GetProfile(profile_path, error_callback);
if (!profile)
return;
std::unique_ptr<base::DictionaryValue> properties(
profile->properties.DeepCopy());
base::ListValue* entry_paths = new base::ListValue;
properties->SetWithoutPathExpansion(shill::kEntriesProperty, entry_paths);
for (base::DictionaryValue::Iterator it(profile->entries); !it.IsAtEnd();
it.Advance()) {
entry_paths->AppendString(it.key());
}
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&PassDictionary, callback, base::Owned(properties.release())));
}
void FakeShillProfileClient::GetEntry(
const dbus::ObjectPath& profile_path,
const std::string& entry_path,
const DictionaryValueCallbackWithoutStatus& callback,
const ErrorCallback& error_callback) {
ProfileProperties* profile = GetProfile(profile_path, error_callback);
if (!profile)
return;
base::DictionaryValue* entry = NULL;
profile->entries.GetDictionaryWithoutPathExpansion(entry_path, &entry);
if (!entry) {
error_callback.Run("Error.InvalidProfileEntry", "Invalid profile entry");
return;
}
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::Bind(&PassDictionary, callback, base::Owned(entry->DeepCopy())));
}
void FakeShillProfileClient::DeleteEntry(const dbus::ObjectPath& profile_path,
const std::string& entry_path,
const base::Closure& callback,
const ErrorCallback& error_callback) {
ProfileProperties* profile = GetProfile(profile_path, error_callback);
if (!profile)
return;
if (!profile->entries.RemoveWithoutPathExpansion(entry_path, NULL)) {
error_callback.Run("Error.InvalidProfileEntry", entry_path);
return;
}
base::StringValue profile_path_value("");
DBusThreadManager::Get()->GetShillServiceClient()->GetTestInterface()->
SetServiceProperty(entry_path,
shill::kProfileProperty,
profile_path_value);
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback);
}
ShillProfileClient::TestInterface* FakeShillProfileClient::GetTestInterface() {
return this;
}
void FakeShillProfileClient::AddProfile(const std::string& profile_path,
const std::string& userhash) {
if (GetProfile(dbus::ObjectPath(profile_path), ErrorCallback()))
return;
ProfileProperties* profile = new ProfileProperties;
profile->properties.SetStringWithoutPathExpansion(shill::kUserHashProperty,
userhash);
profiles_[profile_path] = profile;
DBusThreadManager::Get()->GetShillManagerClient()->GetTestInterface()->
AddProfile(profile_path);
}
void FakeShillProfileClient::AddEntry(const std::string& profile_path,
const std::string& entry_path,
const base::DictionaryValue& properties) {
ProfileProperties* profile = GetProfile(dbus::ObjectPath(profile_path),
ErrorCallback());
DCHECK(profile);
profile->entries.SetWithoutPathExpansion(entry_path, properties.DeepCopy());
DBusThreadManager::Get()->GetShillManagerClient()->GetTestInterface()->
AddManagerService(entry_path, true);
}
bool FakeShillProfileClient::AddService(const std::string& profile_path,
const std::string& service_path) {
ProfileProperties* profile = GetProfile(dbus::ObjectPath(profile_path),
ErrorCallback());
if (!profile) {
LOG(ERROR) << "AddService: No matching profile: " << profile_path
<< " for: " << service_path;
return false;
}
if (profile->entries.HasKey(service_path))
return false;
return AddOrUpdateServiceImpl(profile_path, service_path, profile);
}
bool FakeShillProfileClient::UpdateService(const std::string& profile_path,
const std::string& service_path) {
ProfileProperties* profile = GetProfile(dbus::ObjectPath(profile_path),
ErrorCallback());
if (!profile) {
LOG(ERROR) << "UpdateService: No matching profile: " << profile_path
<< " for: " << service_path;
return false;
}
if (!profile->entries.HasKey(service_path)) {
LOG(ERROR) << "UpdateService: Profile: " << profile_path
<< " does not contain Service: " << service_path;
return false;
}
return AddOrUpdateServiceImpl(profile_path, service_path, profile);
}
bool FakeShillProfileClient::AddOrUpdateServiceImpl(
const std::string& profile_path,
const std::string& service_path,
ProfileProperties* profile) {
ShillServiceClient::TestInterface* service_test =
DBusThreadManager::Get()->GetShillServiceClient()->GetTestInterface();
const base::DictionaryValue* service_properties =
service_test->GetServiceProperties(service_path);
if (!service_properties) {
LOG(ERROR) << "No matching service: " << service_path;
return false;
}
std::string service_profile_path;
service_properties->GetStringWithoutPathExpansion(shill::kProfileProperty,
&service_profile_path);
if (service_profile_path.empty()) {
base::StringValue profile_path_value(profile_path);
service_test->SetServiceProperty(service_path,
shill::kProfileProperty,
profile_path_value);
} else if (service_profile_path != profile_path) {
LOG(ERROR) << "Service has non matching profile path: "
<< service_profile_path;
return false;
}
profile->entries.SetWithoutPathExpansion(service_path,
service_properties->DeepCopy());
return true;
}
void FakeShillProfileClient::GetProfilePaths(
std::vector<std::string>* profiles) {
for (ProfileMap::iterator iter = profiles_.begin();
iter != profiles_.end(); ++iter) {
profiles->push_back(iter->first);
}
}
bool FakeShillProfileClient::GetService(const std::string& service_path,
std::string* profile_path,
base::DictionaryValue* properties) {
properties->Clear();
for (ProfileMap::const_iterator iter = profiles_.begin();
iter != profiles_.end(); ++iter) {
const ProfileProperties* profile = iter->second;
const base::DictionaryValue* entry;
if (!profile->entries.GetDictionaryWithoutPathExpansion(
service_path, &entry)) {
continue;
}
*profile_path = iter->first;
properties->MergeDictionary(entry);
return true;
}
return false;
}
void FakeShillProfileClient::ClearProfiles() {
STLDeleteValues(&profiles_);
}
FakeShillProfileClient::ProfileProperties* FakeShillProfileClient::GetProfile(
const dbus::ObjectPath& profile_path,
const ErrorCallback& error_callback) {
ProfileMap::const_iterator found = profiles_.find(profile_path.value());
if (found == profiles_.end()) {
if (!error_callback.is_null())
error_callback.Run("Error.InvalidProfile", "Invalid profile");
return NULL;
}
return found->second;
}
} // namespace chromeos
| 9,323 | 2,604 |
#include "../include/pe19.h"
#include <cstdlib>
#include <iostream>
int pe19(int argc, char **argv)
{
using namespace std;
uint32_t n = 2000;
if (argc > 1) {
char *end;
n = strtoul(argv[1], &end, 10);
}
cout << "n = " << n << endl;
cout << pe::pe19(n) << endl;
return 0;
}
| 300 | 145 |
// Copyright 2018 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.
#ifndef V8_INTL_SUPPORT
#error Internationalization is expected to be enabled.
#endif // V8_INTL_SUPPORT
#include "src/objects/js-list-format.h"
#include <memory>
#include <vector>
#include "src/elements.h"
#include "src/heap/factory.h"
#include "src/isolate.h"
#include "src/objects-inl.h"
#include "src/objects/intl-objects.h"
#include "src/objects/js-array-inl.h"
#include "src/objects/js-list-format-inl.h"
#include "src/objects/managed.h"
#include "unicode/listformatter.h"
namespace v8 {
namespace internal {
namespace {
const char* kStandard = "standard";
const char* kOr = "or";
const char* kUnit = "unit";
const char* kStandardShort = "standard-short";
const char* kUnitShort = "unit-short";
const char* kUnitNarrow = "unit-narrow";
const char* GetIcuStyleString(JSListFormat::Style style,
JSListFormat::Type type) {
switch (type) {
case JSListFormat::Type::CONJUNCTION:
switch (style) {
case JSListFormat::Style::LONG:
return kStandard;
case JSListFormat::Style::SHORT:
return kStandardShort;
case JSListFormat::Style::NARROW:
// Currently, ListFormat::createInstance on "standard-narrow" will
// fail so we use "standard-short" here.
// See https://unicode.org/cldr/trac/ticket/11254
// TODO(ftang): change to return kStandardNarrow; after the above
// issue fixed in CLDR/ICU.
// CLDR bug: https://unicode.org/cldr/trac/ticket/11254
// ICU bug: https://unicode-org.atlassian.net/browse/ICU-20014
return kStandardShort;
case JSListFormat::Style::COUNT:
UNREACHABLE();
}
case JSListFormat::Type::DISJUNCTION:
switch (style) {
// Currently, ListFormat::createInstance on "or-short" and "or-narrow"
// will fail so we use "or" here.
// See https://unicode.org/cldr/trac/ticket/11254
// TODO(ftang): change to return kOr, kOrShort or kOrNarrow depend on
// style after the above issue fixed in CLDR/ICU.
// CLDR bug: https://unicode.org/cldr/trac/ticket/11254
// ICU bug: https://unicode-org.atlassian.net/browse/ICU-20014
case JSListFormat::Style::LONG:
case JSListFormat::Style::SHORT:
case JSListFormat::Style::NARROW:
return kOr;
case JSListFormat::Style::COUNT:
UNREACHABLE();
}
case JSListFormat::Type::UNIT:
switch (style) {
case JSListFormat::Style::LONG:
return kUnit;
case JSListFormat::Style::SHORT:
return kUnitShort;
case JSListFormat::Style::NARROW:
return kUnitNarrow;
case JSListFormat::Style::COUNT:
UNREACHABLE();
}
case JSListFormat::Type::COUNT:
UNREACHABLE();
}
}
} // namespace
JSListFormat::Style get_style(const char* str) {
switch (str[0]) {
case 'n':
if (strcmp(&str[1], "arrow") == 0) return JSListFormat::Style::NARROW;
break;
case 'l':
if (strcmp(&str[1], "ong") == 0) return JSListFormat::Style::LONG;
break;
case 's':
if (strcmp(&str[1], "hort") == 0) return JSListFormat::Style::SHORT;
break;
}
UNREACHABLE();
}
JSListFormat::Type get_type(const char* str) {
switch (str[0]) {
case 'c':
if (strcmp(&str[1], "onjunction") == 0)
return JSListFormat::Type::CONJUNCTION;
break;
case 'd':
if (strcmp(&str[1], "isjunction") == 0)
return JSListFormat::Type::DISJUNCTION;
break;
case 'u':
if (strcmp(&str[1], "nit") == 0) return JSListFormat::Type::UNIT;
break;
}
UNREACHABLE();
}
MaybeHandle<JSListFormat> JSListFormat::InitializeListFormat(
Isolate* isolate, Handle<JSListFormat> list_format_holder,
Handle<Object> input_locales, Handle<Object> input_options) {
Factory* factory = isolate->factory();
list_format_holder->set_flags(0);
Handle<JSReceiver> options;
// 2. If options is undefined, then
if (input_options->IsUndefined(isolate)) {
// a. Let options be ObjectCreate(null).
options = isolate->factory()->NewJSObjectWithNullProto();
// 3. Else
} else {
// a. Let options be ? ToObject(options).
ASSIGN_RETURN_ON_EXCEPTION(isolate, options,
Object::ToObject(isolate, input_options),
JSListFormat);
}
// 5. Let t be GetOption(options, "type", "string", «"conjunction",
// "disjunction", "unit"», "conjunction").
std::unique_ptr<char[]> type_str = nullptr;
std::vector<const char*> type_values = {"conjunction", "disjunction", "unit"};
Maybe<bool> maybe_found_type = Intl::GetStringOption(
isolate, options, "type", type_values, "Intl.ListFormat", &type_str);
Type type_enum = Type::CONJUNCTION;
MAYBE_RETURN(maybe_found_type, MaybeHandle<JSListFormat>());
if (maybe_found_type.FromJust()) {
DCHECK_NOT_NULL(type_str.get());
type_enum = get_type(type_str.get());
}
// 6. Set listFormat.[[Type]] to t.
list_format_holder->set_type(type_enum);
// 7. Let s be ? GetOption(options, "style", "string",
// «"long", "short", "narrow"», "long").
std::unique_ptr<char[]> style_str = nullptr;
std::vector<const char*> style_values = {"long", "short", "narrow"};
Maybe<bool> maybe_found_style = Intl::GetStringOption(
isolate, options, "style", style_values, "Intl.ListFormat", &style_str);
Style style_enum = Style::LONG;
MAYBE_RETURN(maybe_found_style, MaybeHandle<JSListFormat>());
if (maybe_found_style.FromJust()) {
DCHECK_NOT_NULL(style_str.get());
style_enum = get_style(style_str.get());
}
// 15. Set listFormat.[[Style]] to s.
list_format_holder->set_style(style_enum);
// 10. Let r be ResolveLocale(%ListFormat%.[[AvailableLocales]],
// requestedLocales, opt, undefined, localeData).
Handle<JSObject> r;
ASSIGN_RETURN_ON_EXCEPTION(
isolate, r,
Intl::ResolveLocale(isolate, "listformat", input_locales, options),
JSListFormat);
Handle<Object> locale_obj =
JSObject::GetDataProperty(r, factory->locale_string());
Handle<String> locale;
ASSIGN_RETURN_ON_EXCEPTION(
isolate, locale, Object::ToString(isolate, locale_obj), JSListFormat);
// 18. Set listFormat.[[Locale]] to the value of r.[[Locale]].
list_format_holder->set_locale(*locale);
std::unique_ptr<char[]> locale_name = locale->ToCString();
icu::Locale icu_locale(locale_name.get());
UErrorCode status = U_ZERO_ERROR;
icu::ListFormatter* formatter = icu::ListFormatter::createInstance(
icu_locale, GetIcuStyleString(style_enum, type_enum), status);
if (U_FAILURE(status)) {
delete formatter;
FATAL("Failed to create ICU list formatter, are ICU data files missing?");
}
CHECK_NOT_NULL(formatter);
Handle<Managed<icu::ListFormatter>> managed_formatter =
Managed<icu::ListFormatter>::FromRawPtr(isolate, 0, formatter);
list_format_holder->set_formatter(*managed_formatter);
return list_format_holder;
}
Handle<JSObject> JSListFormat::ResolvedOptions(
Isolate* isolate, Handle<JSListFormat> format_holder) {
Factory* factory = isolate->factory();
Handle<JSObject> result = factory->NewJSObject(isolate->object_function());
Handle<String> locale(format_holder->locale(), isolate);
JSObject::AddProperty(isolate, result, factory->locale_string(), locale,
NONE);
JSObject::AddProperty(isolate, result, factory->style_string(),
format_holder->StyleAsString(), NONE);
JSObject::AddProperty(isolate, result, factory->type_string(),
format_holder->TypeAsString(), NONE);
return result;
}
icu::ListFormatter* JSListFormat::UnpackFormatter(Isolate* isolate,
Handle<JSListFormat> holder) {
return Managed<icu::ListFormatter>::cast(holder->formatter())->raw();
}
Handle<String> JSListFormat::StyleAsString() const {
switch (style()) {
case Style::LONG:
return GetReadOnlyRoots().long_string_handle();
case Style::SHORT:
return GetReadOnlyRoots().short_string_handle();
case Style::NARROW:
return GetReadOnlyRoots().narrow_string_handle();
case Style::COUNT:
UNREACHABLE();
}
}
Handle<String> JSListFormat::TypeAsString() const {
switch (type()) {
case Type::CONJUNCTION:
return GetReadOnlyRoots().conjunction_string_handle();
case Type::DISJUNCTION:
return GetReadOnlyRoots().disjunction_string_handle();
case Type::UNIT:
return GetReadOnlyRoots().unit_string_handle();
case Type::COUNT:
UNREACHABLE();
}
}
namespace {
// TODO(ftang) remove the following hack after icu::ListFormat support
// FieldPosition.
// This is a temporary workaround until icu::ListFormat support FieldPosition
// It is inefficient and won't work correctly on the edge case that the input
// contains fraction of the list pattern.
// For example the following under English will mark the "an" incorrectly
// since the formatted is "a, b, and an".
// listFormat.formatToParts(["a", "b", "an"])
// https://ssl.icu-project.org/trac/ticket/13754
MaybeHandle<JSArray> GenerateListFormatParts(
Isolate* isolate, const icu::UnicodeString& formatted,
const icu::UnicodeString items[], int length) {
Factory* factory = isolate->factory();
int estimate_size = length * 2 + 1;
Handle<JSArray> array = factory->NewJSArray(estimate_size);
int index = 0;
int last_pos = 0;
for (int i = 0; i < length; i++) {
int found = formatted.indexOf(items[i], last_pos);
DCHECK_GE(found, 0);
if (found > last_pos) {
Handle<String> substring;
ASSIGN_RETURN_ON_EXCEPTION(
isolate, substring,
Intl::ToString(isolate, formatted, last_pos, found), JSArray);
Intl::AddElement(isolate, array, index++, factory->literal_string(),
substring);
}
last_pos = found + items[i].length();
Handle<String> substring;
ASSIGN_RETURN_ON_EXCEPTION(
isolate, substring, Intl::ToString(isolate, formatted, found, last_pos),
JSArray);
Intl::AddElement(isolate, array, index++, factory->element_string(),
substring);
}
if (last_pos < formatted.length()) {
Handle<String> substring;
ASSIGN_RETURN_ON_EXCEPTION(
isolate, substring,
Intl::ToString(isolate, formatted, last_pos, formatted.length()),
JSArray);
Intl::AddElement(isolate, array, index++, factory->literal_string(),
substring);
}
return array;
}
// Extract String from JSArray into array of UnicodeString
Maybe<bool> ToUnicodeStringArray(Isolate* isolate, Handle<JSArray> array,
icu::UnicodeString items[], uint32_t length) {
Factory* factory = isolate->factory();
// In general, ElementsAccessor::Get actually isn't guaranteed to give us the
// elements in order. But given that it was created by a builtin we control,
// it shouldn't be possible for it to be problematic. Add DCHECK to ensure
// that.
DCHECK(array->HasFastPackedElements());
auto* accessor = array->GetElementsAccessor();
DCHECK(length == accessor->NumberOfElements(*array));
// ecma402 #sec-createpartsfromlist
// 2. If list contains any element value such that Type(value) is not String,
// throw a TypeError exception.
//
// Per spec it looks like we're supposed to throw a TypeError exception if the
// item isn't already a string, rather than coercing to a string. Moreover,
// the way the spec's written it looks like we're supposed to run through the
// whole list to check that they're all strings before going further.
for (uint32_t i = 0; i < length; i++) {
Handle<Object> item = accessor->Get(array, i);
DCHECK(!item.is_null());
if (!item->IsString()) {
THROW_NEW_ERROR_RETURN_VALUE(
isolate,
NewTypeError(MessageTemplate::kArrayItemNotType,
factory->NewStringFromStaticChars("list"),
factory->NewNumber(i),
factory->NewStringFromStaticChars("String")),
Nothing<bool>());
}
}
for (uint32_t i = 0; i < length; i++) {
Handle<String> string = Handle<String>::cast(accessor->Get(array, i));
DisallowHeapAllocation no_gc;
string = String::Flatten(isolate, string);
std::unique_ptr<uc16[]> sap;
items[i] =
icu::UnicodeString(GetUCharBufferFromFlat(string->GetFlatContent(),
&sap, string->length()),
string->length());
}
return Just(true);
}
} // namespace
Maybe<bool> FormatListCommon(Isolate* isolate,
Handle<JSListFormat> format_holder,
Handle<JSArray> list,
icu::UnicodeString& formatted, uint32_t* length,
std::unique_ptr<icu::UnicodeString[]>& array) {
DCHECK(!list->IsUndefined());
icu::ListFormatter* formatter =
JSListFormat::UnpackFormatter(isolate, format_holder);
CHECK_NOT_NULL(formatter);
*length = list->GetElementsAccessor()->NumberOfElements(*list);
array.reset(new icu::UnicodeString[*length]);
// ecma402 #sec-createpartsfromlist
// 2. If list contains any element value such that Type(value) is not String,
// throw a TypeError exception.
MAYBE_RETURN(ToUnicodeStringArray(isolate, list, array.get(), *length),
Nothing<bool>());
UErrorCode status = U_ZERO_ERROR;
formatter->format(array.get(), *length, formatted, status);
DCHECK(U_SUCCESS(status));
return Just(true);
}
// ecma402 #sec-formatlist
MaybeHandle<String> JSListFormat::FormatList(Isolate* isolate,
Handle<JSListFormat> format_holder,
Handle<JSArray> list) {
icu::UnicodeString formatted;
uint32_t length;
std::unique_ptr<icu::UnicodeString[]> array;
MAYBE_RETURN(
FormatListCommon(isolate, format_holder, list, formatted, &length, array),
Handle<String>());
return Intl::ToString(isolate, formatted);
}
// ecma42 #sec-formatlisttoparts
MaybeHandle<JSArray> JSListFormat::FormatListToParts(
Isolate* isolate, Handle<JSListFormat> format_holder,
Handle<JSArray> list) {
icu::UnicodeString formatted;
uint32_t length;
std::unique_ptr<icu::UnicodeString[]> array;
MAYBE_RETURN(
FormatListCommon(isolate, format_holder, list, formatted, &length, array),
Handle<JSArray>());
return GenerateListFormatParts(isolate, formatted, array.get(), length);
}
} // namespace internal
} // namespace v8
| 14,891 | 4,793 |
// mfcplotDoc.cpp: CmfcplotDoc 类的实现
//
#include "pch.h"
#include "framework.h"
// SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的
// ATL 项目中进行定义,并允许与该项目共享文档代码。
#ifndef SHARED_HANDLERS
#include "mfcplot.h"
#endif
#include "mfcplotDoc.h"
#include <utility>
#include <propkey.h>
#include "CFuncDlg.h"
#include "CNormalFuncDlg.h"
#include "CPolarFuncDlg.h"
#include "CSetXYrangeDlg.h"
#include "CTwoFuncDlg.h"
#include "CDataFuncDlg.h"
#include "CDelFuncDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CmfcplotDoc
IMPLEMENT_DYNCREATE(CmfcplotDoc, CDocument)
BEGIN_MESSAGE_MAP(CmfcplotDoc, CDocument)
ON_COMMAND(ID_AXIS_MENU, &CmfcplotDoc::OnAxisMenu)
ON_COMMAND(ID_GRID_MENU, &CmfcplotDoc::OnGridMenu)
ON_COMMAND(ID_SMALLER_MENU, &CmfcplotDoc::OnSmallerMenu)
ON_COMMAND(ID_BIGGER_MENU, &CmfcplotDoc::OnBiggerMenu)
ON_COMMAND(ID_NORMAL_FUNC_MENU, &CmfcplotDoc::OnNormalFuncMenu)
ON_UPDATE_COMMAND_UI(ID_EDGE_MENU, &CmfcplotDoc::OnUpdateEdgeMenu)
ON_COMMAND(ID_EDGE_MENU, &CmfcplotDoc::OnEdgeMenu)
ON_COMMAND(ID_Menu_SET_XYRANGE, &CmfcplotDoc::OnMenuSetXyrange)
ON_COMMAND(ID_FUNC_MODE, &CmfcplotDoc::OnFuncMode)
ON_UPDATE_COMMAND_UI(ID_FUNC_MODE, &CmfcplotDoc::OnUpdateFuncMode)
ON_UPDATE_COMMAND_UI(ID_AXIS_MENU, &CmfcplotDoc::OnUpdateAxisMenu)
ON_UPDATE_COMMAND_UI(ID_GRID_MENU, &CmfcplotDoc::OnUpdateGridMenu)
ON_COMMAND(ID_POLAR_FUNC_MENU, &CmfcplotDoc::OnPolarFuncMenu)
ON_COMMAND(ID_TWO_FUNC_MENU, &CmfcplotDoc::OnTwoFuncMenu)
ON_COMMAND(ID_DATA_FUNC_MENU, &CmfcplotDoc::OnDataFuncMenu)
ON_COMMAND(ID_FROCE_XRANG, &CmfcplotDoc::OnFroceXrang)
ON_UPDATE_COMMAND_UI(ID_FROCE_XRANG, &CmfcplotDoc::OnUpdateFroceXrang)
ON_COMMAND(ID_DELALL_MENU, &CmfcplotDoc::OnDelallMenu)
ON_COMMAND(ID_NEARPOINT_MENU, &CmfcplotDoc::OnNearpointMenu)
ON_UPDATE_COMMAND_UI(ID_NEARPOINT_MENU, &CmfcplotDoc::OnUpdateNearpointMenu)
ON_COMMAND(ID_AUTORANGE_MENU, &CmfcplotDoc::OnAutorangeMenu)
ON_COMMAND(ID_DELFUNCONE_MENU, &CmfcplotDoc::OnDelfunconeMenu)
END_MESSAGE_MAP()
// CmfcplotDoc 构造/析构
CmfcplotDoc::CmfcplotDoc() noexcept
{
// TODO: 在此添加一次性构造代码
m_WillShowGrid = true;
m_WillShowAxis = true;
m_WillShowEdge = true;
m_SingelMode = true;
m_ForceXrange = false;
m_ShowNearPoint = false;
m_Xmin = -10;
m_Xmax = 10;
m_Ymin = -1;
m_Ymax = 1;
m_FD = nullptr;
}
CmfcplotDoc::~CmfcplotDoc()
{
}
BOOL CmfcplotDoc::OnNewDocument()
{
if (!CDocument::OnNewDocument())
return FALSE;
// TODO: 在此添加重新初始化代码
// (SDI 文档将重用该文档)
return TRUE;
}
// CmfcplotDoc 序列化
void CmfcplotDoc::Serialize(CArchive& ar)
{
m_List.Serialize(ar);
if (ar.IsStoring())
{
// TODO: 在此添加存储代码
ar << m_WillShowGrid << m_WillShowAxis << m_WillShowEdge << m_SingelMode << m_ForceXrange << m_ShowNearPoint \
<< m_Xmin << m_Xmax << m_Ymin << m_Ymax;
}
else
{
// TODO: 在此添加加载代码
ar >> m_WillShowGrid >> m_WillShowAxis >> m_WillShowEdge >> m_SingelMode >> m_ForceXrange >> m_ShowNearPoint \
>> m_Xmin >> m_Xmax >> m_Ymin >> m_Ymax;
}
}
#ifdef SHARED_HANDLERS
// 缩略图的支持
void CmfcplotDoc::OnDrawThumbnail(CDC& dc, LPRECT lprcBounds)
{
// 修改此代码以绘制文档数据
dc.FillSolidRect(lprcBounds, RGB(255, 255, 255));
CString strText = _T("TODO: implement thumbnail drawing here");
LOGFONT lf;
CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT));
pDefaultGUIFont->GetLogFont(&lf);
lf.lfHeight = 36;
CFont fontDraw;
fontDraw.CreateFontIndirect(&lf);
CFont* pOldFont = dc.SelectObject(&fontDraw);
dc.DrawText(strText, lprcBounds, DT_CENTER | DT_WORDBREAK);
dc.SelectObject(pOldFont);
}
// 搜索处理程序的支持
void CmfcplotDoc::InitializeSearchContent()
{
CString strSearchContent;
// 从文档数据设置搜索内容。
// 内容部分应由“;”分隔
// 例如: strSearchContent = _T("point;rectangle;circle;ole object;");
SetSearchContent(strSearchContent);
}
void CmfcplotDoc::SetSearchContent(const CString& value)
{
if (value.IsEmpty())
{
RemoveChunk(PKEY_Search_Contents.fmtid, PKEY_Search_Contents.pid);
}
else
{
CMFCFilterChunkValueImpl *pChunk = nullptr;
ATLTRY(pChunk = new CMFCFilterChunkValueImpl);
if (pChunk != nullptr)
{
pChunk->SetTextValue(PKEY_Search_Contents, value, CHUNK_TEXT);
SetChunkValue(pChunk);
}
}
}
#endif // SHARED_HANDLERS
// CmfcplotDoc 诊断
#ifdef _DEBUG
void CmfcplotDoc::AssertValid() const
{
CDocument::AssertValid();
}
void CmfcplotDoc::Dump(CDumpContext& dc) const
{
CDocument::Dump(dc);
}
#endif //_DEBUG
// CmfcplotDoc 命令
void CmfcplotDoc::OnAxisMenu()
{
// TODO: 在此添加命令处理程序代码
m_WillShowAxis = !m_WillShowAxis;
this->UpdateAllViews(NULL);
}
void CmfcplotDoc::OnGridMenu()
{
// TODO: 在此添加命令处理程序代码
m_WillShowGrid = !m_WillShowGrid;
this->UpdateAllViews(NULL);
}
void CmfcplotDoc::OnSmallerMenu()
{
// TODO: 在此添加命令处理程序代码
double detx = (m_Xmax - m_Xmin) * 0.125;
m_Xmax += detx;
m_Xmin -= detx;
double dety = (m_Ymax - m_Ymin) * 0.125;
m_Ymax += dety;
m_Ymin -= dety;
UpdateAllViews(NULL);
}
void CmfcplotDoc::OnBiggerMenu()
{
// TODO: 在此添加命令处理程序代码
double detx = (m_Xmax - m_Xmin) * 0.1;
m_Xmax -= detx;
m_Xmin += detx;
double dety = (m_Ymax - m_Ymin) * 0.1;
m_Ymax -= dety;
m_Ymin += dety;
UpdateAllViews(NULL);
}
void CmfcplotDoc::OnUpdateEdgeMenu(CCmdUI* pCmdUI)
{
// TODO: 在此添加命令更新用户界面处理程序代码
pCmdUI->SetCheck(m_WillShowEdge);
}
void CmfcplotDoc::OnEdgeMenu()
{
// TODO: 在此添加命令处理程序代码
m_WillShowEdge = !m_WillShowEdge;
UpdateAllViews(NULL);
}
void CmfcplotDoc::OnMenuSetXyrange()
{
// TODO: 在此添加命令处理程序代码
CSetXYrangeDlg dlg(m_Xmin, m_Xmax, m_Ymin, m_Ymax, nullptr);
if (dlg.DoModal()) {
if (dlg.m_Xmin >= dlg.m_Xmax || dlg.m_Ymin >= dlg.m_Ymax)
AfxMessageBox(_T("输入不合法!"));
else {
m_Xmin = dlg.m_Xmin;
m_Xmax = dlg.m_Xmax;
m_Ymin = dlg.m_Ymin;
m_Ymax = dlg.m_Ymax;
UpdateAllViews(NULL);
}
}
}
void CmfcplotDoc::OnFuncMode()
{
// TODO: 在此添加命令处理程序代码
m_SingelMode = !m_SingelMode;
if (m_SingelMode == true) {
this->OnDelallMenu();
}
}
void CmfcplotDoc::OnUpdateFuncMode(CCmdUI* pCmdUI)
{
// TODO: 在此添加命令更新用户界面处理程序代码
pCmdUI->SetCheck(m_SingelMode);
}
void CmfcplotDoc::OnUpdateAxisMenu(CCmdUI* pCmdUI)
{
// TODO: 在此添加命令更新用户界面处理程序代码
pCmdUI->SetCheck(m_WillShowAxis);
}
void CmfcplotDoc::OnUpdateGridMenu(CCmdUI* pCmdUI)
{
// TODO: 在此添加命令更新用户界面处理程序代码
pCmdUI->SetCheck(m_WillShowGrid);
}
void CmfcplotDoc::OnNormalFuncMenu()
{
// TODO: 在此添加命令处理程序代码
//CFuncDlg dlg;
CNormalFuncDlg dlg(m_Xmin, m_Xmax, nullptr);
//
if (dlg.DoModal() == IDOK)
{
if (m_SingelMode) {
if (m_FD) delete m_FD;
m_List.RemoveAll();
}
m_FD = new NormalFD(dlg.m_sEquation, dlg.m_Xmin, dlg.m_Xmax, dlg.m_stepX, dlg.m_color, dlg.m_penWidth, dlg.m_penType);
if (m_FD->CalcList() == false) {
AfxMessageBox(_T("请检查方程是否完整!"));
}
else {
if (m_FD->minY < m_Ymin) m_Ymin = m_FD->minY;
if (m_FD->maxY > m_Ymax) m_Ymax = m_FD->maxY;
m_List.AddTail(m_FD);
}
}
UpdateAllViews(NULL);
}
void CmfcplotDoc::OnPolarFuncMenu()
{
// TODO: 在此添加命令处理程序代码
CPolarFuncDlg dlg;
//
if (dlg.DoModal() == IDOK)
{
if (m_SingelMode) {
if (m_FD) delete m_FD;
m_List.RemoveAll();
}
m_FD = new PolarFD(dlg.m_sEquation, dlg.m_Thetamin, dlg.m_Thetamax, dlg.m_StepTheta, dlg.m_color, dlg.m_penWidth, dlg.m_penType);
if (m_FD->CalcList() == false) {
AfxMessageBox(_T("请检查方程是否完整!"));
}
else {
if (m_FD->minY < m_Ymin) m_Ymin = m_FD->minY;
if (m_FD->maxY > m_Ymax) m_Ymax = m_FD->maxY;
if (m_FD->minX < m_Xmin) m_Xmin = m_FD->minX;
if (m_FD->maxX > m_Xmax) m_Xmax = m_FD->maxX;
m_List.AddTail(m_FD);
}
}
UpdateAllViews(NULL);
}
void CmfcplotDoc::OnTwoFuncMenu()
{
// TODO: 在此添加命令处理程序代码
CTwoFuncDlg dlg;
if (dlg.DoModal() == IDOK)
{
if (m_SingelMode) {
if (m_FD) delete m_FD;
m_List.RemoveAll();
}
m_FD = new TwoFD(dlg.m_sEquationX, dlg.m_sEquationY, dlg.m_Tmin, dlg.m_Tmax, dlg.m_stepT, dlg.m_color, dlg.m_penWidth, dlg.m_penType);
if (m_FD->CalcList() == false) {
AfxMessageBox(_T("请检查方程是否完整!"));
}
else {
if (m_FD->minY < m_Ymin) m_Ymin = m_FD->minY;
if (m_FD->maxY > m_Ymax) m_Ymax = m_FD->maxY;
if (m_FD->minX < m_Xmin) m_Xmin = m_FD->minX;
if (m_FD->maxX > m_Xmax) m_Xmax = m_FD->maxX;
m_List.AddTail(m_FD);
}
}
UpdateAllViews(NULL);
}
void CmfcplotDoc::OnDataFuncMenu()
{
// TODO: 在此添加命令处理程序代码
CDataFuncDlg dlg;
if (dlg.DoModal()) {
if (m_SingelMode) {
if (m_FD) delete m_FD;
m_List.RemoveAll();
}
m_FD = new DataFD(dlg.vetX, dlg.vetY, dlg.m_color, dlg.m_penWidth, dlg.m_penType);
CString str;
if (m_FD->minY < m_Ymin) m_Ymin = m_FD->minY;
if (m_FD->maxY > m_Ymax) m_Ymax = m_FD->maxY;
if (m_FD->minX < m_Xmin) m_Xmin = m_FD->minX;
if (m_FD->maxX > m_Xmax) m_Xmax = m_FD->maxX;
m_List.AddTail(m_FD);
}
UpdateAllViews(NULL);
}
void CmfcplotDoc::OnFroceXrang()
{
// TODO: 在此添加命令处理程序代码
m_ForceXrange = !m_ForceXrange;
UpdateAllViews(NULL);
}
void CmfcplotDoc::OnUpdateFroceXrang(CCmdUI* pCmdUI)
{
// TODO: 在此添加命令更新用户界面处理程序代码
pCmdUI->SetCheck(m_ForceXrange);
}
void CmfcplotDoc::OnNearpointMenu()
{
// TODO: 在此添加命令处理程序代码
m_ShowNearPoint = !m_ShowNearPoint;
}
void CmfcplotDoc::OnUpdateNearpointMenu(CCmdUI* pCmdUI)
{
// TODO: 在此添加命令更新用户界面处理程序代码
pCmdUI->SetCheck(m_ShowNearPoint);
}
void CmfcplotDoc::OnDelallMenu()
{
// TODO: 在此添加命令处理程序代码
POSITION p = m_List.GetHeadPosition();
while (p != nullptr) {
FuncData* tmpFD = (FuncData*)m_List.GetNext(p);
delete tmpFD;
}
m_List.RemoveAll();
UpdateAllViews(NULL);
}
void CmfcplotDoc::OnAutorangeMenu()
{
// TODO: 在此添加命令处理程序代码
double miX = -10, maX = 10, miY = -1, maY = 1;
POSITION p = m_List.GetHeadPosition();
bool flag = true;
while (p) {
FuncData* tmpFD = (FuncData*)m_List.GetNext(p);
if (flag) {
miY = tmpFD->minY;
maY = tmpFD->maxY;
miX = tmpFD->minX;
maX = tmpFD->maxX;
flag = false;
}
else {
if (tmpFD->minY < miY) miY = tmpFD->minY;
if (tmpFD->maxY > maY) maY = tmpFD->maxY;
if (tmpFD->minX < miX) miX = tmpFD->minX;
if (tmpFD->maxX > maX) maX = tmpFD->maxX;
}
}
if (miX == maX) {
miX -= 0.5;
maX += 0.5;
}
if (miY == maY) {
miY += 0.5;
maY -= 0.5;
}
m_Xmin = miX;
m_Xmax = maX;
m_Ymin = miY;
m_Ymax = maY;
UpdateAllViews(NULL);
}
void CmfcplotDoc::OnDelfunconeMenu()
{
// TODO: 在此添加命令处理程序代码
int cnt = 0, id = 0;
CDelFuncDlg dlg;
if (dlg.DoModal()) {
id = dlg.m_id;
}
POSITION p = m_List.GetHeadPosition(),tmpp;
while (p) {
tmpp = p;
FuncData* tmpFD = (FuncData*)m_List.GetNext(p);
cnt++;
if (cnt == id) {
delete tmpFD;
m_List.RemoveAt(tmpp);
}
}
UpdateAllViews(NULL);
}
| 10,503 | 5,655 |
#include <bits/stdc++.h>
using namespace std;
/// decompose(1, -1) //For 1 rooted tree
#define ll long long
#define pb push_back
#define LN 17
const ll MAX = 1e5;
vector <ll> g[MAX + 9];
ll del[MAX + 9], sz[MAX + 9], par[MAX + 9], curSize, depth[MAX + 9], dis[MAX + 9], pa[LN][MAX + 9];
void dfs(ll u, ll p)
{
sz[u] = 1;
for(ll i = 0; i < g[u].size(); i++) {
ll nd = g[u][i];
if(nd == p || del[nd])
continue;
dfs(nd, u);
sz[u] += sz[nd];
}
}
ll findCentroid(ll u, ll p)
{
for(ll i = 0; i < g[u].size(); i++) {
ll nd = g[u][i];
if(nd == p || del[nd] || sz[nd] <= curSize / 2)
continue;
return findCentroid(nd, u);
}
return u;
}
void decompose(ll u, ll p)
{
dfs(u, -1);
curSize = sz[u];
ll cen = findCentroid(u, -1);
if(p == -1) p = cen;
par[cen] = p, del[cen] = 1;
for(ll i = 0; i < g[cen].size(); i++) {
ll nd = g[cen][i];
if(!del[nd])
decompose(nd, cen);
}
}
void depthdfs(ll u, ll p)
{
pa[0][u] = p;
for(ll i = 0; i < g[u].size(); i++) {
ll nd = g[u][i];
if(nd == p)
continue;
depth[nd] = depth[u] + 1;
depthdfs(nd, u);
}
}
int LCA(int u, int v) {
if(depth[u] < depth[v]) swap(u,v);
int diff = depth[u] - depth[v];
for(int i=0; i<LN; i++) if( (diff>>i)&1 ) u = pa[i][u];
if(u == v) return u;
for(int i=LN-1; i>=0; i--) if(pa[i][u] != pa[i][v]) {
u = pa[i][u];
v = pa[i][v];
}
return pa[0][u];
}
ll dist(ll x, ll y)
{
ll d= depth[x] + depth[y] - 2 * depth[LCA(x, y)];
return d;
}
void update(ll nd)
{
ll u = nd;
while(1) {
dis[u] = min(dis[u], dist(u, nd));
if(u == par[u])
break;
u = par[u];
}
}
ll query(ll nd)
{
ll ret = 1e18;
ll u = nd;
while(1) {
ret = min(ret, dis[u] + dist(nd, u));
if(u == par[u])
break;
u = par[u];
}
return ret;
}
int main()
{
for(ll i = 0; i <= MAX; i++) {
dis[i] = 1e18;
for(ll j = 0; j < LN; j++)
pa[j][i] = -1;
}
ll n, m;
cin >> n >> m;
for(ll i = 1; i < n; i++) {
ll u, v;
scanf("%lld %lld", &u, &v);
g[u].pb(v);
g[v].pb(u);
}
decompose(1, -1);
depthdfs(1, -1);
for(int i=1; i<LN; i++)
for(int j=1; j<=n; j++)
if(pa[i-1][j] != -1)
pa[i][j] = pa[i-1][pa[i-1][j]];
update(1);
while(m--) {
ll t, nd;
scanf("%lld %lld", &t, &nd);
if(t == 1)
update(nd);
else
printf("%lld\n", query(nd));
}
return 0;
} | 2,704 | 1,267 |
#include "ComponentManager.hpp"
const std::size_t Component::Type = std::hash<std::string>()(TO_STRING(Component));
// All class definitions for components
// CLASS_DEFINITION(parent class, sub class)
CLASS_DEFINITION(Component, Rotatable)
CLASS_DEFINITION(Component, FreeCamera)
CLASS_DEFINITION(Component, Renderable)
CLASS_DEFINITION(Component, BaseLight)
CLASS_DEFINITION(BaseLight, DirectionalLight)
CLASS_DEFINITION(BaseLight, PointLight)
CLASS_DEFINITION(BaseLight, SpotLight)
CLASS_DEFINITION(Component, ComponentToggler)
CLASS_DEFINITION(Component, GameObjectToggler)
#include "Flow3D/ImGui/ImGuiFreeCameraEditor.hpp"
#include "Flow3D/ImGui/ImGuiGameObjectTogglerEditor.hpp"
#include "Flow3D/ImGui/ImGuiComponentTogglerEditor.hpp"
#include "Flow3D/ImGui/ImGuiDirectionalLightEditor.hpp"
#include "Flow3D/ImGui/ImGuiPointLightEditor.hpp"
#include "Flow3D/ImGui/ImGuiSpotLightEditor.hpp"
#include "Flow3D/ImGui/ImGuiRenderableEditor.hpp"
#include "Flow3D/Serializer.hpp"
#include <io.h> // For access().
#include <sys/types.h> // For stat().
#include <sys/stat.h> // For stat().
#include <filesystem>
std::string ComponentManager::ChooseComponentPopup(std::string componentName)
{
if (componentName == "Rotatable")
{
return "Rotatable";
}
else if (componentName == "FreeCamera")
{
return "FreeCamera";
}
else if (componentName == "Renderable")
{
return "Renderable";
}
else if (componentName == "DirectionalLight")
{
return "DirectionalLight";
}
else if (componentName == "PointLight")
{
return "PointLight";
}
else if (componentName == "SpotLight")
{
return "SpotLight";
}
else if (componentName == "ComponentToggler")
{
return "ComponentToggler";
}
else if (componentName == "GameObjectToggler")
{
return "GameObjectToggler";
}
}
void ComponentManager::DuplicateComponent(Component& component, GameObject& gameObject)
{
std::string componentName = component.GetName();
if (componentName == "FreeCamera")
{
FLOW_CORE_WARN("a camera component should not be copied");
}
else if (componentName == "GameObjectToggler")
{
gameObject.AddComponent<GameObjectToggler>(&gameObject, component.GetEnabled());
GameObjectToggler& goToggler = *dynamic_cast<GameObjectToggler*>(&component);
std::vector<std::tuple<GameObject*, std::string, Keycode>>& gameObjectsToToggle = goToggler.GetGameObjectsToToggle();
GameObjectToggler& togglerOfNewGameObject = gameObject.GetComponent<GameObjectToggler>();
for (unsigned int i = 0; i < gameObjectsToToggle.size(); i++)
{
togglerOfNewGameObject.AddGameObjectToToggle(std::make_tuple(std::get<0>(gameObjectsToToggle[i]),
std::get<1>(gameObjectsToToggle[i]), std::get<2>(gameObjectsToToggle[i])), false);
}
}
else if (componentName == "ComponentToggler")
{
gameObject.AddComponent<ComponentToggler>(&gameObject, component.GetEnabled());
ComponentToggler& toggler = *dynamic_cast<ComponentToggler*>(&component);
std::vector<std::tuple<Component*, Keycode>>& componentsToToggle = toggler.GetComponentsToToggle();
ComponentToggler& togglerOfNewGameObject = gameObject.GetComponent<ComponentToggler>();
for (unsigned int i = 0; i < componentsToToggle.size(); i++)
{
togglerOfNewGameObject.AddComponentToToggle(std::make_tuple(std::get<0>(componentsToToggle[i]),
std::get<1>(componentsToToggle[i])), false);
}
}
else if (componentName == "DirectionalLight")
{
FLOW_CORE_WARN("a directional light component should not be copied");
}
else if (componentName == "PointLight")
{
PointLight& pointLight = *dynamic_cast<PointLight*>(&component);
gameObject.AddComponent<PointLight>(&gameObject, pointLight.GetAmbientIntensity(), pointLight.GetDiffuseIntensity(), pointLight.GetSpecularIntensity(),
pointLight.GetAttenuation(), pointLight.GetEnabled());
Application::Get().GetCurrentScene().AddPointLight(&gameObject.GetComponent<PointLight>());
}
else if (componentName == "SpotLight")
{
SpotLight& spotLight = *dynamic_cast<SpotLight*>(&component);
gameObject.AddComponent<SpotLight>(&gameObject, spotLight.GetAmbientIntensity(), spotLight.GetDiffuseIntensity(), spotLight.GetSpecularIntensity(),
spotLight.GetCutoff(), spotLight.GetOuterCutoff(), spotLight.GetAttenuation(), spotLight.GetEnabled());
Application::Get().GetCurrentScene().AddPointLight(&gameObject.GetComponent<PointLight>());
}
else if (componentName == "Renderable")
{
Renderable& renderable = *dynamic_cast<Renderable*>(&component);
std::string shaderName = renderable.GetShader().m_Name;
Model& model = renderable.GetModel();
std::string modelFilepath = model.filepath;
if (modelFilepath.empty())
{
if (model.GetCube() != nullptr)
{
Cube& cube = *model.GetCube();
if (cube.GetIsTextured())
{
Texture& diffuseTexture = cube.GetDiffuseTexture();
std::string diffusePath = diffuseTexture.path;
Texture& specularTexture = cube.GetSpecularTexture();
std::string specularPath = specularTexture.path;
gameObject.AddComponent<Renderable>(&gameObject, std::make_shared<Model>(std::make_shared<Cube>(ResourceManager::Get().FindTexture(diffusePath),
ResourceManager::Get().FindTexture(specularPath))),
ResourceManager::Get().FindShader(shaderName), renderable.GetBlending(), renderable.GetEnabled());
}
else
{
gameObject.AddComponent<Renderable>(&gameObject, std::make_shared<Model>(std::make_shared<Cube>(cube.GetColor())),
ResourceManager::Get().FindShader(shaderName), renderable.GetBlending(), renderable.GetEnabled());
}
}
else if (model.GetPlane() != nullptr)
{
Plane& plane = *model.GetPlane();
if (plane.GetIsTextured())
{
Texture& diffuseTexture = plane.GetDiffuseTexture();
std::string diffusePath = diffuseTexture.path;
Texture& specularTexture = plane.GetSpecularTexture();
std::string specularPath = specularTexture.path;
gameObject.AddComponent<Renderable>(&gameObject, std::make_shared<Model>(std::make_shared<Plane>(ResourceManager::Get().FindTexture(diffusePath),
ResourceManager::Get().FindTexture(specularPath))),
ResourceManager::Get().FindShader(shaderName), renderable.GetBlending(), renderable.GetEnabled());
}
else
{
gameObject.AddComponent<Renderable>(&gameObject, std::make_shared<Model>(std::make_shared<Plane>(plane.GetColor())),
ResourceManager::Get().FindShader(shaderName), renderable.GetBlending(), renderable.GetEnabled());
}
}
}
else
{
gameObject.AddComponent<Renderable>(&gameObject, ResourceManager::Get().FindModel(modelFilepath),
ResourceManager::Get().FindShader(shaderName), renderable.GetBlending(), renderable.GetEnabled());
}
}
}
void ComponentManager::ShowComponentEditor(std::string componentName, std::vector<std::string> componentNames, Component* component, const std::vector<std::shared_ptr<Component>>& components)
{
if (componentName == "FreeCamera")
{
FreeCameraEditor editor = FreeCameraEditor();
editor.Draw(dynamic_cast<FreeCamera*>(component));
}
else if (componentName == "GameObjectToggler")
{
GameObjectTogglerEditor editor = GameObjectTogglerEditor();
editor.Draw(dynamic_cast<GameObjectToggler*>(component));
}
else if (componentName == "ComponentToggler")
{
ComponentTogglerEditor editor = ComponentTogglerEditor();
editor.Draw(dynamic_cast<ComponentToggler*>(component), components, componentNames);
}
else if (componentName == "DirectionalLight")
{
DirectionalLightEditor editor = DirectionalLightEditor();
editor.Draw(dynamic_cast<DirectionalLight*>(component));
}
else if (componentName == "PointLight")
{
PointLightEditor editor = PointLightEditor();
editor.Draw(dynamic_cast<PointLight*>(component));
}
else if (componentName == "SpotLight")
{
SpotLightEditor editor = SpotLightEditor();
editor.Draw(dynamic_cast<SpotLight*>(component));
}
else if (componentName == "Renderable")
{
RenderableEditor editor = RenderableEditor();
editor.Draw(dynamic_cast<Renderable*>(component));
}
}
void ComponentManager::SerializeComponent(const std::string& componentName, std::ofstream& myfile, Component* component, const std::string& componentDirectory)
{
if (componentName == "Rotatable")
{
Serializer::SerializeRotatable(myfile, component);
}
else if (componentName == "FreeCamera")
{
Serializer::SerializeFreeCamera(myfile, component);
}
else if (componentName == "GameObjectToggler")
{
Serializer::SerializeGameObjectToggler(myfile, component);
}
else if (componentName == "ComponentToggler")
{
Serializer::SerializeComponentToggler(myfile, component);
}
else if (componentName == "DirectionalLight")
{
Serializer::SerializeDirectionalLight(myfile, component);
}
else if (componentName == "PointLight")
{
Serializer::SerializePointLight(myfile, component);
}
else if (componentName == "SpotLight")
{
Serializer::SerializeSpotLight(myfile, component);
}
else if (componentName == "Renderable")
{
Serializer::SerializeRenderable(myfile, component, componentDirectory);
}
}
void ComponentManager::DeserializeComponent(const std::string& componentName, json & json, GameObject & gameObject, Scene & scene, const std::string & componentsDirectory, std::vector<std::shared_ptr<GameObject>>& gameObjectsWithGameObjectToggler)
{
if (componentName == "Rotatable")
{
Serializer::DeserializeRotatable(json, gameObject, scene);
}
else if (componentName == "FreeCamera")
{
Serializer::DeserializeFreeCamera(json, gameObject, scene);
}
else if (componentName == "GameObjectToggler")
{
Serializer::DeserializeGameObjectToggler(json, gameObject, scene, gameObjectsWithGameObjectToggler);
}
else if (componentName == "ComponentToggler")
{
Serializer::DeserializeComponentToggler(json, gameObject, scene);
}
else if (componentName == "DirectionalLight")
{
Serializer::DeserializeDirectionalLight(json, gameObject, scene);
}
else if (componentName == "PointLight")
{
Serializer::DeserializePointLight(json, gameObject, scene);
}
else if (componentName == "SpotLight")
{
Serializer::DeserializeSpotLight(json, gameObject, scene);
}
else if (componentName == "Renderable")
{
Serializer::DeserializeRenderable(json, gameObject, scene, componentsDirectory);
}
}
| 10,265 | 3,520 |
// Copyright (c) 2014, Ruslan Baratov
// All rights reserved.
#include <leathers/push>
#include <leathers/object-layout-change>
#include <leathers/c++98-compat>
#include <leathers/weak-vtables>
#include <leathers/padded>
class Foo {
public:
virtual void foo() {
}
virtual ~Foo() {
}
};
class Boo : virtual public Foo {
public:
virtual void foo() override {
}
virtual ~Boo() override {
}
};
#include <leathers/pop>
#include <leathers/push>
#include <leathers/object-layout-change>
#include <leathers/padded>
#include <leathers/c++98-compat>
#if !defined(SHOW_WARNINGS)
# include <leathers/inherits-via-dominance>
#endif
class Baz : public Boo, virtual public Foo {
virtual ~Baz() override {
}
};
#include <leathers/pop>
int main() {
}
| 804 | 298 |
#include "stdafx.h"
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
int vmax;
public:
int maxPathSum(TreeNode *root)
{
vmax = INT_MIN;
subPath(root);
return vmax;
}
int subPath(TreeNode *root)
{
if (root == NULL)
return 0;
int val = root->val;
int left = subPath(root->left);
int right = subPath(root->right);
if (left >= 0 && right >= 0)
{
vmax = max(vmax, left + right + val);
return max(left, right) + val;
}
else if (left >= 0)
{
vmax = max(vmax, left + val);
return left + val;
}
else if (right >= 0)
{
vmax = max(vmax, right + val);
return right + val;
}
else
{
vmax = max(vmax, val);
return val;
}
}
}; | 1,002 | 331 |
// -----------------------------------------------------------------------
// RTToolbox - DKFZ radiotherapy quantitative evaluation library
//
// Copyright (c) German Cancer Research Center (DKFZ),
// Software development for Integrated Diagnostics and Therapy (SIDT).
// ALL RIGHTS RESERVED.
// See rttbCopyright.txt or
// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notices for more information.
//
//------------------------------------------------------------------------
#include <time.h>
#include "DummyDVHGenerator.h"
namespace rttb
{
namespace testing
{
DummyDVHGenerator::DummyDVHGenerator(): _binSize(DoseTypeGy(0.1)), _voxelVolume(8), _value(0)
{
/* initialize random seed: */
srand(static_cast<unsigned int>(time(nullptr)));
};
core::DVH DummyDVHGenerator::generateDVH(IDType structureID, IDType doseID)
{
core::DVH::DataDifferentialType aDataDifferential;
for (int i = 0; i < 100; i++)
{
_value = DoseCalcType((double(rand()) / RAND_MAX) * 1000);
//cut off values to avoid problems on comparisson with reimported values after
//writing to file.
_value = floor(_value * 1000000) / 1000000;
aDataDifferential.push_back(_value);
}
return core::DVH(aDataDifferential, _binSize, _voxelVolume, structureID, doseID);
}
core::DVH DummyDVHGenerator::generateDVH(IDType structureID, IDType doseID, DoseCalcType value)
{
_value = value;
core::DVH::DataDifferentialType aDataDifferential;
for (int i = 0; i < 100; i++)
{
aDataDifferential.push_back(_value);
}
return core::DVH(aDataDifferential, _binSize, _voxelVolume, structureID, doseID);
}
core::DVH DummyDVHGenerator::generateDVH(IDType structureID, IDType doseID, DoseCalcType minValue,
DoseCalcType maxValue)
{
_voxelVolume = 0.2 * 0.2 * 0.4;
bool decrease = false;
core::DVH::DataDifferentialType aDataDifferential;
for (int i = 0; i <= 200; i++)
{
if ((i > 20) && (i < 180))
{
if ((_value == 0) && (!decrease))
{
_value = DoseCalcType((double(rand()) / RAND_MAX) * 10) + minValue;
}
else if (!decrease)
{
_value = _value + DoseCalcType((double(rand()) / RAND_MAX) * (maxValue / 10));
}
if ((_value > maxValue) || (decrease))
{
decrease = true;
_value = _value - DoseCalcType((double(rand()) / RAND_MAX) * (maxValue / 3));
}
if (_value < 0)
{
_value = 0;
}
}
else
{
_value = 0;
}
aDataDifferential.push_back(_value);
}
return core::DVH(aDataDifferential, _binSize, _voxelVolume, structureID, doseID);
}
}
} | 2,920 | 1,285 |
// Token table - generated by gentoks.py from tokens
#include "tokens.h"
TokenRegistry tokens[] = {
{"*e", T_END},
{"*s", T_STRING},
{"*i", T_IDENT},
{"*n", T_INT},
{"*f", T_FLOAT},
{"*c{", T_OCURLY},
{"*c}", T_CCURLY},
{"*c(", T_OPREN},
{"*c)", T_CPREN},
{"*c,", T_COMMA},
{"*c<", T_LT},
{"audio", T_AUDIO},
{"sample", T_SAMPLE},
{"speech", T_SPEECH},
{"false", T_FALSE},
{"true", T_TRUE},
{"bool", T_BOOL},
{"integer", T_INTEGER},
{"else", T_ELSE},
{"var", T_VAR},
{"expr", T_EXPR},
{"window", T_WINDOW},
{"frame", T_FRAME},
{"linked", T_LINKED},
{"float", T_NAMEFLOAT},
{"pos", T_POS},
{"centred", T_CENTRED},
{"centered", T_CENTERED},
{"min", T_MIN},
{"max", T_MAX},
{"inverse", T_INVERSE},
{"gauge", T_GAUGE},
{"levels", T_LEVELS},
{"number", T_NUMBER},
{"graph", T_GRAPH},
{"compass", T_COMPASS},
{"status", T_STATUS},
{"map", T_MAP},
{"switch", T_SWITCH},
{"title", T_TITLE},
{"subtitle", T_SUBTITLE},
{"range", T_RANGE},
{"out", T_OUT},
{"bands", T_BANDS},
{"previous", T_PREVIOUS},
{"auto", T_AUTO},
{"to", T_TO},
{"col", T_COL},
{"color", T_COLOR},
{"colour", T_COLOUR},
{"colours", T_COLOURS},
{"updateinterval", T_UPDATEINTERVAL},
{"on", T_ON},
{"point", T_POINT},
{"location", T_LOCATION},
{"saturation", T_SATURATION},
{"hue", T_HUE},
{"value", T_VALUE},
{"size", T_SIZE},
{"sizerange", T_SIZERANGE},
{"trail", T_TRAIL},
{"trailevery", T_TRAILEVERY},
{"time", T_TIME},
{"width", T_WIDTH},
{"height", T_HEIGHT},
{"floatrange", T_FLOATRANGE},
{"when", T_WHEN},
{"default", T_DEFAULT},
{"darken", T_DARKEN},
{"button", T_BUTTON},
{"radians", T_RADIANS},
{"degrees", T_DEGREES},
{"length", T_LENGTH},
{"widthrange", T_WIDTHRANGE},
{"lengthrange", T_LENGTHRANGE},
{"vector", T_VECTOR},
{"fontscale", T_FONTSCALE},
{"port", T_PORT},
{"sendport", T_SENDPORT},
{"sendaddr", T_SENDADDR},
{"label", T_LABEL},
{"start", T_START},
{"end", T_END_WD},
{"clip", T_CLIP},
{"immediate", T_IMMEDIATE},
{"key", T_KEY},
{"always", T_ALWAYS},
{"sendinterval", T_SENDINTERVAL},
{"validtime", T_VALIDTIME},
{"momentary", T_MOMENTARY},
{"slider", T_SLIDER},
{"borderless", T_BORDERLESS},
{"spacing", T_SPACING},
{"horizontal", T_HORIZONTAL},
{"vertical", T_VERTICAL},
{"fullscreen", T_FULLSCREEN},
{"screen", T_SCREEN},
{"set", T_SET},
{"epsilon", T_EPSILON},
{"initial", T_INITIAL},
{"nudge", T_NUDGE},
{"up", T_UP},
{"down", T_DOWN},
{"centre", T_CENTRE},
{"line", T_LINE},
{"arrow", T_ARROW},
{"angle", T_ANGLE},
{"special", T_SPECIAL},
{"waypoint", T_WAYPOINT},
{"image", T_IMAGE},
{"alpha", T_ALPHA},
{"disable", T_DISABLE},
{"diamond", T_DIAMOND},
{"topic", T_TOPIC},
{NULL,-10}
};
| 2,693 | 1,310 |
#include <cstdlib>
#include <cassert>
#include <sstream>
#include <iostream>
#include "affectation.h"
#define abs(x) ((static_cast<unsigned int>(x > 0 ? x : -x)))
using namespace satsolver;
Affectation::Affectation(int nb_var) : aff(std::vector<int>()), nb_aff(0), nb_unknown(nb_var) {
for(int i = 0 ; i < nb_var ; i++)
this->aff.push_back(0) ;
}
Affectation::Affectation(Affectation *a) : aff(std::vector<int>(a->aff)), nb_aff(a->nb_aff), nb_unknown(a->nb_unknown) {
}
bool Affectation::is_true(int x) const {
assert(abs(x) <= this->aff.size() && x!=0) ;
if(x>0)
return this->aff[x-1] == TR ;
else
return this->is_false(-x);
}
bool Affectation::is_false(int x) const {
assert(abs(x) <= this->aff.size() && x!=0) ;
if(x>0)
return this->aff[x-1] == FA ;
else
return this->is_true(-x);
}
bool Affectation::is_unknown(int x) const {
assert(abs(x) <= this->aff.size());
assert(x!=0) ;
if (x>0)
return this->aff[x-1] == UN ;
else
return this->is_unknown(-x);
}
void Affectation::set_true(int x) {
if(x>0) {
assert(abs(x) <= this->aff.size() && x!=0) ;
assert(this->is_unknown(x)) ;
if(is_unknown(x))
this->nb_unknown -- ;
this->aff[x-1] = TR ;
}
else
this->set_false(-x);
}
void Affectation::set_false(int x) {
if(x>0) {
assert(abs(x) <= this->aff.size() && x!=0) ;
assert(this->is_unknown(x)) ;
if(is_unknown(x))
this->nb_unknown -- ;
this->aff[x-1] = FA ;
}
else
this->set_true(-x);
}
void Affectation::set_unknown(int x) {
if(x>0) {
assert(abs(x) <= this->aff.size());
assert(x!=0) ;
if(!is_unknown(x))
this->nb_unknown ++ ;
this->aff[abs(x)-1] = UN ;
}
else
this->set_unknown(-x);
}
std::string Affectation::to_string() const {
std::ostringstream oss;
oss << "{" ;
for(unsigned int i = 1 ; i <= this->aff.size() ; i++) {
if (i>1)
oss << ", ";
if(this->is_true(i))
oss << i << "=" << "true";
else if(this->is_false(i))
oss << i << "=" << "false";
else
oss << i << "=" << "unknown";
}
oss << "}" ;
return oss.str() ;
}
std::set<int>* Affectation::to_set() const {
std::set<int> *set = new std::set<int>();
for(unsigned int i = 1 ; i <= this->aff.size() ; i++) {
if(this->is_true(i))
set->insert(i);
else if(this->is_false(i))
set->insert(-i);
}
return set;
}
int Affectation::get_nb_unknown() {
return this->nb_unknown ;
}
unsigned Affectation::get_nb_var() const{
return static_cast<int> (this->aff.size()) ;
}
| 2,780 | 1,076 |
//
// VROPoseFilterLowPass.cpp
// ViroKit
//
// Created by Raj Advani on 2/27/19.
// Copyright © 2019 Viro Media. All rights reserved.
//
// 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 "VROPoseFilterLowPass.h"
VROPoseFrame VROPoseFilterLowPass::temporalFilter(const std::vector<VROPoseFrame> &frames, const VROPoseFrame &combinedFrame,
const VROPoseFrame &newFrame) {
VROPoseFrame dampenedJoints = newPoseFrame();
for (int i = 0; i < kNumBodyJoints; i++) {
VROBodyJointType type = (VROBodyJointType) i;
const std::vector<VROInferredBodyJoint> &samples = combinedFrame[i];
if (samples.empty()) {
continue;
}
float k = 2 / ((float) samples.size() + 1);
VROVector3f emaYesterday = samples[0].getCenter();
float sumConfidence = samples[0].getConfidence();
// Exponentially weight towards the earliest data at the end of the array
// (Items at the front of the array are older).
for (int i = 1; i < samples.size(); i++) {
const VROInferredBodyJoint &sample = samples[i];
VROVector3f emaToday = (sample.getCenter() * k) + (emaYesterday * (1 - k));
emaYesterday = emaToday;
sumConfidence += sample.getConfidence();
}
VROInferredBodyJoint dampenedJoint(type);
dampenedJoint.setCenter(emaYesterday);
dampenedJoint.setConfidence(sumConfidence / (float) samples.size());
dampenedJoints[i] = { dampenedJoint };
}
return dampenedJoints;
}
| 2,703 | 877 |
//
// MapConfigurationTest.cpp
//
// $Id: //poco/1.7/Util/testsuite/src/MapConfigurationTest.cpp#1 $
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "MapConfigurationTest.h"
#include "CppUnit/TestCaller.h"
#include "CppUnit/TestSuite.h"
#include "Poco/Util/MapConfiguration.h"
#include "Poco/AutoPtr.h"
using Poco::Util::AbstractConfiguration;
using Poco::Util::MapConfiguration;
using Poco::AutoPtr;
MapConfigurationTest::MapConfigurationTest(const std::string& name): AbstractConfigurationTest(name)
{
}
MapConfigurationTest::~MapConfigurationTest()
{
}
void MapConfigurationTest::testClear()
{
AutoPtr<MapConfiguration> pConf = new MapConfiguration;
pConf->setString("foo", "bar");
assert (pConf->hasProperty("foo"));
pConf->clear();
assert (!pConf->hasProperty("foo"));
}
AbstractConfiguration* MapConfigurationTest::allocConfiguration() const
{
return new MapConfiguration;
}
void MapConfigurationTest::setUp()
{
}
void MapConfigurationTest::tearDown()
{
}
CppUnit::Test* MapConfigurationTest::suite()
{
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MapConfigurationTest");
AbstractConfigurationTest_addTests(pSuite, MapConfigurationTest);
CppUnit_addTest(pSuite, MapConfigurationTest, testClear);
return pSuite;
}
| 1,363 | 465 |
/**
*
* 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 <cstdio>
#include <fstream>
#include <map>
#include <memory>
#include <utility>
#include <string>
#include <iostream>
#include <set>
#include <algorithm>
#include <random>
#include <cstdlib>
#include "FlowController.h"
#include "TestBase.h"
#include "core/Core.h"
#include "core/FlowFile.h"
#include "utils/file/FileUtils.h"
#include "utils/file/PathUtils.h"
#include "unit/ProvenanceTestHelper.h"
#include "core/Processor.h"
#include "core/ProcessContext.h"
#include "core/ProcessSession.h"
#include "core/ProcessorNode.h"
#include "TailFile.h"
#include "LogAttribute.h"
static std::string NEWLINE_FILE = "" // NOLINT
"one,two,three\n"
"four,five,six, seven";
static const char *TMP_FILE = "minifi-tmpfile.txt";
static const char *STATE_FILE = "minifi-state-file.txt";
namespace {
std::string createTempFile(const std::string &directory, const std::string &file_name, const std::string &contents,
std::ios_base::openmode open_mode = std::ios::out | std::ios::binary) {
std::string full_file_name = directory + utils::file::FileUtils::get_separator() + file_name;
std::ofstream tmpfile{full_file_name, open_mode};
tmpfile << contents;
return full_file_name;
}
void appendTempFile(const std::string &directory, const std::string &file_name, const std::string &contents,
std::ios_base::openmode open_mode = std::ios::app | std::ios::binary) {
createTempFile(directory, file_name, contents, open_mode);
}
void removeFile(const std::string &directory, const std::string &file_name) {
std::string full_file_name = directory + utils::file::FileUtils::get_separator() + file_name;
std::remove(full_file_name.c_str());
}
void renameTempFile(const std::string &directory, const std::string &old_file_name, const std::string &new_file_name) {
std::string old_full_file_name = directory + utils::file::FileUtils::get_separator() + old_file_name;
std::string new_full_file_name = directory + utils::file::FileUtils::get_separator() + new_file_name;
rename(old_full_file_name.c_str(), new_full_file_name.c_str());
}
} // namespace
TEST_CASE("TailFile reads the file until the first delimiter", "[simple]") {
// Create and write to the test file
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
auto id = tailfile->getUUIDStr();
plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true);
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::stringstream temp_file;
temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE;
std::ofstream tmpfile;
tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary);
tmpfile << NEWLINE_FILE;
tmpfile.close();
std::stringstream state_file;
state_file << dir << utils::file::FileUtils::get_separator() << STATE_FILE;
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str());
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
testController.runSession(plan, false);
auto records = plan->getProvenanceRecords();
REQUIRE(records.size() == 5); // line 1: CREATE, MODIFY; line 2: CREATE, MODIFY, DROP
testController.runSession(plan, false);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow files"));
REQUIRE(LogTestController::getInstance().contains("Size:" + std::to_string(NEWLINE_FILE.find_first_of('\n') + 1) + " Offset:0"));
LogTestController::getInstance().reset();
}
TEST_CASE("TailFile picks up the second line if a delimiter is written between runs", "[state]") {
// Create and write to the test file
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
auto id = tailfile->getUUIDStr();
plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true);
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::stringstream temp_file;
temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE;
std::ofstream tmpfile;
tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary);
tmpfile << NEWLINE_FILE;
tmpfile.close();
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str());
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.0-13.txt"));
plan->reset(true); // start a new but with state file
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
std::ofstream appendStream;
appendStream.open(temp_file.str(), std::ios_base::app | std::ios_base::binary);
appendStream << std::endl;
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.14-34.txt"));
LogTestController::getInstance().reset();
}
TEST_CASE("TailFile re-reads the file if the state is deleted between runs", "[state]") {
// Create and write to the test file
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
auto id = tailfile->getUUIDStr();
plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true);
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::stringstream temp_file;
temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE;
std::ofstream tmpfile;
tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary);
tmpfile << NEWLINE_FILE;
tmpfile.close();
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str());
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.0-13.txt"));
plan->reset(true); // start a new but with state file
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
plan->getStateManagerProvider()->getCoreComponentStateManager(*tailfile)->clear();
testController.runSession(plan, true);
// if we lose state we restart
REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.0-13.txt"));
}
TEST_CASE("TailFile picks up the state correctly if it is rewritten between runs", "[state]") {
// Create and write to the test file
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
auto id = tailfile->getUUIDStr();
plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true);
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::stringstream temp_file;
temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE;
std::ofstream tmpfile;
tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary);
tmpfile << NEWLINE_FILE;
tmpfile.close();
std::ofstream appendStream;
appendStream.open(temp_file.str(), std::ios_base::app | std::ios_base::binary);
appendStream.write("\n", 1);
appendStream.close();
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str());
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.0-13.txt"));
std::string filePath, fileName;
REQUIRE(utils::file::PathUtils::getFileNameAndPath(temp_file.str(), filePath, fileName));
// should stay the same
for (int i = 0; i < 5; i++) {
plan->reset(true); // start a new but with state file
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
plan->getStateManagerProvider()->getCoreComponentStateManager(*tailfile)->set({{"file.0.name", fileName},
{"file.0.position", "14"},
{"file.0.current", temp_file.str()}});
testController.runSession(plan, true);
// if we lose state we restart
REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.14-34.txt"));
}
for (int i = 14; i < 34; i++) {
plan->reset(true); // start a new but with state file
plan->getStateManagerProvider()->getCoreComponentStateManager(*tailfile)->set({{"file.0.name", fileName},
{"file.0.position", std::to_string(i)},
{"file.0.current", temp_file.str()}});
testController.runSession(plan, true);
}
plan->runCurrentProcessor();
for (int i = 14; i < 34; i++) {
REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile." + std::to_string(i) + "-34.txt"));
}
}
TEST_CASE("TailFile converts the old-style state file to the new-style state", "[state][migration]") {
// Create and write to the test file
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
auto plan = testController.createPlan();
auto tailfile = plan->addProcessor("TailFile", "tailfileProc");
auto id = tailfile->getUUIDStr();
auto logattribute = plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true);
plan->setProperty(logattribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0");
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::stringstream state_file;
state_file << dir << utils::file::FileUtils::get_separator() << STATE_FILE;
auto statefile = state_file.str() + "." + id;
SECTION("single") {
const std::string temp_file = createTempFile(dir, TMP_FILE, NEWLINE_FILE + '\n');
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file);
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::StateFile.getName(), state_file.str());
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
std::ofstream newstatefile;
newstatefile.open(statefile);
SECTION("legacy") {
newstatefile << "FILENAME=" << temp_file << std::endl;
newstatefile << "POSITION=14" << std::endl;
}
SECTION("newer single") {
newstatefile << "FILENAME=" << TMP_FILE << std::endl;
newstatefile << "POSITION." << TMP_FILE << "=14" << std::endl;
newstatefile << "CURRENT." << TMP_FILE << "=" << temp_file << std::endl;
}
newstatefile.close();
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.14-34.txt"));
std::unordered_map<std::string, std::string> state;
REQUIRE(plan->getStateManagerProvider()->getCoreComponentStateManager(*tailfile)->get(state));
std::string filePath, fileName;
REQUIRE(utils::file::PathUtils::getFileNameAndPath(temp_file, filePath, fileName));
std::unordered_map<std::string, std::string> expected_state{{"file.0.name", fileName},
{"file.0.position", "35"},
{"file.0.current", temp_file},
{"file.0.checksum", "1404369522"}};
for (const auto& key_value_pair : expected_state) {
const auto it = state.find(key_value_pair.first);
REQUIRE(it != state.end());
REQUIRE(it->second == key_value_pair.second);
}
REQUIRE(state.find("file.0.last_read_time") != state.end());
}
SECTION("multiple") {
const std::string file_name_1 = "bar.txt";
const std::string file_name_2 = "foo.txt";
const std::string temp_file_1 = createTempFile(dir, file_name_1, NEWLINE_FILE + '\n');
const std::string temp_file_2 = createTempFile(dir, file_name_2, NEWLINE_FILE + '\n');
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), dir);
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), ".*\\.txt");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::StateFile.getName(), state_file.str());
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
std::ofstream newstatefile;
newstatefile.open(statefile);
newstatefile << "FILENAME=" << file_name_1 << std::endl;
newstatefile << "POSITION." << file_name_1 << "=14" << std::endl;
newstatefile << "CURRENT." << file_name_1 << "=" << temp_file_1 << std::endl;
newstatefile << "FILENAME=" << file_name_2 << std::endl;
newstatefile << "POSITION." << file_name_2 << "=15" << std::endl;
newstatefile << "CURRENT." << file_name_2 << "=" << temp_file_2 << std::endl;
newstatefile.close();
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains(file_name_1.substr(0, file_name_1.rfind('.')) + ".14-34.txt"));
REQUIRE(LogTestController::getInstance().contains(file_name_2.substr(0, file_name_2.rfind('.')) + ".15-34.txt"));
std::unordered_map<std::string, std::string> state;
REQUIRE(plan->getStateManagerProvider()->getCoreComponentStateManager(*tailfile)->get(state));
std::string filePath1, filePath2, fileName1, fileName2;
REQUIRE(utils::file::PathUtils::getFileNameAndPath(temp_file_1, filePath1, fileName1));
REQUIRE(utils::file::PathUtils::getFileNameAndPath(temp_file_2, filePath2, fileName2));
std::unordered_map<std::string, std::string> expected_state{{"file.0.name", fileName1},
{"file.0.position", "35"},
{"file.0.current", temp_file_1},
{"file.0.checksum", "1404369522"},
{"file.1.name", fileName2},
{"file.1.position", "35"},
{"file.1.current", temp_file_2},
{"file.1.checksum", "2289158555"}};
for (const auto& key_value_pair : expected_state) {
const auto it = state.find(key_value_pair.first);
REQUIRE(it != state.end());
REQUIRE(it->second == key_value_pair.second);
}
REQUIRE(state.find("file.0.last_read_time") != state.end());
REQUIRE(state.find("file.1.last_read_time") != state.end());
}
}
TEST_CASE("TailFile picks up the new File to Tail if it is changed between runs", "[state]") {
TestController testController;
LogTestController::getInstance().setDebug<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tail_file = plan->addProcessor("TailFile", "tail_file");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
std::shared_ptr<core::Processor> log_attribute = plan->addProcessor("LogAttribute", "log_attribute", core::Relationship("success", "description"), true);
plan->setProperty(log_attribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0");
char format[] = "/tmp/gt.XXXXXX";
std::string directory = testController.createTempDirectory(format);
std::string first_test_file = createTempFile(directory, "first.log", "my first log line\n");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), first_test_file);
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:first.0-17.log"));
SECTION("The new file gets picked up") {
std::string second_test_file = createTempFile(directory, "second.log", "my second log line\n");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), second_test_file);
plan->reset(true); // clear the memory, but keep the state file
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:second.0-18.log"));
}
SECTION("The old file will no longer be tailed") {
appendTempFile(directory, "first.log", "add some more stuff\n");
std::string second_test_file = createTempFile(directory, "second.log", "");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), second_test_file);
plan->reset(true); // clear the memory, but keep the state file
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 0 flow files"));
}
}
TEST_CASE("TailFile picks up the new File to Tail if it is changed between runs (multiple file mode)", "[state][multiple_file]") {
TestController testController;
LogTestController::getInstance().setDebug<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
std::string directory = testController.createTempDirectory(format);
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tail_file = plan->addProcessor("TailFile", "tail_file");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), directory);
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "first\\..*\\.log");
std::shared_ptr<core::Processor> log_attribute = plan->addProcessor("LogAttribute", "log_attribute", core::Relationship("success", "description"), true);
plan->setProperty(log_attribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0");
createTempFile(directory, "first.fruit.log", "apple\n");
createTempFile(directory, "second.fruit.log", "orange\n");
createTempFile(directory, "first.animal.log", "hippopotamus\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:first.fruit.0-5.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:first.animal.0-12.log"));
appendTempFile(directory, "first.fruit.log", "banana\n");
appendTempFile(directory, "first.animal.log", "hedgehog\n");
SECTION("If a file no longer matches the new regex, then we stop tailing it") {
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "first\\.f.*\\.log");
plan->reset(true); // clear the memory, but keep the state file
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:first.fruit.6-12.log"));
}
SECTION("If a new file matches the new regex, we start tailing it") {
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), ".*\\.fruit\\.log");
plan->reset(true); // clear the memory, but keep the state file
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow file"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:first.fruit.6-12.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:second.fruit.0-6.log"));
}
}
TEST_CASE("TailFile finds the single input file in both Single and Multiple mode", "[simple]") {
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "");
plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true);
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::stringstream temp_file;
temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE;
std::ofstream tmpfile;
tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary);
tmpfile << NEWLINE_FILE;
tmpfile.close();
SECTION("Single") {
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str());
}
SECTION("Multiple") {
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "minifi-.*\\.txt");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), dir);
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec");
}
testController.runSession(plan, false);
auto records = plan->getProvenanceRecords();
REQUIRE(records.size() == 2);
testController.runSession(plan, false);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow files"));
REQUIRE(LogTestController::getInstance().contains("Size:" + std::to_string(NEWLINE_FILE.size()) + " Offset:0"));
LogTestController::getInstance().reset();
}
TEST_CASE("TailFile picks up new files created between runs", "[multiple_file]") {
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfile");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), dir);
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), ".*\\.log");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
std::shared_ptr<core::Processor> logattribute = plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true);
plan->setProperty(logattribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0");
createTempFile(dir, "application.log", "line1\nline2\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
createTempFile(dir, "another.log", "some more content\n");
plan->reset();
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file"));
LogTestController::getInstance().reset();
}
TEST_CASE("TailFile can handle input files getting removed", "[multiple_file]") {
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfile");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), dir);
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), ".*\\.log");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
std::shared_ptr<core::Processor> logattribute = plan->addProcessor("LogAttribute", "logattribute",
core::Relationship("success", "description"),
true);
plan->setProperty(logattribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0");
createTempFile(dir, "one.log", "line one\n");
createTempFile(dir, "two.log", "some stuff\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
plan->reset();
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
appendTempFile(dir, "one.log", "line two\nline three\nline four\n");
removeFile(dir, "two.log");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 3 flow files"));
LogTestController::getInstance().reset();
}
TEST_CASE("TailFile processes a very long line correctly", "[simple]") {
std::string line1("foo\n");
std::string line2(8050, 0);
std::mt19937 gen(std::random_device{}()); // NOLINT (linter wants a space before '{')
std::generate_n(line2.begin(), line2.size() - 1, [&]() -> char {
return 32 + gen() % (127 - 32);
});
line2.back() = '\n';
std::string line3("bar\n");
std::string line4("buzz");
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
LogTestController::getInstance().setTrace<core::ProcessSession>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::stringstream temp_file;
temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE;
std::ofstream tmpfile;
tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary);
tmpfile << line1 << line2 << line3 << line4;
tmpfile.close();
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str());
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
std::shared_ptr<core::Processor> log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0");
plan->setProperty(log_attr, processors::LogAttribute::LogPayload.getName(), "true");
plan->setProperty(log_attr, processors::LogAttribute::HexencodePayload.getName(), "true");
uint32_t line_length = 0U;
SECTION("with line length 80") {
line_length = 80U;
}
SECTION("with line length 200") {
line_length = 200U;
plan->setProperty(log_attr, processors::LogAttribute::MaxPayloadLineLength.getName(), "200");
}
SECTION("with line length 0") {
line_length = 0U;
plan->setProperty(log_attr, processors::LogAttribute::MaxPayloadLineLength.getName(), "0");
}
SECTION("with line length 16") {
line_length = 16U;
plan->setProperty(log_attr, processors::LogAttribute::MaxPayloadLineLength.getName(), "16");
}
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 3 flow files"));
REQUIRE(LogTestController::getInstance().contains(utils::StringUtils::to_hex(line1)));
auto line2_hex = utils::StringUtils::to_hex(line2);
if (line_length == 0U) {
REQUIRE(LogTestController::getInstance().contains(line2_hex));
} else {
std::stringstream line2_hex_lines;
for (size_t i = 0; i < line2_hex.size(); i += line_length) {
line2_hex_lines << line2_hex.substr(i, line_length) << '\n';
}
REQUIRE(LogTestController::getInstance().contains(line2_hex_lines.str()));
}
REQUIRE(LogTestController::getInstance().contains(utils::StringUtils::to_hex(line3)));
REQUIRE(false == LogTestController::getInstance().contains(utils::StringUtils::to_hex(line4), std::chrono::seconds(0)));
LogTestController::getInstance().reset();
}
TEST_CASE("TailFile processes a long line followed by multiple newlines correctly", "[simple][edge_case]") {
// Test having two delimiters on the buffer boundary
std::string line1(4098, '\n');
std::mt19937 gen(std::random_device { }());
std::generate_n(line1.begin(), 4095, [&]() -> char {
return 32 + gen() % (127 - 32);
});
std::string line2("foo\n");
std::string line3("bar\n");
std::string line4("buzz");
// Create and write to the test file
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
LogTestController::getInstance().setTrace<core::ProcessSession>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
auto id = tailfile->getUUIDStr();
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::stringstream temp_file;
temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE;
std::ofstream tmpfile;
tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary);
tmpfile << line1 << line2 << line3 << line4;
tmpfile.close();
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str());
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
std::shared_ptr<core::Processor> log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0");
plan->setProperty(log_attr, processors::LogAttribute::LogPayload.getName(), "true");
plan->setProperty(log_attr, processors::LogAttribute::HexencodePayload.getName(), "true");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 5 flow files"));
auto line1_hex = utils::StringUtils::to_hex(line1.substr(0, 4096));
std::stringstream line1_hex_lines;
for (size_t i = 0; i < line1_hex.size(); i += 80) {
line1_hex_lines << line1_hex.substr(i, 80) << '\n';
}
REQUIRE(LogTestController::getInstance().contains(line1_hex_lines.str()));
REQUIRE(LogTestController::getInstance().contains(utils::StringUtils::to_hex(line2)));
REQUIRE(LogTestController::getInstance().contains(utils::StringUtils::to_hex(line3)));
REQUIRE(false == LogTestController::getInstance().contains(utils::StringUtils::to_hex(line4), std::chrono::seconds(0)));
LogTestController::getInstance().reset();
}
TEST_CASE("TailFile onSchedule throws if file(s) to tail cannot be determined", "[configuration]") {
TestController testController;
LogTestController::getInstance().setDebug<minifi::processors::TailFile>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
SECTION("Single file mode by default") {
SECTION("No FileName") {
}
SECTION("FileName does not contain the path") {
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "minifi-log.txt");
}
}
SECTION("Explicit Single file mode") {
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Single file");
SECTION("No FileName") {
}
SECTION("FileName does not contain the path") {
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "minifi-log.txt");
}
}
SECTION("Multiple file mode") {
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file");
SECTION("No FileName and no BaseDirectory") {
}
SECTION("No BaseDirectory") {
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "minifi-.*\\.txt");
}
}
REQUIRE_THROWS(plan->runNextProcessor());
}
TEST_CASE("TailFile onSchedule throws in Multiple mode if the Base Directory does not exist", "[configuration][multiple_file]") {
TestController testController;
LogTestController::getInstance().setDebug<minifi::processors::TailFile>();
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc");
plan->setProperty(tailfile, processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tailfile, processors::TailFile::FileName.getName(), ".*\\.log");
SECTION("No Base Directory is set") {
REQUIRE_THROWS(plan->runNextProcessor());
}
SECTION("Base Directory is set, but does not exist") {
std::string nonexistent_file_name{"/no-such-directory/688b01d0-9e5f-11ea-820d-f338c34d39a1/31d1a81a-9e5f-11ea-a77b-8b27d514a452"};
plan->setProperty(tailfile, processors::TailFile::BaseDirectory.getName(), nonexistent_file_name);
REQUIRE_THROWS(plan->runNextProcessor());
}
SECTION("Base Directory is set and it exists") {
char format[] = "/tmp/gt.XXXXXX";
std::string directory = testController.createTempDirectory(format);
plan->setProperty(tailfile, processors::TailFile::BaseDirectory.getName(), directory);
plan->setProperty(tailfile, processors::TailFile::LookupFrequency.getName(), "0 sec");
REQUIRE_NOTHROW(plan->runNextProcessor());
}
}
TEST_CASE("TailFile finds and finishes the renamed file and continues with the new log file", "[rotation]") {
TestController testController;
const char DELIM = ',';
size_t expected_pieces = std::count(NEWLINE_FILE.begin(), NEWLINE_FILE.end(), DELIM); // The last piece is left as considered unfinished
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
auto plan = testController.createPlan();
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::string in_file = dir + utils::file::FileUtils::get_separator() + "testfifo.txt";
std::ofstream in_file_stream(in_file, std::ios::out | std::ios::binary);
in_file_stream << NEWLINE_FILE;
in_file_stream.flush();
// Build MiNiFi processing graph
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), std::string(1, DELIM));
SECTION("single") {
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), in_file);
}
SECTION("Multiple") {
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "testfifo.txt");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), dir);
plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec");
}
auto log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0");
plan->setProperty(log_attr, processors::LogAttribute::LogPayload.getName(), "true");
// Log as many FFs as it can to make sure exactly the expected amount is produced
plan->runNextProcessor(); // Tail
plan->runNextProcessor(); // Log
REQUIRE(LogTestController::getInstance().contains(std::string("Logged ") + std::to_string(expected_pieces) + " flow files"));
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // make sure the new file gets newer modification time
in_file_stream << DELIM;
in_file_stream.close();
std::string rotated_file = (in_file + ".1");
REQUIRE(rename(in_file.c_str(), rotated_file.c_str()) == 0);
std::ofstream new_in_file_stream(in_file, std::ios::out | std::ios::binary);
new_in_file_stream << "five" << DELIM << "six" << DELIM;
new_in_file_stream.close();
plan->reset();
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
plan->runNextProcessor(); // Tail
plan->runNextProcessor(); // Log
// Find the last flow file in the rotated file, and then pick up the new file
REQUIRE(LogTestController::getInstance().contains("Logged 3 flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:testfifo.txt.28-34.1"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:testfifo.0-4.txt"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:testfifo.5-8.txt"));
}
TEST_CASE("TailFile finds and finishes multiple rotated files and continues with the new log file", "[rotation]") {
TestController testController;
const char DELIM = ':';
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
auto plan = testController.createPlan();
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::string test_file = dir + utils::file::FileUtils::get_separator() + "fruits.log";
std::ofstream test_file_stream_0(test_file, std::ios::binary);
test_file_stream_0 << "Apple" << DELIM << "Orange" << DELIM;
test_file_stream_0.flush();
// Build MiNiFi processing graph
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), std::string(1, DELIM));
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), test_file);
auto log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.0-5.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.6-12.log"));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
test_file_stream_0 << "Pear" << DELIM;
test_file_stream_0.close();
std::string first_rotated_file = dir + utils::file::FileUtils::get_separator() + "fruits.0.log";
REQUIRE(rename(test_file.c_str(), first_rotated_file.c_str()) == 0);
std::ofstream test_file_stream_1(test_file, std::ios::binary);
test_file_stream_1 << "Pineapple" << DELIM << "Kiwi" << DELIM;
test_file_stream_1.close();
std::string second_rotated_file = dir + utils::file::FileUtils::get_separator() + "fruits.1.log";
REQUIRE(rename(test_file.c_str(), second_rotated_file.c_str()) == 0);
std::ofstream test_file_stream_2(test_file, std::ios::binary);
test_file_stream_2 << "Apricot" << DELIM;
test_file_stream_2.close();
plan->reset();
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 4 flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.0.13-17.log")); // Pear
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.1.0-9.log")); // Pineapple
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.1.10-14.log")); // Kiwi
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.0-7.log")); // Apricot
}
TEST_CASE("TailFile ignores old rotated files", "[rotation]") {
TestController testController;
LogTestController::getInstance().setTrace<minifi::processors::TailFile>();
LogTestController::getInstance().setDebug<core::ProcessSession>();
LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
const std::string dir = testController.createTempDirectory(format);
std::string log_file_name = dir + utils::file::FileUtils::get_separator() + "test.log";
std::shared_ptr<TestPlan> plan = testController.createPlan();
std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfile");
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), log_file_name);
plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n");
std::shared_ptr<core::Processor> logattribute = plan->addProcessor("LogAttribute", "logattribute",
core::Relationship("success", "description"),
true);
plan->setProperty(logattribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0");
createTempFile(dir, "test.2019-08-20", "line1\nline2\nline3\nline4\n"); // very old rotated file
std::this_thread::sleep_for(std::chrono::seconds(1));
createTempFile(dir, "test.log", "line5\nline6\nline7\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 3 flow files"));
REQUIRE(!LogTestController::getInstance().contains("key:filename value:test.2019-08-20"));
std::string rotated_log_file_name = dir + utils::file::FileUtils::get_separator() + "test.2020-05-18";
REQUIRE(rename(log_file_name.c_str(), rotated_log_file_name.c_str()) == 0);
createTempFile(dir, "test.log", "line8\nline9\n");
plan->reset();
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
REQUIRE(!LogTestController::getInstance().contains("key:filename value:test.2019-08-20"));
LogTestController::getInstance().reset();
}
TEST_CASE("TailFile rotation works with multiple input files", "[rotation][multiple_file]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
auto plan = testController.createPlan();
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
createTempFile(dir, "fruit.log", "apple\npear\nbanana\n");
createTempFile(dir, "animal.log", "bear\ngiraffe\n");
createTempFile(dir, "color.log", "red\nblue\nyellow\npurple\n");
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), "\n");
plan->setProperty(tail_file, processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), ".*\\.log");
plan->setProperty(tail_file, processors::TailFile::BaseDirectory.getName(), dir);
plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "0 sec");
auto log_attribute = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attribute, processors::LogAttribute::FlowFilesToLog.getName(), "0");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged " + std::to_string(3 + 2 + 4) + " flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruit.0-5.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruit.6-10.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruit.11-17.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:animal.0-4.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:animal.5-12.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:color.0-3.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:color.4-8.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:color.9-15.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:color.16-22.log"));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
appendTempFile(dir, "fruit.log", "orange\n");
appendTempFile(dir, "animal.log", "axolotl\n");
appendTempFile(dir, "color.log", "aquamarine\n");
renameTempFile(dir, "fruit.log", "fruit.0");
renameTempFile(dir, "animal.log", "animal.0");
createTempFile(dir, "fruit.log", "peach\n");
createTempFile(dir, "animal.log", "dinosaur\n");
appendTempFile(dir, "color.log", "turquoise\n");
plan->reset();
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 6 flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruit.18-24.0"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:fruit.0-5.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:animal.13-20.0"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:animal.0-8.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:color.23-33.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:color.34-43.log"));
}
TEST_CASE("TailFile handles the Rolling Filename Pattern property correctly", "[rotation]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
auto plan = testController.createPlan();
char format[] = "/tmp/gt.XXXXXX";
auto dir = testController.createTempDirectory(format);
std::string test_file = createTempFile(dir, "test.log", "some stuff\n");
// Build MiNiFi processing graph
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), "\n");
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), test_file);
std::vector<std::string> expected_log_lines;
SECTION("If no pattern is set, we use the default, which is ${filename}.*, so the unrelated file will be picked up") {
expected_log_lines = std::vector<std::string>{"Logged 2 flow files",
"test.rolled.11-24.log",
"test.0-15.txt"};
}
SECTION("If a pattern is set to exclude the unrelated file, we no longer pick it up") {
plan->setProperty(tail_file, processors::TailFile::RollingFilenamePattern.getName(), "${filename}.*.log");
expected_log_lines = std::vector<std::string>{"Logged 1 flow file",
"test.rolled.11-24.log"};
}
SECTION("We can also set the pattern to not include the file name") {
plan->setProperty(tail_file, processors::TailFile::RollingFilenamePattern.getName(), "other_roll??.log");
expected_log_lines = std::vector<std::string>{"Logged 1 flow file",
"other_rolled.11-24.log"};
}
auto log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:test.0-10.log"));
std::this_thread::sleep_for(std::chrono::milliseconds(100));
appendTempFile(dir, "test.log", "one more line\n");
renameTempFile(dir, "test.log", "test.rolled.log");
createTempFile(dir, "test.txt", "unrelated stuff\n");
createTempFile(dir, "other_rolled.log", "some stuff\none more line\n"); // same contents as test.rolled.log
plan->reset();
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
testController.runSession(plan, true);
for (const auto &log_line : expected_log_lines) {
REQUIRE(LogTestController::getInstance().contains(log_line));
}
}
TEST_CASE("TailFile finds and finishes the renamed file and continues with the new log file after a restart", "[rotation][restart]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
char log_dir_format[] = "/tmp/gt.XXXXXX";
auto log_dir = testController.createTempDirectory(log_dir_format);
std::string test_file_1 = createTempFile(log_dir, "test.1", "line one\nline two\nline three\n"); // old rotated file
std::this_thread::sleep_for(std::chrono::seconds(1));
std::string test_file = createTempFile(log_dir, "test.log", "line four\nline five\nline six\n"); // current log file
char state_dir_format[] = "/tmp/gt.XXXXXX";
auto state_dir = testController.createTempDirectory(state_dir_format);
utils::Identifier tail_file_uuid = utils::IdGenerator::getIdGenerator()->generate();
const core::Relationship success_relationship{"success", "everything is fine"};
{
auto test_plan = testController.createPlan(nullptr, state_dir.c_str());
auto tail_file = test_plan->addProcessor("TailFile", tail_file_uuid, "Tail", {success_relationship});
test_plan->setProperty(tail_file, processors::TailFile::FileName.getName(), test_file);
auto log_attr = test_plan->addProcessor("LogAttribute", "Log", success_relationship, true);
test_plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0");
test_plan->setProperty(log_attr, processors::LogAttribute::LogPayload.getName(), "true");
testController.runSession(test_plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 3 flow files"));
}
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
appendTempFile(log_dir, "test.log", "line seven\n");
renameTempFile(log_dir, "test.1", "test.2");
renameTempFile(log_dir, "test.log", "test.1");
createTempFile(log_dir, "test.log", "line eight is the last line\n");
{
auto test_plan = testController.createPlan(nullptr, state_dir.c_str());
auto tail_file = test_plan->addProcessor("TailFile", tail_file_uuid, "Tail", {success_relationship});
test_plan->setProperty(tail_file, processors::TailFile::FileName.getName(), test_file);
auto log_attr = test_plan->addProcessor("LogAttribute", "Log", success_relationship, true);
test_plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0");
test_plan->setProperty(log_attr, processors::LogAttribute::LogPayload.getName(), "true");
testController.runSession(test_plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:test.29-39.1"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:test.0-27.log"));
}
}
TEST_CASE("TailFile yields if no work is done", "[yield]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
auto temp_directory = testController.createTempDirectory(format);
auto plan = testController.createPlan();
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), "\n");
plan->setProperty(tail_file, processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), ".*\\.log");
plan->setProperty(tail_file, processors::TailFile::BaseDirectory.getName(), temp_directory);
plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "0 sec");
SECTION("Empty log file => yield") {
createTempFile(temp_directory, "first.log", "");
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() > 0);
SECTION("No logging happened between onTrigger calls => yield") {
plan->reset();
tail_file->clearYield();
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() > 0);
}
SECTION("Some logging happened between onTrigger calls => don't yield") {
plan->reset();
tail_file->clearYield();
appendTempFile(temp_directory, "first.log", "stuff stuff\nand stuff\n");
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() == 0);
}
}
SECTION("Non-empty log file => don't yield") {
createTempFile(temp_directory, "second.log", "some content\n");
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() == 0);
SECTION("No logging happened between onTrigger calls => yield") {
plan->reset();
tail_file->clearYield();
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() > 0);
}
SECTION("Some logging happened between onTrigger calls => don't yield") {
plan->reset();
tail_file->clearYield();
appendTempFile(temp_directory, "second.log", "stuff stuff\nand stuff\n");
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() == 0);
}
}
}
TEST_CASE("TailFile yields if no work is done on any files", "[yield][multiple_file]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
auto temp_directory = testController.createTempDirectory(format);
auto plan = testController.createPlan();
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), "\n");
plan->setProperty(tail_file, processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), ".*\\.log");
plan->setProperty(tail_file, processors::TailFile::BaseDirectory.getName(), temp_directory);
plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "0 sec");
createTempFile(temp_directory, "first.log", "stuff\n");
createTempFile(temp_directory, "second.log", "different stuff\n");
createTempFile(temp_directory, "third.log", "stuff stuff\n");
testController.runSession(plan, true);
plan->reset();
tail_file->clearYield();
SECTION("No file changed => yield") {
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() > 0);
}
SECTION("One file changed => don't yield") {
SECTION("first") { appendTempFile(temp_directory, "first.log", "more stuff\n"); }
SECTION("second") { appendTempFile(temp_directory, "second.log", "more stuff\n"); }
SECTION("third") { appendTempFile(temp_directory, "third.log", "more stuff\n"); }
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() == 0);
}
SECTION("More than one file changed => don't yield") {
SECTION("first and third") {
appendTempFile(temp_directory, "first.log", "more stuff\n");
appendTempFile(temp_directory, "third.log", "more stuff\n");
}
SECTION("all of them") {
appendTempFile(temp_directory, "first.log", "more stuff\n");
appendTempFile(temp_directory, "second.log", "more stuff\n");
appendTempFile(temp_directory, "third.log", "more stuff\n");
}
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() == 0);
}
}
TEST_CASE("TailFile doesn't yield if work was done on rotated files only", "[yield][rotation]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
auto temp_directory = testController.createTempDirectory(format);
std::string full_file_name = createTempFile(temp_directory, "test.log", "stuff\n");
auto plan = testController.createPlan();
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), "\n");
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), full_file_name);
testController.runSession(plan, true);
plan->reset();
tail_file->clearYield();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
SECTION("File rotated but not written => yield") {
renameTempFile(temp_directory, "test.log", "test.1");
SECTION("Don't create empty new log file") {
}
SECTION("Create empty new log file") {
createTempFile(temp_directory, "test.log", "");
}
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() > 0);
}
SECTION("File rotated and new stuff is added => don't yield") {
SECTION("New content before rotation") {
appendTempFile(temp_directory, "test.log", "more stuff\n");
}
renameTempFile(temp_directory, "test.log", "test.1");
SECTION("New content after rotation") {
createTempFile(temp_directory, "test.log", "even more stuff\n");
}
testController.runSession(plan, true);
REQUIRE(tail_file->getYieldTime() == 0);
}
}
TEST_CASE("TailFile handles the Delimiter setting correctly", "[delimiter]") {
std::vector<std::pair<std::string, std::string>> test_cases = {
// first = value of Delimiter in the config
// second = the expected delimiter char which will be used
{"", ""}, {",", ","}, {"\t", "\t"}, {"\\t", "\t"}, {"\n", "\n"}, {"\\n", "\n"}, {"\\", "\\"}, {"\\\\", "\\"}};
for (const auto &test_case : test_cases) {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
auto temp_directory = testController.createTempDirectory(format);
std::string delimiter = test_case.second;
std::string full_file_name = createTempFile(temp_directory, "test.log", "one" + delimiter + "two" + delimiter);
auto plan = testController.createPlan();
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), test_case.first);
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), full_file_name);
auto log_attribute = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attribute, processors::LogAttribute::FlowFilesToLog.getName(), "0");
testController.runSession(plan, true);
if (delimiter.empty()) {
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:test.0-5.log"));
} else {
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:test.0-3.log"));
REQUIRE(LogTestController::getInstance().contains("key:filename value:test.4-7.log"));
}
}
}
TEST_CASE("TailFile handles Unix/Windows line endings correctly", "[simple]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
auto temp_directory = testController.createTempDirectory(format);
std::string full_file_name = createTempFile(temp_directory, "test.log", "line1\nline two\n", std::ios::out); // write in text mode
auto plan = testController.createPlan();
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), full_file_name);
auto log_attribute = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attribute, processors::LogAttribute::FlowFilesToLog.getName(), "0");
testController.runSession(plan, true);
#ifdef WIN32
std::size_t line_ending_size = 2;
#else
std::size_t line_ending_size = 1;
#endif
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
REQUIRE(LogTestController::getInstance().contains("Size:" + std::to_string(5 + line_ending_size) + " Offset:0"));
REQUIRE(LogTestController::getInstance().contains("Size:" + std::to_string(8 + line_ending_size) + " Offset:0"));
}
TEST_CASE("TailFile can tail all files in a directory recursively", "[multiple]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
std::string base_directory = testController.createTempDirectory(format);
std::string directory1 = base_directory + utils::file::FileUtils::get_separator() + "one";
utils::file::FileUtils::create_dir(directory1);
std::string directory11 = directory1 + utils::file::FileUtils::get_separator() + "one_child";
utils::file::FileUtils::create_dir(directory11);
std::string directory2 = base_directory + utils::file::FileUtils::get_separator() + "two";
utils::file::FileUtils::create_dir(directory2);
createTempFile(base_directory, "test.orange.log", "orange juice\n");
createTempFile(directory1, "test.blue.log", "blue\n");
createTempFile(directory1, "test.orange.log", "orange autumn leaves\n");
createTempFile(directory11, "test.camel.log", "camel\n");
createTempFile(directory2, "test.triangle.log", "triangle\n");
auto plan = testController.createPlan();
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tail_file, processors::TailFile::BaseDirectory.getName(), base_directory);
plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "0 sec");
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), ".*\\.log");
auto log_attribute = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attribute, processors::LogAttribute::FlowFilesToLog.getName(), "0");
plan->setProperty(log_attribute, processors::LogAttribute::LogPayload.getName(), "true");
SECTION("Recursive lookup not set => defaults to false") {
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file"));
}
SECTION("Recursive lookup set to false") {
plan->setProperty(tail_file, processors::TailFile::RecursiveLookup.getName(), "false");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file"));
}
SECTION("Recursive lookup set to true") {
plan->setProperty(tail_file, processors::TailFile::RecursiveLookup.getName(), "true");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 5 flow files"));
}
}
TEST_CASE("TailFile interprets the lookup frequency property correctly", "[multiple]") {
TestController testController;
LogTestController::getInstance().setTrace<TestPlan>();
LogTestController::getInstance().setTrace<processors::TailFile>();
LogTestController::getInstance().setTrace<processors::LogAttribute>();
char format[] = "/tmp/gt.XXXXXX";
std::string directory = testController.createTempDirectory(format);
createTempFile(directory, "test.red.log", "cherry\n");
auto plan = testController.createPlan();
auto tail_file = plan->addProcessor("TailFile", "Tail");
plan->setProperty(tail_file, processors::TailFile::TailMode.getName(), "Multiple file");
plan->setProperty(tail_file, processors::TailFile::BaseDirectory.getName(), directory);
plan->setProperty(tail_file, processors::TailFile::FileName.getName(), ".*\\.log");
auto log_attribute = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
plan->setProperty(log_attribute, processors::LogAttribute::FlowFilesToLog.getName(), "0");
testController.runSession(plan, true);
SECTION("Lookup frequency not set => defaults to 10 minutes") {
std::shared_ptr<processors::TailFile> tail_file_processor = std::dynamic_pointer_cast<processors::TailFile>(tail_file);
REQUIRE(tail_file_processor);
REQUIRE(tail_file_processor->getLookupFrequency() == std::chrono::minutes{10});
}
SECTION("Lookup frequency set to zero => new files are picked up immediately") {
plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "0 sec");
plan->reset(true);
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
createTempFile(directory, "test.blue.log", "sky\n");
createTempFile(directory, "test.green.log", "grass\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
}
SECTION("Lookup frequency set to 10 ms => new files are only picked up after 10 ms") {
plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "10 ms");
plan->reset(true);
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
createTempFile(directory, "test.blue.log", "sky\n");
createTempFile(directory, "test.green.log", "grass\n");
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 0 flow files"));
plan->reset(false);
LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output);
std::this_thread::sleep_for(std::chrono::milliseconds(11));
testController.runSession(plan, true);
REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files"));
}
}
| 72,652 | 22,780 |
// 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.
#include "chrome/browser/plugins/plugin_prefs.h"
#include "base/at_exit.h"
#include "base/bind.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/plugins/npapi/mock_plugin_list.h"
#include "webkit/plugins/webplugininfo.h"
using content::BrowserThread;
using content::PluginService;
namespace {
void CanEnablePluginCallback(const base::Closure& quit_closure,
bool expected_can_change,
bool did_change) {
EXPECT_EQ(expected_can_change, did_change);
quit_closure.Run();
}
base::FilePath GetComponentUpdatedPepperFlashPath(
const base::FilePath::StringType& version) {
base::FilePath path;
EXPECT_TRUE(PathService::Get(
chrome::DIR_COMPONENT_UPDATED_PEPPER_FLASH_PLUGIN, &path));
path = path.Append(version);
path = path.Append(chrome::kPepperFlashPluginFilename);
return path;
}
base::FilePath GetBundledPepperFlashPath() {
base::FilePath path;
EXPECT_TRUE(PathService::Get(chrome::FILE_PEPPER_FLASH_PLUGIN, &path));
return path;
}
} // namespace
class PluginPrefsTest : public ::testing::Test {
public:
virtual void SetUp() OVERRIDE {
plugin_prefs_ = new PluginPrefs();
}
void SetPolicyEnforcedPluginPatterns(
const std::set<string16>& disabled,
const std::set<string16>& disabled_exceptions,
const std::set<string16>& enabled) {
plugin_prefs_->SetPolicyEnforcedPluginPatterns(
disabled, disabled_exceptions, enabled);
}
protected:
void EnablePluginSynchronously(bool enabled,
const base::FilePath& path,
bool expected_can_change) {
base::RunLoop run_loop;
plugin_prefs_->EnablePlugin(
enabled, path,
base::Bind(&CanEnablePluginCallback, run_loop.QuitClosure(),
expected_can_change));
run_loop.Run();
}
scoped_refptr<PluginPrefs> plugin_prefs_;
};
TEST_F(PluginPrefsTest, DisabledByPolicy) {
std::set<string16> disabled_plugins;
disabled_plugins.insert(ASCIIToUTF16("Disable this!"));
disabled_plugins.insert(ASCIIToUTF16("*Google*"));
SetPolicyEnforcedPluginPatterns(disabled_plugins,
std::set<string16>(),
std::set<string16>());
EXPECT_EQ(PluginPrefs::NO_POLICY,
plugin_prefs_->PolicyStatusForPlugin(ASCIIToUTF16("42")));
EXPECT_EQ(PluginPrefs::POLICY_DISABLED,
plugin_prefs_->PolicyStatusForPlugin(
ASCIIToUTF16("Disable this!")));
EXPECT_EQ(PluginPrefs::POLICY_DISABLED,
plugin_prefs_->PolicyStatusForPlugin(ASCIIToUTF16("Google Earth")));
}
TEST_F(PluginPrefsTest, EnabledByPolicy) {
std::set<string16> enabled_plugins;
enabled_plugins.insert(ASCIIToUTF16("Enable that!"));
enabled_plugins.insert(ASCIIToUTF16("PDF*"));
SetPolicyEnforcedPluginPatterns(std::set<string16>(),
std::set<string16>(),
enabled_plugins);
EXPECT_EQ(PluginPrefs::NO_POLICY,
plugin_prefs_->PolicyStatusForPlugin(ASCIIToUTF16("42")));
EXPECT_EQ(PluginPrefs::POLICY_ENABLED,
plugin_prefs_->PolicyStatusForPlugin(ASCIIToUTF16("Enable that!")));
EXPECT_EQ(PluginPrefs::POLICY_ENABLED,
plugin_prefs_->PolicyStatusForPlugin(ASCIIToUTF16("PDF Reader")));
}
TEST_F(PluginPrefsTest, EnabledAndDisabledByPolicy) {
const string16 k42(ASCIIToUTF16("42"));
const string16 kEnabled(ASCIIToUTF16("Enabled"));
const string16 kEnabled2(ASCIIToUTF16("Enabled 2"));
const string16 kEnabled3(ASCIIToUTF16("Enabled 3"));
const string16 kException(ASCIIToUTF16("Exception"));
const string16 kException2(ASCIIToUTF16("Exception 2"));
const string16 kGoogleMars(ASCIIToUTF16("Google Mars"));
const string16 kGoogleEarth(ASCIIToUTF16("Google Earth"));
std::set<string16> disabled_plugins;
std::set<string16> disabled_plugins_exceptions;
std::set<string16> enabled_plugins;
disabled_plugins.insert(kEnabled);
disabled_plugins_exceptions.insert(kEnabled);
enabled_plugins.insert(kEnabled);
disabled_plugins_exceptions.insert(kException);
disabled_plugins.insert(kEnabled2);
enabled_plugins.insert(kEnabled2);
disabled_plugins.insert(kException2);
disabled_plugins_exceptions.insert(kException2);
disabled_plugins_exceptions.insert(kEnabled3);
enabled_plugins.insert(kEnabled3);
SetPolicyEnforcedPluginPatterns(disabled_plugins,
disabled_plugins_exceptions,
enabled_plugins);
EXPECT_EQ(PluginPrefs::NO_POLICY, plugin_prefs_->PolicyStatusForPlugin(k42));
EXPECT_EQ(PluginPrefs::POLICY_ENABLED,
plugin_prefs_->PolicyStatusForPlugin(kEnabled));
EXPECT_EQ(PluginPrefs::POLICY_ENABLED,
plugin_prefs_->PolicyStatusForPlugin(kEnabled2));
EXPECT_EQ(PluginPrefs::POLICY_ENABLED,
plugin_prefs_->PolicyStatusForPlugin(kEnabled3));
EXPECT_EQ(PluginPrefs::NO_POLICY,
plugin_prefs_->PolicyStatusForPlugin(kException));
EXPECT_EQ(PluginPrefs::NO_POLICY,
plugin_prefs_->PolicyStatusForPlugin(kException2));
disabled_plugins.clear();
disabled_plugins_exceptions.clear();
enabled_plugins.clear();
disabled_plugins.insert(ASCIIToUTF16("*"));
disabled_plugins_exceptions.insert(ASCIIToUTF16("*Google*"));
enabled_plugins.insert(kGoogleEarth);
SetPolicyEnforcedPluginPatterns(disabled_plugins,
disabled_plugins_exceptions,
enabled_plugins);
EXPECT_EQ(PluginPrefs::POLICY_ENABLED,
plugin_prefs_->PolicyStatusForPlugin(kGoogleEarth));
EXPECT_EQ(PluginPrefs::NO_POLICY,
plugin_prefs_->PolicyStatusForPlugin(kGoogleMars));
EXPECT_EQ(PluginPrefs::POLICY_DISABLED,
plugin_prefs_->PolicyStatusForPlugin(k42));
}
TEST_F(PluginPrefsTest, UnifiedPepperFlashState) {
base::ShadowingAtExitManager at_exit_manager_; // Destroys the PluginService.
base::MessageLoop message_loop;
content::TestBrowserThread ui_thread(BrowserThread::UI, &message_loop);
webkit::npapi::MockPluginList plugin_list;
PluginService::GetInstance()->SetPluginListForTesting(&plugin_list);
PluginService::GetInstance()->Init();
plugin_prefs_->SetPluginListForTesting(&plugin_list);
string16 component_updated_plugin_name(
ASCIIToUTF16("Component-updated Pepper Flash"));
webkit::WebPluginInfo component_updated_plugin_1(
component_updated_plugin_name,
GetComponentUpdatedPepperFlashPath(FILE_PATH_LITERAL("11.3.31.227")),
ASCIIToUTF16("11.3.31.227"),
ASCIIToUTF16(""));
webkit::WebPluginInfo component_updated_plugin_2(
component_updated_plugin_name,
GetComponentUpdatedPepperFlashPath(FILE_PATH_LITERAL("11.3.31.228")),
ASCIIToUTF16("11.3.31.228"),
ASCIIToUTF16(""));
webkit::WebPluginInfo bundled_plugin(ASCIIToUTF16("Pepper Flash"),
GetBundledPepperFlashPath(),
ASCIIToUTF16("11.3.31.229"),
ASCIIToUTF16(""));
plugin_list.AddPluginToLoad(component_updated_plugin_1);
plugin_list.AddPluginToLoad(component_updated_plugin_2);
plugin_list.AddPluginToLoad(bundled_plugin);
// Set the state of any of the three plugins will affect the others.
EnablePluginSynchronously(true, component_updated_plugin_1.path, true);
EXPECT_TRUE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_1));
EXPECT_TRUE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_2));
EXPECT_TRUE(plugin_prefs_->IsPluginEnabled(bundled_plugin));
EnablePluginSynchronously(false, bundled_plugin.path, true);
EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_1));
EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_2));
EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(bundled_plugin));
EnablePluginSynchronously(true, component_updated_plugin_2.path, true);
EXPECT_TRUE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_1));
EXPECT_TRUE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_2));
EXPECT_TRUE(plugin_prefs_->IsPluginEnabled(bundled_plugin));
std::set<string16> disabled_plugins;
disabled_plugins.insert(component_updated_plugin_name);
SetPolicyEnforcedPluginPatterns(disabled_plugins,
std::set<string16>(),
std::set<string16>());
// Policy settings should be respected.
EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_1));
EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_2));
EXPECT_TRUE(plugin_prefs_->IsPluginEnabled(bundled_plugin));
EnablePluginSynchronously(false, bundled_plugin.path, true);
EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(bundled_plugin));
// Trying to change the state of a policy-enforced plugin should not take
// effect. And it shouldn't change the state of other plugins either, even if
// they are not restricted by any policy.
EnablePluginSynchronously(true, component_updated_plugin_1.path, false);
EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_1));
EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_2));
EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(bundled_plugin));
EnablePluginSynchronously(true, bundled_plugin.path, true);
EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_1));
EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_2));
EXPECT_TRUE(plugin_prefs_->IsPluginEnabled(bundled_plugin));
plugin_prefs_->SetPluginListForTesting(NULL);
PluginService::GetInstance()->SetPluginListForTesting(NULL);
}
| 10,277 | 3,406 |
/*!
* \file HftMocker.cpp
* \project WonderTrader
*
* \author Wesley
* \date 2020/03/30
*
* \brief
*/
#include "HftMocker.h"
#include "WtHelper.h"
#include <stdarg.h>
#include <boost/filesystem.hpp>
#include "../Includes/WTSVariant.hpp"
#include "../Includes/WTSContractInfo.hpp"
#include "../Share/decimal.h"
#include "../Share/TimeUtils.hpp"
#include "../Share/StrUtil.hpp"
#include "../WTSTools/WTSLogger.h"
uint32_t makeLocalOrderID()
{
static std::atomic<uint32_t> _auto_order_id{ 0 };
if (_auto_order_id == 0)
{
uint32_t curYear = TimeUtils::getCurDate() / 10000 * 10000 + 101;
_auto_order_id = (uint32_t)((TimeUtils::getLocalTimeNow() - TimeUtils::makeTime(curYear, 0)) / 1000 * 50);
}
return _auto_order_id.fetch_add(1);
}
std::vector<uint32_t> splitVolume(uint32_t vol)
{
if (vol == 0) return std::move(std::vector<uint32_t>());
uint32_t minQty = 1;
uint32_t maxQty = 100;
uint32_t length = maxQty - minQty + 1;
std::vector<uint32_t> ret;
if (vol <= minQty)
{
ret.emplace_back(vol);
}
else
{
uint32_t left = vol;
srand((uint32_t)time(NULL));
while (left > 0)
{
uint32_t curVol = minQty + (uint32_t)rand() % length;
if (curVol >= left)
curVol = left;
if (curVol == 0)
continue;
ret.emplace_back(curVol);
left -= curVol;
}
}
return std::move(ret);
}
std::vector<double> splitVolume(double vol, double minQty = 1.0, double maxQty = 100.0, double qtyTick = 1.0)
{
auto length = (std::size_t)round((maxQty - minQty)/qtyTick) + 1;
std::vector<double> ret;
if (vol <= minQty)
{
ret.emplace_back(vol);
}
else
{
double left = vol;
srand((uint32_t)time(NULL));
while (left > 0)
{
double curVol = minQty + (rand() % length)*qtyTick;
if (curVol >= left)
curVol = left;
if (curVol == 0)
continue;
ret.emplace_back(curVol);
left -= curVol;
}
}
return std::move(ret);
}
uint32_t genRand(uint32_t maxVal = 10000)
{
srand(TimeUtils::getCurMin());
return rand() % maxVal;
}
inline uint32_t makeHftCtxId()
{
static std::atomic<uint32_t> _auto_context_id{ 6000 };
return _auto_context_id.fetch_add(1);
}
HftMocker::HftMocker(HisDataReplayer* replayer, const char* name)
: IHftStraCtx(name)
, _replayer(replayer)
, _strategy(NULL)
, _thrd(NULL)
, _stopped(false)
, _use_newpx(false)
, _error_rate(0)
, _has_hook(false)
, _hook_valid(true)
, _resumed(false)
{
_commodities = CommodityMap::create();
_context_id = makeHftCtxId();
}
HftMocker::~HftMocker()
{
if(_strategy)
{
_factory._fact->deleteStrategy(_strategy);
}
_commodities->release();
}
void HftMocker::procTask()
{
if (_tasks.empty())
{
return;
}
_mtx_control.lock();
while (!_tasks.empty())
{
Task& task = _tasks.front();
task();
{
std::unique_lock<std::mutex> lck(_mtx);
_tasks.pop();
}
}
_mtx_control.unlock();
}
void HftMocker::postTask(Task task)
{
{
std::unique_lock<std::mutex> lck(_mtx);
_tasks.push(task);
return;
}
if(_thrd == NULL)
{
_thrd.reset(new std::thread([this](){
while (!_stopped)
{
if(_tasks.empty())
{
std::this_thread::sleep_for(std::chrono::milliseconds(1));
continue;
}
_mtx_control.lock();
while(!_tasks.empty())
{
Task& task = _tasks.front();
task();
{
std::unique_lock<std::mutex> lck(_mtx);
_tasks.pop();
}
}
_mtx_control.unlock();
}
}));
}
}
bool HftMocker::init_hft_factory(WTSVariant* cfg)
{
if (cfg == NULL)
return false;
const char* module = cfg->getCString("module");
_use_newpx = cfg->getBoolean("use_newpx");
_error_rate = cfg->getUInt32("error_rate");
DllHandle hInst = DLLHelper::load_library(module);
if (hInst == NULL)
return false;
FuncCreateHftStraFact creator = (FuncCreateHftStraFact)DLLHelper::get_symbol(hInst, "createStrategyFact");
if (creator == NULL)
{
DLLHelper::free_library(hInst);
return false;
}
_factory._module_inst = hInst;
_factory._module_path = module;
_factory._creator = creator;
_factory._remover = (FuncDeleteHftStraFact)DLLHelper::get_symbol(hInst, "deleteStrategyFact");
_factory._fact = _factory._creator();
WTSVariant* cfgStra = cfg->get("strategy");
if(cfgStra)
{
_strategy = _factory._fact->createStrategy(cfgStra->getCString("name"), "hft");
_strategy->init(cfgStra->get("params"));
}
return true;
}
void HftMocker::handle_tick(const char* stdCode, WTSTickData* curTick)
{
on_tick(stdCode, curTick);
}
void HftMocker::handle_order_detail(const char* stdCode, WTSOrdDtlData* curOrdDtl)
{
on_order_detail(stdCode, curOrdDtl);
}
void HftMocker::handle_order_queue(const char* stdCode, WTSOrdQueData* curOrdQue)
{
on_order_queue(stdCode, curOrdQue);
}
void HftMocker::handle_transaction(const char* stdCode, WTSTransData* curTrans)
{
on_transaction(stdCode, curTrans);
}
void HftMocker::handle_bar_close(const char* stdCode, const char* period, uint32_t times, WTSBarStruct* newBar)
{
on_bar(stdCode, period, times, newBar);
}
void HftMocker::handle_init()
{
on_init();
on_channel_ready();
}
void HftMocker::handle_schedule(uint32_t uDate, uint32_t uTime)
{
//on_schedule(uDate, uTime);
}
void HftMocker::handle_session_begin(uint32_t curTDate)
{
on_session_begin(curTDate);
}
void HftMocker::handle_session_end(uint32_t curTDate)
{
on_session_end(curTDate);
}
void HftMocker::handle_replay_done()
{
dump_outputs();
this->on_bactest_end();
}
void HftMocker::on_bar(const char* stdCode, const char* period, uint32_t times, WTSBarStruct* newBar)
{
if (_strategy)
_strategy->on_bar(this, stdCode, period, times, newBar);
}
void HftMocker::enable_hook(bool bEnabled /* = true */)
{
_hook_valid = bEnabled;
WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Calculating hook %s", bEnabled ? "enabled" : "disabled");
}
void HftMocker::install_hook()
{
_has_hook = true;
WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "HFT hook installed");
}
void HftMocker::step_tick()
{
if (!_has_hook)
return;
WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Notify calc thread, wait for calc done");
while (!_resumed)
_cond_calc.notify_all();
{
StdUniqueLock lock(_mtx_calc);
_cond_calc.wait(_mtx_calc);
WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Calc done notified");
_resumed = false;
}
}
void HftMocker::on_tick(const char* stdCode, WTSTickData* newTick)
{
_price_map[stdCode] = newTick->price();
{
std::unique_lock<std::recursive_mutex> lck(_mtx_control);
}
update_dyn_profit(stdCode, newTick);
procTask();
if (!_orders.empty())
{
OrderIDs ids;
for (auto it = _orders.begin(); it != _orders.end(); it++)
{
uint32_t localid = it->first;
bool bNeedErase = procOrder(localid);
if (bNeedErase)
ids.emplace_back(localid);
}
for(uint32_t localid : ids)
{
auto it = _orders.find(localid);
_orders.erase(it);
}
}
if (_has_hook && _hook_valid)
{
WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Waiting for resume notify");
StdUniqueLock lock(_mtx_calc);
_cond_calc.wait(_mtx_calc);
WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Calc resumed");
_resumed = true;
}
on_tick_updated(stdCode, newTick);
if (_has_hook && _hook_valid)
{
WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Calc done, notify control thread");
while (_resumed)
_cond_calc.notify_all();
}
}
void HftMocker::on_tick_updated(const char* stdCode, WTSTickData* newTick)
{
auto it = _tick_subs.find(stdCode);
if (it == _tick_subs.end())
return;
if (_strategy)
_strategy->on_tick(this, stdCode, newTick);
}
void HftMocker::on_order_queue(const char* stdCode, WTSOrdQueData* newOrdQue)
{
on_ordque_updated(stdCode, newOrdQue);
}
void HftMocker::on_ordque_updated(const char* stdCode, WTSOrdQueData* newOrdQue)
{
if (_strategy)
_strategy->on_order_queue(this, stdCode, newOrdQue);
}
void HftMocker::on_order_detail(const char* stdCode, WTSOrdDtlData* newOrdDtl)
{
on_orddtl_updated(stdCode, newOrdDtl);
}
void HftMocker::on_orddtl_updated(const char* stdCode, WTSOrdDtlData* newOrdDtl)
{
if (_strategy)
_strategy->on_order_detail(this, stdCode, newOrdDtl);
}
void HftMocker::on_transaction(const char* stdCode, WTSTransData* newTrans)
{
on_trans_updated(stdCode, newTrans);
}
void HftMocker::on_trans_updated(const char* stdCode, WTSTransData* newTrans)
{
if (_strategy)
_strategy->on_transaction(this, stdCode, newTrans);
}
uint32_t HftMocker::id()
{
return _context_id;
}
void HftMocker::on_init()
{
if (_strategy)
_strategy->on_init(this);
}
void HftMocker::on_session_begin(uint32_t curTDate)
{
//每个交易日开始,要把冻结持仓置零
for (auto& it : _pos_map)
{
const char* stdCode = it.first.c_str();
PosInfo& pInfo = (PosInfo&)it.second;
if (!decimal::eq(pInfo._frozen, 0))
{
log_debug("%.0f of %s frozen released on %u", pInfo._frozen, stdCode, curTDate);
pInfo._frozen = 0;
}
}
if (_strategy)
_strategy->on_session_begin(this, curTDate);
}
void HftMocker::on_session_end(uint32_t curTDate)
{
uint32_t curDate = curTDate;// _replayer->get_trading_date();
double total_profit = 0;
double total_dynprofit = 0;
for (auto it = _pos_map.begin(); it != _pos_map.end(); it++)
{
const char* stdCode = it->first.c_str();
const PosInfo& pInfo = it->second;
total_profit += pInfo._closeprofit;
total_dynprofit += pInfo._dynprofit;
}
_fund_logs << StrUtil::printf("%d,%.2f,%.2f,%.2f,%.2f\n", curDate,
_fund_info._total_profit, _fund_info._total_dynprofit,
_fund_info._total_profit + _fund_info._total_dynprofit - _fund_info._total_fees, _fund_info._total_fees);
if (_strategy)
_strategy->on_session_end(this, curTDate);
}
double HftMocker::stra_get_undone(const char* stdCode)
{
double ret = 0;
for (auto it = _orders.begin(); it != _orders.end(); it++)
{
const OrderInfo& ordInfo = it->second;
if (strcmp(ordInfo._code, stdCode) == 0)
{
ret += ordInfo._left * ordInfo._isBuy ? 1 : -1;
}
}
return ret;
}
bool HftMocker::stra_cancel(uint32_t localid)
{
postTask([this, localid](){
auto it = _orders.find(localid);
if (it == _orders.end())
return;
StdLocker<StdRecurMutex> lock(_mtx_ords);
OrderInfo& ordInfo = (OrderInfo&)it->second;
ordInfo._left = 0;
on_order(localid, ordInfo._code, ordInfo._isBuy, ordInfo._total, ordInfo._left, ordInfo._price, true, ordInfo._usertag);
_orders.erase(it);
});
return true;
}
OrderIDs HftMocker::stra_cancel(const char* stdCode, bool isBuy, double qty /* = 0 */)
{
OrderIDs ret;
uint32_t cnt = 0;
for (auto it = _orders.begin(); it != _orders.end(); it++)
{
const OrderInfo& ordInfo = it->second;
if(ordInfo._isBuy == isBuy && strcmp(ordInfo._code, stdCode) == 0)
{
double left = ordInfo._left;
stra_cancel(it->first);
ret.emplace_back(it->first);
cnt++;
if (left < qty)
qty -= left;
else
break;
}
}
return ret;
}
OrderIDs HftMocker::stra_buy(const char* stdCode, double price, double qty, const char* userTag, int flag /* = 0 */)
{
WTSCommodityInfo* commInfo = _replayer->get_commodity_info(stdCode);
if (commInfo == NULL)
{
log_error("Cannot find corresponding commodity info of %s", stdCode);
return OrderIDs();
}
if (decimal::le(qty, 0))
{
log_error("Entrust error: qty {} <= 0", qty);
return OrderIDs();
}
uint32_t localid = makeLocalOrderID();
OrderInfo order;
order._localid = localid;
strcpy(order._code, stdCode);
strcpy(order._usertag, userTag);
order._isBuy = true;
order._price = price;
order._total = qty;
order._left = qty;
{
_mtx_ords.lock();
_orders[localid] = order;
_mtx_ords.unlock();
}
postTask([this, localid](){
const OrderInfo& ordInfo = _orders[localid];
on_entrust(localid, ordInfo._code, true, "下单成功", ordInfo._usertag);
});
OrderIDs ids;
ids.emplace_back(localid);
return ids;
}
void HftMocker::on_order(uint32_t localid, const char* stdCode, bool isBuy, double totalQty, double leftQty, double price, bool isCanceled /* = false */, const char* userTag /* = "" */)
{
if(_strategy)
_strategy->on_order(this, localid, stdCode, isBuy, totalQty, leftQty, price, isCanceled, userTag);
}
void HftMocker::on_trade(uint32_t localid, const char* stdCode, bool isBuy, double vol, double price, const char* userTag/* = ""*/)
{
const PosInfo& posInfo = _pos_map[stdCode];
double curPos = posInfo._volume + vol * (isBuy ? 1 : -1);
do_set_position(stdCode, curPos, price, userTag);
if (_strategy)
_strategy->on_trade(this, localid, stdCode, isBuy, vol, price, userTag);
}
void HftMocker::on_entrust(uint32_t localid, const char* stdCode, bool bSuccess, const char* message, const char* userTag/* = ""*/)
{
if (_strategy)
_strategy->on_entrust(localid, bSuccess, message, userTag);
}
void HftMocker::on_channel_ready()
{
if (_strategy)
_strategy->on_channel_ready(this);
}
void HftMocker::update_dyn_profit(const char* stdCode, WTSTickData* newTick)
{
auto it = _pos_map.find(stdCode);
if (it != _pos_map.end())
{
PosInfo& pInfo = (PosInfo&)it->second;
if (pInfo._volume == 0)
{
pInfo._dynprofit = 0;
}
else
{
bool isLong = decimal::gt(pInfo._volume, 0);
double price = isLong ? newTick->bidprice(0) : newTick->askprice(0);
WTSCommodityInfo* commInfo = _replayer->get_commodity_info(stdCode);
double dynprofit = 0;
for (auto pit = pInfo._details.begin(); pit != pInfo._details.end(); pit++)
{
DetailInfo& dInfo = *pit;
dInfo._profit = dInfo._volume*(price - dInfo._price)*commInfo->getVolScale()*(dInfo._long ? 1 : -1);
if (dInfo._profit > 0)
dInfo._max_profit = max(dInfo._profit, dInfo._max_profit);
else if (dInfo._profit < 0)
dInfo._max_loss = min(dInfo._profit, dInfo._max_loss);
dynprofit += dInfo._profit;
}
pInfo._dynprofit = dynprofit;
}
}
}
bool HftMocker::procOrder(uint32_t localid)
{
auto it = _orders.find(localid);
if (it == _orders.end())
return false;
StdLocker<StdRecurMutex> lock(_mtx_ords);
OrderInfo& ordInfo = (OrderInfo&)it->second;
//第一步,如果在撤单概率中,则执行撤单
if(_error_rate>0 && genRand(10000)<=_error_rate)
{
on_order(localid, ordInfo._code, ordInfo._isBuy, ordInfo._total, ordInfo._left, ordInfo._price, true, ordInfo._usertag);
log_info("Random error order: %u", localid);
return true;
}
else
{
on_order(localid, ordInfo._code, ordInfo._isBuy, ordInfo._total, ordInfo._left, ordInfo._price, false, ordInfo._usertag);
}
WTSTickData* curTick = stra_get_last_tick(ordInfo._code);
if (curTick == NULL)
return false;
double curPx = curTick->price();
double orderQty = ordInfo._isBuy ? curTick->askqty(0) : curTick->bidqty(0); //看对手盘的数量
if (decimal::eq(orderQty, 0.0))
return false;
if (!_use_newpx)
{
curPx = ordInfo._isBuy ? curTick->askprice(0) : curTick->bidprice(0);
//if (curPx == 0.0)
if(decimal::eq(curPx, 0.0))
{
curTick->release();
return false;
}
}
curTick->release();
//如果没有成交条件,则退出逻辑
if(!decimal::eq(ordInfo._price, 0.0))
{
if(ordInfo._isBuy && decimal::gt(curPx, ordInfo._price))
{
//买单,但是当前价大于限价,不成交
return false;
}
if (!ordInfo._isBuy && decimal::lt(curPx, ordInfo._price))
{
//卖单,但是当前价小于限价,不成交
return false;
}
}
/*
* 下面就要模拟成交了
*/
double maxQty = min(orderQty, ordInfo._left);
auto vols = splitVolume((uint32_t)maxQty);
for(uint32_t curQty : vols)
{
on_trade(ordInfo._localid, ordInfo._code, ordInfo._isBuy, curQty, curPx, ordInfo._usertag);
ordInfo._left -= curQty;
on_order(localid, ordInfo._code, ordInfo._isBuy, ordInfo._total, ordInfo._left, ordInfo._price, false, ordInfo._usertag);
double curPos = stra_get_position(ordInfo._code);
_sig_logs << _replayer->get_date() << "." << _replayer->get_raw_time() << "." << _replayer->get_secs() << ","
<< (ordInfo._isBuy ? "+" : "-") << curQty << "," << curPos << "," << curPx << std::endl;
}
//if(ordInfo._left == 0)
if(decimal::eq(ordInfo._left, 0.0))
{
return true;
}
return false;
}
OrderIDs HftMocker::stra_sell(const char* stdCode, double price, double qty, const char* userTag, int flag /* = 0 */)
{
WTSCommodityInfo* commInfo = _replayer->get_commodity_info(stdCode);
if (commInfo == NULL)
{
log_error("Cannot find corresponding commodity info of %s", stdCode);
return OrderIDs();
}
if (decimal::le(qty, 0))
{
log_error("Entrust error: qty {} <= 0", qty);
return OrderIDs();
}
//如果不能做空,则要看可用持仓
if(!commInfo->canShort())
{
double curPos = stra_get_position(stdCode, true);//只读可用持仓
if(decimal::gt(qty, curPos))
{
log_error("No enough position of %s to sell", stdCode);
return OrderIDs();
}
}
uint32_t localid = makeLocalOrderID();
OrderInfo order;
order._localid = localid;
strcpy(order._code, stdCode);
strcpy(order._usertag, userTag);
order._isBuy = false;
order._price = price;
order._total = qty;
order._left = qty;
{
StdLocker<StdRecurMutex> lock(_mtx_ords);
_orders[localid] = order;
}
postTask([this, localid]() {
const OrderInfo& ordInfo = _orders[localid];
on_entrust(localid, ordInfo._code, true, "下单成功", ordInfo._usertag);
});
OrderIDs ids;
ids.emplace_back(localid);
return ids;
}
WTSCommodityInfo* HftMocker::stra_get_comminfo(const char* stdCode)
{
return _replayer->get_commodity_info(stdCode);
}
WTSKlineSlice* HftMocker::stra_get_bars(const char* stdCode, const char* period, uint32_t count)
{
std::string basePeriod = "";
uint32_t times = 1;
if (strlen(period) > 1)
{
basePeriod.append(period, 1);
times = strtoul(period + 1, NULL, 10);
}
else
{
basePeriod = period;
}
return _replayer->get_kline_slice(stdCode, basePeriod.c_str(), count, times);
}
WTSTickSlice* HftMocker::stra_get_ticks(const char* stdCode, uint32_t count)
{
return _replayer->get_tick_slice(stdCode, count);
}
WTSOrdQueSlice* HftMocker::stra_get_order_queue(const char* stdCode, uint32_t count)
{
return _replayer->get_order_queue_slice(stdCode, count);
}
WTSOrdDtlSlice* HftMocker::stra_get_order_detail(const char* stdCode, uint32_t count)
{
return _replayer->get_order_detail_slice(stdCode, count);
}
WTSTransSlice* HftMocker::stra_get_transaction(const char* stdCode, uint32_t count)
{
return _replayer->get_transaction_slice(stdCode, count);
}
WTSTickData* HftMocker::stra_get_last_tick(const char* stdCode)
{
return _replayer->get_last_tick(stdCode);
}
double HftMocker::stra_get_position(const char* stdCode, bool bOnlyValid/* = false*/)
{
const PosInfo& pInfo = _pos_map[stdCode];
if (bOnlyValid)
{
//这里理论上,只有多头才会进到这里
//其他地方要保证,空头持仓的话,_frozen要为0
return pInfo._volume - pInfo._frozen;
}
else
return pInfo._volume;
}
double HftMocker::stra_get_position_profit(const char* stdCode)
{
const PosInfo& pInfo = _pos_map[stdCode];
return pInfo._dynprofit;
}
double HftMocker::stra_get_price(const char* stdCode)
{
return _replayer->get_cur_price(stdCode);
}
uint32_t HftMocker::stra_get_date()
{
return _replayer->get_date();
}
uint32_t HftMocker::stra_get_time()
{
return _replayer->get_raw_time();
}
uint32_t HftMocker::stra_get_secs()
{
return _replayer->get_secs();
}
void HftMocker::stra_sub_ticks(const char* stdCode)
{
/*
* By Wesley @ 2022.03.01
* 主动订阅tick会在本地记一下
* tick数据回调的时候先检查一下
*/
_tick_subs.insert(stdCode);
_replayer->sub_tick(_context_id, stdCode);
}
void HftMocker::stra_sub_order_queues(const char* stdCode)
{
_replayer->sub_order_queue(_context_id, stdCode);
}
void HftMocker::stra_sub_order_details(const char* stdCode)
{
_replayer->sub_order_detail(_context_id, stdCode);
}
void HftMocker::stra_sub_transactions(const char* stdCode)
{
_replayer->sub_transaction(_context_id, stdCode);
}
void HftMocker::stra_log_info(const char* message)
{
WTSLogger::log_dyn_raw("strategy", _name.c_str(), LL_INFO, message);
}
void HftMocker::stra_log_debug(const char* message)
{
WTSLogger::log_dyn_raw("strategy", _name.c_str(), LL_DEBUG, message);
}
void HftMocker::stra_log_error(const char* message)
{
WTSLogger::log_dyn_raw("strategy", _name.c_str(), LL_ERROR, message);
}
const char* HftMocker::stra_load_user_data(const char* key, const char* defVal /*= ""*/)
{
auto it = _user_datas.find(key);
if (it != _user_datas.end())
return it->second.c_str();
return defVal;
}
void HftMocker::stra_save_user_data(const char* key, const char* val)
{
_user_datas[key] = val;
_ud_modified = true;
}
void HftMocker::dump_outputs()
{
std::string folder = WtHelper::getOutputDir();
folder += _name;
folder += "/";
boost::filesystem::create_directories(folder.c_str());
std::string filename = folder + "trades.csv";
std::string content = "code,time,direct,action,price,qty,fee,usertag\n";
content += _trade_logs.str();
StdFile::write_file_content(filename.c_str(), (void*)content.c_str(), content.size());
filename = folder + "closes.csv";
content = "code,direct,opentime,openprice,closetime,closeprice,qty,profit,maxprofit,maxloss,totalprofit,entertag,exittag\n";
content += _close_logs.str();
StdFile::write_file_content(filename.c_str(), (void*)content.c_str(), content.size());
filename = folder + "funds.csv";
content = "date,closeprofit,positionprofit,dynbalance,fee\n";
content += _fund_logs.str();
StdFile::write_file_content(filename.c_str(), (void*)content.c_str(), content.size());
filename = folder + "signals.csv";
content = "time, action, position, price\n";
content += _sig_logs.str();
StdFile::write_file_content(filename.c_str(), (void*)content.c_str(), content.size());
}
void HftMocker::log_trade(const char* stdCode, bool isLong, bool isOpen, uint64_t curTime, double price, double qty, double fee, const char* userTag/* = ""*/)
{
_trade_logs << stdCode << "," << curTime << "," << (isLong ? "LONG" : "SHORT") << "," << (isOpen ? "OPEN" : "CLOSE")
<< "," << price << "," << qty << "," << fee << "," << userTag << "\n";
}
void HftMocker::log_close(const char* stdCode, bool isLong, uint64_t openTime, double openpx, uint64_t closeTime, double closepx, double qty, double profit, double maxprofit, double maxloss,
double totalprofit /* = 0 */, const char* enterTag/* = ""*/, const char* exitTag/* = ""*/)
{
_close_logs << stdCode << "," << (isLong ? "LONG" : "SHORT") << "," << openTime << "," << openpx
<< "," << closeTime << "," << closepx << "," << qty << "," << profit << "," << maxprofit << "," << maxloss << ","
<< totalprofit << "," << enterTag << "," << exitTag << "\n";
}
void HftMocker::do_set_position(const char* stdCode, double qty, double price /* = 0.0 */, const char* userTag /*= ""*/)
{
PosInfo& pInfo = _pos_map[stdCode];
double curPx = price;
if (decimal::eq(price, 0.0))
curPx = _price_map[stdCode];
uint64_t curTm = (uint64_t)_replayer->get_date() * 1000000000 + (uint64_t)_replayer->get_min_time()*100000 + _replayer->get_secs();
uint32_t curTDate = _replayer->get_trading_date();
//手数相等则不用操作了
if (decimal::eq(pInfo._volume, qty))
return;
log_info("[%04u.%05u] %s position updated: %.0f -> %0.f", _replayer->get_min_time(), _replayer->get_secs(), stdCode, pInfo._volume, qty);
WTSCommodityInfo* commInfo = _replayer->get_commodity_info(stdCode);
if (commInfo == NULL)
return;
//成交价
double trdPx = curPx;
double diff = qty - pInfo._volume;
bool isBuy = decimal::gt(diff, 0.0);
if (decimal::gt(pInfo._volume*diff, 0))//当前持仓和仓位变化方向一致, 增加一条明细, 增加数量即可
{
pInfo._volume = qty;
//如果T+1,则冻结仓位要增加
if (commInfo->isT1())
{
//ASSERT(diff>0);
pInfo._frozen += diff;
log_debug("%s frozen position up to %.0f", stdCode, pInfo._frozen);
}
DetailInfo dInfo;
dInfo._long = decimal::gt(qty, 0);
dInfo._price = trdPx;
dInfo._volume = abs(diff);
dInfo._opentime = curTm;
dInfo._opentdate = curTDate;
strcpy(dInfo._usertag, userTag);
pInfo._details.emplace_back(dInfo);
double fee = _replayer->calc_fee(stdCode, trdPx, abs(diff), 0);
_fund_info._total_fees += fee;
log_trade(stdCode, dInfo._long, true, curTm, trdPx, abs(diff), fee, userTag);
}
else
{//持仓方向和仓位变化方向不一致,需要平仓
double left = abs(diff);
pInfo._volume = qty;
if (decimal::eq(pInfo._volume, 0))
pInfo._dynprofit = 0;
uint32_t count = 0;
for (auto it = pInfo._details.begin(); it != pInfo._details.end(); it++)
{
DetailInfo& dInfo = *it;
double maxQty = min(dInfo._volume, left);
if (decimal::eq(maxQty, 0))
continue;
double maxProf = dInfo._max_profit * maxQty / dInfo._volume;
double maxLoss = dInfo._max_loss * maxQty / dInfo._volume;
dInfo._volume -= maxQty;
left -= maxQty;
if (decimal::eq(dInfo._volume, 0))
count++;
double profit = (trdPx - dInfo._price) * maxQty * commInfo->getVolScale();
if (!dInfo._long)
profit *= -1;
pInfo._closeprofit += profit;
pInfo._dynprofit = pInfo._dynprofit*dInfo._volume / (dInfo._volume + maxQty);//浮盈也要做等比缩放
_fund_info._total_profit += profit;
double fee = _replayer->calc_fee(stdCode, trdPx, maxQty, dInfo._opentdate == curTDate ? 2 : 1);
_fund_info._total_fees += fee;
//这里写成交记录
log_trade(stdCode, dInfo._long, false, curTm, trdPx, maxQty, fee, userTag);
//这里写平仓记录
log_close(stdCode, dInfo._long, dInfo._opentime, dInfo._price, curTm, trdPx, maxQty, profit, maxProf, maxLoss, pInfo._closeprofit, dInfo._usertag, userTag);
if (left == 0)
break;
}
//需要清理掉已经平仓完的明细
while (count > 0)
{
auto it = pInfo._details.begin();
pInfo._details.erase(it);
count--;
}
//最后,如果还有剩余的,则需要反手了
if (left > 0)
{
left = left * qty / abs(qty);
//如果T+1,则冻结仓位要增加
if (commInfo->isT1())
{
pInfo._frozen += left;
log_debug("%s frozen position up to %.0f", stdCode, pInfo._frozen);
}
DetailInfo dInfo;
dInfo._long = decimal::gt(qty, 0);
dInfo._price = trdPx;
dInfo._volume = abs(left);
dInfo._opentime = curTm;
dInfo._opentdate = curTDate;
strcpy(dInfo._usertag, userTag);
pInfo._details.emplace_back(dInfo);
//这里还需要写一笔成交记录
double fee = _replayer->calc_fee(stdCode, trdPx, abs(left), 0);
_fund_info._total_fees += fee;
log_trade(stdCode, dInfo._long, true, curTm, trdPx, abs(left), fee, userTag);
}
}
}
| 27,043 | 11,974 |
class Operators {
public:
void* operator new[](size_t size) throw() {
return nullptr;
}
void* operator new (size_t size) throw(){
return nullptr;
}
int operator+(const Operators& o) const {
return 2;
}
Operators operator++() {
return *this;
}
Operators operator++(int) {
return *this;
}
/**
* Operators (8, 6): void, ++ (pre), * x2, this x2, ++ (post) x2, ; x2
* Operands (1): pluszPlusz
*/
void pluszPlusz() {
++*this;
(*this)++++;
//this->operator++();
//this->operator++(2);
}
};
int main() {
return 0;
} | 663 | 233 |
#include "Mesh.h"
#include "CLog.h"
#include "StringFormat.h"
using gfx::engine::Mesh;
namespace
{
const char * CLASSNAME = "Mesh";
}
// Buffers Vertex data into the VBO
void Mesh::init(std::vector<gfx::Vertex_T> * d)
{
m_data_size = d->size();
glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
glGenBuffers(1, &m_buffer);
glBindBuffer(GL_ARRAY_BUFFER, m_buffer);
glBufferData(GL_ARRAY_BUFFER, m_data_size * sizeof(struct gfx::Vertex_T), d->data(), GL_STATIC_DRAW);
glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, sizeof(struct gfx::Vertex_T),
(const GLvoid*)offsetof(struct gfx::Vertex_T, position));
glEnableVertexAttribArray(0);
glVertexAttribPointer((GLuint)1, 3, GL_FLOAT, GL_FALSE, sizeof(struct gfx::Vertex_T),
(const GLvoid*)offsetof(struct gfx::Vertex_T, color));
glEnableVertexAttribArray(1);
glVertexAttribPointer((GLuint)2, 3, GL_FLOAT, GL_FALSE, sizeof(struct gfx::Vertex_T),
(const GLvoid*)offsetof(struct gfx::Vertex_T, normal));
glEnableVertexAttribArray(2);
glVertexAttribPointer((GLuint)3, 2, GL_FLOAT, GL_FALSE, sizeof(struct gfx::Vertex_T),
(const GLvoid*)offsetof(struct gfx::Vertex_T, uv));
glEnableVertexAttribArray(3);
glVertexAttribPointer((GLuint)4, 3, GL_FLOAT, GL_FALSE, sizeof(struct gfx::Vertex_T),
(const GLvoid*)offsetof(struct gfx::Vertex_T, tangent));
glEnableVertexAttribArray(4);
glBindVertexArray(0);
glFlush();
CINFO(alib::StringFormat(" buffered into VAO %0").arg(m_vao).str());
}
// Loads image file into a texture
void Mesh::load_textures(const char *texfilename)
{
if (texfilename != "")
{
m_tex = alib::ImageLoader::loadTextureFromImage(texfilename);
CINFO(alib::StringFormat(" %0 -> Texture ID %1").arg(texfilename).arg(m_tex).str());
}
else
{
CINFO(" no texture file loaded");
}
}
// Draws the mesh including linking the model matrix
void Mesh::draw(int wire_frame, gfx::engine::MeshHandle_T handles)
{
handles.modelMatHandle->load(get_model_mat());
draw_array(wire_frame, handles.textureHandle);
}
// Draws just the VBO and activating the texture
void Mesh::draw_array(int wire_frame, gfx::engine::VarHandle *texture_handle)
{
// load the textures
if (m_tex != GL_TEXTURE0)
{
load_texture_handle(texture_handle);
glActiveTexture(GL_TEXTURE0 + m_tex);
glBindTexture(GL_TEXTURE_2D, m_tex);
}
// draw the data
glBindVertexArray(m_vao);
glDrawArrays(wire_frame ? GL_LINE_LOOP : GL_TRIANGLES, 0, m_data_size);
glBindVertexArray(0);
// unload the texture
if (m_tex != GL_TEXTURE0)
{
glActiveTexture(GL_TEXTURE0 + m_tex);
glBindTexture(GL_TEXTURE_2D, GL_TEXTURE0);
}
glActiveTexture(GL_TEXTURE0);
glFinish();
}
// Override the texture handle seperately
void Mesh::load_texture_handle(gfx::engine::VarHandle * handle)
{
handle->load(m_tex);
}
// Sets the texture
void Mesh::set_tex(GLuint tex)
{
this->m_tex = tex;
}
// Get the model matrix
glm::mat4 Mesh::get_model_mat()
{
return glm::translate(glm::mat4(1.), m_pos) *
glm::rotate(glm::mat4(1.), m_theta, m_rotation) *
glm::rotate(glm::mat4(1.), m_pre_theta, m_pre_rotation) *
glm::scale(glm::mat4(1.), m_scale);
}
Mesh::Mesh() {}
// Texture filename, Vertex data pack, world position, dynamic axis of rotation, and amount, static axis of rotation, and amount, scale vector.
Mesh::Mesh(
const char *texfilename,
std::vector<gfx::Vertex_T> data,
glm::vec3 _pos,
glm::vec3 _rotation,
GLfloat _theta,
glm::vec3 _pre_rotation,
GLfloat _pre_theta,
glm::vec3 _scale
)
{
CINFO("Loading new Mesh...");
CINFO(alib::StringFormat(" Vertex count = %0").arg(data.size()).str());
m_pos = _pos;
m_rotation = _rotation;
m_theta = _theta;
m_scale = _scale;
m_pre_rotation = _pre_rotation;
m_pre_theta = _pre_theta;
load_textures(texfilename);
init(&data);
} | 3,769 | 1,530 |
#include <fc/network/udp_socket.hpp>
#include <fc/network/ip.hpp>
#include <fc/fwd_impl.hpp>
#include <fc/asio.hpp>
namespace fc {
class udp_socket::impl {
public:
impl():_sock( fc::asio::default_io_service() ){}
~impl(){
// _sock.cancel();
}
boost::asio::ip::udp::socket _sock;
};
boost::asio::ip::udp::endpoint to_asio_ep( const fc::ip::endpoint& e ) {
return boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4(e.get_address()), e.port() );
}
fc::ip::endpoint to_fc_ep( const boost::asio::ip::udp::endpoint& e ) {
return fc::ip::endpoint( e.address().to_v4().to_ulong(), e.port() );
}
udp_socket::udp_socket()
:my( new impl() )
{
}
udp_socket::udp_socket( const udp_socket& s )
:my(s.my)
{
}
udp_socket::~udp_socket()
{
try
{
my->_sock.close(); //close boost socket to make any pending reads run their completion handler
}
catch (...) //avoid destructor throw and likely this is just happening because socket wasn't open.
{
}
}
size_t udp_socket::send_to( const char* buffer, size_t length, const ip::endpoint& to )
{
try
{
return my->_sock.send_to( boost::asio::buffer(buffer, length), to_asio_ep(to) );
}
catch( const boost::system::system_error& e )
{
if( e.code() != boost::asio::error::would_block )
throw;
}
promise<size_t>::ptr completion_promise = promise<size_t>::create("udp_socket::send_to");
my->_sock.async_send_to( boost::asio::buffer(buffer, length), to_asio_ep(to),
asio::detail::read_write_handler(completion_promise) );
return completion_promise->wait();
}
size_t udp_socket::send_to( const std::shared_ptr<const char>& buffer, size_t length,
const fc::ip::endpoint& to )
{
try
{
return my->_sock.send_to( boost::asio::buffer(buffer.get(), length), to_asio_ep(to) );
}
catch( const boost::system::system_error& e )
{
if( e.code() != boost::asio::error::would_block )
throw;
}
promise<size_t>::ptr completion_promise = promise<size_t>::create("udp_socket::send_to");
my->_sock.async_send_to( boost::asio::buffer(buffer.get(), length), to_asio_ep(to),
asio::detail::read_write_handler_with_buffer(completion_promise, buffer) );
return completion_promise->wait();
}
void udp_socket::open() {
my->_sock.open( boost::asio::ip::udp::v4() );
my->_sock.non_blocking(true);
}
void udp_socket::set_receive_buffer_size( size_t s ) {
my->_sock.set_option(boost::asio::socket_base::receive_buffer_size(s) );
}
void udp_socket::bind( const fc::ip::endpoint& e ) {
my->_sock.bind( to_asio_ep(e) );
}
size_t udp_socket::receive_from( const std::shared_ptr<char>& receive_buffer, size_t receive_buffer_length, fc::ip::endpoint& from )
{
try
{
boost::asio::ip::udp::endpoint boost_from_endpoint;
size_t bytes_read = my->_sock.receive_from( boost::asio::buffer(receive_buffer.get(), receive_buffer_length),
boost_from_endpoint );
from = to_fc_ep(boost_from_endpoint);
return bytes_read;
}
catch( const boost::system::system_error& e )
{
if( e.code() != boost::asio::error::would_block )
throw;
}
boost::asio::ip::udp::endpoint boost_from_endpoint;
promise<size_t>::ptr completion_promise = promise<size_t>::create("udp_socket::receive_from");
my->_sock.async_receive_from( boost::asio::buffer(receive_buffer.get(), receive_buffer_length),
boost_from_endpoint,
asio::detail::read_write_handler_with_buffer(completion_promise, receive_buffer) );
size_t bytes_read = completion_promise->wait();
from = to_fc_ep(boost_from_endpoint);
return bytes_read;
}
size_t udp_socket::receive_from( char* receive_buffer, size_t receive_buffer_length, fc::ip::endpoint& from )
{
try
{
boost::asio::ip::udp::endpoint boost_from_endpoint;
size_t bytes_read = my->_sock.receive_from( boost::asio::buffer(receive_buffer, receive_buffer_length),
boost_from_endpoint );
from = to_fc_ep(boost_from_endpoint);
return bytes_read;
}
catch( const boost::system::system_error& e )
{
if( e.code() != boost::asio::error::would_block )
throw;
}
boost::asio::ip::udp::endpoint boost_from_endpoint;
promise<size_t>::ptr completion_promise = promise<size_t>::create("udp_socket::receive_from");
my->_sock.async_receive_from( boost::asio::buffer(receive_buffer, receive_buffer_length), boost_from_endpoint,
asio::detail::read_write_handler(completion_promise) );
size_t bytes_read = completion_promise->wait();
from = to_fc_ep(boost_from_endpoint);
return bytes_read;
}
void udp_socket::close() {
//my->_sock.cancel();
my->_sock.close();
}
fc::ip::endpoint udp_socket::local_endpoint()const {
return to_fc_ep( my->_sock.local_endpoint() );
}
void udp_socket::connect( const fc::ip::endpoint& e ) {
my->_sock.connect( to_asio_ep(e) );
}
void udp_socket::set_multicast_enable_loopback( bool s )
{
my->_sock.set_option( boost::asio::ip::multicast::enable_loopback(s) );
}
void udp_socket::set_reuse_address( bool s )
{
my->_sock.set_option( boost::asio::ip::udp::socket::reuse_address(s) );
}
void udp_socket::join_multicast_group( const fc::ip::address& a )
{
my->_sock.set_option( boost::asio::ip::multicast::join_group( boost::asio::ip::address_v4(a) ) );
}
}
| 5,785 | 2,060 |
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
using namespace std;
void error(const char *msg)
{
perror(msg);
exit(1);
}
int main(int argc,char *argv[])
{
int sockfd,portno,n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[1024];
if(argc<3)
{
cout<<"Port Number or Host Name missing.Program terminated.\n"<<argv[0];
exit(1);
}
portno=atoi(argv[2]);
sockfd=socket(AF_INET,SOCK_STREAM,0);
if(sockfd<0)
error("ERROR opening Socket");
server=gethostbyname(argv[1]);
if(server==NULL)
{
cout<<"ERROR no such host.";
}
bzero((char*) &serv_addr,sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
bcopy((char*)server->h_addr,(char*) &serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port=htons(portno);
if(connect(sockfd,(struct sockaddr*) &serv_addr,sizeof(serv_addr))<0)
error("Connection Failed");
while(1)
{
bzero(buffer,1024);
cin.getline(buffer,1024);
n=write(sockfd,buffer,strlen(buffer));
if(n<0)
error("ERROR on Writing.");
bzero(buffer,1024);
n=read(sockfd,buffer,1024);
if(n<0)
error("ERROR on Reading.");
cout<<"Server: "<<buffer<<endl;
int i=strncmp("Bye",buffer,3);
if(i==0)
break;
}
close(sockfd);
return 0;
}
| 1,607 | 612 |
#include "tpch.h"
#include "Toast/Core/Input.h"
#include "Toast/Core/Application.h"
namespace Toast {
bool Input::IsKeyPressed(const KeyCode keycode)
{
auto state = GetAsyncKeyState(static_cast<int>(keycode));
return (state & 0x8000);
}
bool Input::IsMouseButtonPressed(const MouseCode button)
{
auto state = GetAsyncKeyState(static_cast<int>(button));
return (state & 0x8000);
}
DirectX::XMFLOAT2 Input::GetMousePosition()
{
POINT p;
GetCursorPos(&p);
return { (float)p.x, (float)p.y };
}
float Input::GetMouseX()
{
return GetMousePosition().x;
}
float Input::GetMouseY()
{
return GetMousePosition().y;
}
float Input::sMouseWheelDelta;
float Input::GetMouseWheelDelta()
{
return sMouseWheelDelta;
}
void Input::SetMouseWheelDelta(float delta)
{
sMouseWheelDelta = delta;
}
} | 834 | 345 |
// 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/profiles/profile_avatar_icon_util.h"
#include "grit/theme_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_rep.h"
#include "ui/gfx/image/image_unittest_util.h"
namespace {
// Helper function to check that the image is sized properly
// and supports multiple pixel densities.
void VerifyScaling(gfx::Image& image, gfx::Size& size) {
gfx::Size canvas_size(100, 100);
gfx::Canvas canvas(canvas_size, 1.0f, false);
gfx::Canvas canvas2(canvas_size, 2.0f, false);
ASSERT_FALSE(gfx::test::IsEmpty(image));
EXPECT_EQ(image.Size(), size);
gfx::ImageSkia image_skia = *image.ToImageSkia();
canvas.DrawImageInt(image_skia, 15, 10);
EXPECT_TRUE(image.ToImageSkia()->HasRepresentation(1.0f));
canvas2.DrawImageInt(image_skia, 15, 10);
EXPECT_TRUE(image.ToImageSkia()->HasRepresentation(2.0f));
}
TEST(ProfileInfoUtilTest, SizedMenuIcon) {
// Test that an avatar icon isn't changed.
const gfx::Image& profile_image(
ResourceBundle::GetSharedInstance().GetImageNamed(IDR_PROFILE_AVATAR_0));
gfx::Image result =
profiles::GetSizedAvatarIcon(profile_image, false, 50, 50);
EXPECT_FALSE(gfx::test::IsEmpty(result));
EXPECT_TRUE(gfx::test::IsEqual(profile_image, result));
// Test that a rectangular picture (e.g., GAIA image) is changed.
gfx::Image rect_picture(gfx::test::CreateImage());
gfx::Size size(30, 20);
gfx::Image result2 = profiles::GetSizedAvatarIcon(
rect_picture, true, size.width(), size.height());
VerifyScaling(result2, size);
}
TEST(ProfileInfoUtilTest, MenuIcon) {
// Test that an avatar icon isn't changed.
const gfx::Image& profile_image(
ResourceBundle::GetSharedInstance().GetImageNamed(IDR_PROFILE_AVATAR_0));
gfx::Image result = profiles::GetAvatarIconForMenu(profile_image, false);
EXPECT_FALSE(gfx::test::IsEmpty(result));
EXPECT_TRUE(gfx::test::IsEqual(profile_image, result));
// Test that a rectangular picture is changed.
gfx::Image rect_picture(gfx::test::CreateImage());
gfx::Size size(profiles::kAvatarIconWidth, profiles::kAvatarIconHeight);
gfx::Image result2 = profiles::GetAvatarIconForMenu(rect_picture, true);
VerifyScaling(result2, size);
}
TEST(ProfileInfoUtilTest, WebUIIcon) {
// Test that an avatar icon isn't changed.
const gfx::Image& profile_image(
ResourceBundle::GetSharedInstance().GetImageNamed(IDR_PROFILE_AVATAR_0));
gfx::Image result = profiles::GetAvatarIconForWebUI(profile_image, false);
EXPECT_FALSE(gfx::test::IsEmpty(result));
EXPECT_TRUE(gfx::test::IsEqual(profile_image, result));
// Test that a rectangular picture is changed.
gfx::Image rect_picture(gfx::test::CreateImage());
gfx::Size size(profiles::kAvatarIconWidth, profiles::kAvatarIconHeight);
gfx::Image result2 = profiles::GetAvatarIconForWebUI(rect_picture, true);
VerifyScaling(result2, size);
}
TEST(ProfileInfoUtilTest, TitleBarIcon) {
int width = 100;
int height = 40;
// Test that an avatar icon isn't changed.
const gfx::Image& profile_image(
ResourceBundle::GetSharedInstance().GetImageNamed(IDR_PROFILE_AVATAR_0));
gfx::Image result = profiles::GetAvatarIconForTitleBar(
profile_image, false, width, height);
EXPECT_FALSE(gfx::test::IsEmpty(result));
EXPECT_TRUE(gfx::test::IsEqual(profile_image, result));
// Test that a rectangular picture is changed.
gfx::Image rect_picture(gfx::test::CreateImage());
gfx::Size size(width, height);
gfx::Image result2 = profiles::GetAvatarIconForTitleBar(
rect_picture, true, width, height);
VerifyScaling(result2, size);
}
} // namespace
| 3,912 | 1,411 |
/*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
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 <stdio.h>
#include "jcomp.hpp"
#include "jfile.hpp"
#include "jlzw.hpp"
#include "jqueue.tpp"
#include "jargv.hpp"
#include "junicode.hpp"
#include "build-config.h"
#include "workunit.hpp"
#ifndef _WIN32
#include <pwd.h>
#endif
#include "hqlecl.hpp"
#include "hqlir.hpp"
#include "hqlerrors.hpp"
#include "hqlwuerr.hpp"
#include "hqlfold.hpp"
#include "hqlplugins.hpp"
#include "hqlmanifest.hpp"
#include "hqlcollect.hpp"
#include "hqlrepository.hpp"
#include "hqlerror.hpp"
#include "hqlcerrors.hpp"
#include "hqlgram.hpp"
#include "hqltrans.ipp"
#include "hqlutil.hpp"
#include "build-config.h"
#include "rmtfile.hpp"
#ifdef _USE_CPPUNIT
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#endif
//#define TEST_LEGACY_DEPENDENCY_CODE
#define INIFILE "eclcc.ini"
#define SYSTEMCONFDIR CONFIG_DIR
#define DEFAULTINIFILE "eclcc.ini"
#define SYSTEMCONFFILE ENV_CONF_FILE
#define DEFAULT_OUTPUTNAME "a.out"
//=========================================================================================
//The following flag could be used not free items to speed up closedown
static bool optDebugMemLeak = false;
#if defined(_WIN32) && defined(_DEBUG)
static HANDLE leakHandle;
static void appendLeaks(size32_t len, const void * data)
{
SetFilePointer(leakHandle, 0, 0, FILE_END);
DWORD written;
WriteFile(leakHandle, data, len, &written, 0);
}
void initLeakCheck(const char * title)
{
StringBuffer leakFilename("eclccleaks.log");
leakHandle = CreateFile(leakFilename.str(), GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, 0, 0);
if (title)
appendLeaks(strlen(title), title);
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE|_CRTDBG_MODE_DEBUG );
_CrtSetReportFile( _CRT_WARN, leakHandle );
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE|_CRTDBG_MODE_DEBUG );
_CrtSetReportFile( _CRT_ERROR, leakHandle );
_CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE|_CRTDBG_MODE_DEBUG );
_CrtSetReportFile( _CRT_ASSERT, leakHandle );
//
// set the states we want to monitor
//
int LeakTmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
LeakTmpFlag &= ~_CRTDBG_CHECK_CRT_DF;
LeakTmpFlag |= _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(LeakTmpFlag);
}
/**
* Error handler for ctrl-break: Don't care about memory leaks.
*/
void __cdecl IntHandler(int)
{
enableMemLeakChecking(false);
exit(2);
}
#include <signal.h> // for signal()
MODULE_INIT(INIT_PRIORITY_STANDARD)
{
signal(SIGINT, IntHandler);
return true;
}
#else
void initLeakCheck(const char *)
{
}
#endif // _WIN32 && _DEBUG
static bool extractOption(StringBuffer & option, IProperties * globals, const char * envName, const char * propertyName, const char * defaultPrefix, const char * defaultSuffix)
{
if (option.length()) // check if already specified via a command line option
return true;
if (globals->getProp(propertyName, option))
return true;
const char * env = getenv(envName);
if (env)
{
option.append(env);
return true;
}
option.append(defaultPrefix).append(defaultSuffix);
return false;
}
static bool extractOption(StringAttr & option, IProperties * globals, const char * envName, const char * propertyName, const char * defaultPrefix, const char * defaultSuffix)
{
if (option)
return true;
StringBuffer temp;
bool ret = extractOption(temp, globals, envName, propertyName, defaultPrefix, defaultSuffix);
option.set(temp.str());
return ret;
}
static bool getPackageFolder(StringBuffer & path)
{
StringBuffer folder;
splitDirTail(queryCurrentProcessPath(), folder);
removeTrailingPathSepChar(folder);
if (folder.length())
{
StringBuffer foldersFolder;
splitDirTail(folder.str(), foldersFolder);
if (foldersFolder.length())
{
path = foldersFolder;
return true;
}
}
return false;
}
static bool getHomeFolder(StringBuffer & homepath)
{
if (!getHomeDir(homepath))
return false;
addPathSepChar(homepath);
#ifndef WIN32
homepath.append('.');
#endif
homepath.append(DIR_NAME);
return true;
}
struct EclCompileInstance
{
public:
EclCompileInstance(IFile * _inputFile, IErrorReceiver & _errorProcessor, FILE * _errout, const char * _outputFilename, bool _legacyImport, bool _legacyWhen) :
inputFile(_inputFile), errorProcessor(&_errorProcessor), errout(_errout), outputFilename(_outputFilename)
{
legacyImport = _legacyImport;
legacyWhen = _legacyWhen;
ignoreUnknownImport = false;
fromArchive = false;
stats.parseTime = 0;
stats.generateTime = 0;
stats.xmlSize = 0;
stats.cppSize = 0;
}
void logStats();
void checkEclVersionCompatible();
bool reportErrorSummary();
inline IErrorReceiver & queryErrorProcessor() { return *errorProcessor; }
public:
Linked<IFile> inputFile;
Linked<IPropertyTree> archive;
Linked<IWorkUnit> wu;
Owned<IEclRepository> dataServer; // A member which can be cleared after parsing the query
OwnedHqlExpr query; // parsed query - cleared when generating to free memory
StringAttr eclVersion;
const char * outputFilename;
FILE * errout;
Owned<IPropertyTree> srcArchive;
Owned<IPropertyTree> generatedMeta;
bool legacyImport;
bool legacyWhen;
bool fromArchive;
bool ignoreUnknownImport;
struct {
unsigned parseTime;
unsigned generateTime;
offset_t xmlSize;
offset_t cppSize;
} stats;
protected:
Linked<IErrorReceiver> errorProcessor;
};
class EclCC : public CInterfaceOf<ICodegenContextCallback>
{
public:
EclCC(int _argc, const char **_argv)
: programName(_argv[0])
{
argc = _argc;
argv = _argv;
logVerbose = false;
logTimings = false;
optArchive = false;
optCheckEclVersion = true;
optEvaluateResult = false;
optGenerateMeta = false;
optGenerateDepend = false;
optIncludeMeta = false;
optLegacyImport = false;
optLegacyWhen = false;
optShared = false;
optWorkUnit = false;
optNoCompile = false;
optNoLogFile = false;
optNoStdInc = false;
optNoBundles = false;
optOnlyCompile = false;
optBatchMode = false;
optSaveQueryText = false;
optGenerateHeader = false;
optShowPaths = false;
optTargetClusterType = HThorCluster;
optTargetCompiler = DEFAULT_COMPILER;
optThreads = 0;
optLogDetail = 0;
batchPart = 0;
batchSplit = 1;
batchLog = NULL;
cclogFilename.append("cc.").append((unsigned)GetCurrentProcessId()).append(".log");
defaultAllowed = true;
}
bool parseCommandLineOptions(int argc, const char* argv[]);
void loadOptions();
void loadManifestOptions();
bool processFiles();
void processBatchedFile(IFile & file, bool multiThreaded);
virtual void noteCluster(const char *clusterName);
virtual void registerFile(const char * filename, const char * description);
virtual bool allowAccess(const char * category);
protected:
void addFilenameDependency(StringBuffer & target, EclCompileInstance & instance, const char * filename);
void applyApplicationOptions(IWorkUnit * wu);
void applyDebugOptions(IWorkUnit * wu);
bool checkWithinRepository(StringBuffer & attributePath, const char * sourcePathname);
IFileIO * createArchiveOutputFile(EclCompileInstance & instance);
ICppCompiler *createCompiler(const char * coreName, const char * sourceDir = NULL, const char * targetDir = NULL);
void evaluateResult(EclCompileInstance & instance);
bool generatePrecompiledHeader();
void generateOutput(EclCompileInstance & instance);
void instantECL(EclCompileInstance & instance, IWorkUnit *wu, const char * queryFullName, IErrorReceiver & errorProcessor, const char * outputFile);
bool isWithinPath(const char * sourcePathname, const char * searchPath);
void getComplexity(IWorkUnit *wu, IHqlExpression * query, IErrorReceiver & errorProcessor);
void outputXmlToOutputFile(EclCompileInstance & instance, IPropertyTree * xml);
void processSingleQuery(EclCompileInstance & instance,
IFileContents * queryContents,
const char * queryAttributePath);
void processXmlFile(EclCompileInstance & instance, const char *archiveXML);
void processFile(EclCompileInstance & info);
void processReference(EclCompileInstance & instance, const char * queryAttributePath);
void processBatchFiles();
void reportCompileErrors(IErrorReceiver & errorProcessor, const char * processName);
void setDebugOption(const char * name, bool value);
void usage();
inline const char * queryTemplateDir() { return templatePath.length() ? templatePath.str() : NULL; }
protected:
Owned<IEclRepository> pluginsRepository;
Owned<IEclRepository> libraryRepository;
Owned<IEclRepository> bundlesRepository;
Owned<IEclRepository> includeRepository;
const char * programName;
StringBuffer cppIncludePath;
StringBuffer pluginsPath;
StringBuffer hooksPath;
StringBuffer templatePath;
StringBuffer eclLibraryPath;
StringBuffer eclBundlePath;
StringBuffer stdIncludeLibraryPath;
StringBuffer includeLibraryPath;
StringBuffer compilerPath;
StringBuffer libraryPath;
StringBuffer cclogFilename;
StringAttr optLogfile;
StringAttr optIniFilename;
StringAttr optManifestFilename;
StringAttr optOutputDirectory;
StringAttr optOutputFilename;
StringAttr optQueryRepositoryReference;
FILE * batchLog;
IFileArray inputFiles;
StringArray inputFileNames;
StringArray applicationOptions;
StringArray debugOptions;
StringArray warningMappings;
StringArray compileOptions;
StringArray linkOptions;
StringArray libraryPaths;
StringArray allowedPermissions;
StringArray deniedPermissions;
bool defaultAllowed;
ClusterType optTargetClusterType;
CompilerType optTargetCompiler;
unsigned optThreads;
unsigned batchPart;
unsigned batchSplit;
unsigned optLogDetail;
bool logVerbose;
bool logTimings;
bool optArchive;
bool optCheckEclVersion;
bool optEvaluateResult;
bool optGenerateMeta;
bool optGenerateDepend;
bool optIncludeMeta;
bool optWorkUnit;
bool optNoCompile;
bool optNoLogFile;
bool optNoStdInc;
bool optNoBundles;
bool optBatchMode;
bool optShared;
bool optOnlyCompile;
bool optSaveQueryText;
bool optLegacyImport;
bool optLegacyWhen;
bool optGenerateHeader;
bool optShowPaths;
int argc;
const char **argv;
};
//=========================================================================================
static int doSelfTest(int argc, const char *argv[])
{
#ifdef _USE_CPPUNIT
queryStderrLogMsgHandler()->setMessageFields(MSGFIELD_time | MSGFIELD_prefix);
CppUnit::TextUi::TestRunner runner;
if (argc==2)
{
CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry();
runner.addTest( registry.makeTest() );
}
else
{
// MORE - maybe add a 'list' function here?
for (int name = 2; name < argc; name++)
{
if (stricmp(argv[name], "-q")==0)
{
removeLog();
}
else
{
CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry(argv[name]);
runner.addTest( registry.makeTest() );
}
}
}
bool wasSucessful = runner.run( "", false );
releaseAtoms();
return wasSucessful;
#else
return true;
#endif
}
static int doMain(int argc, const char *argv[])
{
if (argc>=2 && stricmp(argv[1], "-selftest")==0)
return doSelfTest(argc, argv);
EclCC processor(argc, argv);
if (!processor.parseCommandLineOptions(argc, argv))
return 1;
try
{
if (!processor.processFiles())
return 2;
}
catch (IException *E)
{
StringBuffer m("Error: ");
E->errorMessage(m);
fputs(m.newline().str(), stderr);
E->Release();
return 2;
}
#ifndef _DEBUG
catch (...)
{
ERRLOG("Unexpected exception\n");
return 4;
}
#endif
return 0;
}
int main(int argc, const char *argv[])
{
EnableSEHtoExceptionMapping();
setTerminateOnSEH(true);
InitModuleObjects();
queryStderrLogMsgHandler()->setMessageFields(0);
// Turn logging down (we turn it back up if -v option seen)
Owned<ILogMsgFilter> filter = getCategoryLogMsgFilter(MSGAUD_user, MSGCLS_error);
queryLogMsgManager()->changeMonitorFilter(queryStderrLogMsgHandler(), filter);
unsigned exitCode = doMain(argc, argv);
releaseAtoms();
removeFileHooks();
return exitCode;
}
//=========================================================================================
bool setTargetPlatformOption(const char *platform, ClusterType &optTargetClusterType)
{
if (!platform || !*platform)
return false;
ClusterType clusterType = getClusterType(platform);
if (clusterType == NoCluster)
{
ERRLOG("Unknown ecl target platform %s\n", platform);
return false;
}
optTargetClusterType = clusterType;
return true;
}
void EclCC::loadManifestOptions()
{
if (!optManifestFilename)
return;
Owned<IPropertyTree> mf = createPTreeFromXMLFile(optManifestFilename);
IPropertyTree *ecl = mf->queryPropTree("ecl");
if (ecl)
{
if (ecl->hasProp("@filename"))
{
StringBuffer dir, abspath;
splitDirTail(optManifestFilename, dir);
makeAbsolutePath(ecl->queryProp("@filename"), dir.str(), abspath);
processArgvFilename(inputFiles, abspath.str());
}
if (!optLegacyImport && !optLegacyWhen)
{
bool optLegacy = ecl->getPropBool("@legacy");
optLegacyImport = ecl->getPropBool("@legacyImport", optLegacy);
optLegacyWhen = ecl->getPropBool("@legacyWhen", optLegacy);
}
if (!optQueryRepositoryReference && ecl->hasProp("@main"))
optQueryRepositoryReference.set(ecl->queryProp("@main"));
if (ecl->hasProp("@targetPlatform"))
setTargetPlatformOption(ecl->queryProp("@targetPlatform"), optTargetClusterType);
else if (ecl->hasProp("@targetClusterType")) //deprecated name
setTargetPlatformOption(ecl->queryProp("@targetClusterType"), optTargetClusterType);
Owned<IPropertyTreeIterator> paths = ecl->getElements("IncludePath");
ForEach(*paths)
{
IPropertyTree &item = paths->query();
if (item.hasProp("@path"))
includeLibraryPath.append(ENVSEPCHAR).append(item.queryProp("@path"));
}
paths.setown(ecl->getElements("LibraryPath"));
ForEach(*paths)
{
IPropertyTree &item = paths->query();
if (item.hasProp("@path"))
libraryPaths.append(item.queryProp("@path"));
}
}
}
void EclCC::loadOptions()
{
Owned<IProperties> globals;
if (!optIniFilename)
{
if (checkFileExists(INIFILE))
optIniFilename.set(INIFILE);
else
{
StringBuffer fn(SYSTEMCONFDIR);
fn.append(PATHSEPSTR).append(DEFAULTINIFILE);
if (checkFileExists(fn))
optIniFilename.set(fn);
}
}
if (logVerbose && optIniFilename.length())
fprintf(stdout, "Found ini file '%s'\n", optIniFilename.get());
globals.setown(createProperties(optIniFilename, true));
if (globals->hasProp("targetGcc"))
optTargetCompiler = globals->getPropBool("targetGcc") ? GccCppCompiler : Vs6CppCompiler;
StringBuffer syspath, homepath;
if (getPackageFolder(syspath) && getHomeFolder(homepath))
{
#if _WIN32
extractOption(compilerPath, globals, "CL_PATH", "compilerPath", syspath, "componentfiles\\cl");
#else
extractOption(compilerPath, globals, "CL_PATH", "compilerPath", "/usr", NULL);
#endif
if (!extractOption(libraryPath, globals, "ECLCC_LIBRARY_PATH", "libraryPath", syspath, "lib"))
libraryPath.append(ENVSEPCHAR).append(syspath).append("plugins");
extractOption(cppIncludePath, globals, "ECLCC_INCLUDE_PATH", "includePath", syspath, "componentfiles" PATHSEPSTR "cl" PATHSEPSTR "include");
extractOption(pluginsPath, globals, "ECLCC_PLUGIN_PATH", "plugins", syspath, "plugins");
extractOption(hooksPath, globals, "HPCC_FILEHOOKS_PATH", "filehooks", syspath, "filehooks");
extractOption(templatePath, globals, "ECLCC_TPL_PATH", "templatePath", syspath, "componentfiles");
extractOption(eclLibraryPath, globals, "ECLCC_ECLLIBRARY_PATH", "eclLibrariesPath", syspath, "share" PATHSEPSTR "ecllibrary" PATHSEPSTR);
extractOption(eclBundlePath, globals, "ECLCC_ECLBUNDLE_PATH", "eclBundlesPath", homepath, PATHSEPSTR "bundles" PATHSEPSTR);
}
extractOption(stdIncludeLibraryPath, globals, "ECLCC_ECLINCLUDE_PATH", "eclIncludePath", ".", NULL);
if (!optLogfile.length() && !optBatchMode && !optNoLogFile)
extractOption(optLogfile, globals, "ECLCC_LOGFILE", "logfile", "eclcc.log", NULL);
if ((logVerbose || optLogfile) && !optNoLogFile)
{
if (optLogfile.length())
{
StringBuffer lf;
openLogFile(lf, optLogfile, optLogDetail, false);
if (logVerbose)
fprintf(stdout, "Logging to '%s'\n",lf.str());
}
}
if (hooksPath.length())
installFileHooks(hooksPath.str());
if (!optNoCompile)
setCompilerPath(compilerPath.str(), cppIncludePath.str(), libraryPath.str(), NULL, optTargetCompiler, logVerbose);
}
//=========================================================================================
void EclCC::applyDebugOptions(IWorkUnit * wu)
{
ForEachItemIn(i, debugOptions)
{
const char * option = debugOptions.item(i);
const char * eq = strchr(option, '=');
if (eq)
{
StringAttr name;
name.set(option, eq-option);
wu->setDebugValue(name, eq+1, true);
}
else
{
size_t len = strlen(option);
if (len)
{
char last = option[len-1];
if (last == '-' || last == '+')
{
StringAttr name;
name.set(option, len-1);
wu->setDebugValueInt(name, last == '+' ? 1 : 0, true);
}
else
wu->setDebugValue(option, "1", true);
}
}
}
}
void EclCC::applyApplicationOptions(IWorkUnit * wu)
{
ForEachItemIn(i, applicationOptions)
{
const char * option = applicationOptions.item(i);
const char * eq = strchr(option, '=');
if (eq)
{
StringAttr name;
name.set(option, eq-option);
wu->setApplicationValue("eclcc", name, eq+1, true);
}
else
{
wu->setApplicationValueInt("eclcc", option, 1, true);
}
}
}
//=========================================================================================
ICppCompiler * EclCC::createCompiler(const char * coreName, const char * sourceDir, const char * targetDir)
{
Owned<ICppCompiler> compiler = ::createCompiler(coreName, sourceDir, targetDir, optTargetCompiler, logVerbose);
compiler->setOnlyCompile(optOnlyCompile);
compiler->setCCLogPath(cclogFilename);
ForEachItemIn(iComp, compileOptions)
compiler->addCompileOption(compileOptions.item(iComp));
ForEachItemIn(iLink, linkOptions)
compiler->addLinkOption(linkOptions.item(iLink));
ForEachItemIn(iLib, libraryPaths)
compiler->addLibraryPath(libraryPaths.item(iLib));
return compiler.getClear();
}
void EclCC::reportCompileErrors(IErrorReceiver & errorProcessor, const char * processName)
{
StringBuffer failText;
StringBuffer absCCLogName;
if (optLogfile.get())
createUNCFilename(optLogfile.get(), absCCLogName, false);
else
absCCLogName = "log file";
failText.appendf("Compile/Link failed for %s (see '%s' for details)",processName,absCCLogName.str());
errorProcessor.reportError(ERR_INTERNALEXCEPTION, failText.toCharArray(), processName, 0, 0, 0);
try
{
StringBuffer s;
Owned<IFile> log = createIFile(cclogFilename);
Owned<IFileIO> io = log->open(IFOread);
if (io)
{
offset_t len = io->size();
if (len)
{
io->read(0, (size32_t)len, s.reserve((size32_t)len));
#ifdef _WIN32
const char * noCompiler = "is not recognized as an internal";
#else
const char * noCompiler = "could not locate compiler";
#endif
if (strstr(s.str(), noCompiler))
{
ERRLOG("Fatal Error: Unable to locate C++ compiler/linker");
}
ERRLOG("\n---------- compiler output --------------\n%s\n--------- end compiler output -----------", s.str());
}
}
}
catch (IException * e)
{
e->Release();
}
}
//=========================================================================================
void EclCC::instantECL(EclCompileInstance & instance, IWorkUnit *wu, const char * queryFullName, IErrorReceiver & errorProcessor, const char * outputFile)
{
StringBuffer processName(outputFile);
if (instance.query && containsAnyActions(instance.query))
{
try
{
const char * templateDir = queryTemplateDir();
bool optSaveTemps = wu->getDebugValueBool("saveEclTempFiles", false);
bool optSaveCpp = optSaveTemps || optNoCompile || wu->getDebugValueBool("saveCppTempFiles", false);
//New scope - testing things are linked correctly
{
Owned<IHqlExprDllGenerator> generator = createDllGenerator(&errorProcessor, processName.toCharArray(), NULL, wu, templateDir, optTargetClusterType, this, false, false);
setWorkunitHash(wu, instance.query);
if (!optShared)
wu->setDebugValueInt("standAloneExe", 1, true);
EclGenerateTarget target = optWorkUnit ? EclGenerateNone : (optNoCompile ? EclGenerateCpp : optShared ? EclGenerateDll : EclGenerateExe);
if (optManifestFilename)
generator->addManifest(optManifestFilename);
if (instance.srcArchive)
{
generator->addManifestFromArchive(instance.srcArchive);
instance.srcArchive.clear();
}
generator->setSaveGeneratedFiles(optSaveCpp);
bool generateOk = generator->processQuery(instance.query, target); // NB: May clear instance.query
instance.stats.cppSize = generator->getGeneratedSize();
if (generateOk && !optNoCompile)
{
Owned<ICppCompiler> compiler = createCompiler(processName.toCharArray());
compiler->setSaveTemps(optSaveTemps);
bool compileOk = true;
if (optShared)
{
compileOk = generator->generateDll(compiler);
}
else
{
if (optTargetClusterType==RoxieCluster)
generator->addLibrary("ccd");
else
generator->addLibrary("hthor");
compileOk = generator->generateExe(compiler);
}
if (!compileOk)
reportCompileErrors(errorProcessor, processName);
}
else
wu->setState(generateOk ? WUStateCompleted : WUStateFailed);
}
if (logVerbose)
{
switch (wu->getState())
{
case WUStateCompiled:
fprintf(stdout, "Output file '%s' created\n",outputFile);
break;
case WUStateFailed:
ERRLOG("Failed to create output file '%s'\n",outputFile);
break;
case WUStateUploadingFiles:
fprintf(stdout, "Output file '%s' created, local file upload required\n",outputFile);
break;
case WUStateCompleted:
fprintf(stdout, "No DLL/SO required\n");
break;
default:
ERRLOG("Unexpected Workunit state %d\n", (int) wu->getState());
break;
}
}
}
catch (IException * e)
{
if (e->errorCode() != HQLERR_ErrorAlreadyReported)
{
StringBuffer exceptionText;
e->errorMessage(exceptionText);
errorProcessor.reportError(ERR_INTERNALEXCEPTION, exceptionText.toCharArray(), queryFullName, 1, 0, 0);
}
e->Release();
}
try
{
Owned<IFile> log = createIFile(cclogFilename);
log->remove();
}
catch (IException * e)
{
e->Release();
}
}
}
//=========================================================================================
void EclCC::getComplexity(IWorkUnit *wu, IHqlExpression * query, IErrorReceiver & errs)
{
double complexity = getECLcomplexity(query, &errs, wu, optTargetClusterType);
LOG(MCstats, unknownJob, "Complexity = %g", complexity);
}
//=========================================================================================
static bool convertPathToModule(StringBuffer & out, const char * filename)
{
const char * dot = strrchr(filename, '.');
if (dot)
{
if (!strieq(dot, ".ecl") && !strieq(dot, ".hql") && !strieq(dot, ".eclmod") && !strieq(dot, ".eclattr"))
return false;
}
else
return false;
const unsigned copyLen = dot-filename;
if (copyLen == 0)
return false;
out.ensureCapacity(copyLen);
for (unsigned i= 0; i < copyLen; i++)
{
char next = filename[i];
if (isPathSepChar(next))
next = '.';
out.append(next);
}
return true;
}
static bool findFilenameInSearchPath(StringBuffer & attributePath, const char * searchPath, const char * expandedSourceName)
{
const char * cur = searchPath;
unsigned lenSource = strlen(expandedSourceName);
loop
{
const char * sep = strchr(cur, ENVSEPCHAR);
StringBuffer curExpanded;
if (!sep)
{
if (*cur)
makeAbsolutePath(cur, curExpanded);
}
else if (sep != cur)
{
StringAttr temp(cur, sep-cur);
makeAbsolutePath(temp, curExpanded);
}
if (curExpanded.length() && (curExpanded.length() < lenSource))
{
#ifdef _WIN32
//windows paths are case insensitive
bool same = memicmp(curExpanded.str(), expandedSourceName, curExpanded.length()) == 0;
#else
bool same = memcmp(curExpanded.str(), expandedSourceName, curExpanded.length()) == 0;
#endif
if (same)
{
const char * tail = expandedSourceName+curExpanded.length();
if (isPathSepChar(*tail))
tail++;
if (convertPathToModule(attributePath, tail))
return true;
}
}
if (!sep)
return false;
cur = sep+1;
}
}
bool EclCC::isWithinPath(const char * sourcePathname, const char * searchPath)
{
if (!sourcePathname)
return false;
StringBuffer expandedSourceName;
makeAbsolutePath(sourcePathname, expandedSourceName);
StringBuffer attributePath;
return findFilenameInSearchPath(attributePath, searchPath, expandedSourceName);
}
bool EclCC::checkWithinRepository(StringBuffer & attributePath, const char * sourcePathname)
{
if (!sourcePathname)
return false;
StringBuffer searchPath;
searchPath.append(eclLibraryPath).append(ENVSEPCHAR);
if (!optNoBundles)
searchPath.append(eclBundlePath).append(ENVSEPCHAR);
if (!optNoStdInc)
searchPath.append(stdIncludeLibraryPath).append(ENVSEPCHAR);
searchPath.append(includeLibraryPath);
StringBuffer expandedSourceName;
makeAbsolutePath(sourcePathname, expandedSourceName);
return findFilenameInSearchPath(attributePath, searchPath, expandedSourceName);
}
void EclCC::evaluateResult(EclCompileInstance & instance)
{
IHqlExpression *query = instance.query;
if (query->getOperator()==no_output)
query = query->queryChild(0);
if (query->getOperator()==no_datasetfromdictionary)
query = query->queryChild(0);
if (query->getOperator()==no_selectfields)
query = query->queryChild(0);
if (query->getOperator()==no_createdictionary)
query = query->queryChild(0);
OwnedHqlExpr folded = foldHqlExpression(instance.queryErrorProcessor(), query, NULL, HFOthrowerror|HFOloseannotations|HFOforcefold|HFOfoldfilterproject|HFOconstantdatasets);
StringBuffer out;
IValue *result = folded->queryValue();
if (result)
result->generateECL(out);
else if (folded->getOperator()==no_list)
{
out.append('[');
ForEachChild(idx, folded)
{
IHqlExpression *child = folded->queryChild(idx);
if (idx)
out.append(", ");
result = child->queryValue();
if (result)
result->generateECL(out);
else
throw MakeStringException(1, "Expression cannot be evaluated");
}
out.append(']');
}
else if (folded->getOperator()==no_inlinetable)
{
IHqlExpression *transformList = folded->queryChild(0);
if (transformList && transformList->getOperator()==no_transformlist)
{
IHqlExpression *transform = transformList->queryChild(0);
assertex(transform && transform->getOperator()==no_transform);
out.append('[');
ForEachChild(idx, transform)
{
IHqlExpression *child = transform->queryChild(idx);
assertex(child->getOperator()==no_assign);
if (idx)
out.append(", ");
result = child->queryChild(1)->queryValue();
if (result)
result->generateECL(out);
else
throw MakeStringException(1, "Expression cannot be evaluated");
}
out.append(']');
}
else
throw MakeStringException(1, "Expression cannot be evaluated");
}
else
{
#ifdef _DEBUG
EclIR::dump_ir(folded);
#endif
throw MakeStringException(1, "Expression cannot be evaluated");
}
printf("%s\n", out.str());
}
void EclCC::processSingleQuery(EclCompileInstance & instance,
IFileContents * queryContents,
const char * queryAttributePath)
{
#ifdef TEST_LEGACY_DEPENDENCY_CODE
setLegacyEclSemantics(instance.legacyImportMode, instance.legacyWhenMode);
Owned<IPropertyTree> dependencies = gatherAttributeDependencies(instance.dataServer, "");
if (dependencies)
saveXML("depends.xml", dependencies);
#endif
Owned<IErrorReceiver> wuErrs = new WorkUnitErrorReceiver(instance.wu, "eclcc");
Owned<IErrorReceiver> compoundErrs = createCompoundErrorReceiver(&instance.queryErrorProcessor(), wuErrs);
Owned<ErrorSeverityMapper> severityMapper = new ErrorSeverityMapper(*compoundErrs);
//Apply command line mappings...
ForEachItemIn(i, warningMappings)
{
if (!severityMapper->addCommandLineMapping(warningMappings.item(i)))
return;
//Preserve command line mappings in the generated archive
if (instance.archive)
instance.archive->addPropTree("OnWarning", createPTree())->setProp("@value",warningMappings.item(i));
}
//Apply preserved onwarning mappings from any source archive
if (instance.srcArchive)
{
Owned<IPropertyTreeIterator> iter = instance.srcArchive->getElements("OnWarning");
ForEach(*iter)
{
const char * option = iter->query().queryProp("@value");
if (!severityMapper->addCommandLineMapping(option))
return;
}
}
IErrorReceiver & errorProcessor = *severityMapper;
//All dlls/exes are essentially cloneable because you may be running multiple instances at once
//The only exception would be a dll created for a one-time query. (Currently handled by eclserver.)
instance.wu->setCloneable(true);
applyDebugOptions(instance.wu);
applyApplicationOptions(instance.wu);
if (optTargetCompiler != DEFAULT_COMPILER)
instance.wu->setDebugValue("targetCompiler", compilerTypeText[optTargetCompiler], true);
bool withinRepository = (queryAttributePath && *queryAttributePath);
bool syntaxChecking = instance.wu->getDebugValueBool("syntaxCheck", false);
size32_t prevErrs = errorProcessor.errCount();
unsigned startTime = msTick();
const char * sourcePathname = queryContents ? queryContents->querySourcePath()->str() : NULL;
const char * defaultErrorPathname = sourcePathname ? sourcePathname : queryAttributePath;
//The following is only here to provide information about the source file being compiled when reporting leaks
setActiveSource(instance.inputFile->queryFilename());
{
//Minimize the scope of the parse context to reduce lifetime of cached items.
HqlParseContext parseCtx(instance.dataServer, instance.archive);
if (optGenerateMeta || optIncludeMeta)
{
HqlParseContext::MetaOptions options;
options.includePublicDefinitions = instance.wu->getDebugValueBool("metaIncludePublic", true);
options.includePrivateDefinitions = instance.wu->getDebugValueBool("metaIncludePrivate", true);
options.onlyGatherRoot = instance.wu->getDebugValueBool("metaIncludeMainOnly", false);
options.includeImports = instance.wu->getDebugValueBool("metaIncludeImports", true);
options.includeExternalUses = instance.wu->getDebugValueBool("metaIncludeExternalUse", true);
options.includeExternalUses = instance.wu->getDebugValueBool("metaIncludeExternalUse", true);
options.includeLocations = instance.wu->getDebugValueBool("metaIncludeLocations", true);
options.includeJavadoc = instance.wu->getDebugValueBool("metaIncludeJavadoc", true);
parseCtx.setGatherMeta(options);
}
setLegacyEclSemantics(instance.legacyImport, instance.legacyWhen);
if (instance.archive)
{
instance.archive->setPropBool("@legacyImport", instance.legacyImport);
instance.archive->setPropBool("@legacyWhen", instance.legacyWhen);
}
parseCtx.ignoreUnknownImport = instance.ignoreUnknownImport;
try
{
HqlLookupContext ctx(parseCtx, &errorProcessor);
if (withinRepository)
{
if (instance.archive)
{
instance.archive->setProp("Query", "");
instance.archive->setProp("Query/@attributePath", queryAttributePath);
}
instance.query.setown(getResolveAttributeFullPath(queryAttributePath, LSFpublic, ctx));
if (!instance.query && !syntaxChecking && (errorProcessor.errCount() == prevErrs))
{
StringBuffer msg;
msg.append("Could not resolve attribute ").append(queryAttributePath);
errorProcessor.reportError(3, msg.str(), defaultErrorPathname, 0, 0, 0);
}
}
else
{
Owned<IHqlScope> scope = createPrivateScope();
if (instance.legacyImport)
importRootModulesToScope(scope, ctx);
instance.query.setown(parseQuery(scope, queryContents, ctx, NULL, NULL, true));
if (instance.archive)
{
StringBuffer queryText;
queryText.append(queryContents->length(), queryContents->getText());
const char * p = queryText;
if (0 == strncmp(p, (const char *)UTF8_BOM,3))
p += 3;
instance.archive->setProp("Query", p );
instance.archive->setProp("Query/@originalFilename", sourcePathname);
}
}
gatherParseWarnings(ctx.errs, instance.query, parseCtx.orphanedWarnings);
if (instance.query && !syntaxChecking && !optGenerateMeta && !optEvaluateResult)
instance.query.setown(convertAttributeToQuery(instance.query, ctx));
instance.stats.parseTime = msTick()-startTime;
if (instance.wu->getDebugValueBool("addTimingToWorkunit", true))
updateWorkunitTimeStat(instance.wu, "eclcc", "workunit", "parse time", NULL, milliToNano(instance.stats.parseTime), 1, 0);
if (optIncludeMeta || optGenerateMeta)
instance.generatedMeta.setown(parseCtx.getMetaTree());
if (optEvaluateResult && !errorProcessor.errCount() && instance.query)
evaluateResult(instance);
}
catch (IException *e)
{
StringBuffer s;
e->errorMessage(s);
errorProcessor.reportError(3, s.toCharArray(), defaultErrorPathname, 1, 0, 0);
e->Release();
}
}
//Free up the repository (and any cached expressions) as soon as the expression has been parsed
instance.dataServer.clear();
if (!syntaxChecking && (errorProcessor.errCount() == prevErrs) && (!instance.query || !containsAnyActions(instance.query)))
{
errorProcessor.reportError(3, "Query is empty", defaultErrorPathname, 1, 0, 0);
return;
}
if (instance.archive)
return;
if (syntaxChecking || optGenerateMeta || optEvaluateResult)
return;
StringBuffer targetFilename;
const char * outputFilename = instance.outputFilename;
if (!outputFilename)
{
addNonEmptyPathSepChar(targetFilename.append(optOutputDirectory));
targetFilename.append(DEFAULT_OUTPUTNAME);
}
else if (strcmp(outputFilename, "-") == 0)
targetFilename.append("stdout:");
else
addNonEmptyPathSepChar(targetFilename.append(optOutputDirectory)).append(outputFilename);
//Check if it overlaps with the source file and add .eclout if so
if (instance.inputFile)
{
const char * originalFilename = instance.inputFile->queryFilename();
if (streq(targetFilename, originalFilename))
targetFilename.append(".eclout");
}
if (errorProcessor.errCount() == prevErrs)
{
const char * queryFullName = NULL;
instantECL(instance, instance.wu, queryFullName, errorProcessor, targetFilename);
}
else
{
if (stdIoHandle(targetFilename) == -1)
{
// MORE - what about intermediate files?
#ifdef _WIN32
StringBuffer goer;
remove(goer.append(targetFilename).append(".exe"));
remove(goer.clear().append(targetFilename).append(".exe.manifest"));
#else
remove(targetFilename);
#endif
}
}
unsigned totalTime = msTick() - startTime;
instance.stats.generateTime = totalTime - instance.stats.parseTime;
if (instance.wu->getDebugValueBool("addTimingToWorkunit", true))
updateWorkunitTimeStat(instance.wu, "eclcc", "workunit", "totalTime", NULL, milliToNano(totalTime), 1, 0);
}
void EclCC::processXmlFile(EclCompileInstance & instance, const char *archiveXML)
{
instance.srcArchive.setown(createPTreeFromXMLString(archiveXML, ipt_caseInsensitive));
IPropertyTree * archiveTree = instance.srcArchive;
Owned<IPropertyTreeIterator> iter = archiveTree->getElements("Option");
ForEach(*iter)
{
IPropertyTree &item = iter->query();
instance.wu->setDebugValue(item.queryProp("@name"), item.queryProp("@value"), true);
}
const char * queryText = archiveTree->queryProp("Query");
const char * queryAttributePath = archiveTree->queryProp("Query/@attributePath");
//Takes precedence over an entry in the archive - so you can submit parts of an archive.
if (optQueryRepositoryReference)
queryAttributePath = optQueryRepositoryReference;
//The legacy mode (if specified) in the archive takes precedence - it needs to match to compile.
instance.legacyImport = archiveTree->getPropBool("@legacyMode", instance.legacyImport);
instance.legacyWhen = archiveTree->getPropBool("@legacyMode", instance.legacyWhen);
instance.legacyImport = archiveTree->getPropBool("@legacyImport", instance.legacyImport);
instance.legacyWhen = archiveTree->getPropBool("@legacyWhen", instance.legacyWhen);
//Some old archives contained imports, but no definitions of the module. This option is to allow them to compile.
//It shouldn't be needed for new archives in non-legacy mode. (But neither should it cause any harm.)
instance.ignoreUnknownImport = archiveTree->getPropBool("@ignoreUnknownImport", true);
instance.eclVersion.set(archiveTree->queryProp("@eclVersion"));
if (optCheckEclVersion)
instance.checkEclVersionCompatible();
Owned<IEclSourceCollection> archiveCollection;
if (archiveTree->getPropBool("@testRemoteInterface", false))
{
//This code is purely here for regression testing some of the classes used in the enterprise version.
Owned<IXmlEclRepository> xmlRepository = createArchiveXmlEclRepository(archiveTree);
archiveCollection.setown(createRemoteXmlEclCollection(NULL, *xmlRepository, NULL, false));
archiveCollection->checkCacheValid();
}
else
archiveCollection.setown(createArchiveEclCollection(archiveTree));
EclRepositoryArray repositories;
repositories.append(*LINK(pluginsRepository));
if (archiveTree->getPropBool("@useLocalSystemLibraries", false)) // Primarily for testing.
repositories.append(*LINK(libraryRepository));
Owned<IFileContents> contents;
StringBuffer fullPath; // Here so it doesn't get freed when leaving the else block
if (queryText || queryAttributePath)
{
const char * sourceFilename = archiveTree->queryProp("Query/@originalFilename");
Owned<ISourcePath> sourcePath = createSourcePath(sourceFilename);
contents.setown(createFileContentsFromText(queryText, sourcePath));
if (queryAttributePath && queryText && *queryText)
{
Owned<IEclSourceCollection> inputFileCollection = createSingleDefinitionEclCollection(queryAttributePath, contents);
repositories.append(*createRepository(inputFileCollection));
}
}
else
{
//This is really only useful for regression testing
const char * queryText = archiveTree->queryProp("SyntaxCheck");
const char * syntaxCheckModule = archiveTree->queryProp("SyntaxCheck/@module");
const char * syntaxCheckAttribute = archiveTree->queryProp("SyntaxCheck/@attribute");
if (!queryText || !syntaxCheckModule || !syntaxCheckAttribute)
throw MakeStringException(1, "No query found in xml");
instance.wu->setDebugValueInt("syntaxCheck", true, true);
fullPath.append(syntaxCheckModule).append('.').append(syntaxCheckAttribute);
queryAttributePath = fullPath.str();
//Create a repository with just that attribute, and place it before the archive in the resolution order.
Owned<IFileContents> contents = createFileContentsFromText(queryText, NULL);
repositories.append(*createSingleDefinitionEclRepository(syntaxCheckModule, syntaxCheckAttribute, contents));
}
repositories.append(*createRepository(archiveCollection));
instance.dataServer.setown(createCompoundRepository(repositories));
//Ensure classes are not linked by anything else
archiveCollection.clear();
repositories.kill();
processSingleQuery(instance, contents, queryAttributePath);
}
//=========================================================================================
void EclCC::processFile(EclCompileInstance & instance)
{
const char * curFilename = instance.inputFile->queryFilename();
assertex(curFilename);
Owned<ISourcePath> sourcePath = createSourcePath(curFilename);
Owned<IFileContents> queryText = createFileContentsFromFile(curFilename, sourcePath);
const char * queryTxt = queryText->getText();
if (optArchive || optGenerateDepend)
instance.archive.setown(createAttributeArchive());
instance.wu.setown(createLocalWorkUnit());
if (optSaveQueryText)
{
Owned<IWUQuery> q = instance.wu->updateQuery();
q->setQueryText(queryTxt);
}
//On a system with userECL not allowed, all compilations must be from checked-in code that has been
//deployed to the eclcc machine via other means (typically via a version-control system)
if (!allowAccess("userECL") && (!optQueryRepositoryReference || queryText->length()))
{
instance.queryErrorProcessor().reportError(HQLERR_UserCodeNotAllowed, HQLERR_UserCodeNotAllowed_Text, NULL, 1, 0, 0);
}
else if (isArchiveQuery(queryTxt))
{
instance.fromArchive = true;
processXmlFile(instance, queryTxt);
}
else
{
StringBuffer attributePath;
bool withinRepository = false;
bool inputFromStdIn = streq(curFilename, "stdin:");
//Specifying --main indicates that the query text (if present) replaces that definition
if (optQueryRepositoryReference)
{
withinRepository = true;
attributePath.clear().append(optQueryRepositoryReference);
}
else
{
withinRepository = !inputFromStdIn && checkWithinRepository(attributePath, curFilename);
}
StringBuffer expandedSourceName;
if (!inputFromStdIn)
makeAbsolutePath(curFilename, expandedSourceName);
else
expandedSourceName.append(curFilename);
EclRepositoryArray repositories;
repositories.append(*LINK(pluginsRepository));
repositories.append(*LINK(libraryRepository));
if (bundlesRepository)
repositories.append(*LINK(bundlesRepository));
//Ensure that this source file is used as the definition (in case there are potential clashes)
//Note, this will not override standard library files.
if (withinRepository)
{
//-main only overrides the definition if the query is non-empty. Otherwise use the existing text.
if (!optQueryRepositoryReference || queryText->length())
{
Owned<IEclSourceCollection> inputFileCollection = createSingleDefinitionEclCollection(attributePath, queryText);
repositories.append(*createRepository(inputFileCollection));
}
}
else
{
//Ensure that $ is valid for any file submitted - even if it isn't in the include direcotories
//Disable this for the moment when running the regression suite.
if (!optBatchMode && !withinRepository && !inputFromStdIn && !optLegacyImport)
{
//Associate the contents of the directory with an internal module called _local_directory_
//(If it was root it might override existing root symbols). $ is the only public way to get at the symbol
const char * moduleName = "_local_directory_";
IIdAtom * moduleNameId = createIdAtom(moduleName);
StringBuffer thisDirectory;
StringBuffer thisTail;
splitFilename(expandedSourceName, &thisDirectory, &thisDirectory, &thisTail, NULL);
attributePath.append(moduleName).append(".").append(thisTail);
Owned<IEclSourceCollection> inputFileCollection = createSingleDefinitionEclCollection(attributePath, queryText);
repositories.append(*createRepository(inputFileCollection));
Owned<IEclSourceCollection> directory = createFileSystemEclCollection(&instance.queryErrorProcessor(), thisDirectory, 0, 0);
Owned<IEclRepository> directoryRepository = createRepository(directory, moduleName);
Owned<IEclRepository> nested = createNestedRepository(moduleNameId, directoryRepository);
repositories.append(*LINK(nested));
}
}
repositories.append(*LINK(includeRepository));
instance.dataServer.setown(createCompoundRepository(repositories));
repositories.kill();
processSingleQuery(instance, queryText, attributePath.str());
}
if (instance.reportErrorSummary() && !instance.archive && !(optGenerateMeta && instance.generatedMeta))
return;
generateOutput(instance);
}
IFileIO * EclCC::createArchiveOutputFile(EclCompileInstance & instance)
{
StringBuffer archiveName;
if (instance.outputFilename && !streq(instance.outputFilename, "-"))
addNonEmptyPathSepChar(archiveName.append(optOutputDirectory)).append(instance.outputFilename);
else
archiveName.append("stdout:");
//Work around windows problem writing 64K to stdout if not redirected/piped
OwnedIFile ifile = createIFile(archiveName);
return ifile->open(IFOcreate);
}
void EclCC::outputXmlToOutputFile(EclCompileInstance & instance, IPropertyTree * xml)
{
OwnedIFileIO ifileio = createArchiveOutputFile(instance);
if (ifileio)
{
//Work around windows problem writing 64K to stdout if not redirected/piped
Owned<IIOStream> stream = createIOStream(ifileio.get());
Owned<IIOStream> buffered = createBufferedIOStream(stream,0x8000);
saveXML(*buffered, xml);
}
}
void EclCC::addFilenameDependency(StringBuffer & target, EclCompileInstance & instance, const char * filename)
{
if (!filename)
return;
//Ignore plugins and standard library components
if (isWithinPath(filename, pluginsPath) || isWithinPath(filename, eclLibraryPath))
return;
//Don't include the input file in the dependencies.
if (instance.inputFile)
{
const char * sourceFilename = instance.inputFile->queryFilename();
if (sourceFilename && streq(sourceFilename, filename))
return;
}
target.append(filename).newline();
}
void EclCC::generateOutput(EclCompileInstance & instance)
{
const char * outputFilename = instance.outputFilename;
if (instance.archive)
{
if (optGenerateDepend)
{
//Walk the archive, and output all filenames that aren't
//a)in a plugin b) in std.lib c) the original source file.
StringBuffer filenames;
Owned<IPropertyTreeIterator> modIter = instance.archive->getElements("Module");
ForEach(*modIter)
{
IPropertyTree * module = &modIter->query();
if (module->hasProp("@plugin"))
continue;
addFilenameDependency(filenames, instance, module->queryProp("@sourcePath"));
Owned<IPropertyTreeIterator> defIter = module->getElements("Attribute");
ForEach(*defIter)
{
IPropertyTree * definition = &defIter->query();
addFilenameDependency(filenames, instance, definition->queryProp("@sourcePath"));
}
}
OwnedIFileIO ifileio = createArchiveOutputFile(instance);
if (ifileio)
ifileio->write(0, filenames.length(), filenames.str());
}
else
{
// Output option settings
Owned<IStringIterator> debugValues = &instance.wu->getDebugValues();
ForEach (*debugValues)
{
SCMStringBuffer debugStr, valueStr;
debugValues->str(debugStr);
instance.wu->getDebugValue(debugStr.str(), valueStr);
Owned<IPropertyTree> option = createPTree("Option");
option->setProp("@name", debugStr.str());
option->setProp("@value", valueStr.str());
instance.archive->addPropTree("Option", option.getClear());
}
if (optManifestFilename)
addManifestResourcesToArchive(instance.archive, optManifestFilename);
outputXmlToOutputFile(instance, instance.archive);
}
}
if (optGenerateMeta && instance.generatedMeta)
outputXmlToOutputFile(instance, instance.generatedMeta);
if (optWorkUnit && instance.wu)
{
StringBuffer xmlFilename;
addNonEmptyPathSepChar(xmlFilename.append(optOutputDirectory));
if (outputFilename)
xmlFilename.append(outputFilename);
else
xmlFilename.append(DEFAULT_OUTPUTNAME);
xmlFilename.append(".xml");
exportWorkUnitToXMLFile(instance.wu, xmlFilename, 0, true, false);
}
}
void EclCC::processReference(EclCompileInstance & instance, const char * queryAttributePath)
{
const char * outputFilename = instance.outputFilename;
instance.wu.setown(createLocalWorkUnit());
if (optArchive || optGenerateDepend)
instance.archive.setown(createAttributeArchive());
EclRepositoryArray repositories;
repositories.append(*LINK(pluginsRepository));
repositories.append(*LINK(libraryRepository));
if (bundlesRepository)
repositories.append(*LINK(bundlesRepository));
repositories.append(*LINK(includeRepository));
instance.dataServer.setown(createCompoundRepository(repositories));
processSingleQuery(instance, NULL, queryAttributePath);
if (instance.reportErrorSummary())
return;
generateOutput(instance);
}
bool EclCC::generatePrecompiledHeader()
{
if (inputFiles.ordinality() != 0)
{
ERRLOG("No input files should be specified when generating precompiled header");
return false;
}
StringArray paths;
paths.appendList(cppIncludePath, ENVSEPSTR);
const char *foundPath = NULL;
ForEachItemIn(idx, paths)
{
StringBuffer fullpath;
fullpath.append(paths.item(idx));
addPathSepChar(fullpath).append("eclinclude4.hpp");
if (checkFileExists(fullpath))
{
foundPath = paths.item(idx);
break;
}
}
if (!foundPath)
{
ERRLOG("Cannot find eclinclude4.hpp");
return false;
}
Owned<ICppCompiler> compiler = createCompiler("eclinclude4.hpp", foundPath, NULL);
compiler->setDebug(true); // a precompiled header with debug can be used for no-debug, but not vice versa
compiler->setPrecompileHeader(true);
if (compiler->compile())
{
try
{
Owned<IFile> log = createIFile(cclogFilename);
log->remove();
}
catch (IException * e)
{
e->Release();
}
return true;
}
else
{
ERRLOG("Compilation failed - see %s for details", cclogFilename.str());
return false;
}
}
bool EclCC::processFiles()
{
loadOptions();
ForEachItemIn(idx, inputFileNames)
{
processArgvFilename(inputFiles, inputFileNames.item(idx));
}
if (optShowPaths)
{
printf("CL_PATH=%s\n", compilerPath.str());
printf("ECLCC_ECLBUNDLE_PATH=%s\n", eclBundlePath.str());
printf("ECLCC_ECLINCLUDE_PATH=%s\n", stdIncludeLibraryPath.str());
printf("ECLCC_ECLLIBRARY_PATH=%s\n", eclLibraryPath.str());
printf("ECLCC_INCLUDE_PATH=%s\n", cppIncludePath.str());
printf("ECLCC_LIBRARY_PATH=%s\n", libraryPath.str());
printf("ECLCC_PLUGIN_PATH=%s\n", pluginsPath.str());
printf("ECLCC_TPL_PATH=%s\n", templatePath.str());
printf("HPCC_FILEHOOKS_PATH=%s\n", hooksPath.str());
return true;
}
if (optGenerateHeader)
{
return generatePrecompiledHeader();
}
else if (inputFiles.ordinality() == 0)
{
if (optBatchMode || !optQueryRepositoryReference)
{
ERRLOG("No input files could be opened");
return false;
}
}
StringBuffer searchPath;
if (!optNoStdInc)
searchPath.append(stdIncludeLibraryPath).append(ENVSEPCHAR);
searchPath.append(includeLibraryPath);
Owned<IErrorReceiver> errs = createFileErrorReceiver(stderr);
pluginsRepository.setown(createNewSourceFileEclRepository(errs, pluginsPath.str(), ESFallowplugins, logVerbose ? PLUGIN_DLL_MODULE : 0));
if (!optNoBundles)
bundlesRepository.setown(createNewSourceFileEclRepository(errs, eclBundlePath.str(), 0, 0));
libraryRepository.setown(createNewSourceFileEclRepository(errs, eclLibraryPath.str(), 0, 0));
includeRepository.setown(createNewSourceFileEclRepository(errs, searchPath.str(), 0, 0));
//Ensure symbols for plugins are initialised - see comment before CHqlMergedScope...
// lookupAllRootDefinitions(pluginsRepository);
bool ok = true;
if (optBatchMode)
{
processBatchFiles();
}
else if (inputFiles.ordinality() == 0)
{
assertex(optQueryRepositoryReference);
EclCompileInstance info(NULL, *errs, stderr, optOutputFilename, optLegacyImport, optLegacyWhen);
processReference(info, optQueryRepositoryReference);
ok = (errs->errCount() == 0);
info.logStats();
}
else
{
EclCompileInstance info(&inputFiles.item(0), *errs, stderr, optOutputFilename, optLegacyImport, optLegacyWhen);
processFile(info);
ok = (errs->errCount() == 0);
info.logStats();
}
if (logTimings)
{
StringBuffer s;
fprintf(stderr, "%s", defaultTimer->getTimings(s).str());
}
return ok;
}
void EclCC::setDebugOption(const char * name, bool value)
{
StringBuffer temp;
temp.append(name).append("=").append(value ? "1" : "0");
debugOptions.append(temp);
}
void EclCompileInstance::checkEclVersionCompatible()
{
//Strange function that might modify errorProcessor...
::checkEclVersionCompatible(errorProcessor, eclVersion);
}
void EclCompileInstance::logStats()
{
if (wu && wu->getDebugValueBool("logCompileStats", false))
{
memsize_t peakVm, peakResident;
getPeakMemUsage(peakVm, peakResident);
//Stats: added as a prefix so it is easy to grep, and a comma so can be read as a csv list.
DBGLOG("Stats:,parse,%u,generate,%u,peakmem,%u,xml,%"I64F"u,cpp,%"I64F"u",
stats.parseTime, stats.generateTime, (unsigned)(peakResident / 0x100000),
(unsigned __int64)stats.xmlSize, (unsigned __int64)stats.cppSize);
}
}
bool EclCompileInstance::reportErrorSummary()
{
if (errorProcessor->errCount() || errorProcessor->warnCount())
{
fprintf(errout, "%d error%s, %d warning%s\n", errorProcessor->errCount(), errorProcessor->errCount()<=1 ? "" : "s",
errorProcessor->warnCount(), errorProcessor->warnCount()<=1?"":"s");
}
return errorProcessor->errCount() != 0;
}
//=========================================================================================
void EclCC::noteCluster(const char *clusterName)
{
}
void EclCC::registerFile(const char * filename, const char * description)
{
}
bool EclCC::allowAccess(const char * category)
{
ForEachItemIn(idx1, deniedPermissions)
{
if (stricmp(deniedPermissions.item(idx1), category)==0)
return false;
}
ForEachItemIn(idx2, allowedPermissions)
{
if (stricmp(allowedPermissions.item(idx2), category)==0)
return true;
}
return defaultAllowed;
}
//=========================================================================================
bool EclCC::parseCommandLineOptions(int argc, const char* argv[])
{
if (argc < 2)
{
usage();
return false;
}
ArgvIterator iter(argc, argv);
StringAttr tempArg;
bool tempBool;
bool showHelp = false;
for (; !iter.done(); iter.next())
{
const char * arg = iter.query();
if (iter.matchFlag(tempArg, "-a"))
{
applicationOptions.append(tempArg);
}
else if (iter.matchOption(tempArg, "--allow"))
{
allowedPermissions.append(tempArg);
}
else if (iter.matchFlag(optBatchMode, "-b"))
{
}
else if (iter.matchOption(tempArg, "-brk"))
{
#if defined(_WIN32) && defined(_DEBUG)
unsigned id = atoi(tempArg);
if (id == 0)
DebugBreak();
else
_CrtSetBreakAlloc(id);
#endif
}
else if (iter.matchFlag(optOnlyCompile, "-c"))
{
}
else if (iter.matchFlag(optCheckEclVersion, "-checkVersion"))
{
}
else if (iter.matchOption(tempArg, "--deny"))
{
if (stricmp(tempArg, "all")==0)
defaultAllowed = false;
else
deniedPermissions.append(tempArg);
}
else if (iter.matchFlag(optArchive, "-E"))
{
}
else if (iter.matchFlag(tempArg, "-f"))
{
debugOptions.append(tempArg);
}
else if (iter.matchFlag(tempBool, "-g"))
{
if (tempBool)
{
debugOptions.append("debugQuery");
debugOptions.append("saveCppTempFiles");
}
else
debugOptions.append("debugQuery=0");
}
else if (strcmp(arg, "-internal")==0)
{
testHqlInternals();
}
else if (iter.matchFlag(tempBool, "-save-cpps"))
{
setDebugOption("saveCppTempFiles", tempBool);
}
else if (iter.matchFlag(tempBool, "-save-temps"))
{
setDebugOption("saveEclTempFiles", tempBool);
}
else if (iter.matchFlag(showHelp, "-help") || iter.matchFlag(showHelp, "--help"))
{
}
else if (iter.matchPathFlag(includeLibraryPath, "-I"))
{
}
else if (iter.matchFlag(tempArg, "-L"))
{
libraryPaths.append(tempArg);
}
else if (iter.matchFlag(tempBool, "-legacy"))
{
optLegacyImport = tempBool;
optLegacyWhen = tempBool;
}
else if (iter.matchFlag(optLegacyImport, "-legacyimport"))
{
}
else if (iter.matchFlag(optLegacyWhen, "-legacywhen"))
{
}
else if (iter.matchOption(optLogfile, "--logfile"))
{
}
else if (iter.matchFlag(optNoLogFile, "--nologfile"))
{
}
else if (iter.matchFlag(optNoStdInc, "--nostdinc"))
{
}
else if (iter.matchFlag(optNoBundles, "--nobundles"))
{
}
else if (iter.matchOption(optLogDetail, "--logdetail"))
{
}
else if (iter.matchOption(optQueryRepositoryReference, "-main"))
{
}
else if (iter.matchFlag(optDebugMemLeak, "-m"))
{
}
else if (iter.matchFlag(optIncludeMeta, "-meta"))
{
}
else if (iter.matchFlag(optGenerateMeta, "-M"))
{
}
else if (iter.matchFlag(optGenerateDepend, "-Md"))
{
}
else if (iter.matchFlag(optEvaluateResult, "-Me"))
{
}
else if (iter.matchFlag(optOutputFilename, "-o"))
{
}
else if (iter.matchFlag(optOutputDirectory, "-P"))
{
}
else if (iter.matchFlag(optGenerateHeader, "-pch"))
{
}
else if (iter.matchFlag(optSaveQueryText, "-q"))
{
}
else if (iter.matchFlag(optNoCompile, "-S"))
{
}
else if (iter.matchFlag(optShared, "-shared"))
{
}
else if (iter.matchFlag(tempBool, "-syntax"))
{
setDebugOption("syntaxCheck", tempBool);
}
else if (iter.matchOption(optIniFilename, "-specs"))
{
if (!checkFileExists(optIniFilename))
{
ERRLOG("Error: INI file '%s' does not exist",optIniFilename.get());
return false;
}
}
else if (iter.matchFlag(optShowPaths, "-showpaths"))
{
}
else if (iter.matchOption(optManifestFilename, "-manifest"))
{
if (!isManifestFileValid(optManifestFilename))
return false;
}
else if (iter.matchOption(tempArg, "-split"))
{
batchPart = atoi(tempArg)-1;
const char * split = strchr(tempArg, ':');
if (!split)
{
ERRLOG("Error: syntax is -split=part:splits\n");
return false;
}
batchSplit = atoi(split+1);
if (batchSplit == 0)
batchSplit = 1;
if (batchPart >= batchSplit)
batchPart = 0;
}
else if (iter.matchFlag(logTimings, "--timings"))
{
}
else if (iter.matchOption(tempArg, "-platform") || /*deprecated*/ iter.matchOption(tempArg, "-target"))
{
if (!setTargetPlatformOption(tempArg.get(), optTargetClusterType))
return false;
}
else if (iter.matchFlag(logVerbose, "-v") || iter.matchFlag(logVerbose, "--verbose"))
{
Owned<ILogMsgFilter> filter = getDefaultLogMsgFilter();
queryLogMsgManager()->changeMonitorFilter(queryStderrLogMsgHandler(), filter);
}
else if (strcmp(arg, "--version")==0)
{
fprintf(stdout,"%s %s\n", LANGUAGE_VERSION, BUILD_TAG);
return false;
}
else if (startsWith(arg, "-Wc,"))
{
expandCommaList(compileOptions, arg+4);
}
else if (startsWith(arg, "-Wl,"))
{
//Pass these straight through to the linker - with -Wl, prefix removed
linkOptions.append(arg+4);
}
else if (startsWith(arg, "-Wp,") || startsWith(arg, "-Wa,"))
{
//Pass these straight through to the gcc compiler
compileOptions.append(arg);
}
else if (iter.matchFlag(optWorkUnit, "-wu"))
{
}
else if (iter.matchFlag(tempArg, "-w"))
{
//Any other option beginning -wxxx are treated as warning mappings
warningMappings.append(tempArg);
}
else if (strcmp(arg, "-")==0)
{
inputFileNames.append("stdin:");
}
else if (arg[0] == '-')
{
ERRLOG("Error: unrecognised option %s",arg);
usage();
return false;
}
else
inputFileNames.append(arg);
}
if (showHelp)
{
usage();
return false;
}
// Option post processing follows:
if (optArchive || optWorkUnit || optGenerateMeta || optGenerateDepend || optShowPaths)
optNoCompile = true;
loadManifestOptions();
if (inputFileNames.ordinality() == 0)
{
if (optGenerateHeader || optShowPaths || (!optBatchMode && optQueryRepositoryReference))
return true;
ERRLOG("No input filenames supplied");
return false;
}
if (optDebugMemLeak)
{
StringBuffer title;
title.append(inputFileNames.item(0)).newline();
initLeakCheck(title);
}
return true;
}
//=========================================================================================
// Exclamation in the first column indicates it is only part of the verbose output
const char * const helpText[] = {
"",
"Usage:",
" eclcc <options> queryfile.ecl",
"",
"General options:",
" -I <path> Add path to locations to search for ecl imports",
" -L <path> Add path to locations to search for system libraries",
" -o <file> Specify name of output file (default a.out if linking to",
" executable, or stdout)",
" -manifest Specify path to manifest file listing resources to add",
" -foption[=value] Set an ecl option (#option)",
" -main <ref> Compile definition <ref> from the source collection",
" -syntax Perform a syntax check of the ECL",
" -platform=hthor Generate code for hthor executable (default)",
" -platform=roxie Generate code for roxie cluster",
" -platform=thor Generate code for thor cluster",
"",
"Output control options",
" -E Output preprocessed ECL in xml archive form",
"! -M Output meta information for the ecl files",
"! -Md Output dependency information",
"! -Me eclcc should evaluate supplied ecl code rather than generating a workunit",
" -q Save ECL query text as part of workunit",
" -wu Only generate workunit information as xml file",
"",
"c++ options",
" -S Generate c++ output, but don't compile",
"! -c compile only (don't link)",
" -g Enable debug symbols in generated code",
" -Wc,xx Pass option xx to the c++ compiler",
"! -Wl,xx Pass option xx to the linker",
"! -Wa,xx Passed straight through to c++ compiler",
"! -Wp,xx Passed straight through to c++ compiler",
"! -save-cpps Do not delete generated c++ files (implied if -g)",
"! -save-temps Do not delete intermediate files",
" -shared Generate workunit shared object instead of a stand-alone exe",
"",
"Other options:",
"! -aoption[=value] Set an application option",
"! --allow=str Allow use of named feature",
"! -b Batch mode. Each source file is processed in turn. Output",
"! name depends on the input filename",
"! -checkVersion Enable/disable ecl version checking from archives",
#ifdef _WIN32
"! -brk <n> Trigger a break point in eclcc after nth allocation",
#endif
"! --deny=all Disallow use of all named features not specifically allowed using --allow",
"! --deny=str Disallow use of named feature",
" -help, --help Display this message",
" -help -v Display verbose help message",
"! -internal Run internal tests",
"! -legacy Use legacy import and when semantics (deprecated)",
"! -legacyimport Use legacy import semantics (deprecated)",
"! -legacywhen Use legacy when/side-effects semantics (deprecated)",
" --logfile <file> Write log to specified file",
"! --logdetail=n Set the level of detail in the log file",
"! --nologfile Do not write any logfile",
#ifdef _WIN32
"! -m Enable leak checking",
#endif
#ifndef _WIN32
"! -pch Generate precompiled header for eclinclude4.hpp",
#endif
"! -P <path> Specify the path of the output files (only with -b option)",
"! -showpaths Print information about the searchpaths eclcc is using",
" -specs file Read eclcc configuration from specified file",
"! -split m:n Process a subset m of n input files (only with -b option)",
" -v --verbose Output additional tracing information while compiling",
" -wcode=level Set the severity for a particular warning code",
"! level=ignore|log|warning|error|fail",
" --version Output version information",
"! --timings Output additional timing information",
"!",
"!#options",
"! -factivitiesPerCpp Number of activities in each c++ file",
"! (requires -fspanMultipleCpp)",
"! -fapplyInstantEclTransformations Limit non file outputs with a CHOOSEN",
"! -fapplyInstantEclTransformationsLimit Number of records to limit to",
"! -fcheckAsserts Check ASSERT() statements",
"! -fmaxCompileThreads Number of compiler instances to compile the c++",
"! -fnoteRecordSizeInGraph Add estimates of record sizes to the graph",
"! -fpickBestEngine Allow simple thor queries to be passed to thor",
"! -fshowActivitySizeInGraph Show estimates of generated c++ size in the graph",
"! -fshowMetaInGraph Add distribution/sort orders to the graph",
"! -fshowRecordCountInGraph Show estimates of record counts in the graph",
"! -fspanMultipleCpp Generate a work unit in multiple c++ files",
"",
};
void EclCC::usage()
{
for (unsigned line=0; line < _elements_in(helpText); line++)
{
const char * text = helpText[line];
if (*text == '!')
{
if (logVerbose)
{
//Allow conditional headers
if (text[1] == ' ')
fprintf(stdout, " %s\n", text+1);
else
fprintf(stdout, "%s\n", text+1);
}
}
else
fprintf(stdout, "%s\n", text);
}
}
//=========================================================================================
// The following methods are concerned with running eclcc in batch mode (primarily to aid regression testing)
void EclCC::processBatchedFile(IFile & file, bool multiThreaded)
{
StringBuffer basename, logFilename, xmlFilename, outFilename;
splitFilename(file.queryFilename(), NULL, NULL, &basename, &basename);
addNonEmptyPathSepChar(logFilename.append(optOutputDirectory)).append(basename).append(".log");
addNonEmptyPathSepChar(xmlFilename.append(optOutputDirectory)).append(basename).append(".xml");
splitFilename(file.queryFilename(), NULL, NULL, &outFilename, &outFilename);
unsigned startTime = msTick();
FILE * logFile = fopen(logFilename.str(), "w");
if (!logFile)
throw MakeStringException(99, "couldn't create log output %s", logFilename.str());
Owned<ILogMsgHandler> handler;
try
{
// Print compiler and arguments to help reproduce problems
for (int i=0; i<argc; i++)
fprintf(logFile, "%s ", argv[i]);
fprintf(logFile, "\n");
fprintf(logFile, "--- %s --- \n", basename.str());
{
if (!multiThreaded)
{
handler.setown(getHandleLogMsgHandler(logFile, 0, false));
Owned<ILogMsgFilter> filter = getCategoryLogMsgFilter(MSGAUD_all, MSGCLS_all, DefaultDetail);
queryLogMsgManager()->addMonitor(handler, filter);
resetUniqueId();
resetLexerUniqueNames();
}
Owned<IErrorReceiver> localErrs = createFileErrorReceiver(logFile);
EclCompileInstance info(&file, *localErrs, logFile, outFilename, optLegacyImport, optLegacyWhen);
processFile(info);
//Following only produces output if the system has been compiled with TRANSFORM_STATS defined
dbglogTransformStats(true);
if (info.wu &&
(info.wu->getDebugValueBool("generatePartialOutputOnError", false) || info.queryErrorProcessor().errCount() == 0))
{
exportWorkUnitToXMLFile(info.wu, xmlFilename, XML_NoBinaryEncode64, true, false);
Owned<IFile> xml = createIFile(xmlFilename);
info.stats.xmlSize = xml->size();
}
info.logStats();
}
}
catch (IException * e)
{
StringBuffer s;
e->errorMessage(s);
e->Release();
fprintf(logFile, "Unexpected exception: %s", s.str());
}
if (handler)
{
queryLogMsgManager()->removeMonitor(handler);
handler.clear();
}
fflush(logFile);
fclose(logFile);
unsigned nowTime = msTick();
StringBuffer s;
s.append(basename).append(":");
s.padTo(50);
s.appendf("%8d ms\n", nowTime-startTime);
fprintf(batchLog, "%s", s.str());
// fflush(batchLog);
}
typedef SafeQueueOf<IFile, true> RegressQueue;
class BatchThread : public Thread
{
public:
BatchThread(EclCC & _compiler, RegressQueue & _queue, Semaphore & _fileReady)
: compiler(_compiler), queue(_queue), fileReady(_fileReady)
{
}
virtual int run()
{
loop
{
fileReady.wait();
IFile * next = queue.dequeue();
if (!next)
return 0;
compiler.processBatchedFile(*next, true);
next->Release();
}
}
protected:
EclCC & compiler;
RegressQueue & queue;
Semaphore & fileReady;
};
int compareFilenames(IInterface * * pleft, IInterface * * pright)
{
IFile * left = static_cast<IFile *>(*pleft);
IFile * right = static_cast<IFile *>(*pright);
return stricmp(pathTail(left->queryFilename()), pathTail(right->queryFilename()));
}
void EclCC::processBatchFiles()
{
Thread * * threads = NULL;
RegressQueue queue;
Semaphore fileReady;
unsigned startAllTime = msTick();
if (optThreads > 0)
{
threads = new Thread * [optThreads];
for (unsigned i = 0; i < optThreads; i++)
{
threads[i] = new BatchThread(*this, queue, fileReady);
threads[i]->start();
}
}
StringBuffer batchLogName;
addNonEmptyPathSepChar(batchLogName.append(optOutputDirectory)).append("_batch_.");
batchLogName.append(batchPart+1);
batchLogName.append(".log");
batchLog = fopen(batchLogName.str(), "w");
if (!batchLog)
throw MakeStringException(99, "couldn't create log output %s", batchLogName.str());
//Divide the files up based on file size, rather than name
inputFiles.sort(compareFilenames);
unsigned __int64 totalSize = 0;
ForEachItemIn(iSize, inputFiles)
{
IFile & cur = inputFiles.item(iSize);
totalSize += cur.size();
}
//Sort the filenames so you have a consistent order between windows and linux
unsigned __int64 averageFileSize = totalSize / inputFiles.ordinality();
unsigned splitter = 0;
unsigned __int64 sizeSoFar = 0;
ForEachItemIn(i, inputFiles)
{
IFile &file = inputFiles.item(i);
if (splitter == batchPart)
{
if (optThreads > 0)
{
queue.enqueue(LINK(&file));
fileReady.signal();
}
else
processBatchedFile(file, false);
}
unsigned __int64 thisSize = file.size();
sizeSoFar += thisSize;
if (sizeSoFar > averageFileSize)
{
sizeSoFar = 0;
splitter++;
}
if (splitter == batchSplit)
splitter = 0;
}
if (optThreads > 0)
{
for (unsigned i = 0; i < optThreads; i++)
fileReady.signal();
for (unsigned j = 0; j < optThreads; j++)
threads[j]->join();
for (unsigned i2 = 0; i2 < optThreads; i2++)
threads[i2]->Release();
delete [] threads;
}
fprintf(batchLog, "@%5ds total time for part %d\n", (msTick()-startAllTime)/1000, batchPart);
fclose(batchLog);
batchLog = NULL;
}
| 81,261 | 23,326 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device/fido/auth_token_requester.h"
#include <set>
#include <utility>
#include "base/bind.h"
#include "base/containers/contains.h"
#include "base/logging.h"
#include "base/stl_util.h"
#include "base/strings/utf_string_conversions.h"
#include "components/device_event_log/device_event_log.h"
#include "device/fido/authenticator_supported_options.h"
#include "device/fido/fido_authenticator.h"
#include "device/fido/fido_constants.h"
namespace device {
using ClientPinAvailability =
AuthenticatorSupportedOptions::ClientPinAvailability;
using UserVerificationAvailability =
AuthenticatorSupportedOptions::UserVerificationAvailability;
using BioEnrollmentAvailability =
AuthenticatorSupportedOptions::BioEnrollmentAvailability;
AuthTokenRequester::Delegate::~Delegate() = default;
AuthTokenRequester::Options::Options() = default;
AuthTokenRequester::Options::Options(Options&&) = default;
AuthTokenRequester::Options& AuthTokenRequester::Options::operator=(Options&&) =
default;
AuthTokenRequester::Options::~Options() = default;
AuthTokenRequester::AuthTokenRequester(Delegate* delegate,
FidoAuthenticator* authenticator,
Options options)
: delegate_(delegate),
authenticator_(authenticator),
options_(std::move(options)),
internal_uv_locked_(options_.internal_uv_locked) {
DCHECK(delegate_);
DCHECK(authenticator_);
DCHECK(authenticator_->Options());
DCHECK(!options_.token_permissions.empty());
DCHECK(!options_.rp_id || !options_.rp_id->empty());
// Authenticators with CTAP2.0-style pinToken support only support certain
// default permissions.
DCHECK(
authenticator_->Options()->supports_pin_uv_auth_token ||
base::STLSetDifference<std::set<pin::Permissions>>(
options_.token_permissions,
std::set<pin::Permissions>{pin::Permissions::kMakeCredential,
pin::Permissions::kGetAssertion,
pin::Permissions::kBioEnrollment,
pin::Permissions::kCredentialManagement})
.empty());
}
AuthTokenRequester::~AuthTokenRequester() = default;
void AuthTokenRequester::ObtainPINUVAuthToken() {
if (authenticator_->Options()->supports_pin_uv_auth_token) {
// Only attempt to obtain a token through internal UV if the authenticator
// supports CTAP 2.1 pinUvAuthTokens. If it does not, it could be a 2.0
// authenticator that supports UV without any sort of token.
const UserVerificationAvailability user_verification_availability =
authenticator_->Options()->user_verification_availability;
switch (user_verification_availability) {
case UserVerificationAvailability::kNotSupported:
case UserVerificationAvailability::kSupportedButNotConfigured:
// Try PIN first.
break;
case UserVerificationAvailability::kSupportedAndConfigured:
ObtainTokenFromInternalUV();
return;
}
}
const ClientPinAvailability client_pin_availability =
authenticator_->Options()->client_pin_availability;
switch (client_pin_availability) {
case ClientPinAvailability::kNotSupported:
delegate_->HavePINUVAuthTokenResultForAuthenticator(
authenticator_, Result::kPreTouchUnsatisfiableRequest, absl::nullopt);
return;
case ClientPinAvailability::kSupportedAndPinSet:
if (options_.skip_pin_touch) {
ObtainTokenFromPIN();
return;
}
authenticator_->GetTouch(base::BindOnce(
&AuthTokenRequester::ObtainTokenFromPIN, weak_factory_.GetWeakPtr()));
return;
case ClientPinAvailability::kSupportedButPinNotSet:
if (options_.skip_pin_touch) {
ObtainTokenFromNewPIN();
return;
}
authenticator_->GetTouch(
base::BindOnce(&AuthTokenRequester::ObtainTokenFromNewPIN,
weak_factory_.GetWeakPtr()));
return;
}
}
void AuthTokenRequester::ObtainTokenFromInternalUV() {
authenticator_->GetUvRetries(base::BindOnce(
&AuthTokenRequester::OnGetUVRetries, weak_factory_.GetWeakPtr()));
}
void AuthTokenRequester::OnGetUVRetries(
CtapDeviceResponseCode status,
absl::optional<pin::RetriesResponse> response) {
if (status != CtapDeviceResponseCode::kSuccess) {
delegate_->HavePINUVAuthTokenResultForAuthenticator(
authenticator_, Result::kPreTouchAuthenticatorResponseInvalid,
absl::nullopt);
return;
}
internal_uv_locked_ = response->retries == 0;
if (response->retries == 0) {
// The authenticator was locked prior to calling
// ObtainTokenFromInternalUV(). Fall back to PIN if able.
if (authenticator_->Options()->client_pin_availability ==
ClientPinAvailability::kSupportedAndPinSet) {
if (options_.skip_pin_touch) {
ObtainTokenFromPIN();
return;
}
authenticator_->GetTouch(base::BindOnce(
&AuthTokenRequester::ObtainTokenFromPIN, weak_factory_.GetWeakPtr()));
return;
}
authenticator_->GetTouch(base::BindOnce(
&AuthTokenRequester::NotifyAuthenticatorSelectedAndFailWithResult,
weak_factory_.GetWeakPtr(),
Result::kPostTouchAuthenticatorInternalUVLock));
return;
}
if (is_internal_uv_retry_) {
delegate_->PromptForInternalUVRetry(response->retries);
}
authenticator_->GetUvToken({std::begin(options_.token_permissions),
std::end(options_.token_permissions)},
options_.rp_id,
base::BindOnce(&AuthTokenRequester::OnGetUVToken,
weak_factory_.GetWeakPtr()));
}
void AuthTokenRequester::OnGetUVToken(
CtapDeviceResponseCode status,
absl::optional<pin::TokenResponse> response) {
if (!base::Contains(
std::set<CtapDeviceResponseCode>{
CtapDeviceResponseCode::kCtap2ErrUvInvalid,
CtapDeviceResponseCode::kCtap2ErrOperationDenied,
CtapDeviceResponseCode::kCtap2ErrUvBlocked,
CtapDeviceResponseCode::kSuccess},
status)) {
// The request was rejected outright, no touch occurred.
FIDO_LOG(ERROR) << "Ignoring status " << static_cast<int>(status)
<< " from " << authenticator_->GetDisplayName();
delegate_->HavePINUVAuthTokenResultForAuthenticator(
authenticator_, Result::kPreTouchAuthenticatorResponseInvalid,
absl::nullopt);
return;
}
if (!NotifyAuthenticatorSelected()) {
return;
}
if (status == CtapDeviceResponseCode::kCtap2ErrOperationDenied) {
// The user explicitly denied to the operation on an authenticator with
// a display.
delegate_->HavePINUVAuthTokenResultForAuthenticator(
authenticator_, Result::kPostTouchAuthenticatorOperationDenied,
absl::nullopt);
return;
}
if (status == CtapDeviceResponseCode::kCtap2ErrUvInvalid) {
// The attempt failed, but a retry is possible.
is_internal_uv_retry_ = true;
ObtainTokenFromInternalUV();
return;
}
if (status == CtapDeviceResponseCode::kCtap2ErrUvBlocked) {
// Fall back to PIN if able.
if (authenticator_->Options()->client_pin_availability ==
ClientPinAvailability::kSupportedAndPinSet) {
internal_uv_locked_ = true;
ObtainTokenFromPIN();
return;
}
// This can be returned pre-touch if the authenticator was already locked at
// the time GetUvToken() was called. However, we checked the number of
// remaining retries just before that to handle that case.
delegate_->HavePINUVAuthTokenResultForAuthenticator(
authenticator_, Result::kPostTouchAuthenticatorInternalUVLock,
absl::nullopt);
return;
}
DCHECK_EQ(status, CtapDeviceResponseCode::kSuccess);
delegate_->HavePINUVAuthTokenResultForAuthenticator(
authenticator_, Result::kSuccess, *response);
}
void AuthTokenRequester::ObtainTokenFromPIN() {
if (NotifyAuthenticatorSelected()) {
authenticator_->GetPinRetries(base::BindOnce(
&AuthTokenRequester::OnGetPINRetries, weak_factory_.GetWeakPtr()));
}
}
void AuthTokenRequester::OnGetPINRetries(
CtapDeviceResponseCode status,
absl::optional<pin::RetriesResponse> response) {
if (status != CtapDeviceResponseCode::kSuccess) {
delegate_->HavePINUVAuthTokenResultForAuthenticator(
authenticator_, Result::kPostTouchAuthenticatorResponseInvalid,
absl::nullopt);
return;
}
if (response->retries == 0) {
delegate_->HavePINUVAuthTokenResultForAuthenticator(
authenticator_, Result::kPostTouchAuthenticatorPINHardLock,
absl::nullopt);
return;
}
pin_retries_ = response->retries;
pin::PINEntryError error;
if (pin_invalid_) {
pin_invalid_ = false;
error = pin::PINEntryError::kWrongPIN;
} else if (internal_uv_locked_) {
error = pin::PINEntryError::kInternalUvLocked;
} else {
error = pin::PINEntryError::kNoError;
}
delegate_->CollectPIN(
pin::PINEntryReason::kChallenge, error,
authenticator_->CurrentMinPINLength(), pin_retries_,
base::BindOnce(&AuthTokenRequester::HavePIN, weak_factory_.GetWeakPtr()));
}
void AuthTokenRequester::HavePIN(std::u16string pin16) {
pin::PINEntryError error = pin::ValidatePIN(
pin16, authenticator_->CurrentMinPINLength(), current_pin_);
if (error != pin::PINEntryError::kNoError) {
delegate_->CollectPIN(pin::PINEntryReason::kChallenge, error,
authenticator_->CurrentMinPINLength(), pin_retries_,
base::BindOnce(&AuthTokenRequester::HavePIN,
weak_factory_.GetWeakPtr()));
return;
}
std::string pin = base::UTF16ToUTF8(pin16);
authenticator_->GetPINToken(pin,
{std::begin(options_.token_permissions),
std::end(options_.token_permissions)},
options_.rp_id,
base::BindOnce(&AuthTokenRequester::OnGetPINToken,
weak_factory_.GetWeakPtr(), pin));
return;
}
void AuthTokenRequester::OnGetPINToken(
std::string pin,
CtapDeviceResponseCode status,
absl::optional<pin::TokenResponse> response) {
if (status == CtapDeviceResponseCode::kCtap2ErrPinInvalid) {
pin_invalid_ = true;
ObtainTokenFromPIN();
return;
}
if (status != CtapDeviceResponseCode::kSuccess) {
Result ret;
switch (status) {
case CtapDeviceResponseCode::kCtap2ErrPinPolicyViolation:
// The user needs to set a new PIN before they can use the device.
current_pin_ = pin;
delegate_->CollectPIN(pin::PINEntryReason::kChange,
pin::PINEntryError::kNoError,
authenticator_->NewMinPINLength(),
/*attempts=*/0,
base::BindOnce(&AuthTokenRequester::HaveNewPIN,
weak_factory_.GetWeakPtr()));
return;
case CtapDeviceResponseCode::kCtap2ErrPinAuthBlocked:
ret = Result::kPostTouchAuthenticatorPINSoftLock;
break;
case CtapDeviceResponseCode::kCtap2ErrPinBlocked:
ret = Result::kPostTouchAuthenticatorPINHardLock;
break;
default:
ret = Result::kPostTouchAuthenticatorResponseInvalid;
break;
}
delegate_->HavePINUVAuthTokenResultForAuthenticator(authenticator_, ret,
absl::nullopt);
return;
}
delegate_->HavePINUVAuthTokenResultForAuthenticator(
authenticator_, Result::kSuccess, std::move(*response));
}
void AuthTokenRequester::ObtainTokenFromNewPIN() {
if (NotifyAuthenticatorSelected()) {
delegate_->CollectPIN(pin::PINEntryReason::kSet,
pin::PINEntryError::kNoError,
authenticator_->NewMinPINLength(),
/*attempts=*/0,
base::BindOnce(&AuthTokenRequester::HaveNewPIN,
weak_factory_.GetWeakPtr()));
}
}
void AuthTokenRequester::HaveNewPIN(std::u16string pin16) {
pin::PINEntryError error =
pin::ValidatePIN(pin16, authenticator_->NewMinPINLength(), current_pin_);
if (error != pin::PINEntryError::kNoError) {
delegate_->CollectPIN(
current_pin_ ? pin::PINEntryReason::kChange : pin::PINEntryReason::kSet,
error, authenticator_->NewMinPINLength(),
/*attempts=*/0,
base::BindOnce(&AuthTokenRequester::HaveNewPIN,
weak_factory_.GetWeakPtr()));
return;
}
std::string pin = base::UTF16ToUTF8(pin16);
if (current_pin_) {
authenticator_->ChangePIN(*current_pin_, pin,
base::BindOnce(&AuthTokenRequester::OnSetPIN,
weak_factory_.GetWeakPtr(), pin));
return;
}
authenticator_->SetPIN(pin, base::BindOnce(&AuthTokenRequester::OnSetPIN,
weak_factory_.GetWeakPtr(), pin));
return;
}
void AuthTokenRequester::OnSetPIN(std::string pin,
CtapDeviceResponseCode status,
absl::optional<pin::EmptyResponse> response) {
if (status != CtapDeviceResponseCode::kSuccess) {
delegate_->HavePINUVAuthTokenResultForAuthenticator(
authenticator_, Result::kPostTouchAuthenticatorResponseInvalid,
absl::nullopt);
return;
}
// Having just set the PIN, we need to immediately turn around and use it to
// get a PIN token.
authenticator_->GetPINToken(std::move(pin),
{std::begin(options_.token_permissions),
std::end(options_.token_permissions)},
options_.rp_id,
base::BindOnce(&AuthTokenRequester::OnGetPINToken,
weak_factory_.GetWeakPtr(), pin));
}
bool AuthTokenRequester::NotifyAuthenticatorSelected() {
if (!authenticator_selected_result_.has_value()) {
authenticator_selected_result_ =
delegate_->AuthenticatorSelectedForPINUVAuthToken(authenticator_);
}
return *authenticator_selected_result_;
}
void AuthTokenRequester::NotifyAuthenticatorSelectedAndFailWithResult(
Result result) {
if (NotifyAuthenticatorSelected()) {
delegate_->HavePINUVAuthTokenResultForAuthenticator(authenticator_, result,
absl::nullopt);
}
}
} // namespace device
| 14,932 | 4,441 |
// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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.
#ifndef MANA_ROUTER_HPP
#define MANA_ROUTER_HPP
#include <sstream>
#include <stdexcept>
#include <algorithm>
#include "route.hpp"
#include "params.hpp"
namespace mana {
//-------------------------------
// This class is used to provide
// route resolution
//-------------------------------
class Router {
private:
//-------------------------------
// Internal class type aliases
//using Span = gsl::span<char>;
using Route_table = std::unordered_map<http::Method, std::vector<Route>>;
//-------------------------------
public:
/**
* @brief Returned in match-method.
* Contains both the End_point and the route parameters so that both can be returned.
*/
struct ParsedRoute {
End_point job;
Params parsed_values;
};
//-------------------------------
// Default constructor to set up
// default routes
//-------------------------------
explicit Router() = default;
//-------------------------------
// Default destructor
//-------------------------------
~Router() noexcept = default;
//-------------------------------
// Default move constructor
//-------------------------------
Router(Router&&) = default;
//-------------------------------
// Default move assignment operator
//-------------------------------
Router& operator = (Router&&) = default;
//-------------------------------
// Add a route mapping for route
// resolution upon request
//
// @tparam (std::string) route - The route to map unto a
// resulting destination
//
// @param result - The route mapping
//
// @return - The object that invoked this method
//-------------------------------
template <typename Routee>
Router& on_options(Routee&& route, End_point result);
//-------------------------------
// Add a route mapping for route
// resolution upon request
//
// @tparam (std::string) route - The route to map unto a
// resulting destination
//
// @param result - The route mapping
//
// @return - The object that invoked this method
//-------------------------------
template <typename Routee>
Router& on_get(Routee&& route, End_point result);
//-------------------------------
// Add a route mapping for route
// resolution upon request
//
// @tparam (std::string) route - The route to map unto a
// resulting destination
//
// @param result - The route mapping
//
// @return - The object that invoked this method
//-------------------------------
template <typename Routee>
Router& on_head(Routee&& route, End_point result);
//-------------------------------
// Add a route mapping for route
// resolution upon request
//
// @tparam (std::string) route - The route to map unto a
// resulting destination
//
// @param result - The route mapping
//
// @return - The object that invoked this method
//-------------------------------
template <typename Routee>
Router& on_post(Routee&& route, End_point result);
//-------------------------------
// Add a route mapping for route
// resolution upon request
//
// @tparam (std::string) route - The route to map unto a
// resulting destination
//
// @param result - The route mapping
//
// @return - The object that invoked this method
//-------------------------------
template <typename Routee>
Router& on_put(Routee&& route, End_point result);
//-------------------------------
// Add a route mapping for route
// resolution upon request
//
// @tparam (std::string) route - The route to map unto a
// resulting destination
//
// @param result - The route mapping
//
// @return - The object that invoked this method
//-------------------------------
template <typename Routee>
Router& on_delete(Routee&& route, End_point result);
//-------------------------------
// Add a route mapping for route
// resolution upon request
//
// @tparam (std::string) route - The route to map unto a
// resulting destination
//
// @param result - The route mapping
//
// @return - The object that invoked this method
//-------------------------------
template <typename Routee>
Router& on_trace(Routee&& route, End_point result);
//-------------------------------
// Add a route mapping for route
// resolution upon request
//
// @tparam (std::string) route - The route to map unto a
// resulting destination
//
// @param result - The route mapping
//
// @return - The object that invoked this method
//-------------------------------
template <typename Routee>
Router& on_connect(Routee&& route, End_point result);
//-------------------------------
// Add a route mapping for route
// resolution upon request
//
// @tparam (std::string) route - The route to map unto a
// resulting destination
//
// @param result - The route mapping
//
// @return - The object that invoked this method
//-------------------------------
template <typename Routee>
Router& on_patch(Routee&& route, End_point result);
//-------------------------------
// General way to add a route mapping for route
// resolution upon request
//
// @param method - HTTP method
//
// @tparam (std::string) route - The route to map unto a
// resulting destination
//
// @param result - The route mapping
//
// @return - The object that invoked this method
//-------------------------------
template <typename Routee>
Router& on(http::Method method, Routee&& route, End_point result);
//-------------------------------
// Install a new route table for
// route resolutions
//
// @tparam (http::Router) new_routes - The new route table
// to install
//
// @return - The object that invoked this method
//-------------------------------
template <typename Routee_Table>
Router& install_new_configuration(Routee_Table&& new_routes);
/**
* Get the route callback where Route_expr matched a given path
*
* @param path : the route path
* @note : not const becuase it uses index operator to a map
**/
inline ParsedRoute match(http::Method, const std::string&);
/**
* @brief Make the router use another router on a given route
* @details Currently only copies the content from the outside
* Router and adds new Route in RouteTable by combining
* root route and the route to the other Route.
*
* Maybe Router should be able to keep a collection of other routers.
*
* @param Routee Root path
* @param Router another router with Routes
*
* @return this Router
*/
template <typename Routee>
Router& use(Routee&&, const Router&);
/**
* @brief Copies Routes from another Router object
*
* @param Router to be copied from
* @return this Router
*/
Router& add(const Router&);
/**
* @brief Optimize route search for all routes by bringing
* the most hitted route to the front of the search queue
*
* @return The object that invoked this method
*/
Router& optimize_route_search();
/**
* @brief Optimize route search for the specified HTTP method
* by bringing the most hitted route to the front of the
* search queue
*
* @param method
* The HTTP method to optimize search for
*
* @return The object that invoked this method
*/
Router& optimize_route_search(const http::Method method);
Router& operator<<(const Router& obj)
{ return add(obj); }
std::string to_string() const;
private:
Router(const Router&) = delete;
Router& operator = (const Router&) = delete;
Route_table route_table_;
}; //< class Router
class Router_error : public std::runtime_error {
using runtime_error::runtime_error;
};
/**--v----------- Implementation Details -----------v--**/
template <typename Routee>
inline Router& Router::on_options(Routee&& route, End_point result) {
route_table_[http::OPTIONS].emplace_back(std::forward<Routee>(route), result);
return *this;
}
template <typename Routee>
inline Router& Router::on_get(Routee&& route, End_point result) {
route_table_[http::GET].emplace_back(std::forward<Routee>(route), result);
return *this;
}
template <typename Routee>
inline Router& Router::on_head(Routee&& route, End_point result) {
route_table_[http::HEAD].emplace_back(std::forward<Routee>(route), result);
return *this;
}
template <typename Routee>
inline Router& Router::on_post(Routee&& route, End_point result) {
route_table_[http::POST].emplace_back(std::forward<Routee>(route), result);
return *this;
}
template <typename Routee>
inline Router& Router::on_put(Routee&& route, End_point result) {
route_table_[http::PUT].emplace_back(std::forward<Routee>(route), result);
return *this;
}
template <typename Routee>
inline Router& Router::on_delete(Routee&& route, End_point result) {
route_table_[http::DELETE].emplace_back(std::forward<Routee>(route), result);
return *this;
}
template <typename Routee>
inline Router& Router::on_trace(Routee&& route, End_point result) {
route_table_[http::TRACE].emplace_back(std::forward<Routee>(route), result);
return *this;
}
template <typename Routee>
inline Router& Router::on_connect(Routee&& route, End_point result) {
route_table_[http::CONNECT].emplace_back(std::forward<Routee>(route), result);
return *this;
}
template <typename Routee>
inline Router& Router::on_patch(Routee&& route, End_point result) {
route_table_[http::PATCH].emplace_back(std::forward<Routee>(route), result);
return *this;
}
template <typename Routee>
inline Router& Router::on(http::Method method, Routee&& route, End_point result) {
route_table_[method].emplace_back(std::forward<Routee>(route), result);
return *this;
}
template <typename Routee_Table>
inline Router& Router::install_new_configuration(Routee_Table&& new_routes) {
route_table_ = std::forward<Routee_Table>(new_routes).route_table_;
return *this;
}
inline Router::ParsedRoute Router::match(http::Method method, const std::string& path) {
auto routes = route_table_[method];
if (routes.empty()) {
throw Router_error("No routes for method " + http::method::str(method).to_string());
}
for (auto& route : routes) {
if (std::regex_match(path, route.expr)) {
++route.hits;
// Set the pairs in params:
Params params;
std::smatch res;
for (std::sregex_iterator i = std::sregex_iterator{path.begin(), path.end(), route.expr};
i != std::sregex_iterator{}; ++i) { res = *i; }
// First parameter/value is in res[1], second in res[2], and so on
for (size_t i = 0; i < route.keys.size(); i++)
params.insert(route.keys[i].name, res[i + 1]);
ParsedRoute parsed_route;
parsed_route.job = route.end_point;
parsed_route.parsed_values = params;
return parsed_route;
}
}
throw Router_error("No matching route for " + http::method::str(method).to_string() + " " + path);
}
template <typename Routee>
inline Router& Router::use(Routee&& root, const Router& router) {
// pair<Method, vector<Route>>
for(auto& method_routes : router.route_table_)
{
auto& method = method_routes.first;
auto& routes = method_routes.second;
// vector<Route>
for(auto& route : routes)
{
std::string path = root + route.path;
on(method, path, route.end_point);
}
}
return *this;
}
inline Router& Router::add(const Router& router) {
for (const auto& e : router.route_table_) {
auto it = route_table_.find(e.first);
if (it not_eq route_table_.end()) {
it->second.insert(it->second.cend(), e.second.cbegin(), e.second.cend());
continue;
}
route_table_[e.first] = e.second;
}
return *this;
}
inline Router& Router::optimize_route_search() {
auto it = route_table_.begin();
auto end = route_table_.end();
while (it not_eq end) {
std::stable_sort(it->second.begin(), it->second.end());
++it;
}
return *this;
}
inline Router& Router::optimize_route_search(const http::Method method) {
auto it = route_table_.find(method);
if (it not_eq route_table_.end()) {
std::stable_sort(it->second.begin(), it->second.end());
}
return *this;
}
inline std::string Router::to_string() const {
std::ostringstream ss;
for(const auto& method_routes : route_table_) {
auto&& method = method_routes.first;
auto&& routes = method_routes.second;
for(auto&& route : routes) {
ss << method << '\t' << route.path << '\n';
}
}
return ss.str();
}
/**--^----------- Implementation Details -----------^--**/
} //< namespace mana
#endif //< MANA_ROUTER_HPP
| 14,417 | 4,111 |
/**
* Copyright (c) 2018, University Osnabrück
* 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 University Osnabrück 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 University Osnabrück 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 <stdio.h>
#include <iostream>
#include <lvr2/reconstruction/LBKdTree.hpp>
namespace lvr2
{
// Static variables
ctpl::thread_pool* LBKdTree::pool;// = new ctpl::thread_pool(8);
int LBKdTree::st_num_threads = 8;
int LBKdTree::st_depth_threads = 3;
/// Public
LBKdTree::LBKdTree( LBPointArray<float>& vertices, int num_threads) {
this->m_values = boost::shared_ptr<LBPointArray<float> >(new LBPointArray<float>);
this->m_splits = boost::shared_ptr<LBPointArray<unsigned char> >(new LBPointArray<unsigned char>);
st_num_threads = num_threads;
st_depth_threads = static_cast<int>(log2(st_num_threads));
pool = new ctpl::thread_pool(st_num_threads);
this->generateKdTree(vertices);
}
LBKdTree::~LBKdTree() {
if(pool)
{
delete pool;
}
}
void LBKdTree::generateKdTree(LBPointArray<float> &vertices) {
LBPointArray<unsigned int>* indices_sorted =
(LBPointArray<unsigned int>*)malloc(vertices.dim * sizeof(LBPointArray<unsigned int>) );
LBPointArray<float>* values_sorted =
(LBPointArray<float>*)malloc(vertices.dim * sizeof(LBPointArray<float>) );
for(unsigned int i=0; i< vertices.dim; i++)
{
pool->push(generateAndSort<float, unsigned int>, vertices, indices_sorted, values_sorted, i);
//generateAndSort<float, unsigned int>(0, vertices, indices_sorted, values_sorted, i);
}
pool->stop(true);
delete pool;
pool = new ctpl::thread_pool(st_num_threads);
this->generateKdTreeArray(vertices, indices_sorted, vertices.dim);
for(unsigned int i=0; i<vertices.dim;i++)
{
//free(indices_sorted[i].elements);
free(values_sorted[i].elements);
}
//free(indices_sorted);
//free(values_sorted);
}
boost::shared_ptr<LBPointArray<float> > LBKdTree::getKdTreeValues() {
return this->m_values;
}
boost::shared_ptr<LBPointArray<unsigned char> > LBKdTree::getKdTreeSplits() {
return this->m_splits;
}
/// Private
void LBKdTree::generateKdTreeArray(LBPointArray<float>& V,
LBPointArray<unsigned int>* sorted_indices, int max_dim) {
// DEBUG CHECK
int first_split_dim = -1;
float best_deviation = -1.0;
// std::cout << "BOX:" << std::endl;
for(int i=0; i<V.dim; i++)
{
float deviation = V.elements[static_cast<unsigned int>(
sorted_indices[i].elements[sorted_indices[i].width-1]+0.5)* V.dim + i]
- V.elements[static_cast<unsigned int>(
sorted_indices[i].elements[i]+0.5)* V.dim + i] ;
// std::cout << "Dim: " << i << " size: "<< deviation << std::endl;
if(deviation > best_deviation)
{
best_deviation = deviation;
first_split_dim = i;
}
}
unsigned int size;
int max_tree_depth;
max_tree_depth = static_cast<int>( log2f(V.width - 1 ) + 2.0 ) ;
if (V.width == 1)
{
max_tree_depth = 1;
}
size = V.width * 2 - 1;
// std::cout << "size values: " << size << std::endl;
this->m_values->elements = (float*)malloc(sizeof(float) * size );
this->m_values->width = size;
this->m_values->dim = 1;
unsigned int size_splits = size - V.width;
// std::cout << "size splits: " << size_splits << std::endl;
this->m_splits->elements = (unsigned char*)malloc(sizeof(unsigned char) * size_splits );
this->m_splits->width = size_splits;
this->m_splits->dim = 1;
LBPointArray<float>* value_ptr = this->m_values.get();
LBPointArray<unsigned char>* splits_ptr = this->m_splits.get();
//start real generate
generateKdTreeRecursive(0, V, sorted_indices, first_split_dim,
max_dim, value_ptr, splits_ptr ,size, max_tree_depth, 0, 0);
pool->stop(true);
delete pool;
pool = new ctpl::thread_pool(st_num_threads);
}
void LBKdTree::fillCriticalIndices(const LBPointArray<float>& V,
LBPointArray<unsigned int>& sorted_indices, unsigned int current_dim,
float split_value, unsigned int split_index,
std::list<unsigned int>& critical_indices_left,
std::list<unsigned int>& critical_indices_right)
{
critical_indices_left.push_back( sorted_indices.elements[split_index] );
unsigned int iterator;
// nach links
for(iterator = split_index-1;
iterator < sorted_indices.width
&& V.elements[ sorted_indices.elements[iterator] * V.dim + current_dim] == split_value;
iterator--)
{
critical_indices_left.push_back( sorted_indices.elements[iterator] );
}
// nach rechts
for(iterator = split_index+1;
iterator < sorted_indices.width
&& V.elements[ sorted_indices.elements[iterator] * V.dim + current_dim] == split_value;
iterator++)
{
critical_indices_right.push_back( sorted_indices.elements[iterator] );
}
}
void LBKdTree::fillCriticalIndicesSet(const LBPointArray<float>& V,
LBPointArray<unsigned int>& sorted_indices, unsigned int current_dim,
float split_value, unsigned int split_index,
std::unordered_set<unsigned int>& critical_indices_left,
std::unordered_set<unsigned int>& critical_indices_right)
{
//critical_indices_left.push_back( sorted_indices.elements[split_index] );
critical_indices_left.insert(sorted_indices.elements[split_index]);
unsigned int iterator;
// nach links
for(iterator = split_index-1;
iterator < sorted_indices.width
&& V.elements[ sorted_indices.elements[iterator] * V.dim + current_dim] == split_value;
iterator--)
{
critical_indices_left.insert( sorted_indices.elements[iterator] );
}
// nach rechts
for(iterator = split_index+1;
iterator < sorted_indices.width
&& V.elements[ sorted_indices.elements[iterator] * V.dim + current_dim] == split_value;
iterator++)
{
critical_indices_right.insert( sorted_indices.elements[iterator] );
}
}
void LBKdTree::generateKdTreeRecursive(int id, LBPointArray<float>& V,
LBPointArray<unsigned int>* sorted_indices, int current_dim, int max_dim,
LBPointArray<float> *values, LBPointArray<unsigned char> *splits ,
int size, int max_tree_depth, int position, int current_depth)
{
int left = position*2+1;
int right = position*2+2;
if( sorted_indices[current_dim].width <= 1 )
{
values->elements[position] = static_cast<float>(sorted_indices[current_dim].elements[0] );
} else {
/// split sorted_indices
unsigned int indices_size = sorted_indices[current_dim].width;
unsigned int v = pow( 2, static_cast<int>( log2(indices_size-1) ) );
unsigned int left_size = indices_size - v/2;
if( left_size > v )
{
left_size = v;
}
unsigned int right_size = indices_size - left_size;
unsigned int split_index = static_cast<unsigned int>(
sorted_indices[current_dim].elements[left_size-1] + 0.5
);
float split_value = V.elements[split_index * V.dim + current_dim ];
// critical indices
// std::list<unsigned int> critical_indices_left;
// std::list<unsigned int> critical_indices_right;
// fillCriticalIndices(V, sorted_indices[current_dim], current_dim, split_value, left_size-1
// critical_indices_left, critical_indices_right);
std::unordered_set<unsigned int> critical_indices_left;
std::unordered_set<unsigned int> critical_indices_right;
fillCriticalIndicesSet(V, sorted_indices[current_dim],
current_dim, split_value, left_size-1, critical_indices_left,
critical_indices_right);
// for(auto it = critical_indices_left.begin(); it != critical_indices_left.end(); it++)
// {
// std::cout << *it << std::endl;
// }
// for(auto it = critical_indices_right.begin(); it != critical_indices_right.end(); it++)
// {
// std::cout << *it << std::endl;
// }
// exit(1);
//std::cout << "Split in dimension: " << current_dim << std::endl;
values->elements[ position ] = split_value;
splits->elements[ position ] = static_cast<unsigned char>(current_dim);
LBPointArray<unsigned int> *sorted_indices_left =
(LBPointArray<unsigned int>*)malloc( 3*sizeof(LBPointArray<unsigned int>) );
LBPointArray<unsigned int> *sorted_indices_right =
(LBPointArray<unsigned int>*)malloc( 3*sizeof(LBPointArray<unsigned int>) );
int next_dim_left = -1;
int next_dim_right = -1;
float biggest_deviation_left = -1.0;
float biggest_deviation_right = -1.0;
for( int i=0; i<max_dim; i++ )
{
sorted_indices_left[i].width = left_size;
sorted_indices_left[i].dim = 1;
sorted_indices_left[i].elements = (unsigned int*)malloc( left_size * sizeof(unsigned int) );
sorted_indices_right[i].width = right_size;
sorted_indices_right[i].dim = 1;
sorted_indices_right[i].elements = (unsigned int*)malloc( right_size * sizeof(unsigned int) );
float deviation_left;
float deviation_right;
if( i == current_dim ){
splitPointArray<unsigned int>( sorted_indices[i],
sorted_indices_left[i],
sorted_indices_right[i]);
deviation_left = fabs(V.elements[sorted_indices_left[i].elements[left_size - 1] * V.dim + i ]
- V.elements[sorted_indices_left[i].elements[0] * V.dim + i ] );
deviation_right = fabs( V.elements[ sorted_indices_right[i].elements[right_size - 1] * V.dim + i ]
- V.elements[sorted_indices_right[i].elements[0] * V.dim + i] );
} else {
// splitPointArrayWithValue<float,unsigned int>(V, sorted_indices[i],
// sorted_indices_left[i], sorted_indices_right[i],
// current_dim, split_value,
// deviation_left, deviation_right, i,
// critical_indices_left, critical_indices_right);
splitPointArrayWithValueSet<float,unsigned int>(V, sorted_indices[i],
sorted_indices_left[i], sorted_indices_right[i],
current_dim, split_value,
deviation_left, deviation_right, i,
critical_indices_left, critical_indices_right);
}
if(deviation_left > biggest_deviation_left )
{
biggest_deviation_left = deviation_left;
next_dim_left = i;
}
if(deviation_right > biggest_deviation_right )
{
biggest_deviation_right = deviation_right;
next_dim_right = i;
}
}
//int next_dim = (current_dim+1)%max_dim;
if(current_depth == st_depth_threads )
{
pool->push(generateKdTreeRecursive, V, sorted_indices_left,
next_dim_left, max_dim, values, splits, size, max_tree_depth,
left, current_depth + 1);
pool->push(generateKdTreeRecursive, V, sorted_indices_right,
next_dim_right, max_dim, values, splits, size, max_tree_depth,
right, current_depth +1);
} else {
//std::cout<< "left " << current_dim << std::endl;
generateKdTreeRecursive(0, V, sorted_indices_left, next_dim_left, max_dim,
values, splits, size, max_tree_depth, left, current_depth + 1);
//std::cout << "right " << current_dim << std::endl;
generateKdTreeRecursive(0, V, sorted_indices_right, next_dim_right, max_dim,
values, splits, size, max_tree_depth, right, current_depth +1);
}
}
for(int i=0; i<max_dim; i++) {
free(sorted_indices[i].elements );
}
free(sorted_indices);
}
} /* namespace lvr2 */
| 13,768 | 4,450 |
#define NO_IMPORT_ARRAY
#define PY_ARRAY_UNIQUE_SYMBOL pycuda_ARRAY_API
#include <vector>
#include "tools.hpp"
#include "wrap_helpers.hpp"
#include <cuda.hpp>
#include <mempool.hpp>
#include <boost/python/stl_iterator.hpp>
namespace py = boost::python;
namespace
{
class device_allocator : public pycuda::context_dependent
{
public:
typedef CUdeviceptr pointer_type;
typedef size_t size_type;
bool is_deferred() const
{
return false;
}
device_allocator *copy() const
{
return new device_allocator(*this);
}
pointer_type allocate(size_type s)
{
pycuda::scoped_context_activation ca(get_context());
return pycuda::mem_alloc(s);
}
void free(pointer_type p)
{
try
{
pycuda::scoped_context_activation ca(get_context());
pycuda::mem_free(p);
}
CUDAPP_CATCH_CLEANUP_ON_DEAD_CONTEXT(pooled_device_allocation);
}
void try_release_blocks()
{
pycuda::run_python_gc();
}
};
class host_allocator
{
private:
unsigned m_flags;
public:
typedef void *pointer_type;
typedef size_t size_type;
bool is_deferred() const
{
return false;
}
host_allocator *copy() const
{
return new host_allocator(*this);
}
host_allocator(unsigned flags=0)
: m_flags(flags)
{ }
pointer_type allocate(size_type s)
{
return pycuda::mem_host_alloc(s, m_flags);
}
void free(pointer_type p)
{
pycuda::mem_host_free(p);
}
void try_release_blocks()
{
pycuda::run_python_gc();
}
};
template<class Allocator>
class context_dependent_memory_pool :
public pycuda::memory_pool<Allocator>,
public pycuda::explicit_context_dependent
{
protected:
void start_holding_blocks()
{ acquire_context(); }
void stop_holding_blocks()
{ release_context(); }
};
class pooled_device_allocation
: public pycuda::context_dependent,
public pycuda::pooled_allocation<context_dependent_memory_pool<device_allocator> >
{
private:
typedef
pycuda::pooled_allocation<context_dependent_memory_pool<device_allocator> >
super;
public:
pooled_device_allocation(
boost::shared_ptr<super::pool_type> p, super::size_type s)
: super(p, s)
{ }
operator CUdeviceptr()
{ return ptr(); }
};
pooled_device_allocation *device_pool_allocate(
boost::shared_ptr<context_dependent_memory_pool<device_allocator> > pool,
context_dependent_memory_pool<device_allocator>::size_type sz)
{
return new pooled_device_allocation(pool, sz);
}
PyObject *pooled_device_allocation_to_long(pooled_device_allocation const &da)
{
#if defined(_WIN32) && defined(_WIN64)
return PyLong_FromUnsignedLongLong(da.ptr());
#else
return PyLong_FromUnsignedLong(da.ptr());
#endif
}
class pooled_host_allocation
: public pycuda::pooled_allocation<pycuda::memory_pool<host_allocator> >
{
private:
typedef
pycuda::pooled_allocation<pycuda::memory_pool<host_allocator> >
super;
public:
pooled_host_allocation(
boost::shared_ptr<super::pool_type> p, super::size_type s)
: super(p, s)
{ }
};
py::handle<> host_pool_allocate(
boost::shared_ptr<pycuda::memory_pool<host_allocator> > pool,
py::object shape, py::object dtype, py::object order_py)
{
PyArray_Descr *tp_descr;
if (PyArray_DescrConverter(dtype.ptr(), &tp_descr) != NPY_SUCCEED)
throw py::error_already_set();
std::vector<npy_intp> dims;
std::copy(
py::stl_input_iterator<npy_intp>(shape),
py::stl_input_iterator<npy_intp>(),
back_inserter(dims));
std::auto_ptr<pooled_host_allocation> alloc(
new pooled_host_allocation(
pool, tp_descr->elsize*pycuda::size_from_dims(dims.size(), &dims.front())));
NPY_ORDER order = PyArray_CORDER;
PyArray_OrderConverter(order_py.ptr(), &order);
int flags = 0;
if (order == PyArray_FORTRANORDER)
flags |= NPY_FARRAY;
else if (order == PyArray_CORDER)
flags |= NPY_CARRAY;
else
throw std::runtime_error("unrecognized order specifier");
py::handle<> result = py::handle<>(PyArray_NewFromDescr(
&PyArray_Type, tp_descr,
int(dims.size()), &dims.front(), /*strides*/ NULL,
alloc->ptr(), flags, /*obj*/NULL));
py::handle<> alloc_py(handle_from_new_ptr(alloc.release()));
PyArray_BASE(result.get()) = alloc_py.get();
Py_INCREF(alloc_py.get());
return result;
}
template<class Wrapper>
void expose_memory_pool(Wrapper &wrapper)
{
typedef typename Wrapper::wrapped_type cl;
wrapper
.add_property("held_blocks", &cl::held_blocks)
.add_property("active_blocks", &cl::active_blocks)
.add_property("managed_bytes", &cl::managed_bytes)
.add_property("active_bytes", &cl::active_bytes)
.DEF_SIMPLE_METHOD(bin_number)
.DEF_SIMPLE_METHOD(alloc_size)
.DEF_SIMPLE_METHOD(free_held)
.DEF_SIMPLE_METHOD(stop_holding)
;
}
}
void pycuda_expose_tools()
{
py::def("bitlog2", pycuda::bitlog2);
{
typedef context_dependent_memory_pool<device_allocator> cl;
py::class_<
cl, boost::noncopyable,
boost::shared_ptr<cl> > wrapper("DeviceMemoryPool");
wrapper
.def("allocate", device_pool_allocate,
py::return_value_policy<py::manage_new_object>())
;
expose_memory_pool(wrapper);
}
{
typedef host_allocator cl;
py::class_<cl> wrapper("PageLockedAllocator",
py::init<py::optional<unsigned> >());
}
{
typedef pycuda::memory_pool<host_allocator> cl;
py::class_<
cl, boost::noncopyable,
boost::shared_ptr<cl> > wrapper(
"PageLockedMemoryPool",
py::init<py::optional<host_allocator const &> >()
);
wrapper
.def("allocate", host_pool_allocate,
(py::arg("shape"), py::arg("dtype"), py::arg("order")="C"));
;
expose_memory_pool(wrapper);
}
{
typedef pooled_device_allocation cl;
py::class_<cl, boost::noncopyable>(
"PooledDeviceAllocation", py::no_init)
.DEF_SIMPLE_METHOD(free)
.def("__int__", &cl::ptr)
.def("__long__", pooled_device_allocation_to_long)
.def("__index__", pooled_device_allocation_to_long)
.def("__len__", &cl::size)
;
py::implicitly_convertible<pooled_device_allocation, CUdeviceptr>();
}
{
typedef pooled_host_allocation cl;
py::class_<cl, boost::noncopyable>(
"PooledHostAllocation", py::no_init)
.DEF_SIMPLE_METHOD(free)
.def("__len__", &cl::size)
;
}
}
| 6,900 | 2,486 |
#ifndef UNICODE
#define UNICODE
#endif
#include <Windows.h>
#include <d2d1.h>
#include <thread>
#pragma comment(lib,"d2d1")
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
void initD2D();
void updateOverlayLocation();
void readData();
void readWindowInfo();
void checkClosedWindow();
HWND hwnd_overlay;
HWND hwnd_game;
HANDLE h_game;
ID2D1Factory * pFactory = NULL;
ID2D1HwndRenderTarget *pRenderTarget = NULL;
ID2D1SolidColorBrush *pBrush;
// Minesweeper properties
const int startX = 15;
const int startY = 100;
const int squareLength = 16;
// Memory locations
DWORD arow = 0x01005334;
DWORD acolumn = 0x01005338;
DWORD afirstSquare = 0x01005361;
int rowSize;
int columnSize;
byte squareData[16][32];
template <class T> void SafeRelease(T **ppT) {
if (*ppT) {
(*ppT)->Release();
*ppT = NULL;
}
}
void readWindowInfo() {
while (true) {
updateOverlayLocation();
readData();
checkClosedWindow();
}
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow) {
// Get Minesweeper process
hwnd_game = FindWindow(NULL, L"Minesweeper");
if (hwnd_game == NULL) {
return 0;
}
DWORD procID;
GetWindowThreadProcessId(hwnd_game, &procID);
h_game = OpenProcess(PROCESS_ALL_ACCESS, FALSE, procID);
const wchar_t CLASS_NAME[] = L"Sample Window Class";
WNDCLASSEX wcex = {};
ZeroMemory(&wcex, sizeof(WNDCLASSEX));
wcex.lpfnWndProc = WindowProc;
wcex.hInstance = hInstance;
wcex.lpszClassName = CLASS_NAME;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
RegisterClassEx(&wcex);
hwnd_overlay = CreateWindowEx(
WS_EX_TRANSPARENT | WS_EX_TOPMOST | WS_EX_LAYERED,
CLASS_NAME,
L"",
WS_POPUP,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL
);
if (hwnd_overlay == NULL) {
return 0;
}
initD2D();
SetLayeredWindowAttributes(hwnd_overlay, RGB(255, 255, 255), 255, LWA_COLORKEY);
ShowWindow(hwnd_overlay, nCmdShow);
UpdateWindow(hwnd_overlay);
std::thread t1(readWindowInfo);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
void initD2D() {
HRESULT hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory);
}
void checkClosedWindow() {
DWORD status;
GetExitCodeProcess(h_game, &status);
if (status != STILL_ACTIVE) {
exit(0);
}
}
void updateOverlayLocation() {
RECT rc;
GetWindowRect(hwnd_game, &rc);
SetWindowPos(hwnd_overlay, NULL, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, NULL);
}
void readData() {
ReadProcessMemory(h_game, (LPCVOID)arow, &columnSize, sizeof(columnSize), NULL);
ReadProcessMemory(h_game, (LPCVOID)acolumn, &rowSize, sizeof(rowSize), NULL);
ReadProcessMemory(h_game, (LPCVOID)afirstSquare, &squareData, sizeof(squareData), NULL);
}
HRESULT CreateGraphicsResources() {
HRESULT hr = S_OK;
if (pRenderTarget == NULL) {
RECT rc;
GetClientRect(hwnd_overlay, &rc);
D2D1_SIZE_U size = D2D1::SizeU(rc.right, rc.bottom);
hr = pFactory->CreateHwndRenderTarget(
D2D1::RenderTargetProperties(),
D2D1::HwndRenderTargetProperties(hwnd_overlay, size),
&pRenderTarget);
if (SUCCEEDED(hr)) {
const D2D1_COLOR_F color = D2D1::ColorF(1.0f, 0, 0);
hr = pRenderTarget->CreateSolidColorBrush(color, &pBrush);
}
}
return hr;
}
void DiscardGraphicsResources()
{
SafeRelease(&pRenderTarget);
SafeRelease(&pBrush);
}
void OnPaint() {
HRESULT hr = CreateGraphicsResources();
if (SUCCEEDED(hr)) {
PAINTSTRUCT ps;
BeginPaint(hwnd_overlay, &ps);
pRenderTarget->BeginDraw();
pRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White));
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < columnSize; j++) {
int x = startX + squareLength * j;
int y = startY + squareLength * i;
if (squareData[i][j] == 143) {
pRenderTarget->DrawLine(D2D1::Point2F(x, y), D2D1::Point2F(x + squareLength, y + squareLength), pBrush, 1.5f);
pRenderTarget->DrawLine(D2D1::Point2F(x, y + squareLength), D2D1::Point2F(x + squareLength, y), pBrush, 1.5f);
}
}
}
hr = pRenderTarget->EndDraw();
if (FAILED(hr) || hr == D2DERR_RECREATE_TARGET) {
DiscardGraphicsResources();
}
EndPaint(hwnd_overlay, &ps);
InvalidateRect(hwnd_overlay, NULL, FALSE);
}
}
void Resize()
{
if (pRenderTarget != NULL)
{
RECT rc;
GetClientRect(hwnd_overlay, &rc);
D2D1_SIZE_U size = D2D1::SizeU(rc.right, rc.bottom);
pRenderTarget->Resize(size);
InvalidateRect(hwnd_overlay, NULL, FALSE);
}
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
switch (uMsg) {
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_PAINT:
OnPaint();
return 0;
case WM_SIZE:
Resize();
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
} | 5,140 | 2,269 |
// 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.
#include "chrome/browser/performance_monitor/startup_timer.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "chrome/browser/performance_monitor/database.h"
#include "chrome/browser/performance_monitor/performance_monitor.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
namespace performance_monitor {
namespace {
// Needed because Database::AddMetric is overloaded, so base::Bind doesn't work.
void AddMetricToDatabaseOnBackgroundThread(Database* database,
const Metric& metric) {
database->AddMetric(metric);
}
} // namespace
// static
StartupTimer* StartupTimer::g_startup_timer_ = NULL;
StartupTimer::StartupTimer() : startup_begin_(base::TimeTicks::Now()),
startup_type_(STARTUP_NORMAL),
performance_monitor_initialized_(false) {
CHECK(!g_startup_timer_);
g_startup_timer_ = this;
// We need this check because, under certain rare circumstances,
// NotificationService::current() will return null, and this will cause a
// segfault in NotificationServiceImpl::AddObserver(). Currently, this only
// happens as a result of the child process launched by BrowserMainTest.
// WarmConnectionFieldTrial_Invalid.
if (content::NotificationService::current()) {
registrar_.Add(this, chrome::NOTIFICATION_PERFORMANCE_MONITOR_INITIALIZED,
content::NotificationService::AllSources());
}
}
StartupTimer::~StartupTimer() {
DCHECK(this == g_startup_timer_);
g_startup_timer_ = NULL;
}
bool StartupTimer::SignalStartupComplete(StartupType startup_type) {
DCHECK(elapsed_startup_time_ == base::TimeDelta());
startup_type_ = startup_type;
elapsed_startup_time_ =
base::TimeTicks::Now() - total_pause_ - startup_begin_;
if (performance_monitor_initialized_)
InsertElapsedStartupTime();
return true;
}
// static
void StartupTimer::PauseTimer() {
// Check that the timer is not already paused.
DCHECK(g_startup_timer_->pause_started_ == base::TimeTicks());
g_startup_timer_->pause_started_ = base::TimeTicks::Now();
}
// static
void StartupTimer::UnpauseTimer() {
// Check that the timer has been paused.
DCHECK(g_startup_timer_->pause_started_ != base::TimeTicks());
g_startup_timer_->total_pause_ += base::TimeTicks::Now() -
g_startup_timer_->pause_started_;
g_startup_timer_->pause_started_ = base::TimeTicks();
}
void StartupTimer::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
CHECK(type == chrome::NOTIFICATION_PERFORMANCE_MONITOR_INITIALIZED);
performance_monitor_initialized_ = true;
if (elapsed_startup_time_ != base::TimeDelta())
InsertElapsedStartupTime();
if (elapsed_session_restore_times_.size())
InsertElapsedSessionRestoreTime();
}
// static
void StartupTimer::SetElapsedSessionRestoreTime(
const base::TimeDelta& elapsed_session_restore_time) {
g_startup_timer_->elapsed_session_restore_times_.push_back(
elapsed_session_restore_time);
if (g_startup_timer_->performance_monitor_initialized_)
g_startup_timer_->InsertElapsedSessionRestoreTime();
}
void StartupTimer::InsertElapsedStartupTime() {
content::BrowserThread::PostBlockingPoolSequencedTask(
Database::kDatabaseSequenceToken,
FROM_HERE,
base::Bind(
&AddMetricToDatabaseOnBackgroundThread,
base::Unretained(PerformanceMonitor::GetInstance()->database()),
Metric(startup_type_ == STARTUP_NORMAL ? METRIC_STARTUP_TIME
: METRIC_TEST_STARTUP_TIME,
base::Time::Now(),
static_cast<double>(
elapsed_startup_time_.ToInternalValue()))));
}
void StartupTimer::InsertElapsedSessionRestoreTime() {
for (std::vector<base::TimeDelta>::const_iterator iter =
elapsed_session_restore_times_.begin();
iter != elapsed_session_restore_times_.end(); ++iter) {
content::BrowserThread::PostBlockingPoolSequencedTask(
Database::kDatabaseSequenceToken,
FROM_HERE,
base::Bind(
&AddMetricToDatabaseOnBackgroundThread,
base::Unretained(PerformanceMonitor::GetInstance()->database()),
Metric(METRIC_SESSION_RESTORE_TIME,
base::Time::Now(),
static_cast<double>(iter->ToInternalValue()))));
}
}
} // namespace performance_monitor
| 5,042 | 1,526 |
//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <string>
#include "cpu_mkldnn_primitive_build.hpp"
#include "ngraph/code_writer.hpp"
#include "ngraph/op/add.hpp"
#include "ngraph/op/avg_pool.hpp"
#include "ngraph/op/batch_norm.hpp"
#include "ngraph/op/concat.hpp"
#include "ngraph/op/constant.hpp"
#include "ngraph/op/convert.hpp"
#include "ngraph/op/convolution.hpp"
#include "ngraph/op/dequantize.hpp"
#include "ngraph/op/experimental/quantized_conv_bias.hpp"
#include "ngraph/op/experimental/quantized_conv_relu.hpp"
#include "ngraph/op/experimental/quantized_dot_bias.hpp"
#include "ngraph/op/get_output_element.hpp"
#include "ngraph/op/lrn.hpp"
#include "ngraph/op/max_pool.hpp"
#include "ngraph/op/quantize.hpp"
#include "ngraph/op/quantized_convolution.hpp"
#include "ngraph/op/quantized_dot.hpp"
#include "ngraph/op/relu.hpp"
#include "ngraph/op/replace_slice.hpp"
#include "ngraph/op/reshape.hpp"
#include "ngraph/op/sigmoid.hpp"
#include "ngraph/op/slice.hpp"
#include "ngraph/op/softmax.hpp"
#include "ngraph/runtime/cpu/cpu_executor.hpp"
#include "ngraph/runtime/cpu/cpu_tensor_view_wrapper.hpp"
#include "ngraph/runtime/cpu/mkldnn_emitter.hpp"
#include "ngraph/runtime/cpu/mkldnn_utils.hpp"
#include "ngraph/runtime/cpu/op/convert_layout.hpp"
#include "ngraph/runtime/cpu/op/lstm.hpp"
#include "ngraph/runtime/cpu/op/max_pool_with_indices.hpp"
#include "ngraph/runtime/cpu/op/rnn.hpp"
#include "ngraph/runtime/cpu/op/update_slice.hpp"
#define WRITE_MKLDNN_DIMS(X) writer << "mkldnn::memory::dims{" << join(X) << "}, \n";
using namespace ngraph;
using namespace ngraph::op;
using namespace ngraph::runtime::cpu;
namespace ngraph
{
namespace runtime
{
namespace cpu
{
namespace pass
{
// serialize memory descriptors
static void serialize_memory_descs(std::ofstream& desc_file,
std::vector<mkldnn::memory::desc>& descs,
size_t index)
{
for (auto i = 0; i < descs.size(); i++)
{
desc_file << index;
desc_file.write(reinterpret_cast<char*>(&descs[i]),
sizeof(mkldnn::memory::desc));
index++;
}
}
// The following functions build the MKLDNN primitive for each type of nGraph Node.
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Add)
{
auto input0_data_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto input1_data_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto sum_pd = mkldnn_emitter.get_elementwise_add_desc(node);
mkldnn_emitter.query_scratchpad_sum(sum_pd);
// Add needs 4 primitives: input0, input1, result, and sum.
index = mkldnn_emitter.reserve_primitive_space(4);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {
input0_data_desc, input1_data_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "std::vector<float> scale_vector(2, 1);\n";
writer << "std::vector<mkldnn::memory::desc> inputs_desc{"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], "
<< "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "]};\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
// elementwise sum primitive descriptor
writer << "mkldnn::sum::primitive_desc sum_pd = "
"mkldnn::sum::primitive_desc(*cg_ctx->mkldnn_descriptors["
<< desc_index + 2
<< "], "
"scale_vector, inputs_desc, cg_ctx->global_cpu_engine, attr);\n";
writer << "\n// build sum primitive\n";
// sum primitive
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::sum(sum_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(sum_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <typename OP>
void construct_primitive_build_string_rnn(
ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter,
ngraph::Node* node,
std::string& construct_string,
std::vector<size_t>& deps,
size_t& index,
std::ofstream& desc_file)
{
const auto& out = node->get_outputs();
const auto& args = node->get_inputs();
auto rnn_node = static_cast<const OP*>(node);
auto src_sequence_length_max =
static_cast<unsigned long>(rnn_node->get_src_sequence_length());
auto direction = static_cast<unsigned long>(rnn_node->get_direction());
auto num_fused_layers =
static_cast<unsigned long>(rnn_node->get_num_fused_layers());
auto feature_size =
static_cast<unsigned long>(rnn_node->get_src_iter_feature_size());
auto batch = static_cast<unsigned long>(rnn_node->get_batch_size());
auto rnn_cell_n_gates =
static_cast<unsigned long>(rnn_node->get_gates_per_cell());
auto get_mkldnn_rnn_direction_string = [&]() {
switch (direction)
{
case 1:
return std::string("mkldnn::rnn_direction::unidirectional_left2right");
case 2: return std::string("mkldnn::rnn_direction::bidirectional_concat");
default: throw ngraph_error("unsupported mkldnn rnn direction");
}
};
auto get_mkldnn_rnn_direction = [&]() {
switch (direction)
{
case 1: return mkldnn::rnn_direction::unidirectional_left2right;
case 2: return mkldnn::rnn_direction::bidirectional_concat;
default: throw ngraph_error("unsupported mkldnn rnn direction");
}
};
if (out[0].get_shape().size() == 2 &&
(out[0].get_shape()[1] != direction * feature_size))
{
throw ngraph_error(
"input slc{ht} feature size is not equal to output dlc{ht} feature "
"size ");
}
if (out[1].get_shape().size() == 2 && (out[1].get_shape()[1] != feature_size) &&
rnn_node->get_num_timesteps() != 1)
{
throw ngraph_error(
"input sic{ht_1|ct_1} feature size is not equal to output "
"dlc{ht_1|ct_1} "
"feature size ");
}
Shape src_layer_tz{
src_sequence_length_max,
batch,
static_cast<unsigned long>(rnn_node->get_src_layer_feature_size())};
Shape src_iter_tz{num_fused_layers, direction, batch, feature_size};
Shape src_iter_c_tz{num_fused_layers, direction, batch, feature_size};
Shape wei_layer_tz{
num_fused_layers,
direction,
static_cast<unsigned long>(rnn_node->get_src_layer_feature_size()),
rnn_cell_n_gates,
feature_size};
Shape wei_iter_tz{
num_fused_layers, direction, feature_size, rnn_cell_n_gates, feature_size};
Shape bias_tz{num_fused_layers, direction, rnn_cell_n_gates, feature_size};
Shape dst_layer_tz{src_sequence_length_max, batch, direction * feature_size};
Shape dst_iter_tz{num_fused_layers, direction, batch, feature_size};
Shape dst_iter_c_tz{num_fused_layers, direction, batch, feature_size};
// We create the memory descriptors used by the user
auto src_layer_md = mkldnn_emitter.build_memory_descriptor(
src_layer_tz, args[0].get_element_type(), mkldnn::memory::format_tag::tnc);
auto src_iter_md = mkldnn_emitter.build_memory_descriptor(
src_iter_tz, args[1].get_element_type(), mkldnn::memory::format_tag::ldnc);
auto src_iter_c_md =
mkldnn_emitter.build_memory_descriptor(src_iter_c_tz,
args[1].get_element_type(),
mkldnn::memory::format_tag::ldnc);
auto wei_layer_md =
mkldnn_emitter.build_memory_descriptor(wei_layer_tz,
args[2].get_element_type(),
mkldnn::memory::format_tag::ldigo);
auto wei_iter_md = mkldnn_emitter.build_memory_descriptor(
wei_iter_tz, args[3].get_element_type(), mkldnn::memory::format_tag::ldigo);
auto bias_md = mkldnn_emitter.build_memory_descriptor(
bias_tz, args[4].get_element_type(), mkldnn::memory::format_tag::ldgo);
auto dst_layer_md = mkldnn_emitter.build_memory_descriptor(
dst_layer_tz, out[0].get_element_type(), mkldnn::memory::format_tag::tnc);
auto dst_iter_md = mkldnn_emitter.build_memory_descriptor(
dst_iter_tz, out[1].get_element_type(), mkldnn::memory::format_tag::ldnc);
auto dst_iter_c_md = mkldnn_emitter.build_memory_descriptor(
dst_iter_c_tz, out[1].get_element_type(), mkldnn::memory::format_tag::ldnc);
// query scratchpad size
auto rnn_desc = mkldnn::lstm_forward::desc(mkldnn::prop_kind::forward_training,
get_mkldnn_rnn_direction(),
src_layer_md,
src_iter_md,
src_iter_c_md,
wei_layer_md,
wei_iter_md,
bias_md,
dst_layer_md,
dst_iter_md,
dst_iter_c_md);
mkldnn_emitter.query_scratchpad_rnn_forward(rnn_desc);
// Lstm/Rnn needs 11 primitives: src_layer, src_iter, src_iter_c, weights_layer,
// weights_iter, bias,
// dst_layer, dst_iter, dst_iter_c, workspace, and rnn_forward.
// It needs a new workspace.
index = mkldnn_emitter.reserve_primitive_space(11, true /* new workspace */);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {src_layer_md,
src_iter_md,
src_iter_c_md,
wei_layer_md,
wei_iter_md,
bias_md,
dst_layer_md,
dst_iter_md,
dst_iter_c_md};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "\n// build lstm/rnn primitive descriptor\n";
writer << "auto rnn_desc = "
"mkldnn::lstm_forward::desc(mkldnn::prop_kind::forward_training, "
<< get_mkldnn_rnn_direction_string() << ", "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 2 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 3 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 4 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 5 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 6 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 7 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 8 << "]);\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "auto rnn_prim_desc = mkldnn::lstm_forward::primitive_desc(rnn_desc, "
"attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "cg_ctx->mkldnn_memories[" << std::to_string(deps[9])
<< "] = new "
"mkldnn::memory(rnn_prim_desc.workspace_desc(), "
"cg_ctx->global_cpu_engine, nullptr);\n";
writer << "auto workspace = "
"(char*)malloc(rnn_prim_desc.workspace_desc().get_size());"
"\n";
writer << "if (!workspace)\n";
writer.block_begin();
writer << "throw std::bad_alloc();\n";
writer.block_end();
writer << "cg_ctx->mkldnn_workspaces.push_back(workspace);\n";
deps[10] = mkldnn_emitter.reserve_workspace();
writer << "\n// build lstm/rnn primitive\n";
// lstm/rnn primitive
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::lstm_forward(rnn_prim_desc);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(rnn_prim_desc.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Lstm)
{
construct_primitive_build_string_rnn<Lstm>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Rnn)
{
construct_primitive_build_string_rnn<Rnn>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <typename OP>
void construct_primitive_build_string_batchnorm(
ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter,
ngraph::Node* node,
std::string& construct_string,
std::vector<size_t>& deps,
size_t& index,
std::ofstream& desc_file,
const bool append_relu,
const bool training)
{
const auto& args = node->get_inputs();
// batchnorm forward needs 6 primitives: input, weights, result, mean,
// variance, and batch_normalization_forward.
index = mkldnn_emitter.reserve_primitive_space(6);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
if (append_relu)
{
writer << "mkldnn::post_ops pops;\n";
writer << "const float ops_scale = 1.f;\n";
writer << "const float ops_alpha = -0.f; // relu negative slope\n";
writer << "const float ops_beta = 0.f;\n";
writer << "pops.append_eltwise("
"ops_scale, mkldnn::algorithm::eltwise_relu, ops_alpha, "
"ops_beta);\n";
}
else
{
writer << "mkldnn::post_ops pops = mkldnn::post_ops();\n";
}
auto weights_shape =
Shape{2, args[0].get_tensor().get_tensor_layout()->get_size()};
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 2);
auto weights_desc = mkldnn_emitter.build_memory_descriptor(
weights_shape, args[0].get_element_type(), mkldnn::memory::format_tag::nc);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
const float ops_scale = 1.f;
const float ops_alpha = -0.f; // relu negative slope
const float ops_beta = 0.f;
mkldnn::post_ops ops;
if (append_relu)
{
ops.append_eltwise(
ops_scale, mkldnn::algorithm::eltwise_relu, ops_alpha, ops_beta);
}
bool use_global_stats;
const mkldnn::memory::desc *mean_desc, *variance_desc;
if (training && args.size() == 3)
{
mean_desc = &mkldnn_utils::get_output_mkldnn_md(node, 1);
variance_desc = &mkldnn_utils::get_output_mkldnn_md(node, 2);
use_global_stats = false;
// query scratchpad size
auto batchnorm_desc =
mkldnn_emitter.get_batchnorm_forward_desc<OP>(node, true);
mkldnn_emitter.query_scratchpad_batchnorm_forward(batchnorm_desc, ops);
}
else
{
mean_desc = &mkldnn_utils::get_input_mkldnn_md(node, 3);
variance_desc = &mkldnn_utils::get_input_mkldnn_md(node, 4);
use_global_stats = true;
// query scratchpad size
auto batchnorm_desc =
mkldnn_emitter.get_batchnorm_forward_desc<OP>(node, false);
mkldnn_emitter.query_scratchpad_batchnorm_forward(batchnorm_desc, ops);
}
auto batchnorm = static_cast<const OP*>(node);
auto eps = batchnorm->get_eps_value();
writer << "mkldnn::primitive_attr bn_attr;\n";
writer << "bn_attr.set_post_ops(pops);\n";
writer << "bn_attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build batchnorm primitive descriptor\n";
if (use_global_stats)
{
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {
input_desc, *mean_desc, *variance_desc, weights_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto batchnorm_desc = "
"mkldnn::batch_normalization_forward::desc(mkldnn::prop_kind::"
"forward_training, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], " << eps
<< ", "
"mkldnn::normalization_flags::use_scale_shift | "
"mkldnn::normalization_flags::use_global_stats);\n";
}
else
{
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {
input_desc, weights_desc, result_desc, *mean_desc, *variance_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto batchnorm_desc = "
"mkldnn::batch_normalization_forward::desc(mkldnn::prop_kind::"
"forward_training, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], " << eps
<< ", "
"mkldnn::normalization_flags::use_scale_shift);\n";
}
writer << "auto batchnorm_prim_desc = "
"mkldnn::batch_normalization_forward::primitive_desc(batchnorm_"
"desc, "
"bn_attr, cg_ctx->global_cpu_engine);\n";
writer << "\n// build batchnorm primitive\n";
// batchnorm primitive
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new "
"mkldnn::batch_normalization_forward(batchnorm_prim_desc);\n";
writer
<< "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(batchnorm_prim_desc.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
BatchNormTraining)
{
construct_primitive_build_string_batchnorm<BatchNormTraining>(
mkldnn_emitter,
node,
construct_string,
deps,
index,
desc_file,
false /*Append relu*/,
true /*Training*/);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
BatchNormInference)
{
construct_primitive_build_string_batchnorm<BatchNormInference>(
mkldnn_emitter,
node,
construct_string,
deps,
index,
desc_file,
false /*Append relu*/,
false /*Training*/);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
BatchNormTrainingRelu)
{
construct_primitive_build_string_batchnorm<BatchNormTrainingRelu>(
mkldnn_emitter,
node,
construct_string,
deps,
index,
desc_file,
true /*Append relu*/,
true /*Training*/);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
BatchNormInferenceRelu)
{
construct_primitive_build_string_batchnorm<BatchNormInferenceRelu>(
mkldnn_emitter,
node,
construct_string,
deps,
index,
desc_file,
true /*Append relu*/,
false /*Training*/);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
BatchNormTrainingBackprop)
{
const auto& args = node->get_inputs();
const auto* batchnorm = static_cast<const BatchNormTrainingBackprop*>(node);
auto eps = batchnorm->get_eps_value();
auto weights_shape =
Shape{2, args[0].get_tensor().get_tensor_layout()->get_size()};
auto weights_desc = mkldnn_emitter.build_memory_descriptor(
weights_shape, args[0].get_element_type(), mkldnn::memory::format_tag::nc);
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 2);
auto mean_desc = mkldnn_utils::get_input_mkldnn_md(node, 3);
auto variance_desc = mkldnn_utils::get_input_mkldnn_md(node, 4);
auto delta_desc = mkldnn_utils::get_input_mkldnn_md(node, 5);
auto dinput_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto dweights_desc = mkldnn_emitter.build_memory_descriptor(
weights_shape, args[0].get_element_type(), mkldnn::memory::format_tag::nc);
// query scratchpad size
auto batchnorm_desc = mkldnn_emitter.get_batchnorm_backward_desc(node);
mkldnn_emitter.query_scratchpad_batchnorm_backward(
batchnorm_desc, input_desc, eps);
// batchnorm backward needs 8 primitives: weights, input, mean, variance,
// dinput, dweights, and batch_normalization_backward.
index = mkldnn_emitter.reserve_primitive_space(8);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {weights_desc,
input_desc,
mean_desc,
variance_desc,
delta_desc,
dinput_desc,
dweights_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto batchnorm_fdesc = "
"mkldnn::batch_normalization_forward::desc(mkldnn::prop_kind::"
"forward_training, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "], " << eps
<< ", "
"mkldnn::normalization_flags::use_scale_shift);\n";
writer << "auto batchnorm_fpd = "
"mkldnn::batch_normalization_forward::primitive_desc("
"batchnorm_fdesc, cg_ctx->global_cpu_engine);\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "auto batchnorm_desc = "
"mkldnn::batch_normalization_backward::desc(mkldnn::prop_kind::"
"backward, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 4 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "], " << eps
<< ", "
"mkldnn::normalization_flags::use_scale_shift);\n";
writer << "auto batchnorm_prim_desc = "
"mkldnn::batch_normalization_backward::primitive_desc(batchnorm_"
"desc, "
"attr, cg_ctx->global_cpu_engine, batchnorm_fpd);\n";
writer << "\n// build batchnorm primitive\n";
// batchnorm primitive
writer << "\n// build batchnorm primitives\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new "
"mkldnn::batch_normalization_backward(batchnorm_prim_desc);\n";
writer
<< "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(batchnorm_prim_desc.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <typename OP>
void construct_primitive_build_string_concat(
ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter,
ngraph::Node* node,
std::string& construct_string,
std::vector<size_t>& deps,
size_t& index,
std::ofstream& desc_file)
{
auto concat = static_cast<OP*>(node);
size_t concat_dim = concat->get_concatenation_axis();
size_t nargs = node->get_inputs().size();
// query scratchpad size
auto concat_pd = mkldnn_emitter.get_concat_desc<OP>(node, nargs);
mkldnn_emitter.query_scratchpad_concat(concat_pd);
// Concat needs number of inputs plus 2 primitives; those two are for result and
// concat.
index = mkldnn_emitter.reserve_primitive_space(nargs + 2);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs;
for (size_t i = 0; i < nargs; i++)
{
descs.push_back(mkldnn_utils::get_input_mkldnn_md(node, i));
}
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
descs.push_back(result_desc);
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "std::vector<mkldnn::memory::desc> inputs_desc;\n";
writer << "for (size_t i = " << desc_index << "; i < " << desc_index + nargs
<< "; i++)\n";
writer.block_begin();
writer << "inputs_desc.push_back(*cg_ctx->mkldnn_descriptors[i]);\n";
writer.block_end();
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "auto concat_prim_desc = "
"mkldnn::concat::primitive_desc( "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + nargs << "], "
<< std::to_string(static_cast<int>(concat_dim))
<< ", inputs_desc, cg_ctx->global_cpu_engine, attr);\n";
writer << "\n// build concat primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::concat(concat_prim_desc);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(concat_prim_desc.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Concat)
{
construct_primitive_build_string_concat<Concat>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(LRN)
{
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto lrn_desc = mkldnn_emitter.get_lrn_forward_desc(node);
mkldnn_emitter.query_scratchpad_lrn_forward(lrn_desc);
// LRN needs 3 primitives: input, result, and lrn_forward.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
const auto* lrn = static_cast<const LRN*>(node);
auto alpha = static_cast<float>(lrn->get_alpha());
auto beta = static_cast<float>(lrn->get_beta());
auto bias = static_cast<float>(lrn->get_bias());
auto nsize = static_cast<int>(lrn->get_nsize());
writer << "auto lrn_desc = "
"mkldnn::lrn_forward::desc(mkldnn::prop_kind::forward_scoring, "
"mkldnn::algorithm::lrn_across_channels, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], " << nsize << ", " << alpha << ", " << beta << ", "
<< bias << ");\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "auto lrn_prim_desc = "
"mkldnn::lrn_forward::primitive_desc(lrn_desc, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// build lrn primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::lrn_forward(lrn_prim_desc);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(lrn_prim_desc.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Slice)
{
const auto& out = node->get_outputs();
const Slice* slice = static_cast<const Slice*>(node);
auto result_shape = out[0].get_shape();
auto lower_bounds = slice->get_lower_bounds();
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// sub memory desc
auto dims = mkldnn::memory::dims(result_shape.begin(), result_shape.end());
auto offsets = mkldnn::memory::dims(lower_bounds.begin(), lower_bounds.end());
auto input_sub_desc = input_desc.submemory_desc(dims, offsets);
// Slice needs 3 primitives: input, result, and reorder.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_sub_desc, result_desc};
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build reorder primitives\n";
writer << "auto reorder_pd = "
"mkldnn::reorder::primitive_desc("
"*cg_ctx->mkldnn_memories["
<< std::to_string(deps[0]) << "]"
", *cg_ctx->mkldnn_memories["
<< std::to_string(deps[1]) << "], attr);\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::reorder(reorder_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(reorder_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <typename OP>
void construct_primitive_build_string_conv(
ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter,
ngraph::Node* node,
std::string& construct_string,
std::vector<size_t>& deps,
size_t& index,
std::ofstream& desc_file)
{
auto convolution = static_cast<const OP*>(node);
// query scratchpad size
auto conv_desc = mkldnn_emitter.get_convolution_forward_desc<OP>(node);
auto conv_attr = mkldnn_emitter.get_convolution_forward_attr<OP>(node);
mkldnn_emitter.query_scratchpad_convolution_forward(conv_desc, conv_attr);
Strides window_dilation_strides_adjusted;
for (size_t s : convolution->get_window_dilation_strides())
{
window_dilation_strides_adjusted.push_back(s - 1);
}
auto data_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto weights_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto strides = convolution->get_window_movement_strides();
auto pad_below = convolution->get_padding_below();
auto pad_above = convolution->get_padding_above();
if (mkldnn_emitter.has_bias<OP>())
{
index = mkldnn_emitter.reserve_primitive_space(5);
}
else
{
index = mkldnn_emitter.reserve_primitive_space(4);
}
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
writer << "// Write in memory descriptors\n";
std::vector<mkldnn::memory::desc> descs = {
data_desc, weights_desc, result_desc};
if (mkldnn_emitter.has_bias<OP>())
{
auto bias_desc = mkldnn_utils::get_input_mkldnn_md(node, 2);
descs.insert(descs.begin() + 2, bias_desc);
}
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "\n// build QConv primitive descriptor\n";
writer << "auto conv_desc = "
"mkldnn::convolution_forward::desc(mkldnn::prop_kind::forward,\n"
"mkldnn::algorithm::convolution_direct,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n";
if (mkldnn_emitter.has_bias<OP>())
{
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 2 << "],\n";
}
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + (descs.size() - 1)
<< "],\n";
WRITE_MKLDNN_DIMS(strides);
WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted);
WRITE_MKLDNN_DIMS(pad_below);
writer << "mkldnn::memory::dims{" << join(pad_above) << "});\n";
writer << "mkldnn::post_ops ops;\n";
if (std::is_same<OP, ngraph::op::ConvolutionBiasAdd>() ||
std::is_same<OP, ngraph::op::ConvolutionAdd>())
{
writer << "ops.append_sum(1.f);\n";
}
if (std::is_same<OP, ngraph::op::QuantizedConvolutionBiasAdd>() ||
std::is_same<OP, ngraph::op::QuantizedConvolutionBiasSignedAdd>())
{
writer << "ops.append_sum(dyn_post_op_scales[0]);\n";
}
if (has_relu<OP>(node))
{
writer << "const float ops_scale = 1.f;\n";
writer << "const float ops_alpha = -0.f; // relu negative slope\n";
writer << "const float ops_beta = 0.f;\n";
writer << "ops.append_eltwise("
"ops_scale, mkldnn::algorithm::eltwise_relu, ops_alpha, "
"ops_beta);\n";
}
writer << "mkldnn::primitive_attr conv_attr;\n";
writer << "conv_attr.set_post_ops(ops);\n";
writer << "conv_attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
if (mkldnn_emitter.is_quantized_conv<OP>())
{
writer << "conv_attr.set_output_scales(mask, dyn_scales);\n";
}
writer << "auto conv_pd = mkldnn::convolution_forward::primitive_desc("
"conv_desc, conv_attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::convolution_forward(conv_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(conv_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Convolution)
{
construct_primitive_build_string_conv<Convolution>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
QuantizedConvolution)
{
construct_primitive_build_string_conv<QuantizedConvolution>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void
MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(ConvolutionRelu)
{
construct_primitive_build_string_conv<ConvolutionRelu>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
QuantizedConvolutionRelu)
{
construct_primitive_build_string_conv<QuantizedConvolutionRelu>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void
MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(ConvolutionBias)
{
construct_primitive_build_string_conv<ConvolutionBias>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
QuantizedConvolutionBias)
{
construct_primitive_build_string_conv<QuantizedConvolutionBias>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
ConvolutionBiasAdd)
{
construct_primitive_build_string_conv<ConvolutionBiasAdd>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
QuantizedConvolutionBiasAdd)
{
construct_primitive_build_string_conv<QuantizedConvolutionBiasAdd>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(ConvolutionAdd)
{
construct_primitive_build_string_conv<ConvolutionAdd>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
QuantizedConvolutionBiasSignedAdd)
{
construct_primitive_build_string_conv<QuantizedConvolutionBiasSignedAdd>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
GroupConvolution)
{
construct_primitive_build_string_conv<GroupConvolution>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
GroupConvolutionBias)
{
construct_primitive_build_string_conv<GroupConvolutionBias>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <typename OP>
void construct_primitive_build_string_conv_backward_filters(
ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter,
ngraph::Node* node,
std::string& construct_string,
std::vector<size_t>& deps,
size_t& index,
std::ofstream& desc_file)
{
auto has_bias = false;
if (mkldnn_emitter.has_bias<OP>())
{
has_bias = true;
}
auto convolution = static_cast<const OP*>(node);
// query scratchpad size
auto bwd_desc = mkldnn_emitter.get_convolution_backward_weights_desc<OP>(node);
auto fwd_desc =
mkldnn_emitter.get_convolution_forward_desc_for_backward_op<OP>(node);
mkldnn_emitter.query_scratchpad_convolution_backward_weights(fwd_desc,
bwd_desc);
Strides window_dilation_strides_adjusted;
for (size_t s : convolution->get_window_dilation_strides_forward())
{
window_dilation_strides_adjusted.push_back(s - 1);
}
auto arg0_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto arg1_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto out0_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto strides = convolution->get_window_movement_strides_forward();
auto pad_below = convolution->get_padding_below_forward();
auto pad_above = convolution->get_padding_above_forward();
mkldnn::algorithm conv_algo = mkldnn_utils::get_conv_algo();
auto conv_algo_string = conv_algo == mkldnn::algorithm::convolution_auto
? "mkldnn::algorithm::convolution_auto,\n"
: "mkldnn::algorithm::convolution_direct,\n";
std::vector<mkldnn::memory::desc> descs = {arg0_desc, arg1_desc, out0_desc};
// ConvolutionBackpropFilter needs 4 primitives: src, diff_dst, diff_weights,
// and convolution_backward_weights.
// ConvolutionBackpropFiltersBias needs 5 primitives: src, diff_dst,
// diff_weights,
// diff_bias, and convolution_backward_weights.
if (has_bias)
{
index = mkldnn_emitter.reserve_primitive_space(5);
auto out1_desc = mkldnn_utils::get_output_mkldnn_md(node, 1);
descs.push_back(out1_desc);
}
else
{
index = mkldnn_emitter.reserve_primitive_space(4);
}
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto fwd_desc = "
"mkldnn::convolution_forward::desc(mkldnn::prop_kind::forward,\n";
writer << conv_algo_string;
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index
<< "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 2 << "],\n";
if (has_bias)
{
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 3 << "],\n";
}
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(strides);
WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted);
WRITE_MKLDNN_DIMS(pad_below);
writer << "mkldnn::memory::dims{" << join(pad_above) << "});\n";
writer << "\nauto bwd_desc = "
"mkldnn::convolution_backward_weights::desc(\n";
writer << conv_algo_string;
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index
<< "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 2 << "],\n";
if (has_bias)
{
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 3 << "],\n";
}
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(strides);
WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted);
WRITE_MKLDNN_DIMS(pad_below);
writer << "mkldnn::memory::dims{" << join(pad_above) << "});\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create forward primitive descriptor\n";
writer << "auto fwd_pd = mkldnn::convolution_forward::primitive_desc(fwd_desc, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// create backward primitive_descriptor\n";
writer << "auto bwd_pd = "
"mkldnn::convolution_backward_weights::primitive_desc(bwd_desc, "
"attr, "
"cg_ctx->global_cpu_engine, fwd_pd);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::convolution_backward_weights(bwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(bwd_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
ConvolutionBackpropFilters)
{
construct_primitive_build_string_conv_backward_filters<
ConvolutionBackpropFilters>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
ConvolutionBiasBackpropFiltersBias)
{
construct_primitive_build_string_conv_backward_filters<
ConvolutionBiasBackpropFiltersBias>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
ConvolutionBackpropData)
{
auto convolution = static_cast<const ConvolutionBackpropData*>(node);
// query scratchpad size
auto bwd_desc = mkldnn_emitter.get_convolution_backward_data_desc<
ngraph::op::ConvolutionBackpropData>(node);
auto fwd_desc = mkldnn_emitter.get_convolution_forward_desc_for_backward_op<
ngraph::op::ConvolutionBackpropData>(node);
mkldnn_emitter.query_scratchpad_convolution_backward_data(fwd_desc, bwd_desc);
Strides window_dilation_strides_adjusted;
for (size_t s : convolution->get_window_dilation_strides_forward())
{
window_dilation_strides_adjusted.push_back(s - 1);
}
auto arg0_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto arg1_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto out0_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto strides = convolution->get_window_movement_strides_forward();
auto pad_below = convolution->get_padding_below_forward();
auto pad_above = convolution->get_padding_above_forward();
mkldnn::algorithm conv_algo = mkldnn_utils::get_conv_algo();
auto conv_algo_string = conv_algo == mkldnn::algorithm::convolution_auto
? "mkldnn::algorithm::convolution_auto,\n"
: "mkldnn::algorithm::convolution_direct,\n";
std::vector<mkldnn::memory::desc> descs = {arg0_desc, arg1_desc, out0_desc};
// ConvolutionBackpropData needs 4 primitives: weights, diff_dst, diff_src,
// and convolution_backward_data.
index = mkldnn_emitter.reserve_primitive_space(4);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto fwd_desc = "
"mkldnn::convolution_forward::desc(mkldnn::prop_kind::forward,\n";
writer << conv_algo_string;
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 2
<< "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n";
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(strides);
WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted);
WRITE_MKLDNN_DIMS(pad_below);
writer << "mkldnn::memory::dims{" << join(pad_above) << "});\n";
writer << "\nauto bwd_desc = "
"mkldnn::convolution_backward_data::desc(\n";
writer << conv_algo_string;
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 2
<< "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n";
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(strides);
WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted);
WRITE_MKLDNN_DIMS(pad_below);
writer << "mkldnn::memory::dims{" << join(pad_above) << "});\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create forward primitive descriptor\n";
writer << "auto fwd_pd = mkldnn::convolution_forward::primitive_desc(fwd_desc, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// create backward primitive_descriptor\n";
writer << "auto bwd_pd = "
"mkldnn::convolution_backward_data::primitive_desc(bwd_desc, attr, "
"cg_ctx->global_cpu_engine, fwd_pd);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::convolution_backward_data(bwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(bwd_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
DeconvolutionBias)
{
auto dconv = static_cast<const DeconvolutionBias*>(node);
// query scratchpad size
auto deconvbias_desc =
mkldnn_emitter
.get_deconvolutionbias_forward_data<ngraph::op::DeconvolutionBias>(
node);
mkldnn_emitter.query_scratchpad_deconvolution_forward(deconvbias_desc);
// For dilation, MKLDNN wants to know how many elements to insert between, not
// how far
// apart to space the elements like nGraph. So we have to subtract 1 from each
// pos.
Strides window_dilation_strides_adjusted;
for (size_t s : dconv->get_window_dilation_strides_forward())
{
window_dilation_strides_adjusted.push_back(s - 1);
}
auto weights_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto delta_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto bias_desc = mkldnn_utils::get_input_mkldnn_md(node, 2);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto window_strides = dconv->get_window_movement_strides_forward();
auto padding_below = dconv->get_padding_below_forward();
auto padding_above = dconv->get_padding_above_forward();
CodeWriter writer;
std::vector<mkldnn::memory::desc> descs = {
weights_desc, delta_desc, bias_desc, result_desc};
// DeconvolutionBias needs 5 primitives: weights, delta, bias, result,
// and deconvolutionbias.
index = mkldnn_emitter.reserve_primitive_space(5);
deps = mkldnn_emitter.get_primitive_deps(index);
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
if (dconv->with_relu())
{
writer << "mkldnn::post_ops pops;\n";
writer << "const float ops_scale = 1.f;\n";
writer << "const float ops_alpha = -0.f; // relu negative slope\n";
writer << "const float ops_beta = 0.f;\n";
writer << "pops.append_eltwise("
"ops_scale, mkldnn::algorithm::eltwise_relu, ops_alpha, "
"ops_beta);\n";
}
else
{
writer << "mkldnn::post_ops pops = mkldnn::post_ops();\n";
}
writer << "mkldnn::primitive_attr dconv_attr;\n";
writer << "dconv_attr.set_post_ops(pops);\n";
writer << "dconv_attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\nauto dconv_desc = "
"mkldnn::deconvolution_forward::desc(\n"
"mkldnn::prop_kind::forward,\n"
"mkldnn::algorithm::deconvolution_direct,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 0 << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 2 << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 3 << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "\n// create forward primitive descriptor\n";
writer << "auto dconv_pd = "
"mkldnn::deconvolution_forward::primitive_desc(dconv_desc, "
"dconv_attr, cg_ctx->global_cpu_engine);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::deconvolution_forward(dconv_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(dconv_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <typename OP>
void construct_primitive_build_string_max_pool(
ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter,
ngraph::Node* node,
std::string& construct_string,
std::vector<size_t>& deps,
size_t& index,
std::ofstream& desc_file)
{
auto pool = static_cast<const OP*>(node);
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto max_pool_desc =
mkldnn_emitter.get_max_pooling_forward_desc<ngraph::op::MaxPool>(node,
false);
mkldnn_emitter.query_scratchpad_pooling_forward(max_pool_desc);
auto window_shape = pool->get_window_shape();
auto window_strides = pool->get_window_movement_strides();
auto padding_below = pool->get_padding_below();
auto padding_above = pool->get_padding_above();
CodeWriter writer;
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "\n// build Maxpool primitive descriptor\n";
writer << "auto max_pool_desc = ";
writer << "mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_"
"inference,\n";
writer << "mkldnn::algorithm::pooling_max,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "auto max_pool_pd = mkldnn::pooling_forward::primitive_desc("
"max_pool_desc, attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::pooling_forward(max_pool_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(max_pool_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <typename OP>
void construct_primitive_build_string_avg_pool(
ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter,
ngraph::Node* node,
std::string& construct_string,
std::vector<size_t>& deps,
size_t& index,
std::ofstream& desc_file)
{
auto pool = static_cast<const OP*>(node);
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto avg_pool_desc =
mkldnn_emitter.get_avg_pooling_forward_desc<ngraph::op::AvgPool>(node,
false);
mkldnn_emitter.query_scratchpad_pooling_forward(avg_pool_desc);
auto window_shape = pool->get_window_shape();
auto window_strides = pool->get_window_movement_strides();
auto padding_below = pool->get_padding_below();
auto padding_above = pool->get_padding_above();
auto include_padding_in_avg_computation =
pool->get_include_padding_in_avg_computation();
CodeWriter writer;
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "\n// build Avgpool primitive descriptor\n";
writer << "auto avg_pool_desc = ";
writer << "mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_"
"inference,\n";
if (include_padding_in_avg_computation)
{
writer << "mkldnn::algorithm::pooling_avg_include_padding,\n";
}
else
{
writer << "mkldnn::algorithm::pooling_avg_exclude_padding,\n";
}
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index
<< "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "auto avg_pool_pd = mkldnn::pooling_forward::primitive_desc("
"avg_pool_desc, attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::pooling_forward(avg_pool_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(avg_pool_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(MaxPool)
{
construct_primitive_build_string_max_pool<MaxPool>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(AvgPool)
{
construct_primitive_build_string_avg_pool<AvgPool>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
MaxPoolWithIndices)
{
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto pool = static_cast<const ngraph::op::MaxPoolWithIndices*>(node);
auto window_shape = pool->get_window_shape();
auto window_strides = pool->get_window_movement_strides();
auto padding_below = pool->get_padding_below();
auto padding_above = pool->get_padding_above();
// query scratchpad size
auto max_pool_desc = mkldnn_emitter.get_max_pooling_with_indices_forward_desc<
ngraph::op::MaxPoolWithIndices>(node);
mkldnn_emitter.query_scratchpad_pooling_forward(max_pool_desc);
// MaxPoolWithIndices needs 4 primitives: input, result, workspace, and
// pooling_forward.
index = mkldnn_emitter.reserve_primitive_space(4);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto pool_desc = "
"mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_training,\n"
"mkldnn::algorithm::pooling_max,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build primitive descriptor\n";
writer << "mkldnn::pooling_forward::primitive_desc fwd_pd{pool_desc, "
"cg_ctx->global_cpu_engine};\n";
writer << "cg_ctx->mkldnn_memories[" << std::to_string(deps[2])
<< "] = new mkldnn::memory(fwd_pd.workspace_desc(), "
"cg_ctx->global_cpu_engine, nullptr);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::pooling_forward(fwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(fwd_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void
MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(AvgPoolBackprop)
{
auto diff_dst_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto diff_src_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto pool = static_cast<const ngraph::op::AvgPoolBackprop*>(node);
auto window_shape = pool->get_window_shape();
auto window_strides = pool->get_window_movement_strides();
auto padding_below = pool->get_padding_below();
auto padding_above = pool->get_padding_above();
auto algo_string = pool->get_include_padding_in_avg_computation()
? "mkldnn::algorithm::pooling_avg_include_padding"
: "mkldnn::algorithm::pooling_avg_exclude_padding";
// query scratchpad size
auto avg_pool_fwd_desc =
mkldnn_emitter.get_avg_pooling_forward_desc<ngraph::op::AvgPoolBackprop>(
node, true);
auto avg_pool_desc =
mkldnn_emitter.get_avg_pooling_backward_desc<ngraph::op::AvgPoolBackprop>(
node);
mkldnn_emitter.query_scratchpad_avg_pooling_backward(avg_pool_fwd_desc,
avg_pool_desc);
// AvgPoolBackprop needs 3 primitives: diff_dst, diff_src, and pooling_backward.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {diff_dst_desc, diff_src_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer
<< "auto fwd_desc = "
"mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_training,\n";
writer << algo_string << ",\n";
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1
<< "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "auto bwd_desc = "
"mkldnn::pooling_backward::desc(\n";
writer << algo_string << ",\n";
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1
<< "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build primitive descriptor\n";
writer << "mkldnn::pooling_forward::primitive_desc fwd_pd{fwd_desc, "
"cg_ctx->global_cpu_engine};\n";
writer << "mkldnn::pooling_backward::primitive_desc bwd_pd{bwd_desc, attr, "
"cg_ctx->global_cpu_engine, fwd_pd};\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::pooling_backward(bwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(bwd_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void
MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(MaxPoolBackprop)
{
auto fprop_src_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto diff_dst_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto diff_src_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto pool = static_cast<const ngraph::op::MaxPoolWithIndices*>(node);
auto window_shape = pool->get_window_shape();
auto window_strides = pool->get_window_movement_strides();
auto padding_below = pool->get_padding_below();
auto padding_above = pool->get_padding_above();
// query scratchpad size
auto fwd_pool_desc =
mkldnn_emitter.get_max_pooling_forward_desc<ngraph::op::MaxPoolBackprop>(
node, true);
auto bwd_pool_desc =
mkldnn_emitter.get_max_pooling_backward_desc<ngraph::op::MaxPoolBackprop>(
node);
mkldnn_emitter.query_scratchpad_max_pooling_backward(fwd_pool_desc,
bwd_pool_desc);
// MaxPoolBackprop needs 6 primitives: fprop_src, diff_dst, diff_src, workspace
// pooling forward, and pooling_backward.
// It needs a new workspace.
index = mkldnn_emitter.reserve_primitive_space(6, true /* new workspace */);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {
fprop_src_desc, diff_dst_desc, diff_src_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto fwd_desc = "
"mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_training,\n"
"mkldnn::algorithm::pooling_max,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 2 << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "\nauto bwd_desc = "
"mkldnn::pooling_backward::desc(\n"
"mkldnn::algorithm::pooling_max,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 2 << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build primitive descriptor\n";
writer << "mkldnn::pooling_forward::primitive_desc fwd_pd{fwd_desc, attr, "
"cg_ctx->global_cpu_engine};\n";
writer << "mkldnn::pooling_backward::primitive_desc bwd_pd{bwd_desc, attr, "
"cg_ctx->global_cpu_engine, fwd_pd};\n";
// This is implemented differently from cpu builder,
// we only use one index and one deps here.
writer << "cg_ctx->mkldnn_memories[" << std::to_string(deps[3])
<< "] = new mkldnn::memory(fwd_pd.workspace_desc(), "
"cg_ctx->global_cpu_engine, nullptr);\n";
writer << "auto workspace = "
"(char*)malloc(fwd_pd.workspace_desc().get_size());"
"\n";
writer << "if (!workspace)\n";
writer.block_begin();
writer << "throw std::bad_alloc();\n";
writer.block_end();
writer << "cg_ctx->mkldnn_workspaces.push_back(workspace);\n";
deps[5] = mkldnn_emitter.reserve_workspace();
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(deps[4])
<< "] = new mkldnn::pooling_forward(fwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(deps[4])
<< "] = new mkldnn::memory::desc(fwd_pd.scratchpad_desc());\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::pooling_backward(bwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(bwd_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
MaxPoolWithIndicesBackprop)
{
auto diff_dst_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto diff_src_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
auto pool = static_cast<const ngraph::op::MaxPoolWithIndices*>(node);
auto window_shape = pool->get_window_shape();
auto window_strides = pool->get_window_movement_strides();
auto padding_below = pool->get_padding_below();
auto padding_above = pool->get_padding_above();
// query scratchpad size
auto fwd_pool_desc =
mkldnn_emitter
.get_max_pooling_forward_desc<ngraph::op::MaxPoolWithIndicesBackprop>(
node, true);
auto bwd_pool_desc =
mkldnn_emitter
.get_max_pooling_backward_desc<ngraph::op::MaxPoolWithIndicesBackprop>(
node);
mkldnn_emitter.query_scratchpad_max_pooling_with_indices_backward(
fwd_pool_desc, bwd_pool_desc);
// MaxPoolWithIndicesBackprop needs 4 primitives: diff_dst, fprop_workspace,
// diff_src
// and pooling_backward.
index = mkldnn_emitter.reserve_primitive_space(4);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {diff_dst_desc, diff_src_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto fwd_desc = "
"mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_training,\n"
"mkldnn::algorithm::pooling_max,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "auto bwd_desc = "
"mkldnn::pooling_backward::desc(\n"
"mkldnn::algorithm::pooling_max,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n";
WRITE_MKLDNN_DIMS(window_strides);
WRITE_MKLDNN_DIMS(window_shape);
WRITE_MKLDNN_DIMS(padding_below);
writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build primitive descriptor\n";
writer << "mkldnn::pooling_forward::primitive_desc fwd_pd{fwd_desc, "
"cg_ctx->global_cpu_engine};\n";
writer << "mkldnn::pooling_backward::primitive_desc bwd_pd{bwd_desc, attr, "
"cg_ctx->global_cpu_engine, fwd_pd};\n";
// this is different from cpu builder because we do not write workspace desc to
// desc_file.
// here workspace's mkldnn primitive index is in deps[2] in stead of deps[1].
writer << "cg_ctx->mkldnn_memories[" << std::to_string(deps[2])
<< "] = new mkldnn::memory(fwd_pd.workspace_desc(), "
"cg_ctx->global_cpu_engine, nullptr);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::pooling_backward(bwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(bwd_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
ngraph::runtime::cpu::op::ConvertLayout)
{
const auto& args = node->get_inputs();
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
bool input_format_is_nchw = mkldnn_utils::mkldnn_md_matches_format_tag(
input_desc.data, mkldnn::memory::format_tag::nchw);
if (input_format_is_nchw &&
mkldnn_utils::mkldnn_md_matches_format_tag(
result_desc.data, mkldnn::memory::format_tag::goihw))
{
// becomes a copy
input_desc = result_desc;
}
else if ((input_format_is_nchw ||
mkldnn_utils::mkldnn_md_matches_format_tag(
input_desc.data, mkldnn::memory::format_tag::nhwc)) &&
(mkldnn_utils::mkldnn_md_matches_format_tag(
result_desc.data, mkldnn::memory::format_tag::OIhw4i16o4i) &&
// check if compensation is conv_s8s8(1U)
result_desc.data.extra.flags & 0x1U))
{
auto arg0_shape = args[0].get_shape();
input_desc = mkldnn::memory::desc(
mkldnn::memory::dims(arg0_shape.begin(), arg0_shape.end()),
mkldnn_utils::get_mkldnn_data_type(args[0].get_element_type()),
mkldnn::memory::format_tag::oihw);
}
else if (input_format_is_nchw && input_desc.data.ndims == 4 &&
result_desc.data.ndims == 5 && node->get_users().size() == 1)
{
Shape weights_shape_groups;
if (auto gconv = std::dynamic_pointer_cast<ngraph::op::GroupConvolution>(
node->get_users()[0]))
{
weights_shape_groups = gconv->get_weights_dimensions();
}
else if (auto gconvb =
std::dynamic_pointer_cast<ngraph::op::GroupConvolutionBias>(
node->get_users()[0]))
{
weights_shape_groups = gconvb->get_weights_dimensions();
}
else
{
throw ngraph_error(
"Incompatible input/output shape in ConvertLayout op");
}
input_desc = mkldnn::memory::desc(
mkldnn::memory::dims(weights_shape_groups.begin(),
weights_shape_groups.end()),
mkldnn_utils::get_mkldnn_data_type(args[0].get_element_type()),
mkldnn::memory::format_tag::goihw);
}
// query scratchpad size
mkldnn_emitter.query_scratchpad_reorder(input_desc, result_desc);
// ConvertLayout needs 3 primitives: input, result, and reorder.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build reorder primitive\n";
writer << "auto reorder_pd = "
"mkldnn::reorder::primitive_desc("
"*cg_ctx->mkldnn_memories["
<< std::to_string(deps[0]) << "]"
", *cg_ctx->mkldnn_memories["
<< std::to_string(deps[1]) << "], attr);\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::reorder(reorder_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(reorder_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(ReluBackprop)
{
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto delta_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto bwd_desc = mkldnn_emitter.get_relu_backward_desc(node);
auto fwd_desc = mkldnn_emitter.get_relu_forward_desc(node);
mkldnn_emitter.query_scratchpad_eltwise_backward(fwd_desc, bwd_desc);
// ReluBackprop needs 4 primitives: input, delta, result, and eltwise_backward.
index = mkldnn_emitter.reserve_primitive_space(4);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, delta_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "const float negative_slope = 0.0f;\n";
writer << "auto fwd_desc = "
"mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward, "
"mkldnn::algorithm::eltwise_relu, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], negative_slope);\n";
writer << "auto bwd_desc = "
"mkldnn::eltwise_backward::desc(mkldnn::algorithm::eltwise_relu, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 2 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], negative_slope);\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create forward relu primitive descriptor\n";
writer
<< "auto relu_fwd_pd = mkldnn::eltwise_forward::primitive_desc(fwd_desc, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// create backward relu primitive_descriptor\n";
writer << "auto relu_bwd_pd = "
"mkldnn::eltwise_backward::primitive_desc(bwd_desc, attr, "
"cg_ctx->global_cpu_engine, relu_fwd_pd);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::eltwise_backward(relu_bwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(relu_bwd_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Relu)
{
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto relu_desc = mkldnn_emitter.get_relu_forward_desc(node);
mkldnn_emitter.query_scratchpad_eltwise_forward(relu_desc);
// Relu needs 3 primitives: input, result, and eltwise_forward.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "const float negative_slope = 0.0f;\n";
writer << "auto relu_desc = "
"mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward, "
"mkldnn::algorithm::eltwise_relu, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], negative_slope);\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create relu primitive_descriptor\n";
writer << "auto relu_pd = "
"mkldnn::eltwise_forward::primitive_desc(relu_desc, attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::eltwise_forward(relu_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(relu_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(CPULeakyRelu)
{
auto leaky_relu_node = static_cast<const ngraph::op::CPULeakyRelu*>(node);
float alpha = leaky_relu_node->get_alpha();
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto leaky_relu_desc = mkldnn_emitter.get_leaky_relu_desc(node);
mkldnn_emitter.query_scratchpad_eltwise_forward(leaky_relu_desc);
// CPULeakyRelu needs 3 primitives: input, result, and eltwise_forward.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "const float alpha = " << alpha << ";\n";
writer << "auto relu_desc = "
"mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward, "
"mkldnn::algorithm::eltwise_relu, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], alpha, 0.0f);\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create relu primitive_descriptor\n";
writer << "auto relu_pd = "
"mkldnn::eltwise_forward::primitive_desc(relu_desc, attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::eltwise_forward(relu_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(relu_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(BoundedRelu)
{
auto bounded_relu_node = static_cast<const ngraph::op::BoundedRelu*>(node);
float alpha = bounded_relu_node->get_alpha();
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto bounded_relu_desc = mkldnn_emitter.get_bounded_relu_desc(node);
mkldnn_emitter.query_scratchpad_eltwise_forward(bounded_relu_desc);
// BoundedRelu needs 3 primitives: input, result, and eltwise_forward.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "const float alpha = " << alpha << ";\n";
writer << "auto relu_desc = "
"mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward, "
"mkldnn::algorithm::eltwise_bounded_relu, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], alpha, 0.0f);\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create relu primitive_descriptor\n";
writer << "auto relu_pd = "
"mkldnn::eltwise_forward::primitive_desc(relu_desc, attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::eltwise_forward(relu_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(relu_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Sigmoid)
{
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto sigmoid_desc = mkldnn_emitter.get_sigmoid_forward_desc(node, false);
mkldnn_emitter.query_scratchpad_eltwise_forward(sigmoid_desc);
// Sigmoid needs 3 primitives: input, result, and eltwise_forward.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto sigmoid_desc = "
"mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward_training, "
"mkldnn::algorithm::eltwise_logistic, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], 0, 0);\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create sigmoid primitive_descriptor\n";
writer << "auto sigmoid_pd = "
"mkldnn::eltwise_forward::primitive_desc(sigmoid_desc, attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::eltwise_forward(sigmoid_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(sigmoid_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void
MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(SigmoidBackprop)
{
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto delta_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto fwd_desc = mkldnn_emitter.get_sigmoid_forward_desc(node, true);
auto bwd_desc = mkldnn_emitter.get_sigmoid_backward_desc(node);
mkldnn_emitter.query_scratchpad_eltwise_backward(fwd_desc, bwd_desc);
// SigmoidBackprop needs 4 primitives: input, delta, result, and
// eltwise_backward.
index = mkldnn_emitter.reserve_primitive_space(4);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, delta_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto fwd_desc = "
"mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward, "
"mkldnn::algorithm::eltwise_logistic, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], 0, 0);\n";
writer << "auto bwd_desc = "
"mkldnn::eltwise_backward::desc(mkldnn::algorithm::eltwise_logistic, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "], "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], 0, 0);\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create forward sigmoid primitive descriptor\n";
writer << "auto sigmoid_fwd_pd = "
"mkldnn::eltwise_forward::primitive_desc(fwd_desc, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// create backward sigmoid primitive_descriptor\n";
writer << "auto sigmoid_bwd_pd = "
"mkldnn::eltwise_backward::primitive_desc(bwd_desc, attr, "
"cg_ctx->global_cpu_engine, sigmoid_fwd_pd);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::eltwise_backward(sigmoid_bwd_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(sigmoid_bwd_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Softmax)
{
auto softmax = static_cast<const ngraph::op::Softmax*>(node);
if (softmax->get_axes().size() != 1)
{
throw ngraph_error("MKLDNN supports softmax only across single axis");
}
int softmax_axis = static_cast<int>(*(softmax->get_axes().begin()));
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto softmax_desc = mkldnn_emitter.get_softmax_forward_desc(node);
mkldnn_emitter.query_scratchpad_softmax_forward(softmax_desc);
// Softmax needs 3 primitives: input, result, and softmax_forward.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "auto softmax_desc = "
"mkldnn::softmax_forward::desc(mkldnn::prop_kind::forward_scoring, "
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "], " << softmax_axis << ");\n";
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// create softmax primitive_descriptor\n";
writer << "auto softmax_pd = "
"mkldnn::softmax_forward::primitive_desc(softmax_desc, attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::softmax_forward(softmax_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(softmax_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Quantize)
{
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
mkldnn_emitter.query_scratchpad_reorder(input_desc, result_desc);
// Quantize needs 3 primitives: input, result, and reorder.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_output_scales(mask, dyn_scales);\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build reorder primitive\n";
writer << "auto reorder_pd = "
"mkldnn::reorder::primitive_desc("
"*cg_ctx->mkldnn_memories["
<< std::to_string(deps[0]) << "]"
", *cg_ctx->mkldnn_memories["
<< std::to_string(deps[1]) << "], attr);\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::reorder(reorder_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(reorder_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Dequantize)
{
auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
mkldnn_emitter.query_scratchpad_reorder(input_desc, result_desc);
// Dequantize needs 3 primitives: input, result, and reorder.
index = mkldnn_emitter.reserve_primitive_space(3);
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc};
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "mkldnn::primitive_attr attr;\n";
writer << "attr.set_output_scales(mask, dyn_scales);\n";
writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
writer << "\n// build reorder primitive\n";
writer << "auto reorder_pd = "
"mkldnn::reorder::primitive_desc("
"*cg_ctx->mkldnn_memories["
<< std::to_string(deps[0]) << "]"
", *cg_ctx->mkldnn_memories["
<< std::to_string(deps[1]) << "], attr);\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::reorder(reorder_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(reorder_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <typename OP>
void construct_primitive_build_string_inner_product(
ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter,
ngraph::Node* node,
std::string& construct_string,
std::vector<size_t>& deps,
size_t& index,
std::ofstream& desc_file)
{
auto has_bias = false;
if (mkldnn_emitter.has_bias<OP>())
{
has_bias = true;
}
auto data_desc = mkldnn_utils::get_input_mkldnn_md(node, 0);
auto weights_desc = mkldnn_utils::get_input_mkldnn_md(node, 1);
auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0);
// query scratchpad size
auto ip_desc = mkldnn_emitter.get_inner_product_forward_desc<OP>(node);
auto ip_attr = mkldnn_emitter.get_inner_product_forward_attr<OP>(node);
mkldnn_emitter.query_scratchpad_ip_forward(ip_desc, ip_attr);
if (has_bias)
{
// QuantizedDotBias needs 5 primitives: input, weights, bias, result, and
// inner_product.
index = mkldnn_emitter.reserve_primitive_space(5);
}
else
{
// QuantizedDot needs 4 primitives: input, weights, result, and
// inner_product.
index = mkldnn_emitter.reserve_primitive_space(4);
}
deps = mkldnn_emitter.get_primitive_deps(index);
CodeWriter writer;
// Write memory descriptors to file
std::vector<mkldnn::memory::desc> descs = {
data_desc, weights_desc, result_desc};
if (has_bias)
{
auto bias_desc = mkldnn_utils::get_input_mkldnn_md(node, 2);
descs.push_back(bias_desc);
}
auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size();
mkldnn_emitter.reserve_descriptor_space(descs.size());
serialize_memory_descs(desc_file, descs, deps[0]);
writer << "\n// build primitive descriptor\n";
writer << "auto ip_desc = "
"mkldnn::inner_product_forward::desc(mkldnn::prop_kind::forward,\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index << "],\n"
"*cg_ctx->mkldnn_descriptors["
<< desc_index + 1 << "],\n";
if (has_bias)
{
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 3 << "],\n";
}
writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 2 << "]);\n";
writer << "\nmkldnn::post_ops ops;\n";
if (std::is_same<OP, ngraph::op::QuantizedDotBias>() &&
has_relu<ngraph::op::QuantizedDotBias>(node))
{
writer << "const float ops_scale = 1.f;\n";
writer << "const float ops_alpha = -0.f; // relu negative slope\n";
writer << "const float ops_beta = 0.f;\n";
writer << "ops.append_eltwise("
"ops_scale, mkldnn::algorithm::eltwise_relu, ops_alpha, "
"ops_beta);\n";
}
writer << "mkldnn::primitive_attr ip_attr;\n";
writer << "ip_attr.set_post_ops(ops);\n";
writer << "ip_attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n";
if (mkldnn_emitter.is_quantized_inner_product<OP>())
{
writer << "ip_attr.set_output_scales(mask, dyn_scales);\n";
}
writer << "auto ip_pd = "
"mkldnn::inner_product_forward::primitive_desc(ip_desc, ip_attr, "
"cg_ctx->global_cpu_engine);\n";
writer << "\n// build primitive\n";
writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index)
<< "] = new mkldnn::inner_product_forward(ip_pd);\n";
writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index)
<< "] = new mkldnn::memory::desc(ip_pd.scratchpad_desc());\n";
construct_string = writer.get_code();
}
template <>
void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(
QuantizedDotBias)
{
construct_primitive_build_string_inner_product<QuantizedDotBias>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
template <>
void
MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(QuantizedMatmul)
{
construct_primitive_build_string_inner_product<QuantizedMatmul>(
mkldnn_emitter, node, construct_string, deps, index, desc_file);
}
}
}
}
}
using namespace ngraph::runtime::cpu::pass;
#define TI(x) std::type_index(typeid(x))
static const PrimitiveBuildStringConstructOpMap prim_build_string_construct_dispatcher{
{TI(Add), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Add>},
{TI(BoundedRelu), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BoundedRelu>},
{TI(Concat), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Concat>},
{TI(runtime::cpu::op::ConvertLayout),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<runtime::cpu::op::ConvertLayout>},
{TI(BatchNormInference),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BatchNormInference>},
{TI(BatchNormTraining),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BatchNormTraining>},
{TI(BatchNormInferenceRelu),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BatchNormInferenceRelu>},
{TI(BatchNormTrainingRelu),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BatchNormTrainingRelu>},
{TI(BatchNormTrainingBackprop),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BatchNormTrainingBackprop>},
{TI(CPULeakyRelu), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<CPULeakyRelu>},
{TI(LRN), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<LRN>},
{TI(Lstm), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Lstm>},
{TI(Relu), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Relu>},
{TI(ReluBackprop), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ReluBackprop>},
{TI(Rnn), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Rnn>},
{TI(Convolution), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Convolution>},
{TI(ConvolutionRelu),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionRelu>},
{TI(ConvolutionBias),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionBias>},
{TI(ConvolutionBiasAdd),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionBiasAdd>},
{TI(ConvolutionAdd),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionAdd>},
{TI(GroupConvolution),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<GroupConvolution>},
{TI(GroupConvolutionBias),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<GroupConvolutionBias>},
{TI(QuantizedConvolution),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedConvolution>},
{TI(QuantizedConvolutionRelu),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedConvolutionRelu>},
{TI(QuantizedConvolutionBias),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedConvolutionBias>},
{TI(QuantizedConvolutionBiasAdd),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedConvolutionBiasAdd>},
{TI(QuantizedConvolutionBiasSignedAdd),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<
QuantizedConvolutionBiasSignedAdd>},
{TI(ConvolutionBackpropData),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionBackpropData>},
{TI(ConvolutionBackpropFilters),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionBackpropFilters>},
{TI(ConvolutionBiasBackpropFiltersBias),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<
ConvolutionBiasBackpropFiltersBias>},
{TI(DeconvolutionBias),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<DeconvolutionBias>},
{TI(MaxPoolWithIndices),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<MaxPoolWithIndices>},
{TI(MaxPoolWithIndicesBackprop),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<MaxPoolWithIndicesBackprop>},
{TI(Sigmoid), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Sigmoid>},
{TI(SigmoidBackprop),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<SigmoidBackprop>},
{TI(Slice), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Slice>},
{TI(Softmax), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Softmax>},
{TI(MaxPool), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<MaxPool>},
{TI(AvgPool), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<AvgPool>},
{TI(AvgPoolBackprop),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<AvgPoolBackprop>},
{TI(MaxPoolBackprop),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<MaxPoolBackprop>},
{TI(Quantize), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Quantize>},
{TI(Dequantize), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Dequantize>},
{TI(QuantizedDotBias),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedDotBias>},
{TI(QuantizedMatmul),
&MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedMatmul>},
};
bool MKLDNNPrimitiveBuildPass::run_on_call_graph(const std::list<std::shared_ptr<Node>>& nodes)
{
std::ofstream desc_file(m_desc_filename, std::ios::out | std::ios::binary);
for (const auto& shp_node : nodes)
{
Node* node = shp_node.get();
if (mkldnn_utils::use_mkldnn_kernel(node))
{
auto handler = prim_build_string_construct_dispatcher.find(TI(*node));
NGRAPH_CHECK(handler != prim_build_string_construct_dispatcher.end(),
"Unsupported node '",
node->description(),
"' in MKLDNNPrimitiveBuildPass");
std::string construct_string;
std::vector<size_t> deps;
size_t index;
handler->second(m_mkldnn_emitter, node, construct_string, deps, index, desc_file);
m_node_primitive_string_deps_index_map[node] =
std::tuple<std::string, std::vector<size_t>, size_t>(construct_string, deps, index);
}
}
return false;
}
#undef TI
| 137,676 | 39,366 |
/*
* Copyright 2004-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/io/async/EventHandler.h>
#include <folly/io/async/EventBase.h>
#include <assert.h>
namespace folly {
EventHandler::EventHandler(EventBase* eventBase, int fd) {
folly_event_set(&event_, fd, 0, &EventHandler::libeventCallback, this);
if (eventBase != nullptr) {
setEventBase(eventBase);
} else {
// Callers must set the EventBase and fd before using this timeout.
// Set event_->ev_base to nullptr to ensure that this happens.
// (otherwise libevent will initialize it to the "default" event_base)
event_.ev_base = nullptr;
eventBase_ = nullptr;
}
}
EventHandler::~EventHandler() {
unregisterHandler();
}
bool EventHandler::registerImpl(uint16_t events, bool internal) {
assert(event_.ev_base != nullptr);
// We have to unregister the event before we can change the event flags
if (isHandlerRegistered()) {
// If the new events are the same are the same as the already registered
// flags, we don't have to do anything. Just return.
auto flags = event_ref_flags(&event_);
if (events == event_.ev_events &&
static_cast<bool>(flags & EVLIST_INTERNAL) == internal) {
return true;
}
event_del(&event_);
}
// Update the event flags
// Unfortunately, event_set() resets the event_base, so we have to remember
// it before hand, then pass it back into event_base_set() afterwards
struct event_base* evb = event_.ev_base;
event_set(
&event_,
event_.ev_fd,
short(events),
&EventHandler::libeventCallback,
this);
event_base_set(evb, &event_);
// Set EVLIST_INTERNAL if this is an internal event
if (internal) {
event_ref_flags(&event_) |= EVLIST_INTERNAL;
}
// Add the event.
//
// Although libevent allows events to wait on both I/O and a timeout,
// we intentionally don't allow an EventHandler to also use a timeout.
// Callers must maintain a separate AsyncTimeout object if they want a
// timeout.
//
// Otherwise, it is difficult to handle persistent events properly. (The I/O
// event and timeout may both fire together the same time around the event
// loop. Normally we would want to inform the caller of the I/O event first,
// then the timeout. However, it is difficult to do this properly since the
// I/O callback could delete the EventHandler.) Additionally, if a caller
// uses the same struct event for both I/O and timeout, and they just want to
// reschedule the timeout, libevent currently makes an epoll_ctl() call even
// if the I/O event flags haven't changed. Using a separate event struct is
// therefore slightly more efficient in this case (although it does take up
// more space).
if (event_add(&event_, nullptr) < 0) {
LOG(ERROR) << "EventBase: failed to register event handler for fd "
<< event_.ev_fd << ": " << strerror(errno);
// Call event_del() to make sure the event is completely uninstalled
event_del(&event_);
return false;
}
return true;
}
void EventHandler::unregisterHandler() {
if (isHandlerRegistered()) {
event_del(&event_);
}
}
void EventHandler::attachEventBase(EventBase* eventBase) {
// attachEventBase() may only be called on detached handlers
assert(event_.ev_base == nullptr);
assert(!isHandlerRegistered());
// This must be invoked from the EventBase's thread
eventBase->dcheckIsInEventBaseThread();
setEventBase(eventBase);
}
void EventHandler::detachEventBase() {
ensureNotRegistered(__func__);
event_.ev_base = nullptr;
}
void EventHandler::changeHandlerFD(int fd) {
ensureNotRegistered(__func__);
// event_set() resets event_base.ev_base, so manually restore it afterwards
struct event_base* evb = event_.ev_base;
folly_event_set(&event_, fd, 0, &EventHandler::libeventCallback, this);
event_.ev_base = evb; // don't use event_base_set(), since evb may be nullptr
}
void EventHandler::initHandler(EventBase* eventBase, int fd) {
ensureNotRegistered(__func__);
folly_event_set(&event_, fd, 0, &EventHandler::libeventCallback, this);
setEventBase(eventBase);
}
void EventHandler::ensureNotRegistered(const char* fn) {
// Neither the EventBase nor file descriptor may be changed while the
// handler is registered. Treat it as a programmer bug and abort the program
// if this requirement is violated.
if (isHandlerRegistered()) {
LOG(ERROR) << fn << " called on registered handler; aborting";
abort();
}
}
void EventHandler::libeventCallback(libevent_fd_t fd, short events, void* arg) {
EventHandler* handler = reinterpret_cast<EventHandler*>(arg);
assert(fd == handler->event_.ev_fd);
(void)fd; // prevent unused variable warnings
auto observer = handler->eventBase_->getExecutionObserver();
if (observer) {
observer->starting(reinterpret_cast<uintptr_t>(handler));
}
// this can't possibly fire if handler->eventBase_ is nullptr
handler->eventBase_->bumpHandlingTime();
handler->handlerReady(uint16_t(events));
if (observer) {
observer->stopped(reinterpret_cast<uintptr_t>(handler));
}
}
void EventHandler::setEventBase(EventBase* eventBase) {
event_base_set(eventBase->getLibeventBase(), &event_);
eventBase_ = eventBase;
}
bool EventHandler::isPending() const {
if (event_ref_flags(&event_) & EVLIST_ACTIVE) {
if (event_.ev_res & EV_READ) {
return true;
}
}
return false;
}
} // namespace folly
| 6,010 | 1,865 |
#include <iostream>
#include <cstdio>
using namespace std;
bool is_prime(int x) {
if (x < 4) {
return true;
}
for (int i = 2; i * i <= x; ++i) {
if (x % i == 0) {
return false;
}
}
return true;
}
void solve() {
int d;
cin >> d;
int p = d + 1;
for (; !is_prime(p); ++p) {}
int q = p + d;
for (; !is_prime(q); ++q) {}
cout << p * q << "\n";
}
int main() {
int t;
cin >> t;
while (t--) {
solve();
}
}
| 456 | 214 |
/**
* // This is the ImmutableListNode's API interface.
* // You should not implement it, or speculate about its implementation.
* class ImmutableListNode {
* public:
* void printValue(); // print the value of the node.
* ImmutableListNode* getNext(); // return the next node.
* };
*/
class Solution {
public:
void printLinkedListInReverse(ImmutableListNode* head) {
if (head == nullptr) {
return;
}
printLinkedListInReverse(head->getNext());
head->printValue();
}
};
| 535 | 154 |
// Copyright Carl Philipp Reh 2009 - 2016.
// 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 MIZUIRO_COLOR_SET_PERCENTAGE_HPP_INCLUDED
#define MIZUIRO_COLOR_SET_PERCENTAGE_HPP_INCLUDED
#include <mizuiro/color/denormalize.hpp>
namespace mizuiro::color
{
template <typename Color, typename Channel, typename Float>
void set_percentage(Color &_color, Channel const &_channel, Float const _value)
{
_color.set(
_channel,
mizuiro::color::denormalize<typename Color::format>(_color.format_store(), _channel, _value));
}
}
#endif
| 678 | 258 |
#include "envoy/config/filter/thrift/rate_limit/v2alpha1/rate_limit.pb.validate.h"
#include "extensions/filters/common/ratelimit/ratelimit_registration.h"
#include "extensions/filters/network/thrift_proxy/filters/ratelimit/config.h"
#include "test/extensions/filters/network/thrift_proxy/mocks.h"
#include "test/mocks/server/mocks.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::_;
using testing::ReturnRef;
namespace Envoy {
namespace Extensions {
namespace ThriftFilters {
namespace RateLimitFilter {
namespace {
envoy::config::filter::thrift::rate_limit::v2alpha1::RateLimit
parseRateLimitFromV2Yaml(const std::string& yaml) {
envoy::config::filter::thrift::rate_limit::v2alpha1::RateLimit rate_limit;
MessageUtil::loadFromYaml(yaml, rate_limit);
return rate_limit;
}
} // namespace
TEST(RateLimitFilterConfigTest, ValidateFail) {
NiceMock<Server::Configuration::MockFactoryContext> context;
EXPECT_THROW(
RateLimitFilterConfig().createFilterFactoryFromProto(
envoy::config::filter::thrift::rate_limit::v2alpha1::RateLimit(), "stats", context),
ProtoValidationException);
}
TEST(RateLimitFilterConfigTest, RateLimitFilterCorrectProto) {
const std::string yaml_string = R"EOF(
domain: "test"
timeout: "1.337s"
)EOF";
auto proto_config = parseRateLimitFromV2Yaml(yaml_string);
NiceMock<Server::Configuration::MockFactoryContext> context;
NiceMock<Server::MockInstance> instance;
// Return the same singleton manager as instance so that config can be found there.
EXPECT_CALL(context, singletonManager()).WillOnce(ReturnRef(instance.singletonManager()));
Filters::Common::RateLimit::ClientFactoryPtr client_factory =
Filters::Common::RateLimit::rateLimitClientFactory(
instance, instance.clusterManager().grpcAsyncClientManager(),
envoy::config::bootstrap::v2::Bootstrap());
EXPECT_CALL(context.cluster_manager_.async_client_manager_, factoryForGrpcService(_, _, _))
.WillOnce(Invoke([](const envoy::api::v2::core::GrpcService&, Stats::Scope&, bool) {
return std::make_unique<NiceMock<Grpc::MockAsyncClientFactory>>();
}));
RateLimitFilterConfig factory;
auto cb = factory.createFilterFactoryFromProto(proto_config, "stats", context);
NetworkFilters::ThriftProxy::ThriftFilters::MockFilterChainFactoryCallbacks filter_callback;
EXPECT_CALL(filter_callback, addDecoderFilter(_));
cb(filter_callback);
}
} // namespace RateLimitFilter
} // namespace ThriftFilters
} // namespace Extensions
} // namespace Envoy
| 2,551 | 804 |
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include "gq.def.hpp"
| 70 | 30 |
#include "AnimNotifyState_SpawnSkinnedMesh.h"
UAnimNotifyState_SpawnSkinnedMesh::UAnimNotifyState_SpawnSkinnedMesh() {
this->ItemCategory = EItemCategory::PrimaryWeapon;
this->UseFirstPersonComponent = false;
}
| 221 | 81 |
// Copyright (C) 2018-2022 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include "gtest/gtest.h"
#include "ngraph/ngraph.hpp"
NGRAPH_SUPPRESS_DEPRECATED_START
using namespace ngraph;
using namespace std;
TEST(node_input_output, input_create) {
auto x = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4});
auto y = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4});
auto add = make_shared<op::v1::Add>(x, y);
auto add_in_0 = add->input(0);
auto add_in_1 = add->input(1);
EXPECT_EQ(add_in_0.get_node(), add.get());
EXPECT_EQ(add_in_0.get_index(), 0);
EXPECT_EQ(add_in_0.get_element_type(), element::f32);
EXPECT_EQ(add_in_0.get_shape(), (Shape{1, 2, 3, 4}));
EXPECT_TRUE(add_in_0.get_partial_shape().same_scheme(PartialShape{1, 2, 3, 4}));
EXPECT_EQ(add_in_0.get_source_output(), Output<Node>(x, 0));
EXPECT_EQ(add_in_1.get_node(), add.get());
EXPECT_EQ(add_in_1.get_index(), 1);
EXPECT_EQ(add_in_1.get_element_type(), element::f32);
EXPECT_EQ(add_in_1.get_shape(), (Shape{1, 2, 3, 4}));
EXPECT_TRUE(add_in_1.get_partial_shape().same_scheme(PartialShape{1, 2, 3, 4}));
EXPECT_EQ(add_in_1.get_source_output(), Output<Node>(y, 0));
EXPECT_THROW(add->input(2), std::out_of_range);
}
TEST(node_input_output, input_create_const) {
auto x = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4});
auto y = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4});
auto add = make_shared<const op::v1::Add>(x, y);
auto add_in_0 = add->input(0);
auto add_in_1 = add->input(1);
EXPECT_EQ(add_in_0.get_node(), add.get());
EXPECT_EQ(add_in_0.get_index(), 0);
EXPECT_EQ(add_in_0.get_element_type(), element::f32);
EXPECT_EQ(add_in_0.get_shape(), (Shape{1, 2, 3, 4}));
EXPECT_TRUE(add_in_0.get_partial_shape().same_scheme(PartialShape{1, 2, 3, 4}));
EXPECT_EQ(add_in_0.get_source_output(), Output<Node>(x, 0));
EXPECT_EQ(add_in_1.get_node(), add.get());
EXPECT_EQ(add_in_1.get_index(), 1);
EXPECT_EQ(add_in_1.get_element_type(), element::f32);
EXPECT_EQ(add_in_1.get_shape(), (Shape{1, 2, 3, 4}));
EXPECT_TRUE(add_in_1.get_partial_shape().same_scheme(PartialShape{1, 2, 3, 4}));
EXPECT_EQ(add_in_1.get_source_output(), Output<Node>(y, 0));
EXPECT_THROW(add->input(2), std::out_of_range);
}
TEST(node_input_output, output_create) {
auto x = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4});
auto y = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4});
auto add = make_shared<op::v1::Add>(x, y);
auto add_out_0 = add->output(0);
add_out_0.set_names({"a", "b"});
EXPECT_EQ(add_out_0.get_names(), std::unordered_set<std::string>({"a", "b"}));
EXPECT_EQ(add_out_0.get_any_name(), "a");
add_out_0.add_names({"c", "d"});
EXPECT_EQ(add_out_0.get_names(), std::unordered_set<std::string>({"a", "b", "c", "d"}));
EXPECT_EQ(add_out_0.get_any_name(), "a");
EXPECT_EQ(add_out_0.get_node(), add.get());
EXPECT_EQ(add_out_0.get_index(), 0);
EXPECT_EQ(add_out_0.get_element_type(), element::f32);
EXPECT_EQ(add_out_0.get_shape(), (Shape{1, 2, 3, 4}));
EXPECT_TRUE(add_out_0.get_partial_shape().same_scheme(PartialShape{1, 2, 3, 4}));
EXPECT_THROW(add->output(1), std::out_of_range);
}
TEST(node_input_output, output_create_const) {
auto x = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4});
auto y = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4});
auto add = make_shared<const op::v1::Add>(x, y);
auto add_out_0 = add->output(0);
EXPECT_EQ(add_out_0.get_names().size(), 0);
EXPECT_EQ(add_out_0.get_node(), add.get());
EXPECT_EQ(add_out_0.get_index(), 0);
EXPECT_EQ(add_out_0.get_element_type(), element::f32);
EXPECT_EQ(add_out_0.get_shape(), (Shape{1, 2, 3, 4}));
EXPECT_TRUE(add_out_0.get_partial_shape().same_scheme(PartialShape{1, 2, 3, 4}));
EXPECT_THROW(add->output(1), std::out_of_range);
}
TEST(node_input_output, output_rt_info) {
auto x = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4});
auto y = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4});
auto add = make_shared<op::v1::Add>(x, y);
auto add_const = make_shared<const op::v1::Add>(x, y);
Output<Node> output = add->output(0);
Output<const Node> output_const = add_const->output(0);
auto& rt = output.get_rt_info();
rt["test"] = nullptr;
EXPECT_TRUE(output.get_rt_info().count("test"));
EXPECT_TRUE(output.get_tensor_ptr()->get_rt_info().count("test"));
EXPECT_TRUE(output_const.get_rt_info().empty());
}
TEST(node_input_output, input_set_argument) {
auto x = make_shared<op::Parameter>(element::f32, Shape{1});
auto y = make_shared<op::Parameter>(element::f32, Shape{2});
auto z = make_shared<op::Parameter>(element::f32, Shape{3});
auto add = make_shared<op::v1::Add>(x, y);
EXPECT_EQ(add->get_input_size(), 2);
EXPECT_EQ(add->input(0).get_shape(), Shape{1});
EXPECT_EQ(add->input(1).get_shape(), Shape{2});
add->set_argument(1, z);
EXPECT_EQ(add->get_input_size(), 2);
EXPECT_EQ(add->input(0).get_shape(), Shape{1});
EXPECT_EQ(add->input(1).get_shape(), Shape{3});
add->set_arguments(NodeVector{z, x});
EXPECT_EQ(add->get_input_size(), 2);
EXPECT_EQ(add->input(0).get_shape(), Shape{3});
EXPECT_EQ(add->input(1).get_shape(), Shape{1});
}
| 5,546 | 2,492 |
#include "interpreter.h"
#include <cstring>
#include <cmath>
#include <algorithm>
#include "scanner.h"
#include "parser.h"
namespace lasm {
Interpreter::Interpreter(BaseError &onError, BaseInstructionSet &is, InterpreterCallback *callback,
FileReader *reader):
onError(onError), instructions(is), callback(callback),
globals(std::make_shared<Environment>(Environment())), environment(globals),
globalLabels(std::make_shared<Environment>(Environment())), labels(globalLabels), reader(reader) {
initGlobals();
}
void Interpreter::initGlobals() {
auto hi = LasmObject(CALLABLE_O, std::static_pointer_cast<Callable>(std::shared_ptr<NativeHi>(new NativeHi())));
globals->define("hi", hi);
auto lo = LasmObject(CALLABLE_O, std::static_pointer_cast<Callable>(std::shared_ptr<NativeLo>(new NativeLo())));
globals->define("lo", lo);
auto address = LasmObject(CALLABLE_O, std::static_pointer_cast<Callable>(
std::shared_ptr<NativeAddress>(new NativeAddress())));
globals->define("_A", address);
auto ord = LasmObject(CALLABLE_O, std::static_pointer_cast<Callable>(
std::shared_ptr<NativeOrd>(new NativeOrd())));
globals->define("ord", ord);
auto len = LasmObject(CALLABLE_O, std::static_pointer_cast<Callable>(
std::shared_ptr<NativeLen>(new NativeLen())));
globals->define("len", len);
auto setEnvName = LasmObject(CALLABLE_O, std::static_pointer_cast<Callable>(
std::shared_ptr<NativeSetEnvName>(new NativeSetEnvName())));
globals->define("setScopeName", setEnvName);
}
std::vector<InstructionResult> Interpreter::interprete(std::vector<std::shared_ptr<Stmt>> stmts,
bool abortOnError, int passes) {
for (int i = 0; i < passes && (!onError.didError() || !abortOnError); i++) {
execPass(stmts);
}
return code;
}
void Interpreter::execPass(std::vector<std::shared_ptr<Stmt>> stmts) {
labels = globalLabels;
environment = globals;
environment->clear();
labelTable.clear();
labelTable.push_back(globalLabels);
code.clear();
initGlobals();
address = 0;
try {
for (auto stmt : stmts) {
execute(stmt);
}
} catch (LasmException &e) {
onError.onError(e.getType(), e.getToken(), &e);
}
pass++;
}
void Interpreter::execute(std::shared_ptr<Stmt> stmt) {
stmt->accept(this);
}
LasmObject Interpreter::evaluate(std::shared_ptr<Expr> expr) {
return std::any_cast<LasmObject>(expr->accept(this));
}
std::any Interpreter::visitBinary(BinaryExpr *expr) {
auto left = evaluate(expr->left);
auto right = evaluate(expr->right);
switch (expr->op->getType()) {
case MINUS:
// first number decides auto-cast
if (left.isNumber() && right.isScalar()) {
return LasmObject(NUMBER_O, left.toNumber() - right.toNumber());
} else if (left.isReal() && right.isScalar()) {
return LasmObject(REAL_O, left.toReal() - right.toReal());
} else {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, left.getType(), expr->op);
}
break;
case SLASH:
if (left.isNumber() && right.isScalar()) {
// integer division by 0 is not valid!
if (right.toNumber() == 0) {
throw LasmDivisionByZero(expr->op);
}
return LasmObject(NUMBER_O, left.toNumber() / right.toNumber());
} else if (left.isReal() && right.isScalar()) {
return LasmObject(REAL_O, left.toReal() / right.toReal());
} else {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, left.getType(), expr->op);
}
break;
case PERCENT:
if (left.isNumber() && right.isNumber()) {
if (right.toNumber() == 0) {
throw LasmDivisionByZero(expr->op);
}
return LasmObject(NUMBER_O, left.toNumber() % right.toNumber());
} else {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O}, left.getType(), expr->op);
}
case STAR:
// first number decides auto-cast
if (left.isNumber() && right.isScalar()) {
return LasmObject(NUMBER_O, left.toNumber() * right.toNumber());
} else if (left.isReal() && right.isScalar()) {
return LasmObject(REAL_O, left.toReal() * right.toReal());
} else {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, left.getType(), expr->op);
}
break;
case PLUS:
// first number decides auto-cast
if (left.isNumber() && right.isScalar()) {
return LasmObject(NUMBER_O, left.toNumber() + right.toNumber());
} else if (left.isReal() && right.isScalar()) {
return LasmObject(REAL_O, left.toReal() + right.toReal());
} else if (left.isString() && right.isString()) {
// string cat
return LasmObject(STRING_O, left.toString() + right.toString());
} else {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O, STRING_O}, left.getType(), expr->op);
}
break;
// comparison
case GREATER:
if (left.isNumber() && right.isScalar()) {
return LasmObject(BOOLEAN_O, left.toNumber() > right.toNumber());
} else if (right.isReal() && right.isScalar()) {
return LasmObject(BOOLEAN_O, left.toReal() > right.toReal());
} else {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, left.getType(), expr->op);
}
case LESS:
if (left.isNumber() && right.isScalar()) {
return LasmObject(BOOLEAN_O, left.toNumber() < right.toNumber());
} else if (left.isReal() && right.isScalar()) {
return LasmObject(BOOLEAN_O, left.toReal() < right.toReal());
} else {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, left.getType(), expr->op);
}
case GREATER_EQUAL:
if (left.isNumber() && right.isScalar()) {
return LasmObject(BOOLEAN_O, left.toNumber() >= right.toNumber());
} else if (left.isReal() && right.isScalar()) {
return LasmObject(BOOLEAN_O, left.toReal() >= right.toReal());
} else {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, left.getType(), expr->op);
}
case LESS_EQUAL:
if (left.isNumber() && left.isScalar()) {
return LasmObject(BOOLEAN_O, left.toNumber() <= right.toNumber());
} else if (left.isReal() && left.isScalar()) {
return LasmObject(BOOLEAN_O, left.toReal() <= right.toReal());
} else {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, left.getType(), expr->op);
}
case BANG_EQUAL:
return LasmObject(BOOLEAN_O, !left.isEqual(right));
case EQUAL_EQUAL:
return LasmObject(BOOLEAN_O, left.isEqual(right));
case BIN_AND:
if (right.isScalar() && left.isScalar()) {
return LasmObject(NUMBER_O, left.toNumber() & right.toNumber());
} else {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, right.getType(), expr->op);
}
case BIN_OR:
if (right.isScalar() && left.isScalar()) {
return LasmObject(NUMBER_O, left.toNumber() | right.toNumber());
} else {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, right.getType(), expr->op);
}
case BIN_XOR:
if (right.isScalar() && left.isScalar()) {
return LasmObject(NUMBER_O, left.toNumber() ^ right.toNumber());
} else {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, right.getType(), expr->op);
}
case BIN_SHIFT_LEFT:
if (right.isScalar() && left.isScalar()) {
return LasmObject(NUMBER_O, left.toNumber() << right.toNumber());
} else {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, right.getType(), expr->op);
}
case BIN_SHIFT_RIGHT:
if (right.isScalar() && left.isScalar()) {
return LasmObject(NUMBER_O, left.toNumber() >> right.toNumber());
} else {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, right.getType(), expr->op);
}
default:
break;
}
// should be unreacbable
return LasmObject(NIL_O, nullptr);
}
std::any Interpreter::visitUnary(UnaryExpr *expr) {
auto right = evaluate(expr->right);
auto sign = -1;
switch (expr->op->getType()) {
case PLUS:
sign = 1;
case MINUS:
if (right.isReal()) {
return LasmObject(REAL_O, sign * right.toReal());
} else if (right.isNumber()) {
return LasmObject(NUMBER_O, sign * right.toNumber());
} else {
// type error!
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, right.getType(), expr->op);
}
break;
case BANG:
return LasmObject(BOOLEAN_O, !right.isTruthy());
case BIN_NOT:
if (right.isScalar()) {
return LasmObject(NUMBER_O, ~right.toNumber());
} else {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, right.getType(), expr->op);
}
default:
break;
}
// should be unreacbable
return LasmObject(NIL_O, nullptr);
}
std::any Interpreter::visitLiteral(LiteralExpr *expr) {
return expr->value;
}
std::any Interpreter::visitGrouping(GroupingExpr *expr) {
return evaluate(expr->expression);
}
std::any Interpreter::visitVariable(VariableExpr *expr) {
// label environment. used for n+1th pass
// only set if it has not already been assigned
bool wasFirstPass = false;
if (!expr->getEnv(address).get() && pass == 0) {
wasFirstPass = true; // if so do not throw
expr->setEnv(address, labels);
}
try {
// TODO can we avoid copy constructor? does it matter?
return LasmObject(environment->get(expr->name).get());
} catch (LasmUndefinedReference &e) {
// attempt getting label by name, but only on second+ pass
if (expr->getEnv(address).get() && !wasFirstPass) {
return LasmObject(expr->getEnv(address)->get(expr->name).get());
} else if (!wasFirstPass) {
throw e; // only re-throw on second+ pass
}
}
return LasmObject(NIL_O, 0);
}
std::any Interpreter::visitAssign(AssignExpr *expr) {
auto value = evaluate(expr->value);
environment->assign(expr->name, value);
return value;
}
std::any Interpreter::visitLogical(LogicalExpr *expr) {
auto left = evaluate(expr->left);
if (expr->op->getType() == OR) {
if (left.isTruthy()) {
return left;
}
} else {
if (!left.isTruthy()) {
return left;
}
}
return evaluate(expr->right);
}
std::any Interpreter::visitCall(CallExpr *expr) {
auto callee = evaluate(expr->callee);
std::vector<LasmObject> arguments;
for (auto arg : expr->arguments) {
arguments.push_back(evaluate(arg));
}
if (callee.getType() != CALLABLE_O) {
throw LasmNotCallable(expr->paren);
}
auto function = callee.toCallable();
if (function->getArity() != arguments.size()) {
throw LasmArityError(expr->paren);
}
return function->call(this, arguments, expr);
}
std::any Interpreter::visitList(ListExpr *expr) {
auto values = std::make_shared<std::vector<LasmObject>>(std::vector<LasmObject>());
// evaluate all array members
for (auto init : expr->list) {
values->push_back(evaluate(init));
}
return LasmObject(LIST_O, values);
}
std::any Interpreter::visitIndex(IndexExpr *expr) {
auto value = evaluate(expr->object);
auto index = evaluate(expr->index);
if (!index.isNumber()) {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O}, index.getType(), expr->token);
}
LasmObject result(NIL_O, nullptr);
if (value.isString()) {
if ((unsigned long)value.toString().length() < (unsigned long)index.toNumber()) {
throw LasmException(INDEX_OUT_OF_BOUNDS, expr->token);
}
return LasmObject(NUMBER_O, (lasmNumber)value.toString().at(index.toNumber()));
} else if (value.isList()) {
if ((unsigned long)value.toList()->size() < (unsigned long)index.toNumber()) {
throw LasmException(INDEX_OUT_OF_BOUNDS, expr->token);
}
return value.toList()->at(index.toNumber());
} else {
throw LasmTypeError(std::vector<ObjectType> {STRING_O, LIST_O}, value.getType(), expr->token);
}
return result;
}
std::any Interpreter::visitIndexAssign(IndexAssignExpr *expr) {
auto value = evaluate(expr->value);
auto index = evaluate(expr->index);
auto object = evaluate(expr->object);
if (!index.isNumber()) {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O}, index.getType(), expr->token);
}
if (object.isList()) {
if ((unsigned long)object.toList()->size() < (unsigned long)index.toNumber()) {
throw LasmException(INDEX_OUT_OF_BOUNDS, expr->token);
}
object.toList()->at(index.toNumber()) = value;
return value;
} else {
throw LasmTypeError(std::vector<ObjectType> {STRING_O, LIST_O}, object.getType(), expr->token);
}
return value;
}
std::any Interpreter::visitExpression(ExpressionStmt *stmt) {
auto obj = std::any_cast<LasmObject>(evaluate(stmt->expr));
if (callback) {
callback->onStatementExecuted(&obj);
}
return std::any();
}
std::any Interpreter::visitLet(LetStmt *stmt) {
LasmObject value = LasmObject(NIL_O, nullptr);
if (stmt->init.get() != nullptr) {
value = evaluate(stmt->init);
}
environment->define(stmt->name->getLexeme(), value);
return std::any();
}
std::any Interpreter::visitBlock(BlockStmt *stmt) {
executeBlock(stmt->statements, std::make_shared<Environment>(Environment(environment)));
return std::any();
}
void Interpreter::executeBlock(std::vector<std::shared_ptr<Stmt>> statements,
std::shared_ptr<Environment> environment, std::shared_ptr<Environment> labels) {
if (!labels.get()) {
labels = std::make_shared<Environment>(Environment(this->labels));
}
labelTable.push_back(labels);
auto previous = this->environment;
auto previousLabels = this->labels;
this->environment = environment;
this->labels = labels;
for (auto statement : statements) {
execute(statement);
}
this->environment = previous;
this->labels = previousLabels;
}
std::any Interpreter::visitIf(IfStmt *stmt) {
if (evaluate(stmt->condition).isTruthy()) {
execute(stmt->thenBranch);
} else if (stmt->elseBranch.get()) {
execute(stmt->elseBranch);
}
return std::any();
}
std::any Interpreter::visitWhile(WhileStmt *stmt) {
auto previousLabels = labels;
while (evaluate(stmt->condition).isTruthy()) {
execute(stmt->body);
}
labels = previousLabels;
return std::any();
}
std::any Interpreter::visitFunction(FunctionStmt *stmt) {
auto fn = std::make_shared<LasmFunction>(LasmFunction(stmt));
LasmObject obj(CALLABLE_O, std::static_pointer_cast<Callable>(fn));
environment->define(stmt->name->getLexeme(), obj);
return std::any();
}
std::any Interpreter::visitReturn(ReturnStmt *stmt) {
LasmObject value(NIL_O, nullptr);
if (stmt->value.get()) {
value = evaluate(stmt->value);
}
// TODO this is kinda ugly but functional
throw Return(value);
}
std::any Interpreter::visitInstruction(InstructionStmt *stmt) {
// TODO catch unresolved labels, return a deep clone of the current environment
// and set unresolved flag along with the expression.
// after assembly ends do a second pass and attempt to
// resolve again
onInstructionResult(instructions.generate(this, stmt->info, stmt));
return std::any();
}
std::any Interpreter::visitDirective(DirectiveStmt *stmt) {
return stmt->directive->execute(this, stmt);
}
std::any Interpreter::visitAlign(AlignStmt *stmt) {
auto alignTo = evaluate(stmt->alignTo);
auto fillValue = evaluate(stmt->fillValue);
if (!alignTo.isScalar()) {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, alignTo.getType(), stmt->token);
} else if (!fillValue.isScalar()) {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, fillValue.getType(), stmt->token);
} else if (fillValue.toNumber() > 0xFF) {
throw LasmException(VALUE_OUT_OF_RANGE, stmt->token);
}
unsigned long size = 0;
// fill until address % fillValue == 0
while ((address % (unsigned long)alignTo.toNumber()) != 0) {
address++;
size++;
}
// make byte array with fill value as instruction result
std::shared_ptr<char[]> data(new char[size]);
memset(data.get(), fillValue.toNumber(), size);
onInstructionResult(InstructionResult(data, size, getAddress()-size, stmt->token));
return std::any();
}
std::any Interpreter::visitFill(FillStmt *stmt) {
auto fillTo = evaluate(stmt->fillAddress);
auto fillValue = evaluate(stmt->fillValue);
if (!fillTo.isScalar()) {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, fillTo.getType(), stmt->token);
} else if (!fillValue.isScalar()) {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, fillValue.getType(), stmt->token);
} else if (fillValue.toNumber() > 0xFF || (unsigned long)fillTo.toNumber() <= address) {
throw LasmException(VALUE_OUT_OF_RANGE, stmt->token);
}
// make data of address-fillTo
unsigned long size = (unsigned long)fillTo.toNumber() - address;
std::shared_ptr<char[]> data(new char[size]);
memset(data.get(), fillValue.toNumber(), size);
address += size;
onInstructionResult(InstructionResult(data, size, getAddress()-size, stmt->token));
return std::any();
}
std::any Interpreter::visitOrg(OrgStmt *stmt) {
auto address = evaluate(stmt->address);
if (!address.isScalar()) {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, address.getType(), stmt->token);
}
this->address = address.toNumber();
return std::any();
}
/**
* uncomment relevant line at compile time
*/
#define NATIVE_BO LITTLE
// #define NATIVE_BO BIG
// TODO test endianess
std::any Interpreter::visitDefineByte(DefineByteStmt *stmt) {
// loop all exprs. each entry gets a node as code
for (auto value : stmt->values) {
auto evaluated = evaluate(value);
std::shared_ptr<char[]> data;
if (evaluated.isString()) {
data = std::shared_ptr<char[]>(new char[evaluated.toString().length()+1]);
// for string we ignore endianess anyway
strncpy(data.get(), evaluated.toString().c_str(), evaluated.toString().length()+1);
onInstructionResult(InstructionResult(data, evaluated.toString().length()+1, getAddress(), stmt->token));
address += evaluated.toString().length()+1;
} else if (evaluated.isScalar() || evaluated.isBool()) {
data = std::shared_ptr<char[]>(new char[stmt->size]);
switch (stmt->size) {
case 1: {
char value = 0;
if (evaluated.isBool()) {
value = evaluated.toBool();
} else if (evaluated.isNumber()) {
value = evaluated.toNumber();
} else {
throw LasmException(VALUE_OUT_OF_RANGE, stmt->token);
}
memcpy(data.get(), &value, stmt->size);
break;
}
case 2: {
short value = 0;
if (evaluated.isBool()) {
value = evaluated.toBool();
} else if (evaluated.isNumber()) {
value = evaluated.toNumber();
} else {
throw LasmException(VALUE_OUT_OF_RANGE, stmt->token);
}
memcpy(data.get(), &value, stmt->size);
break;
}
case 4: {
int value = 0;
if (evaluated.isBool()) {
value = evaluated.toBool();
} else if (evaluated.isNumber()) {
value = evaluated.toNumber();
} else if (evaluated.isReal()) {
float evalFloat = evaluated.toReal();
memcpy(&value, &evalFloat, stmt->size);
} else {
throw LasmException(VALUE_OUT_OF_RANGE, stmt->token);
}
memcpy(data.get(), &value, stmt->size);
break;
}
case 8: {
long value = 0;
if (evaluated.isBool()) {
value = evaluated.toBool();
} else if (evaluated.isNumber()) {
value = evaluated.toNumber();
} else if (evaluated.isReal()) {
double evalFloat = evaluated.toReal();
memcpy(&value, &evalFloat, stmt->size);
} else {
throw LasmException(VALUE_OUT_OF_RANGE, stmt->token);
}
memcpy(data.get(), &value, stmt->size);
break;
}
default:
throw LasmException(VALUE_OUT_OF_RANGE, stmt->token);
}
// is the required endianess the same as the native endianess?
// TODO test this! maybe on a powerpc machine?
if (stmt->endianess != getNativeByteOrder()) {
// swap time!
std::shared_ptr<char[]> swapped(new char[stmt->size]);
std::reverse_copy(data.get(), data.get()+stmt->size, swapped.get());
data = swapped;
}
onInstructionResult(InstructionResult(data, stmt->size, getAddress(), stmt->token));
address += stmt->size;
} else {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O, BOOLEAN_O, STRING_O},
evaluated.getType(), stmt->token);
}
}
return std::any();
}
std::any Interpreter::visitBss(BssStmt *stmt) {
auto startAddress = evaluate(stmt->startAddress);
if (!startAddress.isNumber()) {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O}, startAddress.getType(), stmt->token);
}
// define every value
for (auto declaration : stmt->declarations) {
auto value = evaluate(declaration->init);
if (!value.isNumber()) {
throw LasmTypeError(std::vector<ObjectType> {NUMBER_O}, value.getType(), declaration->name);
}
// add start address to it
environment->define(declaration->name->getLexeme(), startAddress);
startAddress = LasmObject(NUMBER_O, value.toNumber() + startAddress.toNumber());
}
return std::any();
}
std::any Interpreter::visitLabel(LabelStmt *stmt) {
LasmObject obj(NUMBER_O, (lasmNumber)address);
labels->define(stmt->name->getLexeme().substr(0, stmt->name->getLexeme().length()-1), obj);
return std::any();
}
std::any Interpreter::visitIncbin(IncbinStmt *stmt) {
if (!reader) { return std::any(); }
// either read file using the included file reader
// or just use the already buffered value
if (!stmt->data.get()) {
auto path = evaluate(stmt->filePath);
if (path.getType() != STRING_O) {
throw LasmTypeError(std::vector<ObjectType> {STRING_O}, path.getType(), stmt->token);
}
auto stream = reader->openFile(path.toString());
unsigned long size = 0;
auto data = reader->readFullFile(stream, &size);
reader->closeFile(stream);
stmt->data = data;
stmt->size = size;
}
// return result
onInstructionResult(InstructionResult(stmt->data, stmt->size, getAddress(), stmt->token));
address += stmt->size;
return std::any();
}
std::any Interpreter::visitInclude(IncludeStmt *stmt) {
if (!reader) { return std::any(); }
// either read file and then interprete or just interprete right now!
if (!stmt->wasparsed) {
auto path = evaluate(stmt->filePath);
if (path.getType() != STRING_O) {
throw LasmTypeError(std::vector<ObjectType> {STRING_O}, path.getType(), stmt->token);
}
stmt->wasparsed = true;
auto previousPath = reader->getDir();
reader->changeDir(path.toString(), true);
auto stream = reader->openFile(path.toString());
auto source = std::string(reader->readFullFile(stream).get());
reader->closeFile(stream);
Scanner scanner(onError, instructions, source, path.toString());
auto tokens = scanner.scanTokens();
if (onError.didError()) {
return std::any();
}
Parser parser(onError, tokens, instructions);
auto ast = parser.parse();
if (onError.didError()) {
return std::any();
}
stmt->stmts = ast;
reader->changeDir(previousPath);
}
try {
for (auto stmt : stmt->stmts) {
execute(stmt);
}
} catch (LasmException &e) {
onError.onError(e.getType(), e.getToken(), &e);
}
return std::any();
}
void Interpreter::onInstructionResult(InstructionResult result) {
if (pass != 0) {
code.push_back(result);
}
}
Endianess Interpreter::getNativeByteOrder() {
// check endianess
const unsigned int x = 0x12345678;
if (*((char*)&x) == 0x78) {
// little endian
return LITTLE;
}
// big endian
return BIG;
}
}
| 29,784 | 8,355 |
//===- AMDGPUAsmParser.cpp - Parse SI asm to MCInst instructions ----------===//
//
// 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 "AMDGPU.h"
#include "AMDKernelCodeT.h"
#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
#include "MCTargetDesc/AMDGPUTargetStreamer.h"
#include "SIDefines.h"
#include "SIInstrInfo.h"
#include "Utils/AMDGPUAsmUtils.h"
#include "Utils/AMDGPUBaseInfo.h"
#include "Utils/AMDKernelCodeTUtils.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Twine.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCParser/MCAsmLexer.h"
#include "llvm/MC/MCParser/MCAsmParser.h"
#include "llvm/MC/MCParser/MCAsmParserExtension.h"
#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
#include "llvm/MC/MCParser/MCTargetAsmParser.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/AMDGPUMetadata.h"
#include "llvm/Support/AMDHSAKernelDescriptor.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MachineValueType.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/SMLoc.h"
#include "llvm/Support/TargetParser.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstring>
#include <iterator>
#include <map>
#include <memory>
#include <string>
using namespace llvm;
using namespace llvm::AMDGPU;
using namespace llvm::amdhsa;
namespace {
class AMDGPUAsmParser;
enum RegisterKind { IS_UNKNOWN, IS_VGPR, IS_SGPR, IS_TTMP, IS_SPECIAL };
//===----------------------------------------------------------------------===//
// Operand
//===----------------------------------------------------------------------===//
class AMDGPUOperand : public MCParsedAsmOperand {
enum KindTy {
Token,
Immediate,
Register,
Expression
} Kind;
SMLoc StartLoc, EndLoc;
const AMDGPUAsmParser *AsmParser;
public:
AMDGPUOperand(KindTy Kind_, const AMDGPUAsmParser *AsmParser_)
: MCParsedAsmOperand(), Kind(Kind_), AsmParser(AsmParser_) {}
using Ptr = std::unique_ptr<AMDGPUOperand>;
struct Modifiers {
bool Abs = false;
bool Neg = false;
bool Sext = false;
bool hasFPModifiers() const { return Abs || Neg; }
bool hasIntModifiers() const { return Sext; }
bool hasModifiers() const { return hasFPModifiers() || hasIntModifiers(); }
int64_t getFPModifiersOperand() const {
int64_t Operand = 0;
Operand |= Abs ? SISrcMods::ABS : 0;
Operand |= Neg ? SISrcMods::NEG : 0;
return Operand;
}
int64_t getIntModifiersOperand() const {
int64_t Operand = 0;
Operand |= Sext ? SISrcMods::SEXT : 0;
return Operand;
}
int64_t getModifiersOperand() const {
assert(!(hasFPModifiers() && hasIntModifiers())
&& "fp and int modifiers should not be used simultaneously");
if (hasFPModifiers()) {
return getFPModifiersOperand();
} else if (hasIntModifiers()) {
return getIntModifiersOperand();
} else {
return 0;
}
}
friend raw_ostream &operator <<(raw_ostream &OS, AMDGPUOperand::Modifiers Mods);
};
enum ImmTy {
ImmTyNone,
ImmTyGDS,
ImmTyLDS,
ImmTyOffen,
ImmTyIdxen,
ImmTyAddr64,
ImmTyOffset,
ImmTyInstOffset,
ImmTyOffset0,
ImmTyOffset1,
ImmTyGLC,
ImmTySLC,
ImmTyTFE,
ImmTyD16,
ImmTyClampSI,
ImmTyOModSI,
ImmTyDppCtrl,
ImmTyDppRowMask,
ImmTyDppBankMask,
ImmTyDppBoundCtrl,
ImmTySdwaDstSel,
ImmTySdwaSrc0Sel,
ImmTySdwaSrc1Sel,
ImmTySdwaDstUnused,
ImmTyDMask,
ImmTyUNorm,
ImmTyDA,
ImmTyR128A16,
ImmTyLWE,
ImmTyExpTgt,
ImmTyExpCompr,
ImmTyExpVM,
ImmTyFORMAT,
ImmTyHwreg,
ImmTyOff,
ImmTySendMsg,
ImmTyInterpSlot,
ImmTyInterpAttr,
ImmTyAttrChan,
ImmTyOpSel,
ImmTyOpSelHi,
ImmTyNegLo,
ImmTyNegHi,
ImmTySwizzle,
ImmTyHigh
};
struct TokOp {
const char *Data;
unsigned Length;
};
struct ImmOp {
int64_t Val;
ImmTy Type;
bool IsFPImm;
Modifiers Mods;
};
struct RegOp {
unsigned RegNo;
bool IsForcedVOP3;
Modifiers Mods;
};
union {
TokOp Tok;
ImmOp Imm;
RegOp Reg;
const MCExpr *Expr;
};
bool isToken() const override {
if (Kind == Token)
return true;
if (Kind != Expression || !Expr)
return false;
// When parsing operands, we can't always tell if something was meant to be
// a token, like 'gds', or an expression that references a global variable.
// In this case, we assume the string is an expression, and if we need to
// interpret is a token, then we treat the symbol name as the token.
return isa<MCSymbolRefExpr>(Expr);
}
bool isImm() const override {
return Kind == Immediate;
}
bool isInlinableImm(MVT type) const;
bool isLiteralImm(MVT type) const;
bool isRegKind() const {
return Kind == Register;
}
bool isReg() const override {
return isRegKind() && !hasModifiers();
}
bool isRegOrImmWithInputMods(MVT type) const {
return isRegKind() || isInlinableImm(type);
}
bool isRegOrImmWithInt16InputMods() const {
return isRegOrImmWithInputMods(MVT::i16);
}
bool isRegOrImmWithInt32InputMods() const {
return isRegOrImmWithInputMods(MVT::i32);
}
bool isRegOrImmWithInt64InputMods() const {
return isRegOrImmWithInputMods(MVT::i64);
}
bool isRegOrImmWithFP16InputMods() const {
return isRegOrImmWithInputMods(MVT::f16);
}
bool isRegOrImmWithFP32InputMods() const {
return isRegOrImmWithInputMods(MVT::f32);
}
bool isRegOrImmWithFP64InputMods() const {
return isRegOrImmWithInputMods(MVT::f64);
}
bool isVReg() const {
return isRegClass(AMDGPU::VGPR_32RegClassID) ||
isRegClass(AMDGPU::VReg_64RegClassID) ||
isRegClass(AMDGPU::VReg_96RegClassID) ||
isRegClass(AMDGPU::VReg_128RegClassID) ||
isRegClass(AMDGPU::VReg_256RegClassID) ||
isRegClass(AMDGPU::VReg_512RegClassID);
}
bool isVReg32OrOff() const {
return isOff() || isRegClass(AMDGPU::VGPR_32RegClassID);
}
bool isSDWAOperand(MVT type) const;
bool isSDWAFP16Operand() const;
bool isSDWAFP32Operand() const;
bool isSDWAInt16Operand() const;
bool isSDWAInt32Operand() const;
bool isImmTy(ImmTy ImmT) const {
return isImm() && Imm.Type == ImmT;
}
bool isImmModifier() const {
return isImm() && Imm.Type != ImmTyNone;
}
bool isClampSI() const { return isImmTy(ImmTyClampSI); }
bool isOModSI() const { return isImmTy(ImmTyOModSI); }
bool isDMask() const { return isImmTy(ImmTyDMask); }
bool isUNorm() const { return isImmTy(ImmTyUNorm); }
bool isDA() const { return isImmTy(ImmTyDA); }
bool isR128A16() const { return isImmTy(ImmTyR128A16); }
bool isLWE() const { return isImmTy(ImmTyLWE); }
bool isOff() const { return isImmTy(ImmTyOff); }
bool isExpTgt() const { return isImmTy(ImmTyExpTgt); }
bool isExpVM() const { return isImmTy(ImmTyExpVM); }
bool isExpCompr() const { return isImmTy(ImmTyExpCompr); }
bool isOffen() const { return isImmTy(ImmTyOffen); }
bool isIdxen() const { return isImmTy(ImmTyIdxen); }
bool isAddr64() const { return isImmTy(ImmTyAddr64); }
bool isOffset() const { return isImmTy(ImmTyOffset) && isUInt<16>(getImm()); }
bool isOffset0() const { return isImmTy(ImmTyOffset0) && isUInt<16>(getImm()); }
bool isOffset1() const { return isImmTy(ImmTyOffset1) && isUInt<8>(getImm()); }
bool isOffsetU12() const { return (isImmTy(ImmTyOffset) || isImmTy(ImmTyInstOffset)) && isUInt<12>(getImm()); }
bool isOffsetS13() const { return (isImmTy(ImmTyOffset) || isImmTy(ImmTyInstOffset)) && isInt<13>(getImm()); }
bool isGDS() const { return isImmTy(ImmTyGDS); }
bool isLDS() const { return isImmTy(ImmTyLDS); }
bool isGLC() const { return isImmTy(ImmTyGLC); }
bool isSLC() const { return isImmTy(ImmTySLC); }
bool isTFE() const { return isImmTy(ImmTyTFE); }
bool isD16() const { return isImmTy(ImmTyD16); }
bool isFORMAT() const { return isImmTy(ImmTyFORMAT) && isUInt<8>(getImm()); }
bool isBankMask() const { return isImmTy(ImmTyDppBankMask); }
bool isRowMask() const { return isImmTy(ImmTyDppRowMask); }
bool isBoundCtrl() const { return isImmTy(ImmTyDppBoundCtrl); }
bool isSDWADstSel() const { return isImmTy(ImmTySdwaDstSel); }
bool isSDWASrc0Sel() const { return isImmTy(ImmTySdwaSrc0Sel); }
bool isSDWASrc1Sel() const { return isImmTy(ImmTySdwaSrc1Sel); }
bool isSDWADstUnused() const { return isImmTy(ImmTySdwaDstUnused); }
bool isInterpSlot() const { return isImmTy(ImmTyInterpSlot); }
bool isInterpAttr() const { return isImmTy(ImmTyInterpAttr); }
bool isAttrChan() const { return isImmTy(ImmTyAttrChan); }
bool isOpSel() const { return isImmTy(ImmTyOpSel); }
bool isOpSelHi() const { return isImmTy(ImmTyOpSelHi); }
bool isNegLo() const { return isImmTy(ImmTyNegLo); }
bool isNegHi() const { return isImmTy(ImmTyNegHi); }
bool isHigh() const { return isImmTy(ImmTyHigh); }
bool isMod() const {
return isClampSI() || isOModSI();
}
bool isRegOrImm() const {
return isReg() || isImm();
}
bool isRegClass(unsigned RCID) const;
bool isRegOrInlineNoMods(unsigned RCID, MVT type) const {
return (isRegClass(RCID) || isInlinableImm(type)) && !hasModifiers();
}
bool isSCSrcB16() const {
return isRegOrInlineNoMods(AMDGPU::SReg_32RegClassID, MVT::i16);
}
bool isSCSrcV2B16() const {
return isSCSrcB16();
}
bool isSCSrcB32() const {
return isRegOrInlineNoMods(AMDGPU::SReg_32RegClassID, MVT::i32);
}
bool isSCSrcB64() const {
return isRegOrInlineNoMods(AMDGPU::SReg_64RegClassID, MVT::i64);
}
bool isSCSrcF16() const {
return isRegOrInlineNoMods(AMDGPU::SReg_32RegClassID, MVT::f16);
}
bool isSCSrcV2F16() const {
return isSCSrcF16();
}
bool isSCSrcF32() const {
return isRegOrInlineNoMods(AMDGPU::SReg_32RegClassID, MVT::f32);
}
bool isSCSrcF64() const {
return isRegOrInlineNoMods(AMDGPU::SReg_64RegClassID, MVT::f64);
}
bool isSSrcB32() const {
return isSCSrcB32() || isLiteralImm(MVT::i32) || isExpr();
}
bool isSSrcB16() const {
return isSCSrcB16() || isLiteralImm(MVT::i16);
}
bool isSSrcV2B16() const {
llvm_unreachable("cannot happen");
return isSSrcB16();
}
bool isSSrcB64() const {
// TODO: Find out how SALU supports extension of 32-bit literals to 64 bits.
// See isVSrc64().
return isSCSrcB64() || isLiteralImm(MVT::i64);
}
bool isSSrcF32() const {
return isSCSrcB32() || isLiteralImm(MVT::f32) || isExpr();
}
bool isSSrcF64() const {
return isSCSrcB64() || isLiteralImm(MVT::f64);
}
bool isSSrcF16() const {
return isSCSrcB16() || isLiteralImm(MVT::f16);
}
bool isSSrcV2F16() const {
llvm_unreachable("cannot happen");
return isSSrcF16();
}
bool isVCSrcB32() const {
return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::i32);
}
bool isVCSrcB64() const {
return isRegOrInlineNoMods(AMDGPU::VS_64RegClassID, MVT::i64);
}
bool isVCSrcB16() const {
return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::i16);
}
bool isVCSrcV2B16() const {
return isVCSrcB16();
}
bool isVCSrcF32() const {
return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::f32);
}
bool isVCSrcF64() const {
return isRegOrInlineNoMods(AMDGPU::VS_64RegClassID, MVT::f64);
}
bool isVCSrcF16() const {
return isRegOrInlineNoMods(AMDGPU::VS_32RegClassID, MVT::f16);
}
bool isVCSrcV2F16() const {
return isVCSrcF16();
}
bool isVSrcB32() const {
return isVCSrcF32() || isLiteralImm(MVT::i32) || isExpr();
}
bool isVSrcB64() const {
return isVCSrcF64() || isLiteralImm(MVT::i64);
}
bool isVSrcB16() const {
return isVCSrcF16() || isLiteralImm(MVT::i16);
}
bool isVSrcV2B16() const {
llvm_unreachable("cannot happen");
return isVSrcB16();
}
bool isVSrcF32() const {
return isVCSrcF32() || isLiteralImm(MVT::f32) || isExpr();
}
bool isVSrcF64() const {
return isVCSrcF64() || isLiteralImm(MVT::f64);
}
bool isVSrcF16() const {
return isVCSrcF16() || isLiteralImm(MVT::f16);
}
bool isVSrcV2F16() const {
llvm_unreachable("cannot happen");
return isVSrcF16();
}
bool isKImmFP32() const {
return isLiteralImm(MVT::f32);
}
bool isKImmFP16() const {
return isLiteralImm(MVT::f16);
}
bool isMem() const override {
return false;
}
bool isExpr() const {
return Kind == Expression;
}
bool isSoppBrTarget() const {
return isExpr() || isImm();
}
bool isSWaitCnt() const;
bool isHwreg() const;
bool isSendMsg() const;
bool isSwizzle() const;
bool isSMRDOffset8() const;
bool isSMRDOffset20() const;
bool isSMRDLiteralOffset() const;
bool isDPPCtrl() const;
bool isGPRIdxMode() const;
bool isS16Imm() const;
bool isU16Imm() const;
StringRef getExpressionAsToken() const {
assert(isExpr());
const MCSymbolRefExpr *S = cast<MCSymbolRefExpr>(Expr);
return S->getSymbol().getName();
}
StringRef getToken() const {
assert(isToken());
if (Kind == Expression)
return getExpressionAsToken();
return StringRef(Tok.Data, Tok.Length);
}
int64_t getImm() const {
assert(isImm());
return Imm.Val;
}
ImmTy getImmTy() const {
assert(isImm());
return Imm.Type;
}
unsigned getReg() const override {
return Reg.RegNo;
}
SMLoc getStartLoc() const override {
return StartLoc;
}
SMLoc getEndLoc() const override {
return EndLoc;
}
SMRange getLocRange() const {
return SMRange(StartLoc, EndLoc);
}
Modifiers getModifiers() const {
assert(isRegKind() || isImmTy(ImmTyNone));
return isRegKind() ? Reg.Mods : Imm.Mods;
}
void setModifiers(Modifiers Mods) {
assert(isRegKind() || isImmTy(ImmTyNone));
if (isRegKind())
Reg.Mods = Mods;
else
Imm.Mods = Mods;
}
bool hasModifiers() const {
return getModifiers().hasModifiers();
}
bool hasFPModifiers() const {
return getModifiers().hasFPModifiers();
}
bool hasIntModifiers() const {
return getModifiers().hasIntModifiers();
}
uint64_t applyInputFPModifiers(uint64_t Val, unsigned Size) const;
void addImmOperands(MCInst &Inst, unsigned N, bool ApplyModifiers = true) const;
void addLiteralImmOperand(MCInst &Inst, int64_t Val, bool ApplyModifiers) const;
template <unsigned Bitwidth>
void addKImmFPOperands(MCInst &Inst, unsigned N) const;
void addKImmFP16Operands(MCInst &Inst, unsigned N) const {
addKImmFPOperands<16>(Inst, N);
}
void addKImmFP32Operands(MCInst &Inst, unsigned N) const {
addKImmFPOperands<32>(Inst, N);
}
void addRegOperands(MCInst &Inst, unsigned N) const;
void addRegOrImmOperands(MCInst &Inst, unsigned N) const {
if (isRegKind())
addRegOperands(Inst, N);
else if (isExpr())
Inst.addOperand(MCOperand::createExpr(Expr));
else
addImmOperands(Inst, N);
}
void addRegOrImmWithInputModsOperands(MCInst &Inst, unsigned N) const {
Modifiers Mods = getModifiers();
Inst.addOperand(MCOperand::createImm(Mods.getModifiersOperand()));
if (isRegKind()) {
addRegOperands(Inst, N);
} else {
addImmOperands(Inst, N, false);
}
}
void addRegOrImmWithFPInputModsOperands(MCInst &Inst, unsigned N) const {
assert(!hasIntModifiers());
addRegOrImmWithInputModsOperands(Inst, N);
}
void addRegOrImmWithIntInputModsOperands(MCInst &Inst, unsigned N) const {
assert(!hasFPModifiers());
addRegOrImmWithInputModsOperands(Inst, N);
}
void addRegWithInputModsOperands(MCInst &Inst, unsigned N) const {
Modifiers Mods = getModifiers();
Inst.addOperand(MCOperand::createImm(Mods.getModifiersOperand()));
assert(isRegKind());
addRegOperands(Inst, N);
}
void addRegWithFPInputModsOperands(MCInst &Inst, unsigned N) const {
assert(!hasIntModifiers());
addRegWithInputModsOperands(Inst, N);
}
void addRegWithIntInputModsOperands(MCInst &Inst, unsigned N) const {
assert(!hasFPModifiers());
addRegWithInputModsOperands(Inst, N);
}
void addSoppBrTargetOperands(MCInst &Inst, unsigned N) const {
if (isImm())
addImmOperands(Inst, N);
else {
assert(isExpr());
Inst.addOperand(MCOperand::createExpr(Expr));
}
}
static void printImmTy(raw_ostream& OS, ImmTy Type) {
switch (Type) {
case ImmTyNone: OS << "None"; break;
case ImmTyGDS: OS << "GDS"; break;
case ImmTyLDS: OS << "LDS"; break;
case ImmTyOffen: OS << "Offen"; break;
case ImmTyIdxen: OS << "Idxen"; break;
case ImmTyAddr64: OS << "Addr64"; break;
case ImmTyOffset: OS << "Offset"; break;
case ImmTyInstOffset: OS << "InstOffset"; break;
case ImmTyOffset0: OS << "Offset0"; break;
case ImmTyOffset1: OS << "Offset1"; break;
case ImmTyGLC: OS << "GLC"; break;
case ImmTySLC: OS << "SLC"; break;
case ImmTyTFE: OS << "TFE"; break;
case ImmTyD16: OS << "D16"; break;
case ImmTyFORMAT: OS << "FORMAT"; break;
case ImmTyClampSI: OS << "ClampSI"; break;
case ImmTyOModSI: OS << "OModSI"; break;
case ImmTyDppCtrl: OS << "DppCtrl"; break;
case ImmTyDppRowMask: OS << "DppRowMask"; break;
case ImmTyDppBankMask: OS << "DppBankMask"; break;
case ImmTyDppBoundCtrl: OS << "DppBoundCtrl"; break;
case ImmTySdwaDstSel: OS << "SdwaDstSel"; break;
case ImmTySdwaSrc0Sel: OS << "SdwaSrc0Sel"; break;
case ImmTySdwaSrc1Sel: OS << "SdwaSrc1Sel"; break;
case ImmTySdwaDstUnused: OS << "SdwaDstUnused"; break;
case ImmTyDMask: OS << "DMask"; break;
case ImmTyUNorm: OS << "UNorm"; break;
case ImmTyDA: OS << "DA"; break;
case ImmTyR128A16: OS << "R128A16"; break;
case ImmTyLWE: OS << "LWE"; break;
case ImmTyOff: OS << "Off"; break;
case ImmTyExpTgt: OS << "ExpTgt"; break;
case ImmTyExpCompr: OS << "ExpCompr"; break;
case ImmTyExpVM: OS << "ExpVM"; break;
case ImmTyHwreg: OS << "Hwreg"; break;
case ImmTySendMsg: OS << "SendMsg"; break;
case ImmTyInterpSlot: OS << "InterpSlot"; break;
case ImmTyInterpAttr: OS << "InterpAttr"; break;
case ImmTyAttrChan: OS << "AttrChan"; break;
case ImmTyOpSel: OS << "OpSel"; break;
case ImmTyOpSelHi: OS << "OpSelHi"; break;
case ImmTyNegLo: OS << "NegLo"; break;
case ImmTyNegHi: OS << "NegHi"; break;
case ImmTySwizzle: OS << "Swizzle"; break;
case ImmTyHigh: OS << "High"; break;
}
}
void print(raw_ostream &OS) const override {
switch (Kind) {
case Register:
OS << "<register " << getReg() << " mods: " << Reg.Mods << '>';
break;
case Immediate:
OS << '<' << getImm();
if (getImmTy() != ImmTyNone) {
OS << " type: "; printImmTy(OS, getImmTy());
}
OS << " mods: " << Imm.Mods << '>';
break;
case Token:
OS << '\'' << getToken() << '\'';
break;
case Expression:
OS << "<expr " << *Expr << '>';
break;
}
}
static AMDGPUOperand::Ptr CreateImm(const AMDGPUAsmParser *AsmParser,
int64_t Val, SMLoc Loc,
ImmTy Type = ImmTyNone,
bool IsFPImm = false) {
auto Op = llvm::make_unique<AMDGPUOperand>(Immediate, AsmParser);
Op->Imm.Val = Val;
Op->Imm.IsFPImm = IsFPImm;
Op->Imm.Type = Type;
Op->Imm.Mods = Modifiers();
Op->StartLoc = Loc;
Op->EndLoc = Loc;
return Op;
}
static AMDGPUOperand::Ptr CreateToken(const AMDGPUAsmParser *AsmParser,
StringRef Str, SMLoc Loc,
bool HasExplicitEncodingSize = true) {
auto Res = llvm::make_unique<AMDGPUOperand>(Token, AsmParser);
Res->Tok.Data = Str.data();
Res->Tok.Length = Str.size();
Res->StartLoc = Loc;
Res->EndLoc = Loc;
return Res;
}
static AMDGPUOperand::Ptr CreateReg(const AMDGPUAsmParser *AsmParser,
unsigned RegNo, SMLoc S,
SMLoc E,
bool ForceVOP3) {
auto Op = llvm::make_unique<AMDGPUOperand>(Register, AsmParser);
Op->Reg.RegNo = RegNo;
Op->Reg.Mods = Modifiers();
Op->Reg.IsForcedVOP3 = ForceVOP3;
Op->StartLoc = S;
Op->EndLoc = E;
return Op;
}
static AMDGPUOperand::Ptr CreateExpr(const AMDGPUAsmParser *AsmParser,
const class MCExpr *Expr, SMLoc S) {
auto Op = llvm::make_unique<AMDGPUOperand>(Expression, AsmParser);
Op->Expr = Expr;
Op->StartLoc = S;
Op->EndLoc = S;
return Op;
}
};
raw_ostream &operator <<(raw_ostream &OS, AMDGPUOperand::Modifiers Mods) {
OS << "abs:" << Mods.Abs << " neg: " << Mods.Neg << " sext:" << Mods.Sext;
return OS;
}
//===----------------------------------------------------------------------===//
// AsmParser
//===----------------------------------------------------------------------===//
// Holds info related to the current kernel, e.g. count of SGPRs used.
// Kernel scope begins at .amdgpu_hsa_kernel directive, ends at next
// .amdgpu_hsa_kernel or at EOF.
class KernelScopeInfo {
int SgprIndexUnusedMin = -1;
int VgprIndexUnusedMin = -1;
MCContext *Ctx = nullptr;
void usesSgprAt(int i) {
if (i >= SgprIndexUnusedMin) {
SgprIndexUnusedMin = ++i;
if (Ctx) {
MCSymbol * const Sym = Ctx->getOrCreateSymbol(Twine(".kernel.sgpr_count"));
Sym->setVariableValue(MCConstantExpr::create(SgprIndexUnusedMin, *Ctx));
}
}
}
void usesVgprAt(int i) {
if (i >= VgprIndexUnusedMin) {
VgprIndexUnusedMin = ++i;
if (Ctx) {
MCSymbol * const Sym = Ctx->getOrCreateSymbol(Twine(".kernel.vgpr_count"));
Sym->setVariableValue(MCConstantExpr::create(VgprIndexUnusedMin, *Ctx));
}
}
}
public:
KernelScopeInfo() = default;
void initialize(MCContext &Context) {
Ctx = &Context;
usesSgprAt(SgprIndexUnusedMin = -1);
usesVgprAt(VgprIndexUnusedMin = -1);
}
void usesRegister(RegisterKind RegKind, unsigned DwordRegIndex, unsigned RegWidth) {
switch (RegKind) {
case IS_SGPR: usesSgprAt(DwordRegIndex + RegWidth - 1); break;
case IS_VGPR: usesVgprAt(DwordRegIndex + RegWidth - 1); break;
default: break;
}
}
};
class AMDGPUAsmParser : public MCTargetAsmParser {
MCAsmParser &Parser;
// Number of extra operands parsed after the first optional operand.
// This may be necessary to skip hardcoded mandatory operands.
static const unsigned MAX_OPR_LOOKAHEAD = 8;
unsigned ForcedEncodingSize = 0;
bool ForcedDPP = false;
bool ForcedSDWA = false;
KernelScopeInfo KernelScope;
/// @name Auto-generated Match Functions
/// {
#define GET_ASSEMBLER_HEADER
#include "AMDGPUGenAsmMatcher.inc"
/// }
private:
bool ParseAsAbsoluteExpression(uint32_t &Ret);
bool OutOfRangeError(SMRange Range);
/// Calculate VGPR/SGPR blocks required for given target, reserved
/// registers, and user-specified NextFreeXGPR values.
///
/// \param Features [in] Target features, used for bug corrections.
/// \param VCCUsed [in] Whether VCC special SGPR is reserved.
/// \param FlatScrUsed [in] Whether FLAT_SCRATCH special SGPR is reserved.
/// \param XNACKUsed [in] Whether XNACK_MASK special SGPR is reserved.
/// \param NextFreeVGPR [in] Max VGPR number referenced, plus one.
/// \param VGPRRange [in] Token range, used for VGPR diagnostics.
/// \param NextFreeSGPR [in] Max SGPR number referenced, plus one.
/// \param SGPRRange [in] Token range, used for SGPR diagnostics.
/// \param VGPRBlocks [out] Result VGPR block count.
/// \param SGPRBlocks [out] Result SGPR block count.
bool calculateGPRBlocks(const FeatureBitset &Features, bool VCCUsed,
bool FlatScrUsed, bool XNACKUsed,
unsigned NextFreeVGPR, SMRange VGPRRange,
unsigned NextFreeSGPR, SMRange SGPRRange,
unsigned &VGPRBlocks, unsigned &SGPRBlocks);
bool ParseDirectiveAMDGCNTarget();
bool ParseDirectiveAMDHSAKernel();
bool ParseDirectiveMajorMinor(uint32_t &Major, uint32_t &Minor);
bool ParseDirectiveHSACodeObjectVersion();
bool ParseDirectiveHSACodeObjectISA();
bool ParseAMDKernelCodeTValue(StringRef ID, amd_kernel_code_t &Header);
bool ParseDirectiveAMDKernelCodeT();
bool subtargetHasRegister(const MCRegisterInfo &MRI, unsigned RegNo) const;
bool ParseDirectiveAMDGPUHsaKernel();
bool ParseDirectiveISAVersion();
bool ParseDirectiveHSAMetadata();
bool ParseDirectivePALMetadata();
bool AddNextRegisterToList(unsigned& Reg, unsigned& RegWidth,
RegisterKind RegKind, unsigned Reg1,
unsigned RegNum);
bool ParseAMDGPURegister(RegisterKind& RegKind, unsigned& Reg,
unsigned& RegNum, unsigned& RegWidth,
unsigned *DwordRegIndex);
Optional<StringRef> getGprCountSymbolName(RegisterKind RegKind);
void initializeGprCountSymbol(RegisterKind RegKind);
bool updateGprCountSymbols(RegisterKind RegKind, unsigned DwordRegIndex,
unsigned RegWidth);
void cvtMubufImpl(MCInst &Inst, const OperandVector &Operands,
bool IsAtomic, bool IsAtomicReturn, bool IsLds = false);
void cvtDSImpl(MCInst &Inst, const OperandVector &Operands,
bool IsGdsHardcoded);
public:
enum AMDGPUMatchResultTy {
Match_PreferE32 = FIRST_TARGET_MATCH_RESULT_TY
};
using OptionalImmIndexMap = std::map<AMDGPUOperand::ImmTy, unsigned>;
AMDGPUAsmParser(const MCSubtargetInfo &STI, MCAsmParser &_Parser,
const MCInstrInfo &MII,
const MCTargetOptions &Options)
: MCTargetAsmParser(Options, STI, MII), Parser(_Parser) {
MCAsmParserExtension::Initialize(Parser);
if (getFeatureBits().none()) {
// Set default features.
copySTI().ToggleFeature("SOUTHERN_ISLANDS");
}
setAvailableFeatures(ComputeAvailableFeatures(getFeatureBits()));
{
// TODO: make those pre-defined variables read-only.
// Currently there is none suitable machinery in the core llvm-mc for this.
// MCSymbol::isRedefinable is intended for another purpose, and
// AsmParser::parseDirectiveSet() cannot be specialized for specific target.
AMDGPU::IsaVersion ISA = AMDGPU::getIsaVersion(getSTI().getCPU());
MCContext &Ctx = getContext();
if (ISA.Major >= 6 && AMDGPU::IsaInfo::hasCodeObjectV3(&getSTI())) {
MCSymbol *Sym =
Ctx.getOrCreateSymbol(Twine(".amdgcn.gfx_generation_number"));
Sym->setVariableValue(MCConstantExpr::create(ISA.Major, Ctx));
Sym = Ctx.getOrCreateSymbol(Twine(".amdgcn.gfx_generation_minor"));
Sym->setVariableValue(MCConstantExpr::create(ISA.Minor, Ctx));
Sym = Ctx.getOrCreateSymbol(Twine(".amdgcn.gfx_generation_stepping"));
Sym->setVariableValue(MCConstantExpr::create(ISA.Stepping, Ctx));
} else {
MCSymbol *Sym =
Ctx.getOrCreateSymbol(Twine(".option.machine_version_major"));
Sym->setVariableValue(MCConstantExpr::create(ISA.Major, Ctx));
Sym = Ctx.getOrCreateSymbol(Twine(".option.machine_version_minor"));
Sym->setVariableValue(MCConstantExpr::create(ISA.Minor, Ctx));
Sym = Ctx.getOrCreateSymbol(Twine(".option.machine_version_stepping"));
Sym->setVariableValue(MCConstantExpr::create(ISA.Stepping, Ctx));
}
if (ISA.Major >= 6 && AMDGPU::IsaInfo::hasCodeObjectV3(&getSTI())) {
initializeGprCountSymbol(IS_VGPR);
initializeGprCountSymbol(IS_SGPR);
} else
KernelScope.initialize(getContext());
}
}
bool hasXNACK() const {
return AMDGPU::hasXNACK(getSTI());
}
bool hasMIMG_R128() const {
return AMDGPU::hasMIMG_R128(getSTI());
}
bool hasPackedD16() const {
return AMDGPU::hasPackedD16(getSTI());
}
bool isSI() const {
return AMDGPU::isSI(getSTI());
}
bool isCI() const {
return AMDGPU::isCI(getSTI());
}
bool isVI() const {
return AMDGPU::isVI(getSTI());
}
bool isGFX9() const {
return AMDGPU::isGFX9(getSTI());
}
bool hasInv2PiInlineImm() const {
return getFeatureBits()[AMDGPU::FeatureInv2PiInlineImm];
}
bool hasFlatOffsets() const {
return getFeatureBits()[AMDGPU::FeatureFlatInstOffsets];
}
bool hasSGPR102_SGPR103() const {
return !isVI();
}
bool hasIntClamp() const {
return getFeatureBits()[AMDGPU::FeatureIntClamp];
}
AMDGPUTargetStreamer &getTargetStreamer() {
MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
return static_cast<AMDGPUTargetStreamer &>(TS);
}
const MCRegisterInfo *getMRI() const {
// We need this const_cast because for some reason getContext() is not const
// in MCAsmParser.
return const_cast<AMDGPUAsmParser*>(this)->getContext().getRegisterInfo();
}
const MCInstrInfo *getMII() const {
return &MII;
}
const FeatureBitset &getFeatureBits() const {
return getSTI().getFeatureBits();
}
void setForcedEncodingSize(unsigned Size) { ForcedEncodingSize = Size; }
void setForcedDPP(bool ForceDPP_) { ForcedDPP = ForceDPP_; }
void setForcedSDWA(bool ForceSDWA_) { ForcedSDWA = ForceSDWA_; }
unsigned getForcedEncodingSize() const { return ForcedEncodingSize; }
bool isForcedVOP3() const { return ForcedEncodingSize == 64; }
bool isForcedDPP() const { return ForcedDPP; }
bool isForcedSDWA() const { return ForcedSDWA; }
ArrayRef<unsigned> getMatchedVariants() const;
std::unique_ptr<AMDGPUOperand> parseRegister();
bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
unsigned checkTargetMatchPredicate(MCInst &Inst) override;
unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
unsigned Kind) override;
bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
OperandVector &Operands, MCStreamer &Out,
uint64_t &ErrorInfo,
bool MatchingInlineAsm) override;
bool ParseDirective(AsmToken DirectiveID) override;
OperandMatchResultTy parseOperand(OperandVector &Operands, StringRef Mnemonic);
StringRef parseMnemonicSuffix(StringRef Name);
bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
SMLoc NameLoc, OperandVector &Operands) override;
//bool ProcessInstruction(MCInst &Inst);
OperandMatchResultTy parseIntWithPrefix(const char *Prefix, int64_t &Int);
OperandMatchResultTy
parseIntWithPrefix(const char *Prefix, OperandVector &Operands,
AMDGPUOperand::ImmTy ImmTy = AMDGPUOperand::ImmTyNone,
bool (*ConvertResult)(int64_t &) = nullptr);
OperandMatchResultTy parseOperandArrayWithPrefix(
const char *Prefix,
OperandVector &Operands,
AMDGPUOperand::ImmTy ImmTy = AMDGPUOperand::ImmTyNone,
bool (*ConvertResult)(int64_t&) = nullptr);
OperandMatchResultTy
parseNamedBit(const char *Name, OperandVector &Operands,
AMDGPUOperand::ImmTy ImmTy = AMDGPUOperand::ImmTyNone);
OperandMatchResultTy parseStringWithPrefix(StringRef Prefix,
StringRef &Value);
bool parseAbsoluteExpr(int64_t &Val, bool AbsMod = false);
OperandMatchResultTy parseImm(OperandVector &Operands, bool AbsMod = false);
OperandMatchResultTy parseReg(OperandVector &Operands);
OperandMatchResultTy parseRegOrImm(OperandVector &Operands, bool AbsMod = false);
OperandMatchResultTy parseRegOrImmWithFPInputMods(OperandVector &Operands, bool AllowImm = true);
OperandMatchResultTy parseRegOrImmWithIntInputMods(OperandVector &Operands, bool AllowImm = true);
OperandMatchResultTy parseRegWithFPInputMods(OperandVector &Operands);
OperandMatchResultTy parseRegWithIntInputMods(OperandVector &Operands);
OperandMatchResultTy parseVReg32OrOff(OperandVector &Operands);
OperandMatchResultTy parseDfmtNfmt(OperandVector &Operands);
void cvtDSOffset01(MCInst &Inst, const OperandVector &Operands);
void cvtDS(MCInst &Inst, const OperandVector &Operands) { cvtDSImpl(Inst, Operands, false); }
void cvtDSGds(MCInst &Inst, const OperandVector &Operands) { cvtDSImpl(Inst, Operands, true); }
void cvtExp(MCInst &Inst, const OperandVector &Operands);
bool parseCnt(int64_t &IntVal);
OperandMatchResultTy parseSWaitCntOps(OperandVector &Operands);
OperandMatchResultTy parseHwreg(OperandVector &Operands);
private:
struct OperandInfoTy {
int64_t Id;
bool IsSymbolic = false;
OperandInfoTy(int64_t Id_) : Id(Id_) {}
};
bool parseSendMsgConstruct(OperandInfoTy &Msg, OperandInfoTy &Operation, int64_t &StreamId);
bool parseHwregConstruct(OperandInfoTy &HwReg, int64_t &Offset, int64_t &Width);
void errorExpTgt();
OperandMatchResultTy parseExpTgtImpl(StringRef Str, uint8_t &Val);
bool validateInstruction(const MCInst &Inst, const SMLoc &IDLoc);
bool validateSOPLiteral(const MCInst &Inst) const;
bool validateConstantBusLimitations(const MCInst &Inst);
bool validateEarlyClobberLimitations(const MCInst &Inst);
bool validateIntClampSupported(const MCInst &Inst);
bool validateMIMGAtomicDMask(const MCInst &Inst);
bool validateMIMGGatherDMask(const MCInst &Inst);
bool validateMIMGDataSize(const MCInst &Inst);
bool validateMIMGD16(const MCInst &Inst);
bool validateLdsDirect(const MCInst &Inst);
bool usesConstantBus(const MCInst &Inst, unsigned OpIdx);
bool isInlineConstant(const MCInst &Inst, unsigned OpIdx) const;
unsigned findImplicitSGPRReadInVOP(const MCInst &Inst) const;
bool trySkipId(const StringRef Id);
bool trySkipToken(const AsmToken::TokenKind Kind);
bool skipToken(const AsmToken::TokenKind Kind, const StringRef ErrMsg);
bool parseString(StringRef &Val, const StringRef ErrMsg = "expected a string");
bool parseExpr(int64_t &Imm);
public:
OperandMatchResultTy parseOptionalOperand(OperandVector &Operands);
OperandMatchResultTy parseOptionalOpr(OperandVector &Operands);
OperandMatchResultTy parseExpTgt(OperandVector &Operands);
OperandMatchResultTy parseSendMsgOp(OperandVector &Operands);
OperandMatchResultTy parseInterpSlot(OperandVector &Operands);
OperandMatchResultTy parseInterpAttr(OperandVector &Operands);
OperandMatchResultTy parseSOppBrTarget(OperandVector &Operands);
bool parseSwizzleOperands(const unsigned OpNum, int64_t* Op,
const unsigned MinVal,
const unsigned MaxVal,
const StringRef ErrMsg);
OperandMatchResultTy parseSwizzleOp(OperandVector &Operands);
bool parseSwizzleOffset(int64_t &Imm);
bool parseSwizzleMacro(int64_t &Imm);
bool parseSwizzleQuadPerm(int64_t &Imm);
bool parseSwizzleBitmaskPerm(int64_t &Imm);
bool parseSwizzleBroadcast(int64_t &Imm);
bool parseSwizzleSwap(int64_t &Imm);
bool parseSwizzleReverse(int64_t &Imm);
void cvtMubuf(MCInst &Inst, const OperandVector &Operands) { cvtMubufImpl(Inst, Operands, false, false); }
void cvtMubufAtomic(MCInst &Inst, const OperandVector &Operands) { cvtMubufImpl(Inst, Operands, true, false); }
void cvtMubufAtomicReturn(MCInst &Inst, const OperandVector &Operands) { cvtMubufImpl(Inst, Operands, true, true); }
void cvtMubufLds(MCInst &Inst, const OperandVector &Operands) { cvtMubufImpl(Inst, Operands, false, false, true); }
void cvtMtbuf(MCInst &Inst, const OperandVector &Operands);
AMDGPUOperand::Ptr defaultGLC() const;
AMDGPUOperand::Ptr defaultSLC() const;
AMDGPUOperand::Ptr defaultSMRDOffset8() const;
AMDGPUOperand::Ptr defaultSMRDOffset20() const;
AMDGPUOperand::Ptr defaultSMRDLiteralOffset() const;
AMDGPUOperand::Ptr defaultOffsetU12() const;
AMDGPUOperand::Ptr defaultOffsetS13() const;
OperandMatchResultTy parseOModOperand(OperandVector &Operands);
void cvtVOP3(MCInst &Inst, const OperandVector &Operands,
OptionalImmIndexMap &OptionalIdx);
void cvtVOP3OpSel(MCInst &Inst, const OperandVector &Operands);
void cvtVOP3(MCInst &Inst, const OperandVector &Operands);
void cvtVOP3P(MCInst &Inst, const OperandVector &Operands);
void cvtVOP3Interp(MCInst &Inst, const OperandVector &Operands);
void cvtMIMG(MCInst &Inst, const OperandVector &Operands,
bool IsAtomic = false);
void cvtMIMGAtomic(MCInst &Inst, const OperandVector &Operands);
OperandMatchResultTy parseDPPCtrl(OperandVector &Operands);
AMDGPUOperand::Ptr defaultRowMask() const;
AMDGPUOperand::Ptr defaultBankMask() const;
AMDGPUOperand::Ptr defaultBoundCtrl() const;
void cvtDPP(MCInst &Inst, const OperandVector &Operands);
OperandMatchResultTy parseSDWASel(OperandVector &Operands, StringRef Prefix,
AMDGPUOperand::ImmTy Type);
OperandMatchResultTy parseSDWADstUnused(OperandVector &Operands);
void cvtSdwaVOP1(MCInst &Inst, const OperandVector &Operands);
void cvtSdwaVOP2(MCInst &Inst, const OperandVector &Operands);
void cvtSdwaVOP2b(MCInst &Inst, const OperandVector &Operands);
void cvtSdwaVOPC(MCInst &Inst, const OperandVector &Operands);
void cvtSDWA(MCInst &Inst, const OperandVector &Operands,
uint64_t BasicInstType, bool skipVcc = false);
};
struct OptionalOperand {
const char *Name;
AMDGPUOperand::ImmTy Type;
bool IsBit;
bool (*ConvertResult)(int64_t&);
};
} // end anonymous namespace
// May be called with integer type with equivalent bitwidth.
static const fltSemantics *getFltSemantics(unsigned Size) {
switch (Size) {
case 4:
return &APFloat::IEEEsingle();
case 8:
return &APFloat::IEEEdouble();
case 2:
return &APFloat::IEEEhalf();
default:
llvm_unreachable("unsupported fp type");
}
}
static const fltSemantics *getFltSemantics(MVT VT) {
return getFltSemantics(VT.getSizeInBits() / 8);
}
static const fltSemantics *getOpFltSemantics(uint8_t OperandType) {
switch (OperandType) {
case AMDGPU::OPERAND_REG_IMM_INT32:
case AMDGPU::OPERAND_REG_IMM_FP32:
case AMDGPU::OPERAND_REG_INLINE_C_INT32:
case AMDGPU::OPERAND_REG_INLINE_C_FP32:
return &APFloat::IEEEsingle();
case AMDGPU::OPERAND_REG_IMM_INT64:
case AMDGPU::OPERAND_REG_IMM_FP64:
case AMDGPU::OPERAND_REG_INLINE_C_INT64:
case AMDGPU::OPERAND_REG_INLINE_C_FP64:
return &APFloat::IEEEdouble();
case AMDGPU::OPERAND_REG_IMM_INT16:
case AMDGPU::OPERAND_REG_IMM_FP16:
case AMDGPU::OPERAND_REG_INLINE_C_INT16:
case AMDGPU::OPERAND_REG_INLINE_C_FP16:
case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
case AMDGPU::OPERAND_REG_INLINE_C_V2FP16:
return &APFloat::IEEEhalf();
default:
llvm_unreachable("unsupported fp type");
}
}
//===----------------------------------------------------------------------===//
// Operand
//===----------------------------------------------------------------------===//
static bool canLosslesslyConvertToFPType(APFloat &FPLiteral, MVT VT) {
bool Lost;
// Convert literal to single precision
APFloat::opStatus Status = FPLiteral.convert(*getFltSemantics(VT),
APFloat::rmNearestTiesToEven,
&Lost);
// We allow precision lost but not overflow or underflow
if (Status != APFloat::opOK &&
Lost &&
((Status & APFloat::opOverflow) != 0 ||
(Status & APFloat::opUnderflow) != 0)) {
return false;
}
return true;
}
bool AMDGPUOperand::isInlinableImm(MVT type) const {
if (!isImmTy(ImmTyNone)) {
// Only plain immediates are inlinable (e.g. "clamp" attribute is not)
return false;
}
// TODO: We should avoid using host float here. It would be better to
// check the float bit values which is what a few other places do.
// We've had bot failures before due to weird NaN support on mips hosts.
APInt Literal(64, Imm.Val);
if (Imm.IsFPImm) { // We got fp literal token
if (type == MVT::f64 || type == MVT::i64) { // Expected 64-bit operand
return AMDGPU::isInlinableLiteral64(Imm.Val,
AsmParser->hasInv2PiInlineImm());
}
APFloat FPLiteral(APFloat::IEEEdouble(), APInt(64, Imm.Val));
if (!canLosslesslyConvertToFPType(FPLiteral, type))
return false;
if (type.getScalarSizeInBits() == 16) {
return AMDGPU::isInlinableLiteral16(
static_cast<int16_t>(FPLiteral.bitcastToAPInt().getZExtValue()),
AsmParser->hasInv2PiInlineImm());
}
// Check if single precision literal is inlinable
return AMDGPU::isInlinableLiteral32(
static_cast<int32_t>(FPLiteral.bitcastToAPInt().getZExtValue()),
AsmParser->hasInv2PiInlineImm());
}
// We got int literal token.
if (type == MVT::f64 || type == MVT::i64) { // Expected 64-bit operand
return AMDGPU::isInlinableLiteral64(Imm.Val,
AsmParser->hasInv2PiInlineImm());
}
if (type.getScalarSizeInBits() == 16) {
return AMDGPU::isInlinableLiteral16(
static_cast<int16_t>(Literal.getLoBits(16).getSExtValue()),
AsmParser->hasInv2PiInlineImm());
}
return AMDGPU::isInlinableLiteral32(
static_cast<int32_t>(Literal.getLoBits(32).getZExtValue()),
AsmParser->hasInv2PiInlineImm());
}
bool AMDGPUOperand::isLiteralImm(MVT type) const {
// Check that this immediate can be added as literal
if (!isImmTy(ImmTyNone)) {
return false;
}
if (!Imm.IsFPImm) {
// We got int literal token.
if (type == MVT::f64 && hasFPModifiers()) {
// Cannot apply fp modifiers to int literals preserving the same semantics
// for VOP1/2/C and VOP3 because of integer truncation. To avoid ambiguity,
// disable these cases.
return false;
}
unsigned Size = type.getSizeInBits();
if (Size == 64)
Size = 32;
// FIXME: 64-bit operands can zero extend, sign extend, or pad zeroes for FP
// types.
return isUIntN(Size, Imm.Val) || isIntN(Size, Imm.Val);
}
// We got fp literal token
if (type == MVT::f64) { // Expected 64-bit fp operand
// We would set low 64-bits of literal to zeroes but we accept this literals
return true;
}
if (type == MVT::i64) { // Expected 64-bit int operand
// We don't allow fp literals in 64-bit integer instructions. It is
// unclear how we should encode them.
return false;
}
APFloat FPLiteral(APFloat::IEEEdouble(), APInt(64, Imm.Val));
return canLosslesslyConvertToFPType(FPLiteral, type);
}
bool AMDGPUOperand::isRegClass(unsigned RCID) const {
return isRegKind() && AsmParser->getMRI()->getRegClass(RCID).contains(getReg());
}
bool AMDGPUOperand::isSDWAOperand(MVT type) const {
if (AsmParser->isVI())
return isVReg();
else if (AsmParser->isGFX9())
return isRegKind() || isInlinableImm(type);
else
return false;
}
bool AMDGPUOperand::isSDWAFP16Operand() const {
return isSDWAOperand(MVT::f16);
}
bool AMDGPUOperand::isSDWAFP32Operand() const {
return isSDWAOperand(MVT::f32);
}
bool AMDGPUOperand::isSDWAInt16Operand() const {
return isSDWAOperand(MVT::i16);
}
bool AMDGPUOperand::isSDWAInt32Operand() const {
return isSDWAOperand(MVT::i32);
}
uint64_t AMDGPUOperand::applyInputFPModifiers(uint64_t Val, unsigned Size) const
{
assert(isImmTy(ImmTyNone) && Imm.Mods.hasFPModifiers());
assert(Size == 2 || Size == 4 || Size == 8);
const uint64_t FpSignMask = (1ULL << (Size * 8 - 1));
if (Imm.Mods.Abs) {
Val &= ~FpSignMask;
}
if (Imm.Mods.Neg) {
Val ^= FpSignMask;
}
return Val;
}
void AMDGPUOperand::addImmOperands(MCInst &Inst, unsigned N, bool ApplyModifiers) const {
if (AMDGPU::isSISrcOperand(AsmParser->getMII()->get(Inst.getOpcode()),
Inst.getNumOperands())) {
addLiteralImmOperand(Inst, Imm.Val,
ApplyModifiers &
isImmTy(ImmTyNone) && Imm.Mods.hasFPModifiers());
} else {
assert(!isImmTy(ImmTyNone) || !hasModifiers());
Inst.addOperand(MCOperand::createImm(Imm.Val));
}
}
void AMDGPUOperand::addLiteralImmOperand(MCInst &Inst, int64_t Val, bool ApplyModifiers) const {
const auto& InstDesc = AsmParser->getMII()->get(Inst.getOpcode());
auto OpNum = Inst.getNumOperands();
// Check that this operand accepts literals
assert(AMDGPU::isSISrcOperand(InstDesc, OpNum));
if (ApplyModifiers) {
assert(AMDGPU::isSISrcFPOperand(InstDesc, OpNum));
const unsigned Size = Imm.IsFPImm ? sizeof(double) : getOperandSize(InstDesc, OpNum);
Val = applyInputFPModifiers(Val, Size);
}
APInt Literal(64, Val);
uint8_t OpTy = InstDesc.OpInfo[OpNum].OperandType;
if (Imm.IsFPImm) { // We got fp literal token
switch (OpTy) {
case AMDGPU::OPERAND_REG_IMM_INT64:
case AMDGPU::OPERAND_REG_IMM_FP64:
case AMDGPU::OPERAND_REG_INLINE_C_INT64:
case AMDGPU::OPERAND_REG_INLINE_C_FP64:
if (AMDGPU::isInlinableLiteral64(Literal.getZExtValue(),
AsmParser->hasInv2PiInlineImm())) {
Inst.addOperand(MCOperand::createImm(Literal.getZExtValue()));
return;
}
// Non-inlineable
if (AMDGPU::isSISrcFPOperand(InstDesc, OpNum)) { // Expected 64-bit fp operand
// For fp operands we check if low 32 bits are zeros
if (Literal.getLoBits(32) != 0) {
const_cast<AMDGPUAsmParser *>(AsmParser)->Warning(Inst.getLoc(),
"Can't encode literal as exact 64-bit floating-point operand. "
"Low 32-bits will be set to zero");
}
Inst.addOperand(MCOperand::createImm(Literal.lshr(32).getZExtValue()));
return;
}
// We don't allow fp literals in 64-bit integer instructions. It is
// unclear how we should encode them. This case should be checked earlier
// in predicate methods (isLiteralImm())
llvm_unreachable("fp literal in 64-bit integer instruction.");
case AMDGPU::OPERAND_REG_IMM_INT32:
case AMDGPU::OPERAND_REG_IMM_FP32:
case AMDGPU::OPERAND_REG_INLINE_C_INT32:
case AMDGPU::OPERAND_REG_INLINE_C_FP32:
case AMDGPU::OPERAND_REG_IMM_INT16:
case AMDGPU::OPERAND_REG_IMM_FP16:
case AMDGPU::OPERAND_REG_INLINE_C_INT16:
case AMDGPU::OPERAND_REG_INLINE_C_FP16:
case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
case AMDGPU::OPERAND_REG_INLINE_C_V2FP16: {
bool lost;
APFloat FPLiteral(APFloat::IEEEdouble(), Literal);
// Convert literal to single precision
FPLiteral.convert(*getOpFltSemantics(OpTy),
APFloat::rmNearestTiesToEven, &lost);
// We allow precision lost but not overflow or underflow. This should be
// checked earlier in isLiteralImm()
uint64_t ImmVal = FPLiteral.bitcastToAPInt().getZExtValue();
if (OpTy == AMDGPU::OPERAND_REG_INLINE_C_V2INT16 ||
OpTy == AMDGPU::OPERAND_REG_INLINE_C_V2FP16) {
ImmVal |= (ImmVal << 16);
}
Inst.addOperand(MCOperand::createImm(ImmVal));
return;
}
default:
llvm_unreachable("invalid operand size");
}
return;
}
// We got int literal token.
// Only sign extend inline immediates.
// FIXME: No errors on truncation
switch (OpTy) {
case AMDGPU::OPERAND_REG_IMM_INT32:
case AMDGPU::OPERAND_REG_IMM_FP32:
case AMDGPU::OPERAND_REG_INLINE_C_INT32:
case AMDGPU::OPERAND_REG_INLINE_C_FP32:
if (isInt<32>(Val) &&
AMDGPU::isInlinableLiteral32(static_cast<int32_t>(Val),
AsmParser->hasInv2PiInlineImm())) {
Inst.addOperand(MCOperand::createImm(Val));
return;
}
Inst.addOperand(MCOperand::createImm(Val & 0xffffffff));
return;
case AMDGPU::OPERAND_REG_IMM_INT64:
case AMDGPU::OPERAND_REG_IMM_FP64:
case AMDGPU::OPERAND_REG_INLINE_C_INT64:
case AMDGPU::OPERAND_REG_INLINE_C_FP64:
if (AMDGPU::isInlinableLiteral64(Val, AsmParser->hasInv2PiInlineImm())) {
Inst.addOperand(MCOperand::createImm(Val));
return;
}
Inst.addOperand(MCOperand::createImm(Lo_32(Val)));
return;
case AMDGPU::OPERAND_REG_IMM_INT16:
case AMDGPU::OPERAND_REG_IMM_FP16:
case AMDGPU::OPERAND_REG_INLINE_C_INT16:
case AMDGPU::OPERAND_REG_INLINE_C_FP16:
if (isInt<16>(Val) &&
AMDGPU::isInlinableLiteral16(static_cast<int16_t>(Val),
AsmParser->hasInv2PiInlineImm())) {
Inst.addOperand(MCOperand::createImm(Val));
return;
}
Inst.addOperand(MCOperand::createImm(Val & 0xffff));
return;
case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
case AMDGPU::OPERAND_REG_INLINE_C_V2FP16: {
auto LiteralVal = static_cast<uint16_t>(Literal.getLoBits(16).getZExtValue());
assert(AMDGPU::isInlinableLiteral16(LiteralVal,
AsmParser->hasInv2PiInlineImm()));
uint32_t ImmVal = static_cast<uint32_t>(LiteralVal) << 16 |
static_cast<uint32_t>(LiteralVal);
Inst.addOperand(MCOperand::createImm(ImmVal));
return;
}
default:
llvm_unreachable("invalid operand size");
}
}
template <unsigned Bitwidth>
void AMDGPUOperand::addKImmFPOperands(MCInst &Inst, unsigned N) const {
APInt Literal(64, Imm.Val);
if (!Imm.IsFPImm) {
// We got int literal token.
Inst.addOperand(MCOperand::createImm(Literal.getLoBits(Bitwidth).getZExtValue()));
return;
}
bool Lost;
APFloat FPLiteral(APFloat::IEEEdouble(), Literal);
FPLiteral.convert(*getFltSemantics(Bitwidth / 8),
APFloat::rmNearestTiesToEven, &Lost);
Inst.addOperand(MCOperand::createImm(FPLiteral.bitcastToAPInt().getZExtValue()));
}
void AMDGPUOperand::addRegOperands(MCInst &Inst, unsigned N) const {
Inst.addOperand(MCOperand::createReg(AMDGPU::getMCReg(getReg(), AsmParser->getSTI())));
}
//===----------------------------------------------------------------------===//
// AsmParser
//===----------------------------------------------------------------------===//
static int getRegClass(RegisterKind Is, unsigned RegWidth) {
if (Is == IS_VGPR) {
switch (RegWidth) {
default: return -1;
case 1: return AMDGPU::VGPR_32RegClassID;
case 2: return AMDGPU::VReg_64RegClassID;
case 3: return AMDGPU::VReg_96RegClassID;
case 4: return AMDGPU::VReg_128RegClassID;
case 8: return AMDGPU::VReg_256RegClassID;
case 16: return AMDGPU::VReg_512RegClassID;
}
} else if (Is == IS_TTMP) {
switch (RegWidth) {
default: return -1;
case 1: return AMDGPU::TTMP_32RegClassID;
case 2: return AMDGPU::TTMP_64RegClassID;
case 4: return AMDGPU::TTMP_128RegClassID;
case 8: return AMDGPU::TTMP_256RegClassID;
case 16: return AMDGPU::TTMP_512RegClassID;
}
} else if (Is == IS_SGPR) {
switch (RegWidth) {
default: return -1;
case 1: return AMDGPU::SGPR_32RegClassID;
case 2: return AMDGPU::SGPR_64RegClassID;
case 4: return AMDGPU::SGPR_128RegClassID;
case 8: return AMDGPU::SGPR_256RegClassID;
case 16: return AMDGPU::SGPR_512RegClassID;
}
}
return -1;
}
static unsigned getSpecialRegForName(StringRef RegName) {
return StringSwitch<unsigned>(RegName)
.Case("exec", AMDGPU::EXEC)
.Case("vcc", AMDGPU::VCC)
.Case("flat_scratch", AMDGPU::FLAT_SCR)
.Case("xnack_mask", AMDGPU::XNACK_MASK)
.Case("lds_direct", AMDGPU::LDS_DIRECT)
.Case("src_lds_direct", AMDGPU::LDS_DIRECT)
.Case("m0", AMDGPU::M0)
.Case("scc", AMDGPU::SCC)
.Case("tba", AMDGPU::TBA)
.Case("tma", AMDGPU::TMA)
.Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
.Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
.Case("xnack_mask_lo", AMDGPU::XNACK_MASK_LO)
.Case("xnack_mask_hi", AMDGPU::XNACK_MASK_HI)
.Case("vcc_lo", AMDGPU::VCC_LO)
.Case("vcc_hi", AMDGPU::VCC_HI)
.Case("exec_lo", AMDGPU::EXEC_LO)
.Case("exec_hi", AMDGPU::EXEC_HI)
.Case("tma_lo", AMDGPU::TMA_LO)
.Case("tma_hi", AMDGPU::TMA_HI)
.Case("tba_lo", AMDGPU::TBA_LO)
.Case("tba_hi", AMDGPU::TBA_HI)
.Default(0);
}
bool AMDGPUAsmParser::ParseRegister(unsigned &RegNo, SMLoc &StartLoc,
SMLoc &EndLoc) {
auto R = parseRegister();
if (!R) return true;
assert(R->isReg());
RegNo = R->getReg();
StartLoc = R->getStartLoc();
EndLoc = R->getEndLoc();
return false;
}
bool AMDGPUAsmParser::AddNextRegisterToList(unsigned &Reg, unsigned &RegWidth,
RegisterKind RegKind, unsigned Reg1,
unsigned RegNum) {
switch (RegKind) {
case IS_SPECIAL:
if (Reg == AMDGPU::EXEC_LO && Reg1 == AMDGPU::EXEC_HI) {
Reg = AMDGPU::EXEC;
RegWidth = 2;
return true;
}
if (Reg == AMDGPU::FLAT_SCR_LO && Reg1 == AMDGPU::FLAT_SCR_HI) {
Reg = AMDGPU::FLAT_SCR;
RegWidth = 2;
return true;
}
if (Reg == AMDGPU::XNACK_MASK_LO && Reg1 == AMDGPU::XNACK_MASK_HI) {
Reg = AMDGPU::XNACK_MASK;
RegWidth = 2;
return true;
}
if (Reg == AMDGPU::VCC_LO && Reg1 == AMDGPU::VCC_HI) {
Reg = AMDGPU::VCC;
RegWidth = 2;
return true;
}
if (Reg == AMDGPU::TBA_LO && Reg1 == AMDGPU::TBA_HI) {
Reg = AMDGPU::TBA;
RegWidth = 2;
return true;
}
if (Reg == AMDGPU::TMA_LO && Reg1 == AMDGPU::TMA_HI) {
Reg = AMDGPU::TMA;
RegWidth = 2;
return true;
}
return false;
case IS_VGPR:
case IS_SGPR:
case IS_TTMP:
if (Reg1 != Reg + RegWidth) {
return false;
}
RegWidth++;
return true;
default:
llvm_unreachable("unexpected register kind");
}
}
bool AMDGPUAsmParser::ParseAMDGPURegister(RegisterKind &RegKind, unsigned &Reg,
unsigned &RegNum, unsigned &RegWidth,
unsigned *DwordRegIndex) {
if (DwordRegIndex) { *DwordRegIndex = 0; }
const MCRegisterInfo *TRI = getContext().getRegisterInfo();
if (getLexer().is(AsmToken::Identifier)) {
StringRef RegName = Parser.getTok().getString();
if ((Reg = getSpecialRegForName(RegName))) {
Parser.Lex();
RegKind = IS_SPECIAL;
} else {
unsigned RegNumIndex = 0;
if (RegName[0] == 'v') {
RegNumIndex = 1;
RegKind = IS_VGPR;
} else if (RegName[0] == 's') {
RegNumIndex = 1;
RegKind = IS_SGPR;
} else if (RegName.startswith("ttmp")) {
RegNumIndex = strlen("ttmp");
RegKind = IS_TTMP;
} else {
return false;
}
if (RegName.size() > RegNumIndex) {
// Single 32-bit register: vXX.
if (RegName.substr(RegNumIndex).getAsInteger(10, RegNum))
return false;
Parser.Lex();
RegWidth = 1;
} else {
// Range of registers: v[XX:YY]. ":YY" is optional.
Parser.Lex();
int64_t RegLo, RegHi;
if (getLexer().isNot(AsmToken::LBrac))
return false;
Parser.Lex();
if (getParser().parseAbsoluteExpression(RegLo))
return false;
const bool isRBrace = getLexer().is(AsmToken::RBrac);
if (!isRBrace && getLexer().isNot(AsmToken::Colon))
return false;
Parser.Lex();
if (isRBrace) {
RegHi = RegLo;
} else {
if (getParser().parseAbsoluteExpression(RegHi))
return false;
if (getLexer().isNot(AsmToken::RBrac))
return false;
Parser.Lex();
}
RegNum = (unsigned) RegLo;
RegWidth = (RegHi - RegLo) + 1;
}
}
} else if (getLexer().is(AsmToken::LBrac)) {
// List of consecutive registers: [s0,s1,s2,s3]
Parser.Lex();
if (!ParseAMDGPURegister(RegKind, Reg, RegNum, RegWidth, nullptr))
return false;
if (RegWidth != 1)
return false;
RegisterKind RegKind1;
unsigned Reg1, RegNum1, RegWidth1;
do {
if (getLexer().is(AsmToken::Comma)) {
Parser.Lex();
} else if (getLexer().is(AsmToken::RBrac)) {
Parser.Lex();
break;
} else if (ParseAMDGPURegister(RegKind1, Reg1, RegNum1, RegWidth1, nullptr)) {
if (RegWidth1 != 1) {
return false;
}
if (RegKind1 != RegKind) {
return false;
}
if (!AddNextRegisterToList(Reg, RegWidth, RegKind1, Reg1, RegNum1)) {
return false;
}
} else {
return false;
}
} while (true);
} else {
return false;
}
switch (RegKind) {
case IS_SPECIAL:
RegNum = 0;
RegWidth = 1;
break;
case IS_VGPR:
case IS_SGPR:
case IS_TTMP:
{
unsigned Size = 1;
if (RegKind == IS_SGPR || RegKind == IS_TTMP) {
// SGPR and TTMP registers must be aligned. Max required alignment is 4 dwords.
Size = std::min(RegWidth, 4u);
}
if (RegNum % Size != 0)
return false;
if (DwordRegIndex) { *DwordRegIndex = RegNum; }
RegNum = RegNum / Size;
int RCID = getRegClass(RegKind, RegWidth);
if (RCID == -1)
return false;
const MCRegisterClass RC = TRI->getRegClass(RCID);
if (RegNum >= RC.getNumRegs())
return false;
Reg = RC.getRegister(RegNum);
break;
}
default:
llvm_unreachable("unexpected register kind");
}
if (!subtargetHasRegister(*TRI, Reg))
return false;
return true;
}
Optional<StringRef>
AMDGPUAsmParser::getGprCountSymbolName(RegisterKind RegKind) {
switch (RegKind) {
case IS_VGPR:
return StringRef(".amdgcn.next_free_vgpr");
case IS_SGPR:
return StringRef(".amdgcn.next_free_sgpr");
default:
return None;
}
}
void AMDGPUAsmParser::initializeGprCountSymbol(RegisterKind RegKind) {
auto SymbolName = getGprCountSymbolName(RegKind);
assert(SymbolName && "initializing invalid register kind");
MCSymbol *Sym = getContext().getOrCreateSymbol(*SymbolName);
Sym->setVariableValue(MCConstantExpr::create(0, getContext()));
}
bool AMDGPUAsmParser::updateGprCountSymbols(RegisterKind RegKind,
unsigned DwordRegIndex,
unsigned RegWidth) {
// Symbols are only defined for GCN targets
if (AMDGPU::getIsaVersion(getSTI().getCPU()).Major < 6)
return true;
auto SymbolName = getGprCountSymbolName(RegKind);
if (!SymbolName)
return true;
MCSymbol *Sym = getContext().getOrCreateSymbol(*SymbolName);
int64_t NewMax = DwordRegIndex + RegWidth - 1;
int64_t OldCount;
if (!Sym->isVariable())
return !Error(getParser().getTok().getLoc(),
".amdgcn.next_free_{v,s}gpr symbols must be variable");
if (!Sym->getVariableValue(false)->evaluateAsAbsolute(OldCount))
return !Error(
getParser().getTok().getLoc(),
".amdgcn.next_free_{v,s}gpr symbols must be absolute expressions");
if (OldCount <= NewMax)
Sym->setVariableValue(MCConstantExpr::create(NewMax + 1, getContext()));
return true;
}
std::unique_ptr<AMDGPUOperand> AMDGPUAsmParser::parseRegister() {
const auto &Tok = Parser.getTok();
SMLoc StartLoc = Tok.getLoc();
SMLoc EndLoc = Tok.getEndLoc();
RegisterKind RegKind;
unsigned Reg, RegNum, RegWidth, DwordRegIndex;
if (!ParseAMDGPURegister(RegKind, Reg, RegNum, RegWidth, &DwordRegIndex)) {
return nullptr;
}
if (AMDGPU::IsaInfo::hasCodeObjectV3(&getSTI())) {
if (!updateGprCountSymbols(RegKind, DwordRegIndex, RegWidth))
return nullptr;
} else
KernelScope.usesRegister(RegKind, DwordRegIndex, RegWidth);
return AMDGPUOperand::CreateReg(this, Reg, StartLoc, EndLoc, false);
}
bool
AMDGPUAsmParser::parseAbsoluteExpr(int64_t &Val, bool AbsMod) {
if (AbsMod && getLexer().peekTok().is(AsmToken::Pipe) &&
(getLexer().getKind() == AsmToken::Integer ||
getLexer().getKind() == AsmToken::Real)) {
// This is a workaround for handling operands like these:
// |1.0|
// |-1|
// This syntax is not compatible with syntax of standard
// MC expressions (due to the trailing '|').
SMLoc EndLoc;
const MCExpr *Expr;
if (getParser().parsePrimaryExpr(Expr, EndLoc)) {
return true;
}
return !Expr->evaluateAsAbsolute(Val);
}
return getParser().parseAbsoluteExpression(Val);
}
OperandMatchResultTy
AMDGPUAsmParser::parseImm(OperandVector &Operands, bool AbsMod) {
// TODO: add syntactic sugar for 1/(2*PI)
bool Minus = false;
if (getLexer().getKind() == AsmToken::Minus) {
const AsmToken NextToken = getLexer().peekTok();
if (!NextToken.is(AsmToken::Integer) &&
!NextToken.is(AsmToken::Real)) {
return MatchOperand_NoMatch;
}
Minus = true;
Parser.Lex();
}
SMLoc S = Parser.getTok().getLoc();
switch(getLexer().getKind()) {
case AsmToken::Integer: {
int64_t IntVal;
if (parseAbsoluteExpr(IntVal, AbsMod))
return MatchOperand_ParseFail;
if (Minus)
IntVal *= -1;
Operands.push_back(AMDGPUOperand::CreateImm(this, IntVal, S));
return MatchOperand_Success;
}
case AsmToken::Real: {
int64_t IntVal;
if (parseAbsoluteExpr(IntVal, AbsMod))
return MatchOperand_ParseFail;
APFloat F(BitsToDouble(IntVal));
if (Minus)
F.changeSign();
Operands.push_back(
AMDGPUOperand::CreateImm(this, F.bitcastToAPInt().getZExtValue(), S,
AMDGPUOperand::ImmTyNone, true));
return MatchOperand_Success;
}
default:
return MatchOperand_NoMatch;
}
}
OperandMatchResultTy
AMDGPUAsmParser::parseReg(OperandVector &Operands) {
if (auto R = parseRegister()) {
assert(R->isReg());
R->Reg.IsForcedVOP3 = isForcedVOP3();
Operands.push_back(std::move(R));
return MatchOperand_Success;
}
return MatchOperand_NoMatch;
}
OperandMatchResultTy
AMDGPUAsmParser::parseRegOrImm(OperandVector &Operands, bool AbsMod) {
auto res = parseImm(Operands, AbsMod);
if (res != MatchOperand_NoMatch) {
return res;
}
return parseReg(Operands);
}
OperandMatchResultTy
AMDGPUAsmParser::parseRegOrImmWithFPInputMods(OperandVector &Operands,
bool AllowImm) {
bool Negate = false, Negate2 = false, Abs = false, Abs2 = false;
if (getLexer().getKind()== AsmToken::Minus) {
const AsmToken NextToken = getLexer().peekTok();
// Disable ambiguous constructs like '--1' etc. Should use neg(-1) instead.
if (NextToken.is(AsmToken::Minus)) {
Error(Parser.getTok().getLoc(), "invalid syntax, expected 'neg' modifier");
return MatchOperand_ParseFail;
}
// '-' followed by an integer literal N should be interpreted as integer
// negation rather than a floating-point NEG modifier applied to N.
// Beside being contr-intuitive, such use of floating-point NEG modifier
// results in different meaning of integer literals used with VOP1/2/C
// and VOP3, for example:
// v_exp_f32_e32 v5, -1 // VOP1: src0 = 0xFFFFFFFF
// v_exp_f32_e64 v5, -1 // VOP3: src0 = 0x80000001
// Negative fp literals should be handled likewise for unifomtity
if (!NextToken.is(AsmToken::Integer) && !NextToken.is(AsmToken::Real)) {
Parser.Lex();
Negate = true;
}
}
if (getLexer().getKind() == AsmToken::Identifier &&
Parser.getTok().getString() == "neg") {
if (Negate) {
Error(Parser.getTok().getLoc(), "expected register or immediate");
return MatchOperand_ParseFail;
}
Parser.Lex();
Negate2 = true;
if (getLexer().isNot(AsmToken::LParen)) {
Error(Parser.getTok().getLoc(), "expected left paren after neg");
return MatchOperand_ParseFail;
}
Parser.Lex();
}
if (getLexer().getKind() == AsmToken::Identifier &&
Parser.getTok().getString() == "abs") {
Parser.Lex();
Abs2 = true;
if (getLexer().isNot(AsmToken::LParen)) {
Error(Parser.getTok().getLoc(), "expected left paren after abs");
return MatchOperand_ParseFail;
}
Parser.Lex();
}
if (getLexer().getKind() == AsmToken::Pipe) {
if (Abs2) {
Error(Parser.getTok().getLoc(), "expected register or immediate");
return MatchOperand_ParseFail;
}
Parser.Lex();
Abs = true;
}
OperandMatchResultTy Res;
if (AllowImm) {
Res = parseRegOrImm(Operands, Abs);
} else {
Res = parseReg(Operands);
}
if (Res != MatchOperand_Success) {
return Res;
}
AMDGPUOperand::Modifiers Mods;
if (Abs) {
if (getLexer().getKind() != AsmToken::Pipe) {
Error(Parser.getTok().getLoc(), "expected vertical bar");
return MatchOperand_ParseFail;
}
Parser.Lex();
Mods.Abs = true;
}
if (Abs2) {
if (getLexer().isNot(AsmToken::RParen)) {
Error(Parser.getTok().getLoc(), "expected closing parentheses");
return MatchOperand_ParseFail;
}
Parser.Lex();
Mods.Abs = true;
}
if (Negate) {
Mods.Neg = true;
} else if (Negate2) {
if (getLexer().isNot(AsmToken::RParen)) {
Error(Parser.getTok().getLoc(), "expected closing parentheses");
return MatchOperand_ParseFail;
}
Parser.Lex();
Mods.Neg = true;
}
if (Mods.hasFPModifiers()) {
AMDGPUOperand &Op = static_cast<AMDGPUOperand &>(*Operands.back());
Op.setModifiers(Mods);
}
return MatchOperand_Success;
}
OperandMatchResultTy
AMDGPUAsmParser::parseRegOrImmWithIntInputMods(OperandVector &Operands,
bool AllowImm) {
bool Sext = false;
if (getLexer().getKind() == AsmToken::Identifier &&
Parser.getTok().getString() == "sext") {
Parser.Lex();
Sext = true;
if (getLexer().isNot(AsmToken::LParen)) {
Error(Parser.getTok().getLoc(), "expected left paren after sext");
return MatchOperand_ParseFail;
}
Parser.Lex();
}
OperandMatchResultTy Res;
if (AllowImm) {
Res = parseRegOrImm(Operands);
} else {
Res = parseReg(Operands);
}
if (Res != MatchOperand_Success) {
return Res;
}
AMDGPUOperand::Modifiers Mods;
if (Sext) {
if (getLexer().isNot(AsmToken::RParen)) {
Error(Parser.getTok().getLoc(), "expected closing parentheses");
return MatchOperand_ParseFail;
}
Parser.Lex();
Mods.Sext = true;
}
if (Mods.hasIntModifiers()) {
AMDGPUOperand &Op = static_cast<AMDGPUOperand &>(*Operands.back());
Op.setModifiers(Mods);
}
return MatchOperand_Success;
}
OperandMatchResultTy
AMDGPUAsmParser::parseRegWithFPInputMods(OperandVector &Operands) {
return parseRegOrImmWithFPInputMods(Operands, false);
}
OperandMatchResultTy
AMDGPUAsmParser::parseRegWithIntInputMods(OperandVector &Operands) {
return parseRegOrImmWithIntInputMods(Operands, false);
}
OperandMatchResultTy AMDGPUAsmParser::parseVReg32OrOff(OperandVector &Operands) {
std::unique_ptr<AMDGPUOperand> Reg = parseRegister();
if (Reg) {
Operands.push_back(std::move(Reg));
return MatchOperand_Success;
}
const AsmToken &Tok = Parser.getTok();
if (Tok.getString() == "off") {
Operands.push_back(AMDGPUOperand::CreateImm(this, 0, Tok.getLoc(),
AMDGPUOperand::ImmTyOff, false));
Parser.Lex();
return MatchOperand_Success;
}
return MatchOperand_NoMatch;
}
unsigned AMDGPUAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
uint64_t TSFlags = MII.get(Inst.getOpcode()).TSFlags;
if ((getForcedEncodingSize() == 32 && (TSFlags & SIInstrFlags::VOP3)) ||
(getForcedEncodingSize() == 64 && !(TSFlags & SIInstrFlags::VOP3)) ||
(isForcedDPP() && !(TSFlags & SIInstrFlags::DPP)) ||
(isForcedSDWA() && !(TSFlags & SIInstrFlags::SDWA)) )
return Match_InvalidOperand;
if ((TSFlags & SIInstrFlags::VOP3) &&
(TSFlags & SIInstrFlags::VOPAsmPrefer32Bit) &&
getForcedEncodingSize() != 64)
return Match_PreferE32;
if (Inst.getOpcode() == AMDGPU::V_MAC_F32_sdwa_vi ||
Inst.getOpcode() == AMDGPU::V_MAC_F16_sdwa_vi) {
// v_mac_f32/16 allow only dst_sel == DWORD;
auto OpNum =
AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::dst_sel);
const auto &Op = Inst.getOperand(OpNum);
if (!Op.isImm() || Op.getImm() != AMDGPU::SDWA::SdwaSel::DWORD) {
return Match_InvalidOperand;
}
}
if ((TSFlags & SIInstrFlags::FLAT) && !hasFlatOffsets()) {
// FIXME: Produces error without correct column reported.
auto OpNum =
AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::offset);
const auto &Op = Inst.getOperand(OpNum);
if (Op.getImm() != 0)
return Match_InvalidOperand;
}
return Match_Success;
}
// What asm variants we should check
ArrayRef<unsigned> AMDGPUAsmParser::getMatchedVariants() const {
if (getForcedEncodingSize() == 32) {
static const unsigned Variants[] = {AMDGPUAsmVariants::DEFAULT};
return makeArrayRef(Variants);
}
if (isForcedVOP3()) {
static const unsigned Variants[] = {AMDGPUAsmVariants::VOP3};
return makeArrayRef(Variants);
}
if (isForcedSDWA()) {
static const unsigned Variants[] = {AMDGPUAsmVariants::SDWA,
AMDGPUAsmVariants::SDWA9};
return makeArrayRef(Variants);
}
if (isForcedDPP()) {
static const unsigned Variants[] = {AMDGPUAsmVariants::DPP};
return makeArrayRef(Variants);
}
static const unsigned Variants[] = {
AMDGPUAsmVariants::DEFAULT, AMDGPUAsmVariants::VOP3,
AMDGPUAsmVariants::SDWA, AMDGPUAsmVariants::SDWA9, AMDGPUAsmVariants::DPP
};
return makeArrayRef(Variants);
}
unsigned AMDGPUAsmParser::findImplicitSGPRReadInVOP(const MCInst &Inst) const {
const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
const unsigned Num = Desc.getNumImplicitUses();
for (unsigned i = 0; i < Num; ++i) {
unsigned Reg = Desc.ImplicitUses[i];
switch (Reg) {
case AMDGPU::FLAT_SCR:
case AMDGPU::VCC:
case AMDGPU::M0:
return Reg;
default:
break;
}
}
return AMDGPU::NoRegister;
}
// NB: This code is correct only when used to check constant
// bus limitations because GFX7 support no f16 inline constants.
// Note that there are no cases when a GFX7 opcode violates
// constant bus limitations due to the use of an f16 constant.
bool AMDGPUAsmParser::isInlineConstant(const MCInst &Inst,
unsigned OpIdx) const {
const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
if (!AMDGPU::isSISrcOperand(Desc, OpIdx)) {
return false;
}
const MCOperand &MO = Inst.getOperand(OpIdx);
int64_t Val = MO.getImm();
auto OpSize = AMDGPU::getOperandSize(Desc, OpIdx);
switch (OpSize) { // expected operand size
case 8:
return AMDGPU::isInlinableLiteral64(Val, hasInv2PiInlineImm());
case 4:
return AMDGPU::isInlinableLiteral32(Val, hasInv2PiInlineImm());
case 2: {
const unsigned OperandType = Desc.OpInfo[OpIdx].OperandType;
if (OperandType == AMDGPU::OPERAND_REG_INLINE_C_V2INT16 ||
OperandType == AMDGPU::OPERAND_REG_INLINE_C_V2FP16) {
return AMDGPU::isInlinableLiteralV216(Val, hasInv2PiInlineImm());
} else {
return AMDGPU::isInlinableLiteral16(Val, hasInv2PiInlineImm());
}
}
default:
llvm_unreachable("invalid operand size");
}
}
bool AMDGPUAsmParser::usesConstantBus(const MCInst &Inst, unsigned OpIdx) {
const MCOperand &MO = Inst.getOperand(OpIdx);
if (MO.isImm()) {
return !isInlineConstant(Inst, OpIdx);
}
return !MO.isReg() ||
isSGPR(mc2PseudoReg(MO.getReg()), getContext().getRegisterInfo());
}
bool AMDGPUAsmParser::validateConstantBusLimitations(const MCInst &Inst) {
const unsigned Opcode = Inst.getOpcode();
const MCInstrDesc &Desc = MII.get(Opcode);
unsigned ConstantBusUseCount = 0;
if (Desc.TSFlags &
(SIInstrFlags::VOPC |
SIInstrFlags::VOP1 | SIInstrFlags::VOP2 |
SIInstrFlags::VOP3 | SIInstrFlags::VOP3P |
SIInstrFlags::SDWA)) {
// Check special imm operands (used by madmk, etc)
if (AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::imm) != -1) {
++ConstantBusUseCount;
}
unsigned SGPRUsed = findImplicitSGPRReadInVOP(Inst);
if (SGPRUsed != AMDGPU::NoRegister) {
++ConstantBusUseCount;
}
const int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
const int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
const int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
const int OpIndices[] = { Src0Idx, Src1Idx, Src2Idx };
for (int OpIdx : OpIndices) {
if (OpIdx == -1) break;
const MCOperand &MO = Inst.getOperand(OpIdx);
if (usesConstantBus(Inst, OpIdx)) {
if (MO.isReg()) {
const unsigned Reg = mc2PseudoReg(MO.getReg());
// Pairs of registers with a partial intersections like these
// s0, s[0:1]
// flat_scratch_lo, flat_scratch
// flat_scratch_lo, flat_scratch_hi
// are theoretically valid but they are disabled anyway.
// Note that this code mimics SIInstrInfo::verifyInstruction
if (Reg != SGPRUsed) {
++ConstantBusUseCount;
}
SGPRUsed = Reg;
} else { // Expression or a literal
++ConstantBusUseCount;
}
}
}
}
return ConstantBusUseCount <= 1;
}
bool AMDGPUAsmParser::validateEarlyClobberLimitations(const MCInst &Inst) {
const unsigned Opcode = Inst.getOpcode();
const MCInstrDesc &Desc = MII.get(Opcode);
const int DstIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::vdst);
if (DstIdx == -1 ||
Desc.getOperandConstraint(DstIdx, MCOI::EARLY_CLOBBER) == -1) {
return true;
}
const MCRegisterInfo *TRI = getContext().getRegisterInfo();
const int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
const int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
const int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
assert(DstIdx != -1);
const MCOperand &Dst = Inst.getOperand(DstIdx);
assert(Dst.isReg());
const unsigned DstReg = mc2PseudoReg(Dst.getReg());
const int SrcIndices[] = { Src0Idx, Src1Idx, Src2Idx };
for (int SrcIdx : SrcIndices) {
if (SrcIdx == -1) break;
const MCOperand &Src = Inst.getOperand(SrcIdx);
if (Src.isReg()) {
const unsigned SrcReg = mc2PseudoReg(Src.getReg());
if (isRegIntersect(DstReg, SrcReg, TRI)) {
return false;
}
}
}
return true;
}
bool AMDGPUAsmParser::validateIntClampSupported(const MCInst &Inst) {
const unsigned Opc = Inst.getOpcode();
const MCInstrDesc &Desc = MII.get(Opc);
if ((Desc.TSFlags & SIInstrFlags::IntClamp) != 0 && !hasIntClamp()) {
int ClampIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp);
assert(ClampIdx != -1);
return Inst.getOperand(ClampIdx).getImm() == 0;
}
return true;
}
bool AMDGPUAsmParser::validateMIMGDataSize(const MCInst &Inst) {
const unsigned Opc = Inst.getOpcode();
const MCInstrDesc &Desc = MII.get(Opc);
if ((Desc.TSFlags & SIInstrFlags::MIMG) == 0)
return true;
int VDataIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdata);
int DMaskIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dmask);
int TFEIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::tfe);
assert(VDataIdx != -1);
assert(DMaskIdx != -1);
assert(TFEIdx != -1);
unsigned VDataSize = AMDGPU::getRegOperandSize(getMRI(), Desc, VDataIdx);
unsigned TFESize = Inst.getOperand(TFEIdx).getImm()? 1 : 0;
unsigned DMask = Inst.getOperand(DMaskIdx).getImm() & 0xf;
if (DMask == 0)
DMask = 1;
unsigned DataSize =
(Desc.TSFlags & SIInstrFlags::Gather4) ? 4 : countPopulation(DMask);
if (hasPackedD16()) {
int D16Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::d16);
if (D16Idx >= 0 && Inst.getOperand(D16Idx).getImm())
DataSize = (DataSize + 1) / 2;
}
return (VDataSize / 4) == DataSize + TFESize;
}
bool AMDGPUAsmParser::validateMIMGAtomicDMask(const MCInst &Inst) {
const unsigned Opc = Inst.getOpcode();
const MCInstrDesc &Desc = MII.get(Opc);
if ((Desc.TSFlags & SIInstrFlags::MIMG) == 0)
return true;
if (!Desc.mayLoad() || !Desc.mayStore())
return true; // Not atomic
int DMaskIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dmask);
unsigned DMask = Inst.getOperand(DMaskIdx).getImm() & 0xf;
// This is an incomplete check because image_atomic_cmpswap
// may only use 0x3 and 0xf while other atomic operations
// may use 0x1 and 0x3. However these limitations are
// verified when we check that dmask matches dst size.
return DMask == 0x1 || DMask == 0x3 || DMask == 0xf;
}
bool AMDGPUAsmParser::validateMIMGGatherDMask(const MCInst &Inst) {
const unsigned Opc = Inst.getOpcode();
const MCInstrDesc &Desc = MII.get(Opc);
if ((Desc.TSFlags & SIInstrFlags::Gather4) == 0)
return true;
int DMaskIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::dmask);
unsigned DMask = Inst.getOperand(DMaskIdx).getImm() & 0xf;
// GATHER4 instructions use dmask in a different fashion compared to
// other MIMG instructions. The only useful DMASK values are
// 1=red, 2=green, 4=blue, 8=alpha. (e.g. 1 returns
// (red,red,red,red) etc.) The ISA document doesn't mention
// this.
return DMask == 0x1 || DMask == 0x2 || DMask == 0x4 || DMask == 0x8;
}
bool AMDGPUAsmParser::validateMIMGD16(const MCInst &Inst) {
const unsigned Opc = Inst.getOpcode();
const MCInstrDesc &Desc = MII.get(Opc);
if ((Desc.TSFlags & SIInstrFlags::MIMG) == 0)
return true;
int D16Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::d16);
if (D16Idx >= 0 && Inst.getOperand(D16Idx).getImm()) {
if (isCI() || isSI())
return false;
}
return true;
}
bool AMDGPUAsmParser::validateLdsDirect(const MCInst &Inst) {
using namespace SIInstrFlags;
const unsigned Opcode = Inst.getOpcode();
const MCInstrDesc &Desc = MII.get(Opcode);
// lds_direct register is defined so that it can be used
// with 9-bit operands only. Ignore encodings which do not accept these.
if ((Desc.TSFlags & (VOP1 | VOP2 | VOP3 | VOPC | VOP3P | SIInstrFlags::SDWA)) == 0)
return true;
const int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
const int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
const int Src2Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2);
const int SrcIndices[] = { Src1Idx, Src2Idx };
// lds_direct cannot be specified as either src1 or src2.
for (int SrcIdx : SrcIndices) {
if (SrcIdx == -1) break;
const MCOperand &Src = Inst.getOperand(SrcIdx);
if (Src.isReg() && Src.getReg() == LDS_DIRECT) {
return false;
}
}
if (Src0Idx == -1)
return true;
const MCOperand &Src = Inst.getOperand(Src0Idx);
if (!Src.isReg() || Src.getReg() != LDS_DIRECT)
return true;
// lds_direct is specified as src0. Check additional limitations.
// FIXME: This is a workaround for bug 37943
// which allows 64-bit VOP3 opcodes use 32-bit operands.
if (AMDGPU::getRegOperandSize(getMRI(), Desc, Src0Idx) != 4)
return false;
// Documentation does not disable lds_direct for SDWA, but SP3 assembler does.
// FIXME: This inconsistence needs to be investigated further.
if (Desc.TSFlags & SIInstrFlags::SDWA)
return false;
// The following opcodes do not accept lds_direct which is explicitly stated
// in AMD documentation. However SP3 disables lds_direct for most other 'rev'
// opcodes as well (e.g. for v_subrev_u32 but not for v_subrev_f32).
// FIXME: This inconsistence needs to be investigated further.
switch (Opcode) {
case AMDGPU::V_LSHLREV_B32_e32_si:
case AMDGPU::V_LSHLREV_B32_e64_si:
case AMDGPU::V_LSHLREV_B16_e32_vi:
case AMDGPU::V_LSHLREV_B16_e64_vi:
case AMDGPU::V_LSHLREV_B32_e32_vi:
case AMDGPU::V_LSHLREV_B32_e64_vi:
case AMDGPU::V_LSHLREV_B64_vi:
case AMDGPU::V_LSHRREV_B32_e32_si:
case AMDGPU::V_LSHRREV_B32_e64_si:
case AMDGPU::V_LSHRREV_B16_e32_vi:
case AMDGPU::V_LSHRREV_B16_e64_vi:
case AMDGPU::V_LSHRREV_B32_e32_vi:
case AMDGPU::V_LSHRREV_B32_e64_vi:
case AMDGPU::V_LSHRREV_B64_vi:
case AMDGPU::V_ASHRREV_I32_e64_si:
case AMDGPU::V_ASHRREV_I32_e32_si:
case AMDGPU::V_ASHRREV_I16_e32_vi:
case AMDGPU::V_ASHRREV_I16_e64_vi:
case AMDGPU::V_ASHRREV_I32_e32_vi:
case AMDGPU::V_ASHRREV_I32_e64_vi:
case AMDGPU::V_ASHRREV_I64_vi:
case AMDGPU::V_PK_LSHLREV_B16_vi:
case AMDGPU::V_PK_LSHRREV_B16_vi:
case AMDGPU::V_PK_ASHRREV_I16_vi:
return false;
default:
return true;
}
}
bool AMDGPUAsmParser::validateSOPLiteral(const MCInst &Inst) const {
unsigned Opcode = Inst.getOpcode();
const MCInstrDesc &Desc = MII.get(Opcode);
if (!(Desc.TSFlags & (SIInstrFlags::SOP2 | SIInstrFlags::SOPC)))
return true;
const int Src0Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0);
const int Src1Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1);
const int OpIndices[] = { Src0Idx, Src1Idx };
unsigned NumLiterals = 0;
uint32_t LiteralValue;
for (int OpIdx : OpIndices) {
if (OpIdx == -1) break;
const MCOperand &MO = Inst.getOperand(OpIdx);
if (MO.isImm() &&
// Exclude special imm operands (like that used by s_set_gpr_idx_on)
AMDGPU::isSISrcOperand(Desc, OpIdx) &&
!isInlineConstant(Inst, OpIdx)) {
uint32_t Value = static_cast<uint32_t>(MO.getImm());
if (NumLiterals == 0 || LiteralValue != Value) {
LiteralValue = Value;
++NumLiterals;
}
}
}
return NumLiterals <= 1;
}
bool AMDGPUAsmParser::validateInstruction(const MCInst &Inst,
const SMLoc &IDLoc) {
if (!validateLdsDirect(Inst)) {
Error(IDLoc,
"invalid use of lds_direct");
return false;
}
if (!validateSOPLiteral(Inst)) {
Error(IDLoc,
"only one literal operand is allowed");
return false;
}
if (!validateConstantBusLimitations(Inst)) {
Error(IDLoc,
"invalid operand (violates constant bus restrictions)");
return false;
}
if (!validateEarlyClobberLimitations(Inst)) {
Error(IDLoc,
"destination must be different than all sources");
return false;
}
if (!validateIntClampSupported(Inst)) {
Error(IDLoc,
"integer clamping is not supported on this GPU");
return false;
}
// For MUBUF/MTBUF d16 is a part of opcode, so there is nothing to validate.
if (!validateMIMGD16(Inst)) {
Error(IDLoc,
"d16 modifier is not supported on this GPU");
return false;
}
if (!validateMIMGDataSize(Inst)) {
Error(IDLoc,
"image data size does not match dmask and tfe");
return false;
}
if (!validateMIMGAtomicDMask(Inst)) {
Error(IDLoc,
"invalid atomic image dmask");
return false;
}
if (!validateMIMGGatherDMask(Inst)) {
Error(IDLoc,
"invalid image_gather dmask: only one bit must be set");
return false;
}
return true;
}
static std::string AMDGPUMnemonicSpellCheck(StringRef S, uint64_t FBS,
unsigned VariantID = 0);
bool AMDGPUAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
OperandVector &Operands,
MCStreamer &Out,
uint64_t &ErrorInfo,
bool MatchingInlineAsm) {
MCInst Inst;
unsigned Result = Match_Success;
for (auto Variant : getMatchedVariants()) {
uint64_t EI;
auto R = MatchInstructionImpl(Operands, Inst, EI, MatchingInlineAsm,
Variant);
// We order match statuses from least to most specific. We use most specific
// status as resulting
// Match_MnemonicFail < Match_InvalidOperand < Match_MissingFeature < Match_PreferE32
if ((R == Match_Success) ||
(R == Match_PreferE32) ||
(R == Match_MissingFeature && Result != Match_PreferE32) ||
(R == Match_InvalidOperand && Result != Match_MissingFeature
&& Result != Match_PreferE32) ||
(R == Match_MnemonicFail && Result != Match_InvalidOperand
&& Result != Match_MissingFeature
&& Result != Match_PreferE32)) {
Result = R;
ErrorInfo = EI;
}
if (R == Match_Success)
break;
}
switch (Result) {
default: break;
case Match_Success:
if (!validateInstruction(Inst, IDLoc)) {
return true;
}
Inst.setLoc(IDLoc);
Out.EmitInstruction(Inst, getSTI());
return false;
case Match_MissingFeature:
return Error(IDLoc, "instruction not supported on this GPU");
case Match_MnemonicFail: {
uint64_t FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
std::string Suggestion = AMDGPUMnemonicSpellCheck(
((AMDGPUOperand &)*Operands[0]).getToken(), FBS);
return Error(IDLoc, "invalid instruction" + Suggestion,
((AMDGPUOperand &)*Operands[0]).getLocRange());
}
case Match_InvalidOperand: {
SMLoc ErrorLoc = IDLoc;
if (ErrorInfo != ~0ULL) {
if (ErrorInfo >= Operands.size()) {
return Error(IDLoc, "too few operands for instruction");
}
ErrorLoc = ((AMDGPUOperand &)*Operands[ErrorInfo]).getStartLoc();
if (ErrorLoc == SMLoc())
ErrorLoc = IDLoc;
}
return Error(ErrorLoc, "invalid operand for instruction");
}
case Match_PreferE32:
return Error(IDLoc, "internal error: instruction without _e64 suffix "
"should be encoded as e32");
}
llvm_unreachable("Implement any new match types added!");
}
bool AMDGPUAsmParser::ParseAsAbsoluteExpression(uint32_t &Ret) {
int64_t Tmp = -1;
if (getLexer().isNot(AsmToken::Integer) && getLexer().isNot(AsmToken::Identifier)) {
return true;
}
if (getParser().parseAbsoluteExpression(Tmp)) {
return true;
}
Ret = static_cast<uint32_t>(Tmp);
return false;
}
bool AMDGPUAsmParser::ParseDirectiveMajorMinor(uint32_t &Major,
uint32_t &Minor) {
if (ParseAsAbsoluteExpression(Major))
return TokError("invalid major version");
if (getLexer().isNot(AsmToken::Comma))
return TokError("minor version number required, comma expected");
Lex();
if (ParseAsAbsoluteExpression(Minor))
return TokError("invalid minor version");
return false;
}
bool AMDGPUAsmParser::ParseDirectiveAMDGCNTarget() {
if (getSTI().getTargetTriple().getArch() != Triple::amdgcn)
return TokError("directive only supported for amdgcn architecture");
std::string Target;
SMLoc TargetStart = getTok().getLoc();
if (getParser().parseEscapedString(Target))
return true;
SMRange TargetRange = SMRange(TargetStart, getTok().getLoc());
std::string ExpectedTarget;
raw_string_ostream ExpectedTargetOS(ExpectedTarget);
IsaInfo::streamIsaVersion(&getSTI(), ExpectedTargetOS);
if (Target != ExpectedTargetOS.str())
return getParser().Error(TargetRange.Start, "target must match options",
TargetRange);
getTargetStreamer().EmitDirectiveAMDGCNTarget(Target);
return false;
}
bool AMDGPUAsmParser::OutOfRangeError(SMRange Range) {
return getParser().Error(Range.Start, "value out of range", Range);
}
bool AMDGPUAsmParser::calculateGPRBlocks(
const FeatureBitset &Features, bool VCCUsed, bool FlatScrUsed,
bool XNACKUsed, unsigned NextFreeVGPR, SMRange VGPRRange,
unsigned NextFreeSGPR, SMRange SGPRRange, unsigned &VGPRBlocks,
unsigned &SGPRBlocks) {
// TODO(scott.linder): These calculations are duplicated from
// AMDGPUAsmPrinter::getSIProgramInfo and could be unified.
IsaVersion Version = getIsaVersion(getSTI().getCPU());
unsigned NumVGPRs = NextFreeVGPR;
unsigned NumSGPRs = NextFreeSGPR;
unsigned MaxAddressableNumSGPRs = IsaInfo::getAddressableNumSGPRs(&getSTI());
if (Version.Major >= 8 && !Features.test(FeatureSGPRInitBug) &&
NumSGPRs > MaxAddressableNumSGPRs)
return OutOfRangeError(SGPRRange);
NumSGPRs +=
IsaInfo::getNumExtraSGPRs(&getSTI(), VCCUsed, FlatScrUsed, XNACKUsed);
if ((Version.Major <= 7 || Features.test(FeatureSGPRInitBug)) &&
NumSGPRs > MaxAddressableNumSGPRs)
return OutOfRangeError(SGPRRange);
if (Features.test(FeatureSGPRInitBug))
NumSGPRs = IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
VGPRBlocks = IsaInfo::getNumVGPRBlocks(&getSTI(), NumVGPRs);
SGPRBlocks = IsaInfo::getNumSGPRBlocks(&getSTI(), NumSGPRs);
return false;
}
bool AMDGPUAsmParser::ParseDirectiveAMDHSAKernel() {
if (getSTI().getTargetTriple().getArch() != Triple::amdgcn)
return TokError("directive only supported for amdgcn architecture");
if (getSTI().getTargetTriple().getOS() != Triple::AMDHSA)
return TokError("directive only supported for amdhsa OS");
StringRef KernelName;
if (getParser().parseIdentifier(KernelName))
return true;
kernel_descriptor_t KD = getDefaultAmdhsaKernelDescriptor();
StringSet<> Seen;
IsaVersion IVersion = getIsaVersion(getSTI().getCPU());
SMRange VGPRRange;
uint64_t NextFreeVGPR = 0;
SMRange SGPRRange;
uint64_t NextFreeSGPR = 0;
unsigned UserSGPRCount = 0;
bool ReserveVCC = true;
bool ReserveFlatScr = true;
bool ReserveXNACK = hasXNACK();
while (true) {
while (getLexer().is(AsmToken::EndOfStatement))
Lex();
if (getLexer().isNot(AsmToken::Identifier))
return TokError("expected .amdhsa_ directive or .end_amdhsa_kernel");
StringRef ID = getTok().getIdentifier();
SMRange IDRange = getTok().getLocRange();
Lex();
if (ID == ".end_amdhsa_kernel")
break;
if (Seen.find(ID) != Seen.end())
return TokError(".amdhsa_ directives cannot be repeated");
Seen.insert(ID);
SMLoc ValStart = getTok().getLoc();
int64_t IVal;
if (getParser().parseAbsoluteExpression(IVal))
return true;
SMLoc ValEnd = getTok().getLoc();
SMRange ValRange = SMRange(ValStart, ValEnd);
if (IVal < 0)
return OutOfRangeError(ValRange);
uint64_t Val = IVal;
#define PARSE_BITS_ENTRY(FIELD, ENTRY, VALUE, RANGE) \
if (!isUInt<ENTRY##_WIDTH>(VALUE)) \
return OutOfRangeError(RANGE); \
AMDHSA_BITS_SET(FIELD, ENTRY, VALUE);
if (ID == ".amdhsa_group_segment_fixed_size") {
if (!isUInt<sizeof(KD.group_segment_fixed_size) * CHAR_BIT>(Val))
return OutOfRangeError(ValRange);
KD.group_segment_fixed_size = Val;
} else if (ID == ".amdhsa_private_segment_fixed_size") {
if (!isUInt<sizeof(KD.private_segment_fixed_size) * CHAR_BIT>(Val))
return OutOfRangeError(ValRange);
KD.private_segment_fixed_size = Val;
} else if (ID == ".amdhsa_user_sgpr_private_segment_buffer") {
PARSE_BITS_ENTRY(KD.kernel_code_properties,
KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER,
Val, ValRange);
UserSGPRCount++;
} else if (ID == ".amdhsa_user_sgpr_dispatch_ptr") {
PARSE_BITS_ENTRY(KD.kernel_code_properties,
KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR, Val,
ValRange);
UserSGPRCount++;
} else if (ID == ".amdhsa_user_sgpr_queue_ptr") {
PARSE_BITS_ENTRY(KD.kernel_code_properties,
KERNEL_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR, Val,
ValRange);
UserSGPRCount++;
} else if (ID == ".amdhsa_user_sgpr_kernarg_segment_ptr") {
PARSE_BITS_ENTRY(KD.kernel_code_properties,
KERNEL_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR,
Val, ValRange);
UserSGPRCount++;
} else if (ID == ".amdhsa_user_sgpr_dispatch_id") {
PARSE_BITS_ENTRY(KD.kernel_code_properties,
KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID, Val,
ValRange);
UserSGPRCount++;
} else if (ID == ".amdhsa_user_sgpr_flat_scratch_init") {
PARSE_BITS_ENTRY(KD.kernel_code_properties,
KERNEL_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT, Val,
ValRange);
UserSGPRCount++;
} else if (ID == ".amdhsa_user_sgpr_private_segment_size") {
PARSE_BITS_ENTRY(KD.kernel_code_properties,
KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_SIZE,
Val, ValRange);
UserSGPRCount++;
} else if (ID == ".amdhsa_system_sgpr_private_segment_wavefront_offset") {
PARSE_BITS_ENTRY(
KD.compute_pgm_rsrc2,
COMPUTE_PGM_RSRC2_ENABLE_SGPR_PRIVATE_SEGMENT_WAVEFRONT_OFFSET, Val,
ValRange);
} else if (ID == ".amdhsa_system_sgpr_workgroup_id_x") {
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc2,
COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_ID_X, Val,
ValRange);
} else if (ID == ".amdhsa_system_sgpr_workgroup_id_y") {
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc2,
COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_ID_Y, Val,
ValRange);
} else if (ID == ".amdhsa_system_sgpr_workgroup_id_z") {
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc2,
COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_ID_Z, Val,
ValRange);
} else if (ID == ".amdhsa_system_sgpr_workgroup_info") {
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc2,
COMPUTE_PGM_RSRC2_ENABLE_SGPR_WORKGROUP_INFO, Val,
ValRange);
} else if (ID == ".amdhsa_system_vgpr_workitem_id") {
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc2,
COMPUTE_PGM_RSRC2_ENABLE_VGPR_WORKITEM_ID, Val,
ValRange);
} else if (ID == ".amdhsa_next_free_vgpr") {
VGPRRange = ValRange;
NextFreeVGPR = Val;
} else if (ID == ".amdhsa_next_free_sgpr") {
SGPRRange = ValRange;
NextFreeSGPR = Val;
} else if (ID == ".amdhsa_reserve_vcc") {
if (!isUInt<1>(Val))
return OutOfRangeError(ValRange);
ReserveVCC = Val;
} else if (ID == ".amdhsa_reserve_flat_scratch") {
if (IVersion.Major < 7)
return getParser().Error(IDRange.Start, "directive requires gfx7+",
IDRange);
if (!isUInt<1>(Val))
return OutOfRangeError(ValRange);
ReserveFlatScr = Val;
} else if (ID == ".amdhsa_reserve_xnack_mask") {
if (IVersion.Major < 8)
return getParser().Error(IDRange.Start, "directive requires gfx8+",
IDRange);
if (!isUInt<1>(Val))
return OutOfRangeError(ValRange);
ReserveXNACK = Val;
} else if (ID == ".amdhsa_float_round_mode_32") {
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc1,
COMPUTE_PGM_RSRC1_FLOAT_ROUND_MODE_32, Val, ValRange);
} else if (ID == ".amdhsa_float_round_mode_16_64") {
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc1,
COMPUTE_PGM_RSRC1_FLOAT_ROUND_MODE_16_64, Val, ValRange);
} else if (ID == ".amdhsa_float_denorm_mode_32") {
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc1,
COMPUTE_PGM_RSRC1_FLOAT_DENORM_MODE_32, Val, ValRange);
} else if (ID == ".amdhsa_float_denorm_mode_16_64") {
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc1,
COMPUTE_PGM_RSRC1_FLOAT_DENORM_MODE_16_64, Val,
ValRange);
} else if (ID == ".amdhsa_dx10_clamp") {
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc1,
COMPUTE_PGM_RSRC1_ENABLE_DX10_CLAMP, Val, ValRange);
} else if (ID == ".amdhsa_ieee_mode") {
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc1, COMPUTE_PGM_RSRC1_ENABLE_IEEE_MODE,
Val, ValRange);
} else if (ID == ".amdhsa_fp16_overflow") {
if (IVersion.Major < 9)
return getParser().Error(IDRange.Start, "directive requires gfx9+",
IDRange);
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc1, COMPUTE_PGM_RSRC1_FP16_OVFL, Val,
ValRange);
} else if (ID == ".amdhsa_exception_fp_ieee_invalid_op") {
PARSE_BITS_ENTRY(
KD.compute_pgm_rsrc2,
COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_INVALID_OPERATION, Val,
ValRange);
} else if (ID == ".amdhsa_exception_fp_denorm_src") {
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc2,
COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_FP_DENORMAL_SOURCE,
Val, ValRange);
} else if (ID == ".amdhsa_exception_fp_ieee_div_zero") {
PARSE_BITS_ENTRY(
KD.compute_pgm_rsrc2,
COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_DIVISION_BY_ZERO, Val,
ValRange);
} else if (ID == ".amdhsa_exception_fp_ieee_overflow") {
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc2,
COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_OVERFLOW,
Val, ValRange);
} else if (ID == ".amdhsa_exception_fp_ieee_underflow") {
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc2,
COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_UNDERFLOW,
Val, ValRange);
} else if (ID == ".amdhsa_exception_fp_ieee_inexact") {
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc2,
COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_IEEE_754_FP_INEXACT,
Val, ValRange);
} else if (ID == ".amdhsa_exception_int_div_zero") {
PARSE_BITS_ENTRY(KD.compute_pgm_rsrc2,
COMPUTE_PGM_RSRC2_ENABLE_EXCEPTION_INT_DIVIDE_BY_ZERO,
Val, ValRange);
} else {
return getParser().Error(IDRange.Start,
"unknown .amdhsa_kernel directive", IDRange);
}
#undef PARSE_BITS_ENTRY
}
if (Seen.find(".amdhsa_next_free_vgpr") == Seen.end())
return TokError(".amdhsa_next_free_vgpr directive is required");
if (Seen.find(".amdhsa_next_free_sgpr") == Seen.end())
return TokError(".amdhsa_next_free_sgpr directive is required");
unsigned VGPRBlocks;
unsigned SGPRBlocks;
if (calculateGPRBlocks(getFeatureBits(), ReserveVCC, ReserveFlatScr,
ReserveXNACK, NextFreeVGPR, VGPRRange, NextFreeSGPR,
SGPRRange, VGPRBlocks, SGPRBlocks))
return true;
if (!isUInt<COMPUTE_PGM_RSRC1_GRANULATED_WORKITEM_VGPR_COUNT_WIDTH>(
VGPRBlocks))
return OutOfRangeError(VGPRRange);
AMDHSA_BITS_SET(KD.compute_pgm_rsrc1,
COMPUTE_PGM_RSRC1_GRANULATED_WORKITEM_VGPR_COUNT, VGPRBlocks);
if (!isUInt<COMPUTE_PGM_RSRC1_GRANULATED_WAVEFRONT_SGPR_COUNT_WIDTH>(
SGPRBlocks))
return OutOfRangeError(SGPRRange);
AMDHSA_BITS_SET(KD.compute_pgm_rsrc1,
COMPUTE_PGM_RSRC1_GRANULATED_WAVEFRONT_SGPR_COUNT,
SGPRBlocks);
if (!isUInt<COMPUTE_PGM_RSRC2_USER_SGPR_COUNT_WIDTH>(UserSGPRCount))
return TokError("too many user SGPRs enabled");
AMDHSA_BITS_SET(KD.compute_pgm_rsrc2, COMPUTE_PGM_RSRC2_USER_SGPR_COUNT,
UserSGPRCount);
getTargetStreamer().EmitAmdhsaKernelDescriptor(
getSTI(), KernelName, KD, NextFreeVGPR, NextFreeSGPR, ReserveVCC,
ReserveFlatScr, ReserveXNACK);
return false;
}
bool AMDGPUAsmParser::ParseDirectiveHSACodeObjectVersion() {
uint32_t Major;
uint32_t Minor;
if (ParseDirectiveMajorMinor(Major, Minor))
return true;
getTargetStreamer().EmitDirectiveHSACodeObjectVersion(Major, Minor);
return false;
}
bool AMDGPUAsmParser::ParseDirectiveHSACodeObjectISA() {
uint32_t Major;
uint32_t Minor;
uint32_t Stepping;
StringRef VendorName;
StringRef ArchName;
// If this directive has no arguments, then use the ISA version for the
// targeted GPU.
if (getLexer().is(AsmToken::EndOfStatement)) {
AMDGPU::IsaVersion ISA = AMDGPU::getIsaVersion(getSTI().getCPU());
getTargetStreamer().EmitDirectiveHSACodeObjectISA(ISA.Major, ISA.Minor,
ISA.Stepping,
"AMD", "AMDGPU");
return false;
}
if (ParseDirectiveMajorMinor(Major, Minor))
return true;
if (getLexer().isNot(AsmToken::Comma))
return TokError("stepping version number required, comma expected");
Lex();
if (ParseAsAbsoluteExpression(Stepping))
return TokError("invalid stepping version");
if (getLexer().isNot(AsmToken::Comma))
return TokError("vendor name required, comma expected");
Lex();
if (getLexer().isNot(AsmToken::String))
return TokError("invalid vendor name");
VendorName = getLexer().getTok().getStringContents();
Lex();
if (getLexer().isNot(AsmToken::Comma))
return TokError("arch name required, comma expected");
Lex();
if (getLexer().isNot(AsmToken::String))
return TokError("invalid arch name");
ArchName = getLexer().getTok().getStringContents();
Lex();
getTargetStreamer().EmitDirectiveHSACodeObjectISA(Major, Minor, Stepping,
VendorName, ArchName);
return false;
}
bool AMDGPUAsmParser::ParseAMDKernelCodeTValue(StringRef ID,
amd_kernel_code_t &Header) {
// max_scratch_backing_memory_byte_size is deprecated. Ignore it while parsing
// assembly for backwards compatibility.
if (ID == "max_scratch_backing_memory_byte_size") {
Parser.eatToEndOfStatement();
return false;
}
SmallString<40> ErrStr;
raw_svector_ostream Err(ErrStr);
if (!parseAmdKernelCodeField(ID, getParser(), Header, Err)) {
return TokError(Err.str());
}
Lex();
return false;
}
bool AMDGPUAsmParser::ParseDirectiveAMDKernelCodeT() {
amd_kernel_code_t Header;
AMDGPU::initDefaultAMDKernelCodeT(Header, &getSTI());
while (true) {
// Lex EndOfStatement. This is in a while loop, because lexing a comment
// will set the current token to EndOfStatement.
while(getLexer().is(AsmToken::EndOfStatement))
Lex();
if (getLexer().isNot(AsmToken::Identifier))
return TokError("expected value identifier or .end_amd_kernel_code_t");
StringRef ID = getLexer().getTok().getIdentifier();
Lex();
if (ID == ".end_amd_kernel_code_t")
break;
if (ParseAMDKernelCodeTValue(ID, Header))
return true;
}
getTargetStreamer().EmitAMDKernelCodeT(Header);
return false;
}
bool AMDGPUAsmParser::ParseDirectiveAMDGPUHsaKernel() {
if (getLexer().isNot(AsmToken::Identifier))
return TokError("expected symbol name");
StringRef KernelName = Parser.getTok().getString();
getTargetStreamer().EmitAMDGPUSymbolType(KernelName,
ELF::STT_AMDGPU_HSA_KERNEL);
Lex();
if (!AMDGPU::IsaInfo::hasCodeObjectV3(&getSTI()))
KernelScope.initialize(getContext());
return false;
}
bool AMDGPUAsmParser::ParseDirectiveISAVersion() {
if (getSTI().getTargetTriple().getArch() != Triple::amdgcn) {
return Error(getParser().getTok().getLoc(),
".amd_amdgpu_isa directive is not available on non-amdgcn "
"architectures");
}
auto ISAVersionStringFromASM = getLexer().getTok().getStringContents();
std::string ISAVersionStringFromSTI;
raw_string_ostream ISAVersionStreamFromSTI(ISAVersionStringFromSTI);
IsaInfo::streamIsaVersion(&getSTI(), ISAVersionStreamFromSTI);
if (ISAVersionStringFromASM != ISAVersionStreamFromSTI.str()) {
return Error(getParser().getTok().getLoc(),
".amd_amdgpu_isa directive does not match triple and/or mcpu "
"arguments specified through the command line");
}
getTargetStreamer().EmitISAVersion(ISAVersionStreamFromSTI.str());
Lex();
return false;
}
bool AMDGPUAsmParser::ParseDirectiveHSAMetadata() {
const char *AssemblerDirectiveBegin;
const char *AssemblerDirectiveEnd;
std::tie(AssemblerDirectiveBegin, AssemblerDirectiveEnd) =
AMDGPU::IsaInfo::hasCodeObjectV3(&getSTI())
? std::make_tuple(HSAMD::V3::AssemblerDirectiveBegin,
HSAMD::V3::AssemblerDirectiveEnd)
: std::make_tuple(HSAMD::AssemblerDirectiveBegin,
HSAMD::AssemblerDirectiveEnd);
if (getSTI().getTargetTriple().getOS() != Triple::AMDHSA) {
return Error(getParser().getTok().getLoc(),
(Twine(AssemblerDirectiveBegin) + Twine(" directive is "
"not available on non-amdhsa OSes")).str());
}
std::string HSAMetadataString;
raw_string_ostream YamlStream(HSAMetadataString);
getLexer().setSkipSpace(false);
bool FoundEnd = false;
while (!getLexer().is(AsmToken::Eof)) {
while (getLexer().is(AsmToken::Space)) {
YamlStream << getLexer().getTok().getString();
Lex();
}
if (getLexer().is(AsmToken::Identifier)) {
StringRef ID = getLexer().getTok().getIdentifier();
if (ID == AssemblerDirectiveEnd) {
Lex();
FoundEnd = true;
break;
}
}
YamlStream << Parser.parseStringToEndOfStatement()
<< getContext().getAsmInfo()->getSeparatorString();
Parser.eatToEndOfStatement();
}
getLexer().setSkipSpace(true);
if (getLexer().is(AsmToken::Eof) && !FoundEnd) {
return TokError(Twine("expected directive ") +
Twine(HSAMD::AssemblerDirectiveEnd) + Twine(" not found"));
}
YamlStream.flush();
if (IsaInfo::hasCodeObjectV3(&getSTI())) {
if (!getTargetStreamer().EmitHSAMetadataV3(HSAMetadataString))
return Error(getParser().getTok().getLoc(), "invalid HSA metadata");
} else {
if (!getTargetStreamer().EmitHSAMetadataV2(HSAMetadataString))
return Error(getParser().getTok().getLoc(), "invalid HSA metadata");
}
return false;
}
bool AMDGPUAsmParser::ParseDirectivePALMetadata() {
if (getSTI().getTargetTriple().getOS() != Triple::AMDPAL) {
return Error(getParser().getTok().getLoc(),
(Twine(PALMD::AssemblerDirective) + Twine(" directive is "
"not available on non-amdpal OSes")).str());
}
PALMD::Metadata PALMetadata;
for (;;) {
uint32_t Value;
if (ParseAsAbsoluteExpression(Value)) {
return TokError(Twine("invalid value in ") +
Twine(PALMD::AssemblerDirective));
}
PALMetadata.push_back(Value);
if (getLexer().isNot(AsmToken::Comma))
break;
Lex();
}
getTargetStreamer().EmitPALMetadata(PALMetadata);
return false;
}
bool AMDGPUAsmParser::ParseDirective(AsmToken DirectiveID) {
StringRef IDVal = DirectiveID.getString();
if (AMDGPU::IsaInfo::hasCodeObjectV3(&getSTI())) {
if (IDVal == ".amdgcn_target")
return ParseDirectiveAMDGCNTarget();
if (IDVal == ".amdhsa_kernel")
return ParseDirectiveAMDHSAKernel();
// TODO: Restructure/combine with PAL metadata directive.
if (IDVal == AMDGPU::HSAMD::V3::AssemblerDirectiveBegin)
return ParseDirectiveHSAMetadata();
} else {
if (IDVal == ".hsa_code_object_version")
return ParseDirectiveHSACodeObjectVersion();
if (IDVal == ".hsa_code_object_isa")
return ParseDirectiveHSACodeObjectISA();
if (IDVal == ".amd_kernel_code_t")
return ParseDirectiveAMDKernelCodeT();
if (IDVal == ".amdgpu_hsa_kernel")
return ParseDirectiveAMDGPUHsaKernel();
if (IDVal == ".amd_amdgpu_isa")
return ParseDirectiveISAVersion();
if (IDVal == AMDGPU::HSAMD::AssemblerDirectiveBegin)
return ParseDirectiveHSAMetadata();
}
if (IDVal == PALMD::AssemblerDirective)
return ParseDirectivePALMetadata();
return true;
}
bool AMDGPUAsmParser::subtargetHasRegister(const MCRegisterInfo &MRI,
unsigned RegNo) const {
for (MCRegAliasIterator R(AMDGPU::TTMP12_TTMP13_TTMP14_TTMP15, &MRI, true);
R.isValid(); ++R) {
if (*R == RegNo)
return isGFX9();
}
switch (RegNo) {
case AMDGPU::TBA:
case AMDGPU::TBA_LO:
case AMDGPU::TBA_HI:
case AMDGPU::TMA:
case AMDGPU::TMA_LO:
case AMDGPU::TMA_HI:
return !isGFX9();
case AMDGPU::XNACK_MASK:
case AMDGPU::XNACK_MASK_LO:
case AMDGPU::XNACK_MASK_HI:
return !isCI() && !isSI() && hasXNACK();
default:
break;
}
if (isCI())
return true;
if (isSI()) {
// No flat_scr
switch (RegNo) {
case AMDGPU::FLAT_SCR:
case AMDGPU::FLAT_SCR_LO:
case AMDGPU::FLAT_SCR_HI:
return false;
default:
return true;
}
}
// VI only has 102 SGPRs, so make sure we aren't trying to use the 2 more that
// SI/CI have.
for (MCRegAliasIterator R(AMDGPU::SGPR102_SGPR103, &MRI, true);
R.isValid(); ++R) {
if (*R == RegNo)
return false;
}
return true;
}
OperandMatchResultTy
AMDGPUAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
// Try to parse with a custom parser
OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
// If we successfully parsed the operand or if there as an error parsing,
// we are done.
//
// If we are parsing after we reach EndOfStatement then this means we
// are appending default values to the Operands list. This is only done
// by custom parser, so we shouldn't continue on to the generic parsing.
if (ResTy == MatchOperand_Success || ResTy == MatchOperand_ParseFail ||
getLexer().is(AsmToken::EndOfStatement))
return ResTy;
ResTy = parseRegOrImm(Operands);
if (ResTy == MatchOperand_Success)
return ResTy;
const auto &Tok = Parser.getTok();
SMLoc S = Tok.getLoc();
const MCExpr *Expr = nullptr;
if (!Parser.parseExpression(Expr)) {
Operands.push_back(AMDGPUOperand::CreateExpr(this, Expr, S));
return MatchOperand_Success;
}
// Possibly this is an instruction flag like 'gds'.
if (Tok.getKind() == AsmToken::Identifier) {
Operands.push_back(AMDGPUOperand::CreateToken(this, Tok.getString(), S));
Parser.Lex();
return MatchOperand_Success;
}
return MatchOperand_NoMatch;
}
StringRef AMDGPUAsmParser::parseMnemonicSuffix(StringRef Name) {
// Clear any forced encodings from the previous instruction.
setForcedEncodingSize(0);
setForcedDPP(false);
setForcedSDWA(false);
if (Name.endswith("_e64")) {
setForcedEncodingSize(64);
return Name.substr(0, Name.size() - 4);
} else if (Name.endswith("_e32")) {
setForcedEncodingSize(32);
return Name.substr(0, Name.size() - 4);
} else if (Name.endswith("_dpp")) {
setForcedDPP(true);
return Name.substr(0, Name.size() - 4);
} else if (Name.endswith("_sdwa")) {
setForcedSDWA(true);
return Name.substr(0, Name.size() - 5);
}
return Name;
}
bool AMDGPUAsmParser::ParseInstruction(ParseInstructionInfo &Info,
StringRef Name,
SMLoc NameLoc, OperandVector &Operands) {
// Add the instruction mnemonic
Name = parseMnemonicSuffix(Name);
Operands.push_back(AMDGPUOperand::CreateToken(this, Name, NameLoc));
while (!getLexer().is(AsmToken::EndOfStatement)) {
OperandMatchResultTy Res = parseOperand(Operands, Name);
// Eat the comma or space if there is one.
if (getLexer().is(AsmToken::Comma))
Parser.Lex();
switch (Res) {
case MatchOperand_Success: break;
case MatchOperand_ParseFail:
Error(getLexer().getLoc(), "failed parsing operand.");
while (!getLexer().is(AsmToken::EndOfStatement)) {
Parser.Lex();
}
return true;
case MatchOperand_NoMatch:
Error(getLexer().getLoc(), "not a valid operand.");
while (!getLexer().is(AsmToken::EndOfStatement)) {
Parser.Lex();
}
return true;
}
}
return false;
}
//===----------------------------------------------------------------------===//
// Utility functions
//===----------------------------------------------------------------------===//
OperandMatchResultTy
AMDGPUAsmParser::parseIntWithPrefix(const char *Prefix, int64_t &Int) {
switch(getLexer().getKind()) {
default: return MatchOperand_NoMatch;
case AsmToken::Identifier: {
StringRef Name = Parser.getTok().getString();
if (!Name.equals(Prefix)) {
return MatchOperand_NoMatch;
}
Parser.Lex();
if (getLexer().isNot(AsmToken::Colon))
return MatchOperand_ParseFail;
Parser.Lex();
bool IsMinus = false;
if (getLexer().getKind() == AsmToken::Minus) {
Parser.Lex();
IsMinus = true;
}
if (getLexer().isNot(AsmToken::Integer))
return MatchOperand_ParseFail;
if (getParser().parseAbsoluteExpression(Int))
return MatchOperand_ParseFail;
if (IsMinus)
Int = -Int;
break;
}
}
return MatchOperand_Success;
}
OperandMatchResultTy
AMDGPUAsmParser::parseIntWithPrefix(const char *Prefix, OperandVector &Operands,
AMDGPUOperand::ImmTy ImmTy,
bool (*ConvertResult)(int64_t&)) {
SMLoc S = Parser.getTok().getLoc();
int64_t Value = 0;
OperandMatchResultTy Res = parseIntWithPrefix(Prefix, Value);
if (Res != MatchOperand_Success)
return Res;
if (ConvertResult && !ConvertResult(Value)) {
return MatchOperand_ParseFail;
}
Operands.push_back(AMDGPUOperand::CreateImm(this, Value, S, ImmTy));
return MatchOperand_Success;
}
OperandMatchResultTy AMDGPUAsmParser::parseOperandArrayWithPrefix(
const char *Prefix,
OperandVector &Operands,
AMDGPUOperand::ImmTy ImmTy,
bool (*ConvertResult)(int64_t&)) {
StringRef Name = Parser.getTok().getString();
if (!Name.equals(Prefix))
return MatchOperand_NoMatch;
Parser.Lex();
if (getLexer().isNot(AsmToken::Colon))
return MatchOperand_ParseFail;
Parser.Lex();
if (getLexer().isNot(AsmToken::LBrac))
return MatchOperand_ParseFail;
Parser.Lex();
unsigned Val = 0;
SMLoc S = Parser.getTok().getLoc();
// FIXME: How to verify the number of elements matches the number of src
// operands?
for (int I = 0; I < 4; ++I) {
if (I != 0) {
if (getLexer().is(AsmToken::RBrac))
break;
if (getLexer().isNot(AsmToken::Comma))
return MatchOperand_ParseFail;
Parser.Lex();
}
if (getLexer().isNot(AsmToken::Integer))
return MatchOperand_ParseFail;
int64_t Op;
if (getParser().parseAbsoluteExpression(Op))
return MatchOperand_ParseFail;
if (Op != 0 && Op != 1)
return MatchOperand_ParseFail;
Val |= (Op << I);
}
Parser.Lex();
Operands.push_back(AMDGPUOperand::CreateImm(this, Val, S, ImmTy));
return MatchOperand_Success;
}
OperandMatchResultTy
AMDGPUAsmParser::parseNamedBit(const char *Name, OperandVector &Operands,
AMDGPUOperand::ImmTy ImmTy) {
int64_t Bit = 0;
SMLoc S = Parser.getTok().getLoc();
// We are at the end of the statement, and this is a default argument, so
// use a default value.
if (getLexer().isNot(AsmToken::EndOfStatement)) {
switch(getLexer().getKind()) {
case AsmToken::Identifier: {
StringRef Tok = Parser.getTok().getString();
if (Tok == Name) {
if (Tok == "r128" && isGFX9())
Error(S, "r128 modifier is not supported on this GPU");
if (Tok == "a16" && !isGFX9())
Error(S, "a16 modifier is not supported on this GPU");
Bit = 1;
Parser.Lex();
} else if (Tok.startswith("no") && Tok.endswith(Name)) {
Bit = 0;
Parser.Lex();
} else {
return MatchOperand_NoMatch;
}
break;
}
default:
return MatchOperand_NoMatch;
}
}
Operands.push_back(AMDGPUOperand::CreateImm(this, Bit, S, ImmTy));
return MatchOperand_Success;
}
static void addOptionalImmOperand(
MCInst& Inst, const OperandVector& Operands,
AMDGPUAsmParser::OptionalImmIndexMap& OptionalIdx,
AMDGPUOperand::ImmTy ImmT,
int64_t Default = 0) {
auto i = OptionalIdx.find(ImmT);
if (i != OptionalIdx.end()) {
unsigned Idx = i->second;
((AMDGPUOperand &)*Operands[Idx]).addImmOperands(Inst, 1);
} else {
Inst.addOperand(MCOperand::createImm(Default));
}
}
OperandMatchResultTy
AMDGPUAsmParser::parseStringWithPrefix(StringRef Prefix, StringRef &Value) {
if (getLexer().isNot(AsmToken::Identifier)) {
return MatchOperand_NoMatch;
}
StringRef Tok = Parser.getTok().getString();
if (Tok != Prefix) {
return MatchOperand_NoMatch;
}
Parser.Lex();
if (getLexer().isNot(AsmToken::Colon)) {
return MatchOperand_ParseFail;
}
Parser.Lex();
if (getLexer().isNot(AsmToken::Identifier)) {
return MatchOperand_ParseFail;
}
Value = Parser.getTok().getString();
return MatchOperand_Success;
}
// dfmt and nfmt (in a tbuffer instruction) are parsed as one to allow their
// values to live in a joint format operand in the MCInst encoding.
OperandMatchResultTy
AMDGPUAsmParser::parseDfmtNfmt(OperandVector &Operands) {
SMLoc S = Parser.getTok().getLoc();
int64_t Dfmt = 0, Nfmt = 0;
// dfmt and nfmt can appear in either order, and each is optional.
bool GotDfmt = false, GotNfmt = false;
while (!GotDfmt || !GotNfmt) {
if (!GotDfmt) {
auto Res = parseIntWithPrefix("dfmt", Dfmt);
if (Res != MatchOperand_NoMatch) {
if (Res != MatchOperand_Success)
return Res;
if (Dfmt >= 16) {
Error(Parser.getTok().getLoc(), "out of range dfmt");
return MatchOperand_ParseFail;
}
GotDfmt = true;
Parser.Lex();
continue;
}
}
if (!GotNfmt) {
auto Res = parseIntWithPrefix("nfmt", Nfmt);
if (Res != MatchOperand_NoMatch) {
if (Res != MatchOperand_Success)
return Res;
if (Nfmt >= 8) {
Error(Parser.getTok().getLoc(), "out of range nfmt");
return MatchOperand_ParseFail;
}
GotNfmt = true;
Parser.Lex();
continue;
}
}
break;
}
if (!GotDfmt && !GotNfmt)
return MatchOperand_NoMatch;
auto Format = Dfmt | Nfmt << 4;
Operands.push_back(
AMDGPUOperand::CreateImm(this, Format, S, AMDGPUOperand::ImmTyFORMAT));
return MatchOperand_Success;
}
//===----------------------------------------------------------------------===//
// ds
//===----------------------------------------------------------------------===//
void AMDGPUAsmParser::cvtDSOffset01(MCInst &Inst,
const OperandVector &Operands) {
OptionalImmIndexMap OptionalIdx;
for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
// Add the register arguments
if (Op.isReg()) {
Op.addRegOperands(Inst, 1);
continue;
}
// Handle optional arguments
OptionalIdx[Op.getImmTy()] = i;
}
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyOffset0);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyOffset1);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyGDS);
Inst.addOperand(MCOperand::createReg(AMDGPU::M0)); // m0
}
void AMDGPUAsmParser::cvtDSImpl(MCInst &Inst, const OperandVector &Operands,
bool IsGdsHardcoded) {
OptionalImmIndexMap OptionalIdx;
for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
// Add the register arguments
if (Op.isReg()) {
Op.addRegOperands(Inst, 1);
continue;
}
if (Op.isToken() && Op.getToken() == "gds") {
IsGdsHardcoded = true;
continue;
}
// Handle optional arguments
OptionalIdx[Op.getImmTy()] = i;
}
AMDGPUOperand::ImmTy OffsetType =
(Inst.getOpcode() == AMDGPU::DS_SWIZZLE_B32_si ||
Inst.getOpcode() == AMDGPU::DS_SWIZZLE_B32_vi) ? AMDGPUOperand::ImmTySwizzle :
AMDGPUOperand::ImmTyOffset;
addOptionalImmOperand(Inst, Operands, OptionalIdx, OffsetType);
if (!IsGdsHardcoded) {
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyGDS);
}
Inst.addOperand(MCOperand::createReg(AMDGPU::M0)); // m0
}
void AMDGPUAsmParser::cvtExp(MCInst &Inst, const OperandVector &Operands) {
OptionalImmIndexMap OptionalIdx;
unsigned OperandIdx[4];
unsigned EnMask = 0;
int SrcIdx = 0;
for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
// Add the register arguments
if (Op.isReg()) {
assert(SrcIdx < 4);
OperandIdx[SrcIdx] = Inst.size();
Op.addRegOperands(Inst, 1);
++SrcIdx;
continue;
}
if (Op.isOff()) {
assert(SrcIdx < 4);
OperandIdx[SrcIdx] = Inst.size();
Inst.addOperand(MCOperand::createReg(AMDGPU::NoRegister));
++SrcIdx;
continue;
}
if (Op.isImm() && Op.getImmTy() == AMDGPUOperand::ImmTyExpTgt) {
Op.addImmOperands(Inst, 1);
continue;
}
if (Op.isToken() && Op.getToken() == "done")
continue;
// Handle optional arguments
OptionalIdx[Op.getImmTy()] = i;
}
assert(SrcIdx == 4);
bool Compr = false;
if (OptionalIdx.find(AMDGPUOperand::ImmTyExpCompr) != OptionalIdx.end()) {
Compr = true;
Inst.getOperand(OperandIdx[1]) = Inst.getOperand(OperandIdx[2]);
Inst.getOperand(OperandIdx[2]).setReg(AMDGPU::NoRegister);
Inst.getOperand(OperandIdx[3]).setReg(AMDGPU::NoRegister);
}
for (auto i = 0; i < SrcIdx; ++i) {
if (Inst.getOperand(OperandIdx[i]).getReg() != AMDGPU::NoRegister) {
EnMask |= Compr? (0x3 << i * 2) : (0x1 << i);
}
}
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyExpVM);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyExpCompr);
Inst.addOperand(MCOperand::createImm(EnMask));
}
//===----------------------------------------------------------------------===//
// s_waitcnt
//===----------------------------------------------------------------------===//
static bool
encodeCnt(
const AMDGPU::IsaVersion ISA,
int64_t &IntVal,
int64_t CntVal,
bool Saturate,
unsigned (*encode)(const IsaVersion &Version, unsigned, unsigned),
unsigned (*decode)(const IsaVersion &Version, unsigned))
{
bool Failed = false;
IntVal = encode(ISA, IntVal, CntVal);
if (CntVal != decode(ISA, IntVal)) {
if (Saturate) {
IntVal = encode(ISA, IntVal, -1);
} else {
Failed = true;
}
}
return Failed;
}
bool AMDGPUAsmParser::parseCnt(int64_t &IntVal) {
StringRef CntName = Parser.getTok().getString();
int64_t CntVal;
Parser.Lex();
if (getLexer().isNot(AsmToken::LParen))
return true;
Parser.Lex();
if (getLexer().isNot(AsmToken::Integer))
return true;
SMLoc ValLoc = Parser.getTok().getLoc();
if (getParser().parseAbsoluteExpression(CntVal))
return true;
AMDGPU::IsaVersion ISA = AMDGPU::getIsaVersion(getSTI().getCPU());
bool Failed = true;
bool Sat = CntName.endswith("_sat");
if (CntName == "vmcnt" || CntName == "vmcnt_sat") {
Failed = encodeCnt(ISA, IntVal, CntVal, Sat, encodeVmcnt, decodeVmcnt);
} else if (CntName == "expcnt" || CntName == "expcnt_sat") {
Failed = encodeCnt(ISA, IntVal, CntVal, Sat, encodeExpcnt, decodeExpcnt);
} else if (CntName == "lgkmcnt" || CntName == "lgkmcnt_sat") {
Failed = encodeCnt(ISA, IntVal, CntVal, Sat, encodeLgkmcnt, decodeLgkmcnt);
}
if (Failed) {
Error(ValLoc, "too large value for " + CntName);
return true;
}
if (getLexer().isNot(AsmToken::RParen)) {
return true;
}
Parser.Lex();
if (getLexer().is(AsmToken::Amp) || getLexer().is(AsmToken::Comma)) {
const AsmToken NextToken = getLexer().peekTok();
if (NextToken.is(AsmToken::Identifier)) {
Parser.Lex();
}
}
return false;
}
OperandMatchResultTy
AMDGPUAsmParser::parseSWaitCntOps(OperandVector &Operands) {
AMDGPU::IsaVersion ISA = AMDGPU::getIsaVersion(getSTI().getCPU());
int64_t Waitcnt = getWaitcntBitMask(ISA);
SMLoc S = Parser.getTok().getLoc();
switch(getLexer().getKind()) {
default: return MatchOperand_ParseFail;
case AsmToken::Integer:
// The operand can be an integer value.
if (getParser().parseAbsoluteExpression(Waitcnt))
return MatchOperand_ParseFail;
break;
case AsmToken::Identifier:
do {
if (parseCnt(Waitcnt))
return MatchOperand_ParseFail;
} while(getLexer().isNot(AsmToken::EndOfStatement));
break;
}
Operands.push_back(AMDGPUOperand::CreateImm(this, Waitcnt, S));
return MatchOperand_Success;
}
bool AMDGPUAsmParser::parseHwregConstruct(OperandInfoTy &HwReg, int64_t &Offset,
int64_t &Width) {
using namespace llvm::AMDGPU::Hwreg;
if (Parser.getTok().getString() != "hwreg")
return true;
Parser.Lex();
if (getLexer().isNot(AsmToken::LParen))
return true;
Parser.Lex();
if (getLexer().is(AsmToken::Identifier)) {
HwReg.IsSymbolic = true;
HwReg.Id = ID_UNKNOWN_;
const StringRef tok = Parser.getTok().getString();
int Last = ID_SYMBOLIC_LAST_;
if (isSI() || isCI() || isVI())
Last = ID_SYMBOLIC_FIRST_GFX9_;
for (int i = ID_SYMBOLIC_FIRST_; i < Last; ++i) {
if (tok == IdSymbolic[i]) {
HwReg.Id = i;
break;
}
}
Parser.Lex();
} else {
HwReg.IsSymbolic = false;
if (getLexer().isNot(AsmToken::Integer))
return true;
if (getParser().parseAbsoluteExpression(HwReg.Id))
return true;
}
if (getLexer().is(AsmToken::RParen)) {
Parser.Lex();
return false;
}
// optional params
if (getLexer().isNot(AsmToken::Comma))
return true;
Parser.Lex();
if (getLexer().isNot(AsmToken::Integer))
return true;
if (getParser().parseAbsoluteExpression(Offset))
return true;
if (getLexer().isNot(AsmToken::Comma))
return true;
Parser.Lex();
if (getLexer().isNot(AsmToken::Integer))
return true;
if (getParser().parseAbsoluteExpression(Width))
return true;
if (getLexer().isNot(AsmToken::RParen))
return true;
Parser.Lex();
return false;
}
OperandMatchResultTy AMDGPUAsmParser::parseHwreg(OperandVector &Operands) {
using namespace llvm::AMDGPU::Hwreg;
int64_t Imm16Val = 0;
SMLoc S = Parser.getTok().getLoc();
switch(getLexer().getKind()) {
default: return MatchOperand_NoMatch;
case AsmToken::Integer:
// The operand can be an integer value.
if (getParser().parseAbsoluteExpression(Imm16Val))
return MatchOperand_NoMatch;
if (Imm16Val < 0 || !isUInt<16>(Imm16Val)) {
Error(S, "invalid immediate: only 16-bit values are legal");
// Do not return error code, but create an imm operand anyway and proceed
// to the next operand, if any. That avoids unneccessary error messages.
}
break;
case AsmToken::Identifier: {
OperandInfoTy HwReg(ID_UNKNOWN_);
int64_t Offset = OFFSET_DEFAULT_;
int64_t Width = WIDTH_M1_DEFAULT_ + 1;
if (parseHwregConstruct(HwReg, Offset, Width))
return MatchOperand_ParseFail;
if (HwReg.Id < 0 || !isUInt<ID_WIDTH_>(HwReg.Id)) {
if (HwReg.IsSymbolic)
Error(S, "invalid symbolic name of hardware register");
else
Error(S, "invalid code of hardware register: only 6-bit values are legal");
}
if (Offset < 0 || !isUInt<OFFSET_WIDTH_>(Offset))
Error(S, "invalid bit offset: only 5-bit values are legal");
if ((Width-1) < 0 || !isUInt<WIDTH_M1_WIDTH_>(Width-1))
Error(S, "invalid bitfield width: only values from 1 to 32 are legal");
Imm16Val = (HwReg.Id << ID_SHIFT_) | (Offset << OFFSET_SHIFT_) | ((Width-1) << WIDTH_M1_SHIFT_);
}
break;
}
Operands.push_back(AMDGPUOperand::CreateImm(this, Imm16Val, S, AMDGPUOperand::ImmTyHwreg));
return MatchOperand_Success;
}
bool AMDGPUOperand::isSWaitCnt() const {
return isImm();
}
bool AMDGPUOperand::isHwreg() const {
return isImmTy(ImmTyHwreg);
}
bool AMDGPUAsmParser::parseSendMsgConstruct(OperandInfoTy &Msg, OperandInfoTy &Operation, int64_t &StreamId) {
using namespace llvm::AMDGPU::SendMsg;
if (Parser.getTok().getString() != "sendmsg")
return true;
Parser.Lex();
if (getLexer().isNot(AsmToken::LParen))
return true;
Parser.Lex();
if (getLexer().is(AsmToken::Identifier)) {
Msg.IsSymbolic = true;
Msg.Id = ID_UNKNOWN_;
const std::string tok = Parser.getTok().getString();
for (int i = ID_GAPS_FIRST_; i < ID_GAPS_LAST_; ++i) {
switch(i) {
default: continue; // Omit gaps.
case ID_INTERRUPT: case ID_GS: case ID_GS_DONE: case ID_SYSMSG: break;
}
if (tok == IdSymbolic[i]) {
Msg.Id = i;
break;
}
}
Parser.Lex();
} else {
Msg.IsSymbolic = false;
if (getLexer().isNot(AsmToken::Integer))
return true;
if (getParser().parseAbsoluteExpression(Msg.Id))
return true;
if (getLexer().is(AsmToken::Integer))
if (getParser().parseAbsoluteExpression(Msg.Id))
Msg.Id = ID_UNKNOWN_;
}
if (Msg.Id == ID_UNKNOWN_) // Don't know how to parse the rest.
return false;
if (!(Msg.Id == ID_GS || Msg.Id == ID_GS_DONE || Msg.Id == ID_SYSMSG)) {
if (getLexer().isNot(AsmToken::RParen))
return true;
Parser.Lex();
return false;
}
if (getLexer().isNot(AsmToken::Comma))
return true;
Parser.Lex();
assert(Msg.Id == ID_GS || Msg.Id == ID_GS_DONE || Msg.Id == ID_SYSMSG);
Operation.Id = ID_UNKNOWN_;
if (getLexer().is(AsmToken::Identifier)) {
Operation.IsSymbolic = true;
const char* const *S = (Msg.Id == ID_SYSMSG) ? OpSysSymbolic : OpGsSymbolic;
const int F = (Msg.Id == ID_SYSMSG) ? OP_SYS_FIRST_ : OP_GS_FIRST_;
const int L = (Msg.Id == ID_SYSMSG) ? OP_SYS_LAST_ : OP_GS_LAST_;
const StringRef Tok = Parser.getTok().getString();
for (int i = F; i < L; ++i) {
if (Tok == S[i]) {
Operation.Id = i;
break;
}
}
Parser.Lex();
} else {
Operation.IsSymbolic = false;
if (getLexer().isNot(AsmToken::Integer))
return true;
if (getParser().parseAbsoluteExpression(Operation.Id))
return true;
}
if ((Msg.Id == ID_GS || Msg.Id == ID_GS_DONE) && Operation.Id != OP_GS_NOP) {
// Stream id is optional.
if (getLexer().is(AsmToken::RParen)) {
Parser.Lex();
return false;
}
if (getLexer().isNot(AsmToken::Comma))
return true;
Parser.Lex();
if (getLexer().isNot(AsmToken::Integer))
return true;
if (getParser().parseAbsoluteExpression(StreamId))
return true;
}
if (getLexer().isNot(AsmToken::RParen))
return true;
Parser.Lex();
return false;
}
OperandMatchResultTy AMDGPUAsmParser::parseInterpSlot(OperandVector &Operands) {
if (getLexer().getKind() != AsmToken::Identifier)
return MatchOperand_NoMatch;
StringRef Str = Parser.getTok().getString();
int Slot = StringSwitch<int>(Str)
.Case("p10", 0)
.Case("p20", 1)
.Case("p0", 2)
.Default(-1);
SMLoc S = Parser.getTok().getLoc();
if (Slot == -1)
return MatchOperand_ParseFail;
Parser.Lex();
Operands.push_back(AMDGPUOperand::CreateImm(this, Slot, S,
AMDGPUOperand::ImmTyInterpSlot));
return MatchOperand_Success;
}
OperandMatchResultTy AMDGPUAsmParser::parseInterpAttr(OperandVector &Operands) {
if (getLexer().getKind() != AsmToken::Identifier)
return MatchOperand_NoMatch;
StringRef Str = Parser.getTok().getString();
if (!Str.startswith("attr"))
return MatchOperand_NoMatch;
StringRef Chan = Str.take_back(2);
int AttrChan = StringSwitch<int>(Chan)
.Case(".x", 0)
.Case(".y", 1)
.Case(".z", 2)
.Case(".w", 3)
.Default(-1);
if (AttrChan == -1)
return MatchOperand_ParseFail;
Str = Str.drop_back(2).drop_front(4);
uint8_t Attr;
if (Str.getAsInteger(10, Attr))
return MatchOperand_ParseFail;
SMLoc S = Parser.getTok().getLoc();
Parser.Lex();
if (Attr > 63) {
Error(S, "out of bounds attr");
return MatchOperand_Success;
}
SMLoc SChan = SMLoc::getFromPointer(Chan.data());
Operands.push_back(AMDGPUOperand::CreateImm(this, Attr, S,
AMDGPUOperand::ImmTyInterpAttr));
Operands.push_back(AMDGPUOperand::CreateImm(this, AttrChan, SChan,
AMDGPUOperand::ImmTyAttrChan));
return MatchOperand_Success;
}
void AMDGPUAsmParser::errorExpTgt() {
Error(Parser.getTok().getLoc(), "invalid exp target");
}
OperandMatchResultTy AMDGPUAsmParser::parseExpTgtImpl(StringRef Str,
uint8_t &Val) {
if (Str == "null") {
Val = 9;
return MatchOperand_Success;
}
if (Str.startswith("mrt")) {
Str = Str.drop_front(3);
if (Str == "z") { // == mrtz
Val = 8;
return MatchOperand_Success;
}
if (Str.getAsInteger(10, Val))
return MatchOperand_ParseFail;
if (Val > 7)
errorExpTgt();
return MatchOperand_Success;
}
if (Str.startswith("pos")) {
Str = Str.drop_front(3);
if (Str.getAsInteger(10, Val))
return MatchOperand_ParseFail;
if (Val > 3)
errorExpTgt();
Val += 12;
return MatchOperand_Success;
}
if (Str.startswith("param")) {
Str = Str.drop_front(5);
if (Str.getAsInteger(10, Val))
return MatchOperand_ParseFail;
if (Val >= 32)
errorExpTgt();
Val += 32;
return MatchOperand_Success;
}
if (Str.startswith("invalid_target_")) {
Str = Str.drop_front(15);
if (Str.getAsInteger(10, Val))
return MatchOperand_ParseFail;
errorExpTgt();
return MatchOperand_Success;
}
return MatchOperand_NoMatch;
}
OperandMatchResultTy AMDGPUAsmParser::parseExpTgt(OperandVector &Operands) {
uint8_t Val;
StringRef Str = Parser.getTok().getString();
auto Res = parseExpTgtImpl(Str, Val);
if (Res != MatchOperand_Success)
return Res;
SMLoc S = Parser.getTok().getLoc();
Parser.Lex();
Operands.push_back(AMDGPUOperand::CreateImm(this, Val, S,
AMDGPUOperand::ImmTyExpTgt));
return MatchOperand_Success;
}
OperandMatchResultTy
AMDGPUAsmParser::parseSendMsgOp(OperandVector &Operands) {
using namespace llvm::AMDGPU::SendMsg;
int64_t Imm16Val = 0;
SMLoc S = Parser.getTok().getLoc();
switch(getLexer().getKind()) {
default:
return MatchOperand_NoMatch;
case AsmToken::Integer:
// The operand can be an integer value.
if (getParser().parseAbsoluteExpression(Imm16Val))
return MatchOperand_NoMatch;
if (Imm16Val < 0 || !isUInt<16>(Imm16Val)) {
Error(S, "invalid immediate: only 16-bit values are legal");
// Do not return error code, but create an imm operand anyway and proceed
// to the next operand, if any. That avoids unneccessary error messages.
}
break;
case AsmToken::Identifier: {
OperandInfoTy Msg(ID_UNKNOWN_);
OperandInfoTy Operation(OP_UNKNOWN_);
int64_t StreamId = STREAM_ID_DEFAULT_;
if (parseSendMsgConstruct(Msg, Operation, StreamId))
return MatchOperand_ParseFail;
do {
// Validate and encode message ID.
if (! ((ID_INTERRUPT <= Msg.Id && Msg.Id <= ID_GS_DONE)
|| Msg.Id == ID_SYSMSG)) {
if (Msg.IsSymbolic)
Error(S, "invalid/unsupported symbolic name of message");
else
Error(S, "invalid/unsupported code of message");
break;
}
Imm16Val = (Msg.Id << ID_SHIFT_);
// Validate and encode operation ID.
if (Msg.Id == ID_GS || Msg.Id == ID_GS_DONE) {
if (! (OP_GS_FIRST_ <= Operation.Id && Operation.Id < OP_GS_LAST_)) {
if (Operation.IsSymbolic)
Error(S, "invalid symbolic name of GS_OP");
else
Error(S, "invalid code of GS_OP: only 2-bit values are legal");
break;
}
if (Operation.Id == OP_GS_NOP
&& Msg.Id != ID_GS_DONE) {
Error(S, "invalid GS_OP: NOP is for GS_DONE only");
break;
}
Imm16Val |= (Operation.Id << OP_SHIFT_);
}
if (Msg.Id == ID_SYSMSG) {
if (! (OP_SYS_FIRST_ <= Operation.Id && Operation.Id < OP_SYS_LAST_)) {
if (Operation.IsSymbolic)
Error(S, "invalid/unsupported symbolic name of SYSMSG_OP");
else
Error(S, "invalid/unsupported code of SYSMSG_OP");
break;
}
Imm16Val |= (Operation.Id << OP_SHIFT_);
}
// Validate and encode stream ID.
if ((Msg.Id == ID_GS || Msg.Id == ID_GS_DONE) && Operation.Id != OP_GS_NOP) {
if (! (STREAM_ID_FIRST_ <= StreamId && StreamId < STREAM_ID_LAST_)) {
Error(S, "invalid stream id: only 2-bit values are legal");
break;
}
Imm16Val |= (StreamId << STREAM_ID_SHIFT_);
}
} while (false);
}
break;
}
Operands.push_back(AMDGPUOperand::CreateImm(this, Imm16Val, S, AMDGPUOperand::ImmTySendMsg));
return MatchOperand_Success;
}
bool AMDGPUOperand::isSendMsg() const {
return isImmTy(ImmTySendMsg);
}
//===----------------------------------------------------------------------===//
// parser helpers
//===----------------------------------------------------------------------===//
bool
AMDGPUAsmParser::trySkipId(const StringRef Id) {
if (getLexer().getKind() == AsmToken::Identifier &&
Parser.getTok().getString() == Id) {
Parser.Lex();
return true;
}
return false;
}
bool
AMDGPUAsmParser::trySkipToken(const AsmToken::TokenKind Kind) {
if (getLexer().getKind() == Kind) {
Parser.Lex();
return true;
}
return false;
}
bool
AMDGPUAsmParser::skipToken(const AsmToken::TokenKind Kind,
const StringRef ErrMsg) {
if (!trySkipToken(Kind)) {
Error(Parser.getTok().getLoc(), ErrMsg);
return false;
}
return true;
}
bool
AMDGPUAsmParser::parseExpr(int64_t &Imm) {
return !getParser().parseAbsoluteExpression(Imm);
}
bool
AMDGPUAsmParser::parseString(StringRef &Val, const StringRef ErrMsg) {
SMLoc S = Parser.getTok().getLoc();
if (getLexer().getKind() == AsmToken::String) {
Val = Parser.getTok().getStringContents();
Parser.Lex();
return true;
} else {
Error(S, ErrMsg);
return false;
}
}
//===----------------------------------------------------------------------===//
// swizzle
//===----------------------------------------------------------------------===//
LLVM_READNONE
static unsigned
encodeBitmaskPerm(const unsigned AndMask,
const unsigned OrMask,
const unsigned XorMask) {
using namespace llvm::AMDGPU::Swizzle;
return BITMASK_PERM_ENC |
(AndMask << BITMASK_AND_SHIFT) |
(OrMask << BITMASK_OR_SHIFT) |
(XorMask << BITMASK_XOR_SHIFT);
}
bool
AMDGPUAsmParser::parseSwizzleOperands(const unsigned OpNum, int64_t* Op,
const unsigned MinVal,
const unsigned MaxVal,
const StringRef ErrMsg) {
for (unsigned i = 0; i < OpNum; ++i) {
if (!skipToken(AsmToken::Comma, "expected a comma")){
return false;
}
SMLoc ExprLoc = Parser.getTok().getLoc();
if (!parseExpr(Op[i])) {
return false;
}
if (Op[i] < MinVal || Op[i] > MaxVal) {
Error(ExprLoc, ErrMsg);
return false;
}
}
return true;
}
bool
AMDGPUAsmParser::parseSwizzleQuadPerm(int64_t &Imm) {
using namespace llvm::AMDGPU::Swizzle;
int64_t Lane[LANE_NUM];
if (parseSwizzleOperands(LANE_NUM, Lane, 0, LANE_MAX,
"expected a 2-bit lane id")) {
Imm = QUAD_PERM_ENC;
for (auto i = 0; i < LANE_NUM; ++i) {
Imm |= Lane[i] << (LANE_SHIFT * i);
}
return true;
}
return false;
}
bool
AMDGPUAsmParser::parseSwizzleBroadcast(int64_t &Imm) {
using namespace llvm::AMDGPU::Swizzle;
SMLoc S = Parser.getTok().getLoc();
int64_t GroupSize;
int64_t LaneIdx;
if (!parseSwizzleOperands(1, &GroupSize,
2, 32,
"group size must be in the interval [2,32]")) {
return false;
}
if (!isPowerOf2_64(GroupSize)) {
Error(S, "group size must be a power of two");
return false;
}
if (parseSwizzleOperands(1, &LaneIdx,
0, GroupSize - 1,
"lane id must be in the interval [0,group size - 1]")) {
Imm = encodeBitmaskPerm(BITMASK_MAX - GroupSize + 1, LaneIdx, 0);
return true;
}
return false;
}
bool
AMDGPUAsmParser::parseSwizzleReverse(int64_t &Imm) {
using namespace llvm::AMDGPU::Swizzle;
SMLoc S = Parser.getTok().getLoc();
int64_t GroupSize;
if (!parseSwizzleOperands(1, &GroupSize,
2, 32, "group size must be in the interval [2,32]")) {
return false;
}
if (!isPowerOf2_64(GroupSize)) {
Error(S, "group size must be a power of two");
return false;
}
Imm = encodeBitmaskPerm(BITMASK_MAX, 0, GroupSize - 1);
return true;
}
bool
AMDGPUAsmParser::parseSwizzleSwap(int64_t &Imm) {
using namespace llvm::AMDGPU::Swizzle;
SMLoc S = Parser.getTok().getLoc();
int64_t GroupSize;
if (!parseSwizzleOperands(1, &GroupSize,
1, 16, "group size must be in the interval [1,16]")) {
return false;
}
if (!isPowerOf2_64(GroupSize)) {
Error(S, "group size must be a power of two");
return false;
}
Imm = encodeBitmaskPerm(BITMASK_MAX, 0, GroupSize);
return true;
}
bool
AMDGPUAsmParser::parseSwizzleBitmaskPerm(int64_t &Imm) {
using namespace llvm::AMDGPU::Swizzle;
if (!skipToken(AsmToken::Comma, "expected a comma")) {
return false;
}
StringRef Ctl;
SMLoc StrLoc = Parser.getTok().getLoc();
if (!parseString(Ctl)) {
return false;
}
if (Ctl.size() != BITMASK_WIDTH) {
Error(StrLoc, "expected a 5-character mask");
return false;
}
unsigned AndMask = 0;
unsigned OrMask = 0;
unsigned XorMask = 0;
for (size_t i = 0; i < Ctl.size(); ++i) {
unsigned Mask = 1 << (BITMASK_WIDTH - 1 - i);
switch(Ctl[i]) {
default:
Error(StrLoc, "invalid mask");
return false;
case '0':
break;
case '1':
OrMask |= Mask;
break;
case 'p':
AndMask |= Mask;
break;
case 'i':
AndMask |= Mask;
XorMask |= Mask;
break;
}
}
Imm = encodeBitmaskPerm(AndMask, OrMask, XorMask);
return true;
}
bool
AMDGPUAsmParser::parseSwizzleOffset(int64_t &Imm) {
SMLoc OffsetLoc = Parser.getTok().getLoc();
if (!parseExpr(Imm)) {
return false;
}
if (!isUInt<16>(Imm)) {
Error(OffsetLoc, "expected a 16-bit offset");
return false;
}
return true;
}
bool
AMDGPUAsmParser::parseSwizzleMacro(int64_t &Imm) {
using namespace llvm::AMDGPU::Swizzle;
if (skipToken(AsmToken::LParen, "expected a left parentheses")) {
SMLoc ModeLoc = Parser.getTok().getLoc();
bool Ok = false;
if (trySkipId(IdSymbolic[ID_QUAD_PERM])) {
Ok = parseSwizzleQuadPerm(Imm);
} else if (trySkipId(IdSymbolic[ID_BITMASK_PERM])) {
Ok = parseSwizzleBitmaskPerm(Imm);
} else if (trySkipId(IdSymbolic[ID_BROADCAST])) {
Ok = parseSwizzleBroadcast(Imm);
} else if (trySkipId(IdSymbolic[ID_SWAP])) {
Ok = parseSwizzleSwap(Imm);
} else if (trySkipId(IdSymbolic[ID_REVERSE])) {
Ok = parseSwizzleReverse(Imm);
} else {
Error(ModeLoc, "expected a swizzle mode");
}
return Ok && skipToken(AsmToken::RParen, "expected a closing parentheses");
}
return false;
}
OperandMatchResultTy
AMDGPUAsmParser::parseSwizzleOp(OperandVector &Operands) {
SMLoc S = Parser.getTok().getLoc();
int64_t Imm = 0;
if (trySkipId("offset")) {
bool Ok = false;
if (skipToken(AsmToken::Colon, "expected a colon")) {
if (trySkipId("swizzle")) {
Ok = parseSwizzleMacro(Imm);
} else {
Ok = parseSwizzleOffset(Imm);
}
}
Operands.push_back(AMDGPUOperand::CreateImm(this, Imm, S, AMDGPUOperand::ImmTySwizzle));
return Ok? MatchOperand_Success : MatchOperand_ParseFail;
} else {
// Swizzle "offset" operand is optional.
// If it is omitted, try parsing other optional operands.
return parseOptionalOpr(Operands);
}
}
bool
AMDGPUOperand::isSwizzle() const {
return isImmTy(ImmTySwizzle);
}
//===----------------------------------------------------------------------===//
// sopp branch targets
//===----------------------------------------------------------------------===//
OperandMatchResultTy
AMDGPUAsmParser::parseSOppBrTarget(OperandVector &Operands) {
SMLoc S = Parser.getTok().getLoc();
switch (getLexer().getKind()) {
default: return MatchOperand_ParseFail;
case AsmToken::Integer: {
int64_t Imm;
if (getParser().parseAbsoluteExpression(Imm))
return MatchOperand_ParseFail;
Operands.push_back(AMDGPUOperand::CreateImm(this, Imm, S));
return MatchOperand_Success;
}
case AsmToken::Identifier:
Operands.push_back(AMDGPUOperand::CreateExpr(this,
MCSymbolRefExpr::create(getContext().getOrCreateSymbol(
Parser.getTok().getString()), getContext()), S));
Parser.Lex();
return MatchOperand_Success;
}
}
//===----------------------------------------------------------------------===//
// mubuf
//===----------------------------------------------------------------------===//
AMDGPUOperand::Ptr AMDGPUAsmParser::defaultGLC() const {
return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyGLC);
}
AMDGPUOperand::Ptr AMDGPUAsmParser::defaultSLC() const {
return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTySLC);
}
void AMDGPUAsmParser::cvtMubufImpl(MCInst &Inst,
const OperandVector &Operands,
bool IsAtomic,
bool IsAtomicReturn,
bool IsLds) {
bool IsLdsOpcode = IsLds;
bool HasLdsModifier = false;
OptionalImmIndexMap OptionalIdx;
assert(IsAtomicReturn ? IsAtomic : true);
for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
// Add the register arguments
if (Op.isReg()) {
Op.addRegOperands(Inst, 1);
continue;
}
// Handle the case where soffset is an immediate
if (Op.isImm() && Op.getImmTy() == AMDGPUOperand::ImmTyNone) {
Op.addImmOperands(Inst, 1);
continue;
}
HasLdsModifier = Op.isLDS();
// Handle tokens like 'offen' which are sometimes hard-coded into the
// asm string. There are no MCInst operands for these.
if (Op.isToken()) {
continue;
}
assert(Op.isImm());
// Handle optional arguments
OptionalIdx[Op.getImmTy()] = i;
}
// This is a workaround for an llvm quirk which may result in an
// incorrect instruction selection. Lds and non-lds versions of
// MUBUF instructions are identical except that lds versions
// have mandatory 'lds' modifier. However this modifier follows
// optional modifiers and llvm asm matcher regards this 'lds'
// modifier as an optional one. As a result, an lds version
// of opcode may be selected even if it has no 'lds' modifier.
if (IsLdsOpcode && !HasLdsModifier) {
int NoLdsOpcode = AMDGPU::getMUBUFNoLdsInst(Inst.getOpcode());
if (NoLdsOpcode != -1) { // Got lds version - correct it.
Inst.setOpcode(NoLdsOpcode);
IsLdsOpcode = false;
}
}
// Copy $vdata_in operand and insert as $vdata for MUBUF_Atomic RTN insns.
if (IsAtomicReturn) {
MCInst::iterator I = Inst.begin(); // $vdata_in is always at the beginning.
Inst.insert(I, *I);
}
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyOffset);
if (!IsAtomic) { // glc is hard-coded.
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyGLC);
}
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySLC);
if (!IsLdsOpcode) { // tfe is not legal with lds opcodes
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyTFE);
}
}
void AMDGPUAsmParser::cvtMtbuf(MCInst &Inst, const OperandVector &Operands) {
OptionalImmIndexMap OptionalIdx;
for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[i]);
// Add the register arguments
if (Op.isReg()) {
Op.addRegOperands(Inst, 1);
continue;
}
// Handle the case where soffset is an immediate
if (Op.isImm() && Op.getImmTy() == AMDGPUOperand::ImmTyNone) {
Op.addImmOperands(Inst, 1);
continue;
}
// Handle tokens like 'offen' which are sometimes hard-coded into the
// asm string. There are no MCInst operands for these.
if (Op.isToken()) {
continue;
}
assert(Op.isImm());
// Handle optional arguments
OptionalIdx[Op.getImmTy()] = i;
}
addOptionalImmOperand(Inst, Operands, OptionalIdx,
AMDGPUOperand::ImmTyOffset);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyFORMAT);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyGLC);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySLC);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyTFE);
}
//===----------------------------------------------------------------------===//
// mimg
//===----------------------------------------------------------------------===//
void AMDGPUAsmParser::cvtMIMG(MCInst &Inst, const OperandVector &Operands,
bool IsAtomic) {
unsigned I = 1;
const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
}
if (IsAtomic) {
// Add src, same as dst
assert(Desc.getNumDefs() == 1);
((AMDGPUOperand &)*Operands[I - 1]).addRegOperands(Inst, 1);
}
OptionalImmIndexMap OptionalIdx;
for (unsigned E = Operands.size(); I != E; ++I) {
AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
// Add the register arguments
if (Op.isReg()) {
Op.addRegOperands(Inst, 1);
} else if (Op.isImmModifier()) {
OptionalIdx[Op.getImmTy()] = I;
} else {
llvm_unreachable("unexpected operand type");
}
}
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyDMask);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyUNorm);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyGLC);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySLC);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyR128A16);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyTFE);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyLWE);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyDA);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyD16);
}
void AMDGPUAsmParser::cvtMIMGAtomic(MCInst &Inst, const OperandVector &Operands) {
cvtMIMG(Inst, Operands, true);
}
//===----------------------------------------------------------------------===//
// smrd
//===----------------------------------------------------------------------===//
bool AMDGPUOperand::isSMRDOffset8() const {
return isImm() && isUInt<8>(getImm());
}
bool AMDGPUOperand::isSMRDOffset20() const {
return isImm() && isUInt<20>(getImm());
}
bool AMDGPUOperand::isSMRDLiteralOffset() const {
// 32-bit literals are only supported on CI and we only want to use them
// when the offset is > 8-bits.
return isImm() && !isUInt<8>(getImm()) && isUInt<32>(getImm());
}
AMDGPUOperand::Ptr AMDGPUAsmParser::defaultSMRDOffset8() const {
return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyOffset);
}
AMDGPUOperand::Ptr AMDGPUAsmParser::defaultSMRDOffset20() const {
return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyOffset);
}
AMDGPUOperand::Ptr AMDGPUAsmParser::defaultSMRDLiteralOffset() const {
return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyOffset);
}
AMDGPUOperand::Ptr AMDGPUAsmParser::defaultOffsetU12() const {
return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyOffset);
}
AMDGPUOperand::Ptr AMDGPUAsmParser::defaultOffsetS13() const {
return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyOffset);
}
//===----------------------------------------------------------------------===//
// vop3
//===----------------------------------------------------------------------===//
static bool ConvertOmodMul(int64_t &Mul) {
if (Mul != 1 && Mul != 2 && Mul != 4)
return false;
Mul >>= 1;
return true;
}
static bool ConvertOmodDiv(int64_t &Div) {
if (Div == 1) {
Div = 0;
return true;
}
if (Div == 2) {
Div = 3;
return true;
}
return false;
}
static bool ConvertBoundCtrl(int64_t &BoundCtrl) {
if (BoundCtrl == 0) {
BoundCtrl = 1;
return true;
}
if (BoundCtrl == -1) {
BoundCtrl = 0;
return true;
}
return false;
}
// Note: the order in this table matches the order of operands in AsmString.
static const OptionalOperand AMDGPUOptionalOperandTable[] = {
{"offen", AMDGPUOperand::ImmTyOffen, true, nullptr},
{"idxen", AMDGPUOperand::ImmTyIdxen, true, nullptr},
{"addr64", AMDGPUOperand::ImmTyAddr64, true, nullptr},
{"offset0", AMDGPUOperand::ImmTyOffset0, false, nullptr},
{"offset1", AMDGPUOperand::ImmTyOffset1, false, nullptr},
{"gds", AMDGPUOperand::ImmTyGDS, true, nullptr},
{"lds", AMDGPUOperand::ImmTyLDS, true, nullptr},
{"offset", AMDGPUOperand::ImmTyOffset, false, nullptr},
{"inst_offset", AMDGPUOperand::ImmTyInstOffset, false, nullptr},
{"dfmt", AMDGPUOperand::ImmTyFORMAT, false, nullptr},
{"glc", AMDGPUOperand::ImmTyGLC, true, nullptr},
{"slc", AMDGPUOperand::ImmTySLC, true, nullptr},
{"tfe", AMDGPUOperand::ImmTyTFE, true, nullptr},
{"d16", AMDGPUOperand::ImmTyD16, true, nullptr},
{"high", AMDGPUOperand::ImmTyHigh, true, nullptr},
{"clamp", AMDGPUOperand::ImmTyClampSI, true, nullptr},
{"omod", AMDGPUOperand::ImmTyOModSI, false, ConvertOmodMul},
{"unorm", AMDGPUOperand::ImmTyUNorm, true, nullptr},
{"da", AMDGPUOperand::ImmTyDA, true, nullptr},
{"r128", AMDGPUOperand::ImmTyR128A16, true, nullptr},
{"a16", AMDGPUOperand::ImmTyR128A16, true, nullptr},
{"lwe", AMDGPUOperand::ImmTyLWE, true, nullptr},
{"d16", AMDGPUOperand::ImmTyD16, true, nullptr},
{"dmask", AMDGPUOperand::ImmTyDMask, false, nullptr},
{"row_mask", AMDGPUOperand::ImmTyDppRowMask, false, nullptr},
{"bank_mask", AMDGPUOperand::ImmTyDppBankMask, false, nullptr},
{"bound_ctrl", AMDGPUOperand::ImmTyDppBoundCtrl, false, ConvertBoundCtrl},
{"dst_sel", AMDGPUOperand::ImmTySdwaDstSel, false, nullptr},
{"src0_sel", AMDGPUOperand::ImmTySdwaSrc0Sel, false, nullptr},
{"src1_sel", AMDGPUOperand::ImmTySdwaSrc1Sel, false, nullptr},
{"dst_unused", AMDGPUOperand::ImmTySdwaDstUnused, false, nullptr},
{"compr", AMDGPUOperand::ImmTyExpCompr, true, nullptr },
{"vm", AMDGPUOperand::ImmTyExpVM, true, nullptr},
{"op_sel", AMDGPUOperand::ImmTyOpSel, false, nullptr},
{"op_sel_hi", AMDGPUOperand::ImmTyOpSelHi, false, nullptr},
{"neg_lo", AMDGPUOperand::ImmTyNegLo, false, nullptr},
{"neg_hi", AMDGPUOperand::ImmTyNegHi, false, nullptr}
};
OperandMatchResultTy AMDGPUAsmParser::parseOptionalOperand(OperandVector &Operands) {
unsigned size = Operands.size();
assert(size > 0);
OperandMatchResultTy res = parseOptionalOpr(Operands);
// This is a hack to enable hardcoded mandatory operands which follow
// optional operands.
//
// Current design assumes that all operands after the first optional operand
// are also optional. However implementation of some instructions violates
// this rule (see e.g. flat/global atomic which have hardcoded 'glc' operands).
//
// To alleviate this problem, we have to (implicitly) parse extra operands
// to make sure autogenerated parser of custom operands never hit hardcoded
// mandatory operands.
if (size == 1 || ((AMDGPUOperand &)*Operands[size - 1]).isRegKind()) {
// We have parsed the first optional operand.
// Parse as many operands as necessary to skip all mandatory operands.
for (unsigned i = 0; i < MAX_OPR_LOOKAHEAD; ++i) {
if (res != MatchOperand_Success ||
getLexer().is(AsmToken::EndOfStatement)) break;
if (getLexer().is(AsmToken::Comma)) Parser.Lex();
res = parseOptionalOpr(Operands);
}
}
return res;
}
OperandMatchResultTy AMDGPUAsmParser::parseOptionalOpr(OperandVector &Operands) {
OperandMatchResultTy res;
for (const OptionalOperand &Op : AMDGPUOptionalOperandTable) {
// try to parse any optional operand here
if (Op.IsBit) {
res = parseNamedBit(Op.Name, Operands, Op.Type);
} else if (Op.Type == AMDGPUOperand::ImmTyOModSI) {
res = parseOModOperand(Operands);
} else if (Op.Type == AMDGPUOperand::ImmTySdwaDstSel ||
Op.Type == AMDGPUOperand::ImmTySdwaSrc0Sel ||
Op.Type == AMDGPUOperand::ImmTySdwaSrc1Sel) {
res = parseSDWASel(Operands, Op.Name, Op.Type);
} else if (Op.Type == AMDGPUOperand::ImmTySdwaDstUnused) {
res = parseSDWADstUnused(Operands);
} else if (Op.Type == AMDGPUOperand::ImmTyOpSel ||
Op.Type == AMDGPUOperand::ImmTyOpSelHi ||
Op.Type == AMDGPUOperand::ImmTyNegLo ||
Op.Type == AMDGPUOperand::ImmTyNegHi) {
res = parseOperandArrayWithPrefix(Op.Name, Operands, Op.Type,
Op.ConvertResult);
} else if (Op.Type == AMDGPUOperand::ImmTyFORMAT) {
res = parseDfmtNfmt(Operands);
} else {
res = parseIntWithPrefix(Op.Name, Operands, Op.Type, Op.ConvertResult);
}
if (res != MatchOperand_NoMatch) {
return res;
}
}
return MatchOperand_NoMatch;
}
OperandMatchResultTy AMDGPUAsmParser::parseOModOperand(OperandVector &Operands) {
StringRef Name = Parser.getTok().getString();
if (Name == "mul") {
return parseIntWithPrefix("mul", Operands,
AMDGPUOperand::ImmTyOModSI, ConvertOmodMul);
}
if (Name == "div") {
return parseIntWithPrefix("div", Operands,
AMDGPUOperand::ImmTyOModSI, ConvertOmodDiv);
}
return MatchOperand_NoMatch;
}
void AMDGPUAsmParser::cvtVOP3OpSel(MCInst &Inst, const OperandVector &Operands) {
cvtVOP3P(Inst, Operands);
int Opc = Inst.getOpcode();
int SrcNum;
const int Ops[] = { AMDGPU::OpName::src0,
AMDGPU::OpName::src1,
AMDGPU::OpName::src2 };
for (SrcNum = 0;
SrcNum < 3 && AMDGPU::getNamedOperandIdx(Opc, Ops[SrcNum]) != -1;
++SrcNum);
assert(SrcNum > 0);
int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
if ((OpSel & (1 << SrcNum)) != 0) {
int ModIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers);
uint32_t ModVal = Inst.getOperand(ModIdx).getImm();
Inst.getOperand(ModIdx).setImm(ModVal | SISrcMods::DST_OP_SEL);
}
}
static bool isRegOrImmWithInputMods(const MCInstrDesc &Desc, unsigned OpNum) {
// 1. This operand is input modifiers
return Desc.OpInfo[OpNum].OperandType == AMDGPU::OPERAND_INPUT_MODS
// 2. This is not last operand
&& Desc.NumOperands > (OpNum + 1)
// 3. Next operand is register class
&& Desc.OpInfo[OpNum + 1].RegClass != -1
// 4. Next register is not tied to any other operand
&& Desc.getOperandConstraint(OpNum + 1, MCOI::OperandConstraint::TIED_TO) == -1;
}
void AMDGPUAsmParser::cvtVOP3Interp(MCInst &Inst, const OperandVector &Operands)
{
OptionalImmIndexMap OptionalIdx;
unsigned Opc = Inst.getOpcode();
unsigned I = 1;
const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
}
for (unsigned E = Operands.size(); I != E; ++I) {
AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
if (isRegOrImmWithInputMods(Desc, Inst.getNumOperands())) {
Op.addRegOrImmWithFPInputModsOperands(Inst, 2);
} else if (Op.isInterpSlot() ||
Op.isInterpAttr() ||
Op.isAttrChan()) {
Inst.addOperand(MCOperand::createImm(Op.Imm.Val));
} else if (Op.isImmModifier()) {
OptionalIdx[Op.getImmTy()] = I;
} else {
llvm_unreachable("unhandled operand type");
}
}
if (AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::high) != -1) {
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyHigh);
}
if (AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp) != -1) {
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyClampSI);
}
if (AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod) != -1) {
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyOModSI);
}
}
void AMDGPUAsmParser::cvtVOP3(MCInst &Inst, const OperandVector &Operands,
OptionalImmIndexMap &OptionalIdx) {
unsigned Opc = Inst.getOpcode();
unsigned I = 1;
const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
}
if (AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers) != -1) {
// This instruction has src modifiers
for (unsigned E = Operands.size(); I != E; ++I) {
AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
if (isRegOrImmWithInputMods(Desc, Inst.getNumOperands())) {
Op.addRegOrImmWithFPInputModsOperands(Inst, 2);
} else if (Op.isImmModifier()) {
OptionalIdx[Op.getImmTy()] = I;
} else if (Op.isRegOrImm()) {
Op.addRegOrImmOperands(Inst, 1);
} else {
llvm_unreachable("unhandled operand type");
}
}
} else {
// No src modifiers
for (unsigned E = Operands.size(); I != E; ++I) {
AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
if (Op.isMod()) {
OptionalIdx[Op.getImmTy()] = I;
} else {
Op.addRegOrImmOperands(Inst, 1);
}
}
}
if (AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::clamp) != -1) {
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyClampSI);
}
if (AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::omod) != -1) {
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyOModSI);
}
// Special case v_mac_{f16, f32} and v_fmac_f32 (gfx906):
// it has src2 register operand that is tied to dst operand
// we don't allow modifiers for this operand in assembler so src2_modifiers
// should be 0.
if (Opc == AMDGPU::V_MAC_F32_e64_si ||
Opc == AMDGPU::V_MAC_F32_e64_vi ||
Opc == AMDGPU::V_MAC_F16_e64_vi ||
Opc == AMDGPU::V_FMAC_F32_e64_vi) {
auto it = Inst.begin();
std::advance(it, AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2_modifiers));
it = Inst.insert(it, MCOperand::createImm(0)); // no modifiers for src2
++it;
Inst.insert(it, Inst.getOperand(0)); // src2 = dst
}
}
void AMDGPUAsmParser::cvtVOP3(MCInst &Inst, const OperandVector &Operands) {
OptionalImmIndexMap OptionalIdx;
cvtVOP3(Inst, Operands, OptionalIdx);
}
void AMDGPUAsmParser::cvtVOP3P(MCInst &Inst,
const OperandVector &Operands) {
OptionalImmIndexMap OptIdx;
const int Opc = Inst.getOpcode();
const MCInstrDesc &Desc = MII.get(Opc);
const bool IsPacked = (Desc.TSFlags & SIInstrFlags::IsPacked) != 0;
cvtVOP3(Inst, Operands, OptIdx);
if (AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::vdst_in) != -1) {
assert(!IsPacked);
Inst.addOperand(Inst.getOperand(0));
}
// FIXME: This is messy. Parse the modifiers as if it was a normal VOP3
// instruction, and then figure out where to actually put the modifiers
addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyOpSel);
int OpSelHiIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel_hi);
if (OpSelHiIdx != -1) {
int DefaultVal = IsPacked ? -1 : 0;
addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyOpSelHi,
DefaultVal);
}
int NegLoIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::neg_lo);
if (NegLoIdx != -1) {
assert(IsPacked);
addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyNegLo);
addOptionalImmOperand(Inst, Operands, OptIdx, AMDGPUOperand::ImmTyNegHi);
}
const int Ops[] = { AMDGPU::OpName::src0,
AMDGPU::OpName::src1,
AMDGPU::OpName::src2 };
const int ModOps[] = { AMDGPU::OpName::src0_modifiers,
AMDGPU::OpName::src1_modifiers,
AMDGPU::OpName::src2_modifiers };
int OpSelIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::op_sel);
unsigned OpSel = Inst.getOperand(OpSelIdx).getImm();
unsigned OpSelHi = 0;
unsigned NegLo = 0;
unsigned NegHi = 0;
if (OpSelHiIdx != -1) {
OpSelHi = Inst.getOperand(OpSelHiIdx).getImm();
}
if (NegLoIdx != -1) {
int NegHiIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::neg_hi);
NegLo = Inst.getOperand(NegLoIdx).getImm();
NegHi = Inst.getOperand(NegHiIdx).getImm();
}
for (int J = 0; J < 3; ++J) {
int OpIdx = AMDGPU::getNamedOperandIdx(Opc, Ops[J]);
if (OpIdx == -1)
break;
uint32_t ModVal = 0;
if ((OpSel & (1 << J)) != 0)
ModVal |= SISrcMods::OP_SEL_0;
if ((OpSelHi & (1 << J)) != 0)
ModVal |= SISrcMods::OP_SEL_1;
if ((NegLo & (1 << J)) != 0)
ModVal |= SISrcMods::NEG;
if ((NegHi & (1 << J)) != 0)
ModVal |= SISrcMods::NEG_HI;
int ModIdx = AMDGPU::getNamedOperandIdx(Opc, ModOps[J]);
Inst.getOperand(ModIdx).setImm(Inst.getOperand(ModIdx).getImm() | ModVal);
}
}
//===----------------------------------------------------------------------===//
// dpp
//===----------------------------------------------------------------------===//
bool AMDGPUOperand::isDPPCtrl() const {
using namespace AMDGPU::DPP;
bool result = isImm() && getImmTy() == ImmTyDppCtrl && isUInt<9>(getImm());
if (result) {
int64_t Imm = getImm();
return (Imm >= DppCtrl::QUAD_PERM_FIRST && Imm <= DppCtrl::QUAD_PERM_LAST) ||
(Imm >= DppCtrl::ROW_SHL_FIRST && Imm <= DppCtrl::ROW_SHL_LAST) ||
(Imm >= DppCtrl::ROW_SHR_FIRST && Imm <= DppCtrl::ROW_SHR_LAST) ||
(Imm >= DppCtrl::ROW_ROR_FIRST && Imm <= DppCtrl::ROW_ROR_LAST) ||
(Imm == DppCtrl::WAVE_SHL1) ||
(Imm == DppCtrl::WAVE_ROL1) ||
(Imm == DppCtrl::WAVE_SHR1) ||
(Imm == DppCtrl::WAVE_ROR1) ||
(Imm == DppCtrl::ROW_MIRROR) ||
(Imm == DppCtrl::ROW_HALF_MIRROR) ||
(Imm == DppCtrl::BCAST15) ||
(Imm == DppCtrl::BCAST31);
}
return false;
}
bool AMDGPUOperand::isGPRIdxMode() const {
return isImm() && isUInt<4>(getImm());
}
bool AMDGPUOperand::isS16Imm() const {
return isImm() && (isInt<16>(getImm()) || isUInt<16>(getImm()));
}
bool AMDGPUOperand::isU16Imm() const {
return isImm() && isUInt<16>(getImm());
}
OperandMatchResultTy
AMDGPUAsmParser::parseDPPCtrl(OperandVector &Operands) {
using namespace AMDGPU::DPP;
SMLoc S = Parser.getTok().getLoc();
StringRef Prefix;
int64_t Int;
if (getLexer().getKind() == AsmToken::Identifier) {
Prefix = Parser.getTok().getString();
} else {
return MatchOperand_NoMatch;
}
if (Prefix == "row_mirror") {
Int = DppCtrl::ROW_MIRROR;
Parser.Lex();
} else if (Prefix == "row_half_mirror") {
Int = DppCtrl::ROW_HALF_MIRROR;
Parser.Lex();
} else {
// Check to prevent parseDPPCtrlOps from eating invalid tokens
if (Prefix != "quad_perm"
&& Prefix != "row_shl"
&& Prefix != "row_shr"
&& Prefix != "row_ror"
&& Prefix != "wave_shl"
&& Prefix != "wave_rol"
&& Prefix != "wave_shr"
&& Prefix != "wave_ror"
&& Prefix != "row_bcast") {
return MatchOperand_NoMatch;
}
Parser.Lex();
if (getLexer().isNot(AsmToken::Colon))
return MatchOperand_ParseFail;
if (Prefix == "quad_perm") {
// quad_perm:[%d,%d,%d,%d]
Parser.Lex();
if (getLexer().isNot(AsmToken::LBrac))
return MatchOperand_ParseFail;
Parser.Lex();
if (getParser().parseAbsoluteExpression(Int) || !(0 <= Int && Int <=3))
return MatchOperand_ParseFail;
for (int i = 0; i < 3; ++i) {
if (getLexer().isNot(AsmToken::Comma))
return MatchOperand_ParseFail;
Parser.Lex();
int64_t Temp;
if (getParser().parseAbsoluteExpression(Temp) || !(0 <= Temp && Temp <=3))
return MatchOperand_ParseFail;
const int shift = i*2 + 2;
Int += (Temp << shift);
}
if (getLexer().isNot(AsmToken::RBrac))
return MatchOperand_ParseFail;
Parser.Lex();
} else {
// sel:%d
Parser.Lex();
if (getParser().parseAbsoluteExpression(Int))
return MatchOperand_ParseFail;
if (Prefix == "row_shl" && 1 <= Int && Int <= 15) {
Int |= DppCtrl::ROW_SHL0;
} else if (Prefix == "row_shr" && 1 <= Int && Int <= 15) {
Int |= DppCtrl::ROW_SHR0;
} else if (Prefix == "row_ror" && 1 <= Int && Int <= 15) {
Int |= DppCtrl::ROW_ROR0;
} else if (Prefix == "wave_shl" && 1 == Int) {
Int = DppCtrl::WAVE_SHL1;
} else if (Prefix == "wave_rol" && 1 == Int) {
Int = DppCtrl::WAVE_ROL1;
} else if (Prefix == "wave_shr" && 1 == Int) {
Int = DppCtrl::WAVE_SHR1;
} else if (Prefix == "wave_ror" && 1 == Int) {
Int = DppCtrl::WAVE_ROR1;
} else if (Prefix == "row_bcast") {
if (Int == 15) {
Int = DppCtrl::BCAST15;
} else if (Int == 31) {
Int = DppCtrl::BCAST31;
} else {
return MatchOperand_ParseFail;
}
} else {
return MatchOperand_ParseFail;
}
}
}
Operands.push_back(AMDGPUOperand::CreateImm(this, Int, S, AMDGPUOperand::ImmTyDppCtrl));
return MatchOperand_Success;
}
AMDGPUOperand::Ptr AMDGPUAsmParser::defaultRowMask() const {
return AMDGPUOperand::CreateImm(this, 0xf, SMLoc(), AMDGPUOperand::ImmTyDppRowMask);
}
AMDGPUOperand::Ptr AMDGPUAsmParser::defaultBankMask() const {
return AMDGPUOperand::CreateImm(this, 0xf, SMLoc(), AMDGPUOperand::ImmTyDppBankMask);
}
AMDGPUOperand::Ptr AMDGPUAsmParser::defaultBoundCtrl() const {
return AMDGPUOperand::CreateImm(this, 0, SMLoc(), AMDGPUOperand::ImmTyDppBoundCtrl);
}
void AMDGPUAsmParser::cvtDPP(MCInst &Inst, const OperandVector &Operands) {
OptionalImmIndexMap OptionalIdx;
unsigned I = 1;
const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
}
for (unsigned E = Operands.size(); I != E; ++I) {
auto TiedTo = Desc.getOperandConstraint(Inst.getNumOperands(),
MCOI::TIED_TO);
if (TiedTo != -1) {
assert((unsigned)TiedTo < Inst.getNumOperands());
// handle tied old or src2 for MAC instructions
Inst.addOperand(Inst.getOperand(TiedTo));
}
AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
// Add the register arguments
if (Op.isReg() && Op.Reg.RegNo == AMDGPU::VCC) {
// VOP2b (v_add_u32, v_sub_u32 ...) dpp use "vcc" token.
// Skip it.
continue;
} if (isRegOrImmWithInputMods(Desc, Inst.getNumOperands())) {
Op.addRegWithFPInputModsOperands(Inst, 2);
} else if (Op.isDPPCtrl()) {
Op.addImmOperands(Inst, 1);
} else if (Op.isImm()) {
// Handle optional arguments
OptionalIdx[Op.getImmTy()] = I;
} else {
llvm_unreachable("Invalid operand type");
}
}
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyDppRowMask, 0xf);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyDppBankMask, 0xf);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyDppBoundCtrl);
}
//===----------------------------------------------------------------------===//
// sdwa
//===----------------------------------------------------------------------===//
OperandMatchResultTy
AMDGPUAsmParser::parseSDWASel(OperandVector &Operands, StringRef Prefix,
AMDGPUOperand::ImmTy Type) {
using namespace llvm::AMDGPU::SDWA;
SMLoc S = Parser.getTok().getLoc();
StringRef Value;
OperandMatchResultTy res;
res = parseStringWithPrefix(Prefix, Value);
if (res != MatchOperand_Success) {
return res;
}
int64_t Int;
Int = StringSwitch<int64_t>(Value)
.Case("BYTE_0", SdwaSel::BYTE_0)
.Case("BYTE_1", SdwaSel::BYTE_1)
.Case("BYTE_2", SdwaSel::BYTE_2)
.Case("BYTE_3", SdwaSel::BYTE_3)
.Case("WORD_0", SdwaSel::WORD_0)
.Case("WORD_1", SdwaSel::WORD_1)
.Case("DWORD", SdwaSel::DWORD)
.Default(0xffffffff);
Parser.Lex(); // eat last token
if (Int == 0xffffffff) {
return MatchOperand_ParseFail;
}
Operands.push_back(AMDGPUOperand::CreateImm(this, Int, S, Type));
return MatchOperand_Success;
}
OperandMatchResultTy
AMDGPUAsmParser::parseSDWADstUnused(OperandVector &Operands) {
using namespace llvm::AMDGPU::SDWA;
SMLoc S = Parser.getTok().getLoc();
StringRef Value;
OperandMatchResultTy res;
res = parseStringWithPrefix("dst_unused", Value);
if (res != MatchOperand_Success) {
return res;
}
int64_t Int;
Int = StringSwitch<int64_t>(Value)
.Case("UNUSED_PAD", DstUnused::UNUSED_PAD)
.Case("UNUSED_SEXT", DstUnused::UNUSED_SEXT)
.Case("UNUSED_PRESERVE", DstUnused::UNUSED_PRESERVE)
.Default(0xffffffff);
Parser.Lex(); // eat last token
if (Int == 0xffffffff) {
return MatchOperand_ParseFail;
}
Operands.push_back(AMDGPUOperand::CreateImm(this, Int, S, AMDGPUOperand::ImmTySdwaDstUnused));
return MatchOperand_Success;
}
void AMDGPUAsmParser::cvtSdwaVOP1(MCInst &Inst, const OperandVector &Operands) {
cvtSDWA(Inst, Operands, SIInstrFlags::VOP1);
}
void AMDGPUAsmParser::cvtSdwaVOP2(MCInst &Inst, const OperandVector &Operands) {
cvtSDWA(Inst, Operands, SIInstrFlags::VOP2);
}
void AMDGPUAsmParser::cvtSdwaVOP2b(MCInst &Inst, const OperandVector &Operands) {
cvtSDWA(Inst, Operands, SIInstrFlags::VOP2, true);
}
void AMDGPUAsmParser::cvtSdwaVOPC(MCInst &Inst, const OperandVector &Operands) {
cvtSDWA(Inst, Operands, SIInstrFlags::VOPC, isVI());
}
void AMDGPUAsmParser::cvtSDWA(MCInst &Inst, const OperandVector &Operands,
uint64_t BasicInstType, bool skipVcc) {
using namespace llvm::AMDGPU::SDWA;
OptionalImmIndexMap OptionalIdx;
bool skippedVcc = false;
unsigned I = 1;
const MCInstrDesc &Desc = MII.get(Inst.getOpcode());
for (unsigned J = 0; J < Desc.getNumDefs(); ++J) {
((AMDGPUOperand &)*Operands[I++]).addRegOperands(Inst, 1);
}
for (unsigned E = Operands.size(); I != E; ++I) {
AMDGPUOperand &Op = ((AMDGPUOperand &)*Operands[I]);
if (skipVcc && !skippedVcc && Op.isReg() && Op.Reg.RegNo == AMDGPU::VCC) {
// VOP2b (v_add_u32, v_sub_u32 ...) sdwa use "vcc" token as dst.
// Skip it if it's 2nd (e.g. v_add_i32_sdwa v1, vcc, v2, v3)
// or 4th (v_addc_u32_sdwa v1, vcc, v2, v3, vcc) operand.
// Skip VCC only if we didn't skip it on previous iteration.
if (BasicInstType == SIInstrFlags::VOP2 &&
(Inst.getNumOperands() == 1 || Inst.getNumOperands() == 5)) {
skippedVcc = true;
continue;
} else if (BasicInstType == SIInstrFlags::VOPC &&
Inst.getNumOperands() == 0) {
skippedVcc = true;
continue;
}
}
if (isRegOrImmWithInputMods(Desc, Inst.getNumOperands())) {
Op.addRegOrImmWithInputModsOperands(Inst, 2);
} else if (Op.isImm()) {
// Handle optional arguments
OptionalIdx[Op.getImmTy()] = I;
} else {
llvm_unreachable("Invalid operand type");
}
skippedVcc = false;
}
if (Inst.getOpcode() != AMDGPU::V_NOP_sdwa_gfx9 &&
Inst.getOpcode() != AMDGPU::V_NOP_sdwa_vi) {
// v_nop_sdwa_sdwa_vi/gfx9 has no optional sdwa arguments
switch (BasicInstType) {
case SIInstrFlags::VOP1:
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyClampSI, 0);
if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::omod) != -1) {
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyOModSI, 0);
}
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaDstSel, SdwaSel::DWORD);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaDstUnused, DstUnused::UNUSED_PRESERVE);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaSrc0Sel, SdwaSel::DWORD);
break;
case SIInstrFlags::VOP2:
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyClampSI, 0);
if (AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::omod) != -1) {
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyOModSI, 0);
}
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaDstSel, SdwaSel::DWORD);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaDstUnused, DstUnused::UNUSED_PRESERVE);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaSrc0Sel, SdwaSel::DWORD);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaSrc1Sel, SdwaSel::DWORD);
break;
case SIInstrFlags::VOPC:
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTyClampSI, 0);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaSrc0Sel, SdwaSel::DWORD);
addOptionalImmOperand(Inst, Operands, OptionalIdx, AMDGPUOperand::ImmTySdwaSrc1Sel, SdwaSel::DWORD);
break;
default:
llvm_unreachable("Invalid instruction type. Only VOP1, VOP2 and VOPC allowed");
}
}
// special case v_mac_{f16, f32}:
// it has src2 register operand that is tied to dst operand
if (Inst.getOpcode() == AMDGPU::V_MAC_F32_sdwa_vi ||
Inst.getOpcode() == AMDGPU::V_MAC_F16_sdwa_vi) {
auto it = Inst.begin();
std::advance(
it, AMDGPU::getNamedOperandIdx(Inst.getOpcode(), AMDGPU::OpName::src2));
Inst.insert(it, Inst.getOperand(0)); // src2 = dst
}
}
/// Force static initialization.
extern "C" void LLVMInitializeAMDGPUAsmParser() {
RegisterMCAsmParser<AMDGPUAsmParser> A(getTheAMDGPUTarget());
RegisterMCAsmParser<AMDGPUAsmParser> B(getTheGCNTarget());
}
#define GET_REGISTER_MATCHER
#define GET_MATCHER_IMPLEMENTATION
#define GET_MNEMONIC_SPELL_CHECKER
#include "AMDGPUGenAsmMatcher.inc"
// This fuction should be defined after auto-generated include so that we have
// MatchClassKind enum defined
unsigned AMDGPUAsmParser::validateTargetOperandClass(MCParsedAsmOperand &Op,
unsigned Kind) {
// Tokens like "glc" would be parsed as immediate operands in ParseOperand().
// But MatchInstructionImpl() expects to meet token and fails to validate
// operand. This method checks if we are given immediate operand but expect to
// get corresponding token.
AMDGPUOperand &Operand = (AMDGPUOperand&)Op;
switch (Kind) {
case MCK_addr64:
return Operand.isAddr64() ? Match_Success : Match_InvalidOperand;
case MCK_gds:
return Operand.isGDS() ? Match_Success : Match_InvalidOperand;
case MCK_lds:
return Operand.isLDS() ? Match_Success : Match_InvalidOperand;
case MCK_glc:
return Operand.isGLC() ? Match_Success : Match_InvalidOperand;
case MCK_idxen:
return Operand.isIdxen() ? Match_Success : Match_InvalidOperand;
case MCK_offen:
return Operand.isOffen() ? Match_Success : Match_InvalidOperand;
case MCK_SSrcB32:
// When operands have expression values, they will return true for isToken,
// because it is not possible to distinguish between a token and an
// expression at parse time. MatchInstructionImpl() will always try to
// match an operand as a token, when isToken returns true, and when the
// name of the expression is not a valid token, the match will fail,
// so we need to handle it here.
return Operand.isSSrcB32() ? Match_Success : Match_InvalidOperand;
case MCK_SSrcF32:
return Operand.isSSrcF32() ? Match_Success : Match_InvalidOperand;
case MCK_SoppBrTarget:
return Operand.isSoppBrTarget() ? Match_Success : Match_InvalidOperand;
case MCK_VReg32OrOff:
return Operand.isVReg32OrOff() ? Match_Success : Match_InvalidOperand;
case MCK_InterpSlot:
return Operand.isInterpSlot() ? Match_Success : Match_InvalidOperand;
case MCK_Attr:
return Operand.isInterpAttr() ? Match_Success : Match_InvalidOperand;
case MCK_AttrChan:
return Operand.isAttrChan() ? Match_Success : Match_InvalidOperand;
default:
return Match_InvalidOperand;
}
}
| 183,449 | 68,966 |
#ifndef APYTUU_ENGINE_GEOM_EX
#define APYTUU_ENGINE_GEOM_EX
namespace apytuu_engine_geom{
class GeomException{
public:
private:
};
}
#endif
| 144 | 72 |
#include "muscle.h"
#include "msa.h"
#include "tree.h"
#include "clust.h"
#include "clustsetmsa.h"
#include "distcalc.h"
static void SaveMSADist(const MSA &msa, MSADist &d, const char *FileName)
{
FILE *f = fopen(FileName, "w");
if (f == 0)
Quit("Cannot create %s", FileName);
unsigned n = msa.GetSeqCount();
for (unsigned i = 0; i < n; ++i)
{
fprintf(f, "%10.10s ", msa.GetSeqName(i));
for (unsigned j = 0; j < n; ++j)
fprintf(f, " %9g", d.ComputeDist(msa, i, j));
fprintf(f, "\n");
}
fclose(f);
}
static void TreeFromMSA_NJ(const MSA &msa, Tree &tree, CLUSTER Cluster,
DISTANCE Distance, const char *SaveFileName)
{
MSADist MD(Distance);
ClustSetMSA Set(msa, MD);
if (SaveFileName != 0)
SaveMSADist(msa, MD, SaveFileName);
Clust C;
C.Create(Set, Cluster);
tree.FromClust(C);
}
static void SaveDC(const DistCalcMSA &DC, const char *FileName)
{
FILE *f = fopen(FileName, "w");
if (f == 0)
Quit("Cannot create %s", FileName);
unsigned n = DC.GetCount();
fprintf(f, "%u\n", n);
float *Dist = new float[n];
for (unsigned i = 0; i < n; ++i)
{
fprintf(f, "%10.10s ", DC.GetName(i));
DC.CalcDistRange(i, Dist);
for (unsigned j = 0; j < i; ++j)
fprintf(f, " %9g", Dist[j]);
fprintf(f, "\n");
}
fclose(f);
}
static void TreeFromMSA_UPGMA(const MSA &msa, Tree &tree, CLUSTER Cluster,
DISTANCE Distance, const char *SaveFileName)
{
LINKAGE Linkage = LINKAGE_Undefined;
switch (Cluster)
{
case CLUSTER_UPGMA:
Linkage = LINKAGE_Avg;
break;
case CLUSTER_UPGMAMin:
Linkage = LINKAGE_Min;
break;
case CLUSTER_UPGMAMax:
Linkage = LINKAGE_Max;
break;
case CLUSTER_UPGMB:
Linkage = LINKAGE_Biased;
break;
default:
Quit("TreeFromMSA_UPGMA, CLUSTER_%u not supported", Cluster);
}
DistCalcMSA DC;
DC.Init(msa, Distance);
if (SaveFileName != 0)
SaveDC(DC, SaveFileName);
UPGMA2(DC, tree, Linkage);
}
void TreeFromMSA(const MSA &msa, Tree &tree, CLUSTER Cluster,
DISTANCE Distance, ROOT Root, const char *SaveFileName)
{
if (CLUSTER_NeighborJoining == Cluster)
TreeFromMSA_NJ(msa, tree, Cluster, Distance, SaveFileName);
else
TreeFromMSA_UPGMA(msa, tree, Cluster, Distance, SaveFileName);
FixRoot(tree, Root);
}
| 2,215 | 1,016 |
/* Copyright (c) 2010-2011 mbed.org, MIT License
*
* 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 "stdint.h"
#include "USBEndpoints.h"
#include "USBDevice.h"
#include "USBDescriptor.h"
//#define DEBUG
/* Device status */
#define DEVICE_STATUS_SELF_POWERED (1U<<0)
#define DEVICE_STATUS_REMOTE_WAKEUP (1U<<1)
/* Endpoint status */
#define ENDPOINT_STATUS_HALT (1U<<0)
/* Standard feature selectors */
#define DEVICE_REMOTE_WAKEUP (1)
#define ENDPOINT_HALT (0)
/* Macro to convert wIndex endpoint number to physical endpoint number */
#define WINDEX_TO_PHYSICAL(endpoint) (((endpoint & 0x0f) << 1) + \
((endpoint & 0x80) ? 1 : 0))
bool USBDevice::requestGetDescriptor(void)
{
bool success = false;
#ifdef DEBUG
printf("get descr: type: %d\r\n", DESCRIPTOR_TYPE(transfer.setup.wValue));
#endif
switch (DESCRIPTOR_TYPE(transfer.setup.wValue))
{
case DEVICE_DESCRIPTOR:
if (deviceDesc() != NULL)
{
if ((deviceDesc()[0] == DEVICE_DESCRIPTOR_LENGTH) \
&& (deviceDesc()[1] == DEVICE_DESCRIPTOR))
{
#ifdef DEBUG
printf("device descr\r\n");
#endif
transfer.remaining = DEVICE_DESCRIPTOR_LENGTH;
transfer.ptr = deviceDesc();
transfer.direction = DEVICE_TO_HOST;
success = true;
}
}
break;
case CONFIGURATION_DESCRIPTOR:
if (configurationDesc() != NULL)
{
if ((configurationDesc()[0] == CONFIGURATION_DESCRIPTOR_LENGTH) \
&& (configurationDesc()[1] == CONFIGURATION_DESCRIPTOR))
{
#ifdef DEBUG
printf("conf descr request\r\n");
#endif
/* Get wTotalLength */
transfer.remaining = configurationDesc()[2] \
| (configurationDesc()[3] << 8);
transfer.ptr = configurationDesc();
transfer.direction = DEVICE_TO_HOST;
success = true;
}
}
break;
case STRING_DESCRIPTOR:
#ifdef DEBUG
printf("str descriptor\r\n");
#endif
switch (DESCRIPTOR_INDEX(transfer.setup.wValue))
{
case STRING_OFFSET_LANGID:
#ifdef DEBUG
printf("1\r\n");
#endif
transfer.remaining = stringLangidDesc()[0];
transfer.ptr = stringLangidDesc();
transfer.direction = DEVICE_TO_HOST;
success = true;
break;
case STRING_OFFSET_IMANUFACTURER:
#ifdef DEBUG
printf("2\r\n");
#endif
transfer.remaining = stringImanufacturerDesc()[0];
transfer.ptr = stringImanufacturerDesc();
transfer.direction = DEVICE_TO_HOST;
success = true;
break;
case STRING_OFFSET_IPRODUCT:
#ifdef DEBUG
printf("3\r\n");
#endif
transfer.remaining = stringIproductDesc()[0];
transfer.ptr = stringIproductDesc();
transfer.direction = DEVICE_TO_HOST;
success = true;
break;
case STRING_OFFSET_ISERIAL:
#ifdef DEBUG
printf("4\r\n");
#endif
transfer.remaining = stringIserialDesc()[0];
transfer.ptr = stringIserialDesc();
transfer.direction = DEVICE_TO_HOST;
success = true;
break;
case STRING_OFFSET_ICONFIGURATION:
#ifdef DEBUG
printf("5\r\n");
#endif
transfer.remaining = stringIConfigurationDesc()[0];
transfer.ptr = stringIConfigurationDesc();
transfer.direction = DEVICE_TO_HOST;
success = true;
break;
case STRING_OFFSET_IINTERFACE:
#ifdef DEBUG
printf("6\r\n");
#endif
transfer.remaining = stringIinterfaceDesc()[0];
transfer.ptr = stringIinterfaceDesc();
transfer.direction = DEVICE_TO_HOST;
success = true;
break;
}
break;
case INTERFACE_DESCRIPTOR:
#ifdef DEBUG
printf("interface descr\r\n");
#endif
case ENDPOINT_DESCRIPTOR:
#ifdef DEBUG
printf("endpoint descr\r\n");
#endif
/* TODO: Support is optional, not implemented here */
break;
default:
#ifdef DEBUG
printf("ERROR\r\n");
#endif
break;
}
return success;
}
void USBDevice::decodeSetupPacket(uint8_t *data, SETUP_PACKET *packet)
{
/* Fill in the elements of a SETUP_PACKET structure from raw data */
packet->bmRequestType.dataTransferDirection = (data[0] & 0x80) >> 7;
packet->bmRequestType.Type = (data[0] & 0x60) >> 5;
packet->bmRequestType.Recipient = data[0] & 0x1f;
packet->bRequest = data[1];
packet->wValue = (data[2] | (uint16_t)data[3] << 8);
packet->wIndex = (data[4] | (uint16_t)data[5] << 8);
packet->wLength = (data[6] | (uint16_t)data[7] << 8);
}
bool USBDevice::controlOut(void)
{
/* Control transfer data OUT stage */
uint8_t buffer[MAX_PACKET_SIZE_EP0];
uint32_t packetSize;
/* Check we should be transferring data OUT */
if (transfer.direction != HOST_TO_DEVICE)
{
return false;
}
/* Read from endpoint */
packetSize = EP0getReadResult(buffer);
/* Check if transfer size is valid */
if (packetSize > transfer.remaining)
{
/* Too big */
return false;
}
/* Update transfer */
transfer.ptr += packetSize;
transfer.remaining -= packetSize;
/* Check if transfer has completed */
if (transfer.remaining == 0)
{
/* Transfer completed */
if (transfer.notify)
{
/* Notify class layer. */
USBCallback_requestCompleted(buffer, packetSize);
transfer.notify = false;
}
/* Status stage */
EP0write(NULL, 0);
}
else
{
EP0read();
}
return true;
}
bool USBDevice::controlIn(void)
{
/* Control transfer data IN stage */
uint32_t packetSize;
/* Check if transfer has completed (status stage transactions */
/* also have transfer.remaining == 0) */
if (transfer.remaining == 0)
{
if (transfer.zlp)
{
/* Send zero length packet */
EP0write(NULL, 0);
transfer.zlp = false;
}
/* Transfer completed */
if (transfer.notify)
{
/* Notify class layer. */
USBCallback_requestCompleted(NULL, 0);
transfer.notify = false;
}
EP0read();
EP0readStage();
/* Completed */
return true;
}
/* Check we should be transferring data IN */
if (transfer.direction != DEVICE_TO_HOST)
{
return false;
}
packetSize = transfer.remaining;
if (packetSize > MAX_PACKET_SIZE_EP0)
{
packetSize = MAX_PACKET_SIZE_EP0;
}
/* Write to endpoint */
EP0write(transfer.ptr, packetSize);
/* Update transfer */
transfer.ptr += packetSize;
transfer.remaining -= packetSize;
return true;
}
bool USBDevice::requestSetAddress(void)
{
/* Set the device address */
setAddress(transfer.setup.wValue);
if (transfer.setup.wValue == 0)
{
device.state = DEFAULT;
}
else
{
device.state = ADDRESS;
}
return true;
}
bool USBDevice::requestSetConfiguration(void)
{
device.configuration = transfer.setup.wValue;
/* Set the device configuration */
if (device.configuration == 0)
{
/* Not configured */
unconfigureDevice();
device.state = ADDRESS;
}
else
{
if (USBCallback_setConfiguration(device.configuration))
{
/* Valid configuration */
configureDevice();
device.state = CONFIGURED;
}
else
{
return false;
}
}
return true;
}
bool USBDevice::requestGetConfiguration(void)
{
/* Send the device configuration */
transfer.ptr = &device.configuration;
transfer.remaining = sizeof(device.configuration);
transfer.direction = DEVICE_TO_HOST;
return true;
}
bool USBDevice::requestGetInterface(void)
{
/* Return the selected alternate setting for an interface */
if (device.state != CONFIGURED)
{
return false;
}
/* Send the alternate setting */
transfer.setup.wIndex = currentInterface;
transfer.ptr = ¤tAlternate;
transfer.remaining = sizeof(currentAlternate);
transfer.direction = DEVICE_TO_HOST;
return true;
}
bool USBDevice::requestSetInterface(void)
{
bool success = false;
if(USBCallback_setInterface(transfer.setup.wIndex, transfer.setup.wValue))
{
success = true;
currentInterface = transfer.setup.wIndex;
currentAlternate = transfer.setup.wValue;
}
return success;
}
bool USBDevice::requestSetFeature()
{
bool success = false;
if (device.state != CONFIGURED)
{
/* Endpoint or interface must be zero */
if (transfer.setup.wIndex != 0)
{
return false;
}
}
switch (transfer.setup.bmRequestType.Recipient)
{
case DEVICE_RECIPIENT:
/* TODO: Remote wakeup feature not supported */
break;
case ENDPOINT_RECIPIENT:
if (transfer.setup.wValue == ENDPOINT_HALT)
{
/* TODO: We should check that the endpoint number is valid */
stallEndpoint(
WINDEX_TO_PHYSICAL(transfer.setup.wIndex));
success = true;
}
break;
default:
break;
}
return success;
}
bool USBDevice::requestClearFeature()
{
bool success = false;
if (device.state != CONFIGURED)
{
/* Endpoint or interface must be zero */
if (transfer.setup.wIndex != 0)
{
return false;
}
}
switch (transfer.setup.bmRequestType.Recipient)
{
case DEVICE_RECIPIENT:
/* TODO: Remote wakeup feature not supported */
break;
case ENDPOINT_RECIPIENT:
/* TODO: We should check that the endpoint number is valid */
if (transfer.setup.wValue == ENDPOINT_HALT)
{
unstallEndpoint( WINDEX_TO_PHYSICAL(transfer.setup.wIndex));
success = true;
}
break;
default:
break;
}
return success;
}
bool USBDevice::requestGetStatus(void)
{
static uint16_t status;
bool success = false;
if (device.state != CONFIGURED)
{
/* Endpoint or interface must be zero */
if (transfer.setup.wIndex != 0)
{
return false;
}
}
switch (transfer.setup.bmRequestType.Recipient)
{
case DEVICE_RECIPIENT:
/* TODO: Currently only supports self powered devices */
status = DEVICE_STATUS_SELF_POWERED;
success = true;
break;
case INTERFACE_RECIPIENT:
status = 0;
success = true;
break;
case ENDPOINT_RECIPIENT:
/* TODO: We should check that the endpoint number is valid */
if (getEndpointStallState(
WINDEX_TO_PHYSICAL(transfer.setup.wIndex)))
{
status = ENDPOINT_STATUS_HALT;
}
else
{
status = 0;
}
success = true;
break;
default:
break;
}
if (success)
{
/* Send the status */
transfer.ptr = (uint8_t *)&status; /* Assumes little endian */
transfer.remaining = sizeof(status);
transfer.direction = DEVICE_TO_HOST;
}
return success;
}
bool USBDevice::requestSetup(void)
{
bool success = false;
/* Process standard requests */
if ((transfer.setup.bmRequestType.Type == STANDARD_TYPE))
{
switch (transfer.setup.bRequest)
{
case GET_STATUS:
success = requestGetStatus();
break;
case CLEAR_FEATURE:
success = requestClearFeature();
break;
case SET_FEATURE:
success = requestSetFeature();
break;
case SET_ADDRESS:
success = requestSetAddress();
break;
case GET_DESCRIPTOR:
success = requestGetDescriptor();
break;
case SET_DESCRIPTOR:
/* TODO: Support is optional, not implemented here */
success = false;
break;
case GET_CONFIGURATION:
success = requestGetConfiguration();
break;
case SET_CONFIGURATION:
success = requestSetConfiguration();
break;
case GET_INTERFACE:
success = requestGetInterface();
break;
case SET_INTERFACE:
success = requestSetInterface();
break;
default:
break;
}
}
return success;
}
bool USBDevice::controlSetup(void)
{
bool success = false;
/* Control transfer setup stage */
uint8_t buffer[MAX_PACKET_SIZE_EP0];
EP0setup(buffer);
/* Initialise control transfer state */
decodeSetupPacket(buffer, &transfer.setup);
transfer.ptr = NULL;
transfer.remaining = 0;
transfer.direction = 0;
transfer.zlp = false;
transfer.notify = false;
#ifdef DEBUG
printf("dataTransferDirection: %d\r\nType: %d\r\nRecipient: %d\r\nbRequest: %d\r\nwValue: %d\r\nwIndex: %d\r\nwLength: %d\r\n",transfer.setup.bmRequestType.dataTransferDirection,
transfer.setup.bmRequestType.Type,
transfer.setup.bmRequestType.Recipient,
transfer.setup.bRequest,
transfer.setup.wValue,
transfer.setup.wIndex,
transfer.setup.wLength);
#endif
/* Class / vendor specific */
success = USBCallback_request();
if (!success)
{
/* Standard requests */
if (!requestSetup())
{
#ifdef DEBUG
printf("fail!!!!\r\n");
#endif
return false;
}
}
/* Check transfer size and direction */
if (transfer.setup.wLength>0)
{
if (transfer.setup.bmRequestType.dataTransferDirection \
== DEVICE_TO_HOST)
{
/* IN data stage is required */
if (transfer.direction != DEVICE_TO_HOST)
{
return false;
}
/* Transfer must be less than or equal to the size */
/* requested by the host */
if (transfer.remaining > transfer.setup.wLength)
{
transfer.remaining = transfer.setup.wLength;
}
}
else
{
/* OUT data stage is required */
if (transfer.direction != HOST_TO_DEVICE)
{
return false;
}
/* Transfer must be equal to the size requested by the host */
if (transfer.remaining != transfer.setup.wLength)
{
return false;
}
}
}
else
{
/* No data stage; transfer size must be zero */
if (transfer.remaining != 0)
{
return false;
}
}
/* Data or status stage if applicable */
if (transfer.setup.wLength>0)
{
if (transfer.setup.bmRequestType.dataTransferDirection \
== DEVICE_TO_HOST)
{
/* Check if we'll need to send a zero length packet at */
/* the end of this transfer */
if (transfer.setup.wLength > transfer.remaining)
{
/* Device wishes to transfer less than host requested */
if ((transfer.remaining % MAX_PACKET_SIZE_EP0) == 0)
{
/* Transfer is a multiple of EP0 max packet size */
transfer.zlp = true;
}
}
/* IN stage */
controlIn();
}
else
{
/* OUT stage */
EP0read();
}
}
else
{
/* Status stage */
EP0write(NULL, 0);
}
return true;
}
void USBDevice::busReset(void)
{
device.state = DEFAULT;
device.configuration = 0;
device.suspended = false;
/* Call class / vendor specific busReset function */
USBCallback_busReset();
}
void USBDevice::EP0setupCallback(void)
{
/* Endpoint 0 setup event */
if (!controlSetup())
{
/* Protocol stall */
EP0stall();
}
/* Return true if an OUT data stage is expected */
}
void USBDevice::EP0out(void)
{
/* Endpoint 0 OUT data event */
if (!controlOut())
{
/* Protocol stall; this will stall both endpoints */
EP0stall();
}
}
void USBDevice::EP0in(void)
{
#ifdef DEBUG
printf("EP0IN\r\n");
#endif
/* Endpoint 0 IN data event */
if (!controlIn())
{
/* Protocol stall; this will stall both endpoints */
EP0stall();
}
}
bool USBDevice::configured(void)
{
/* Returns true if device is in the CONFIGURED state */
return (device.state == CONFIGURED);
}
void USBDevice::connect(bool blocking)
{
/* Connect device */
USBHAL::connect();
if (blocking) {
/* Block if not configured */
while (!configured());
}
}
void USBDevice::disconnect(void)
{
/* Disconnect device */
USBHAL::disconnect();
/* Set initial device state */
device.state = POWERED;
device.configuration = 0;
device.suspended = false;
}
CONTROL_TRANSFER * USBDevice::getTransferPtr(void)
{
return &transfer;
}
bool USBDevice::addEndpoint(uint8_t endpoint, uint32_t maxPacket)
{
return realiseEndpoint(endpoint, maxPacket, 0);
}
bool USBDevice::addRateFeedbackEndpoint(uint8_t endpoint, uint32_t maxPacket)
{
/* For interrupt endpoints only */
return realiseEndpoint(endpoint, maxPacket, RATE_FEEDBACK_MODE);
}
uint8_t * USBDevice::findDescriptor(uint8_t descriptorType)
{
/* Find a descriptor within the list of descriptors */
/* following a configuration descriptor. */
uint16_t wTotalLength;
uint8_t *ptr;
if (configurationDesc() == NULL)
{
return NULL;
}
/* Check this is a configuration descriptor */
if ((configurationDesc()[0] != CONFIGURATION_DESCRIPTOR_LENGTH) \
|| (configurationDesc()[1] != CONFIGURATION_DESCRIPTOR))
{
return NULL;
}
wTotalLength = configurationDesc()[2] | (configurationDesc()[3] << 8);
/* Check there are some more descriptors to follow */
if (wTotalLength <= (CONFIGURATION_DESCRIPTOR_LENGTH+2))
/* +2 is for bLength and bDescriptorType of next descriptor */
{
return NULL;
}
/* Start at first descriptor after the configuration descriptor */
ptr = &(configurationDesc()[CONFIGURATION_DESCRIPTOR_LENGTH]);
do {
if (ptr[1] /* bDescriptorType */ == descriptorType)
{
/* Found */
return ptr;
}
/* Skip to next descriptor */
ptr += ptr[0]; /* bLength */
} while (ptr < (configurationDesc() + wTotalLength));
/* Reached end of the descriptors - not found */
return NULL;
}
void USBDevice::connectStateChanged(unsigned int connected)
{
}
void USBDevice::suspendStateChanged(unsigned int suspended)
{
}
USBDevice::USBDevice(uint16_t vendor_id, uint16_t product_id, uint16_t product_release){
VENDOR_ID = vendor_id;
PRODUCT_ID = product_id;
PRODUCT_RELEASE = product_release;
/* Set initial device state */
device.state = POWERED;
device.configuration = 0;
device.suspended = false;
};
bool USBDevice::readStart(uint8_t endpoint, uint32_t maxSize)
{
return endpointRead(endpoint, maxSize) == EP_PENDING;
}
bool USBDevice::write(uint8_t endpoint, uint8_t * buffer, uint32_t size, uint32_t maxSize)
{
EP_STATUS result;
if (size > maxSize)
{
return false;
}
if(!configured()) {
return false;
}
/* Send report */
result = endpointWrite(endpoint, buffer, size);
if (result != EP_PENDING)
{
return false;
}
/* Wait for completion */
do {
result = endpointWriteResult(endpoint);
} while ((result == EP_PENDING) && configured());
return (result == EP_COMPLETED);
}
bool USBDevice::writeNB(uint8_t endpoint, uint8_t * buffer, uint32_t size, uint32_t maxSize)
{
EP_STATUS result;
if (size > maxSize)
{
return false;
}
if(!configured()) {
return false;
}
/* Send report */
result = endpointWrite(endpoint, buffer, size);
if (result != EP_PENDING)
{
return false;
}
result = endpointWriteResult(endpoint);
return (result == EP_COMPLETED);
}
bool USBDevice::readEP(uint8_t endpoint, uint8_t * buffer, uint32_t * size, uint32_t maxSize)
{
EP_STATUS result;
if(!configured()) {
return false;
}
/* Wait for completion */
do {
result = endpointReadResult(endpoint, buffer, size);
} while ((result == EP_PENDING) && configured());
return (result == EP_COMPLETED);
}
bool USBDevice::readEP_NB(uint8_t endpoint, uint8_t * buffer, uint32_t * size, uint32_t maxSize)
{
EP_STATUS result;
if(!configured()) {
return false;
}
result = endpointReadResult(endpoint, buffer, size);
return (result == EP_COMPLETED);
}
uint8_t * USBDevice::deviceDesc() {
static uint8_t deviceDescriptor[] = {
DEVICE_DESCRIPTOR_LENGTH, /* bLength */
DEVICE_DESCRIPTOR, /* bDescriptorType */
LSB(USB_VERSION_2_0), /* bcdUSB (LSB) */
MSB(USB_VERSION_2_0), /* bcdUSB (MSB) */
0x00, /* bDeviceClass */
0x00, /* bDeviceSubClass */
0x00, /* bDeviceprotocol */
MAX_PACKET_SIZE_EP0, /* bMaxPacketSize0 */
(uint8_t)(LSB(VENDOR_ID)), /* idVendor (LSB) */
(uint8_t)(MSB(VENDOR_ID)), /* idVendor (MSB) */
(uint8_t)(LSB(PRODUCT_ID)), /* idProduct (LSB) */
(uint8_t)(MSB(PRODUCT_ID)), /* idProduct (MSB) */
(uint8_t)(LSB(PRODUCT_RELEASE)), /* bcdDevice (LSB) */
(uint8_t)(MSB(PRODUCT_RELEASE)), /* bcdDevice (MSB) */
STRING_OFFSET_IMANUFACTURER, /* iManufacturer */
STRING_OFFSET_IPRODUCT, /* iProduct */
STRING_OFFSET_ISERIAL, /* iSerialNumber */
0x01 /* bNumConfigurations */
};
return deviceDescriptor;
}
uint8_t * USBDevice::stringLangidDesc() {
static uint8_t stringLangidDescriptor[] = {
0x04, /*bLength*/
STRING_DESCRIPTOR, /*bDescriptorType 0x03*/
0x09,0x04, /*bString Lang ID - 0x0409 - English*/
};
return stringLangidDescriptor;
}
uint8_t * USBDevice::stringImanufacturerDesc() {
static uint8_t stringImanufacturerDescriptor[] = {
0x12, /*bLength*/
STRING_DESCRIPTOR, /*bDescriptorType 0x03*/
'm',0,'b',0,'e',0,'d',0,'.',0,'o',0,'r',0,'g',0, /*bString iManufacturer - mbed.org*/
};
return stringImanufacturerDescriptor;
}
uint8_t * USBDevice::stringIserialDesc() {
static uint8_t stringIserialDescriptor[] = {
0x16, /*bLength*/
STRING_DESCRIPTOR, /*bDescriptorType 0x03*/
'0',0,'1',0,'2',0,'3',0,'4',0,'5',0,'6',0,'7',0,'8',0,'9',0, /*bString iSerial - 0123456789*/
};
return stringIserialDescriptor;
}
uint8_t * USBDevice::stringIConfigurationDesc() {
static uint8_t stringIconfigurationDescriptor[] = {
0x06, /*bLength*/
STRING_DESCRIPTOR, /*bDescriptorType 0x03*/
'0',0,'1',0, /*bString iConfiguration - 01*/
};
return stringIconfigurationDescriptor;
}
uint8_t * USBDevice::stringIinterfaceDesc() {
static uint8_t stringIinterfaceDescriptor[] = {
0x08, /*bLength*/
STRING_DESCRIPTOR, /*bDescriptorType 0x03*/
'U',0,'S',0,'B',0, /*bString iInterface - USB*/
};
return stringIinterfaceDescriptor;
}
uint8_t * USBDevice::stringIproductDesc() {
static uint8_t stringIproductDescriptor[] = {
0x16, /*bLength*/
STRING_DESCRIPTOR, /*bDescriptorType 0x03*/
'U',0,'S',0,'B',0,' ',0,'D',0,'E',0,'V',0,'I',0,'C',0,'E',0 /*bString iProduct - USB DEVICE*/
};
return stringIproductDescriptor;
}
| 27,933 | 8,095 |
/*****************************************************************************************************************
* ReelRobotix Inc. - Software License Agreement Copyright (c) 2018-2020
* Authors: Pablo Inigo Blasco, Brett Aldrich
*
******************************************************************************************************************/
#include <move_group_interface_client/client_behaviors/cb_attach_object.h>
#include <move_group_interface_client/components/cp_grasping_objects.h>
namespace cl_move_group_interface
{
CbAttachObject::CbAttachObject(std::string targetObjectName)
: targetObjectName_(targetObjectName)
{
}
CbAttachObject::CbAttachObject()
{
}
void CbAttachObject::onEntry()
{
cl_move_group_interface::ClMoveGroup *moveGroup;
this->requiresClient(moveGroup);
cl_move_group_interface::GraspingComponent *graspingComponent;
this->requiresComponent(graspingComponent);
// auto cubepos = cubeinfo->pose_->toPoseStampedMsg();
moveit_msgs::CollisionObject targetCollisionObject;
bool found = graspingComponent->getGraspingObject(targetObjectName_, targetCollisionObject);
if (found)
{
targetCollisionObject.operation = moveit_msgs::CollisionObject::ADD;
targetCollisionObject.header.stamp = ros::Time::now();
moveGroup->planningSceneInterface.applyCollisionObject(targetCollisionObject);
// collisionObjects.push_back(cubeCollision);
graspingComponent->currentAttachedObjectName = targetObjectName_;
moveGroup->moveGroupClientInterface.attachObject(targetObjectName_, "gripper_link", graspingComponent->fingerTipNames);
}
}
void CbAttachObject::onExit()
{
}
} // namespace cl_move_group_interface | 1,854 | 510 |
#include <pybind11/pybind11.h>
#include <pybind11/stl_bind.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
#include <FTDCParser.h>
#include <vector>
#include <filesystem>
#include <boost/format.hpp>
namespace py = pybind11;
using namespace py::literals;
using namespace ftdcparser;
typedef std::vector<std::string> MetricNames;
#define FALSE 0
#define STRINGIFY(x) #x
#define MACRO_STRINGIFY(x) STRINGIFY(x)
//TODO: Check for memory leaks.
// helper function to avoid making a copy when returning a py::array_t
// author: https://github.com/YannickJadoul
// source: https://github.com/pybind/pybind11/issues/1042#issuecomment-642215028
template <typename Sequence>
inline py::array_t<typename Sequence::value_type>
as_pyarray(Sequence &&seq) {
auto size = seq.size();
auto data = seq.data();
std::unique_ptr<Sequence> seq_ptr = std::make_unique<Sequence>(std::move(seq));
auto capsule = py::capsule(seq_ptr.get(), [](void *p) { std::unique_ptr<Sequence>(reinterpret_cast<Sequence*>(p)); });
seq_ptr.release();
return py::array(size, data, capsule);
}
inline py::array_t<uint64_t >
as_pyarray(MetricsPtr m) {
auto size = m->size();
auto data = m->data();
std::unique_ptr<MetricsPtr> seq_ptr = std::make_unique<MetricsPtr>(std::move(m));
auto capsule = py::capsule(seq_ptr.get(),
[](void *p) { std::unique_ptr<Metrics>(reinterpret_cast<Metrics *>(p)); });
seq_ptr.release();
return py::array(size, data, capsule);
}
struct ParserClass {
FTDCParser *pParser;
std::vector<std::string> metadata;
std::vector<std::string> fileList;
MetricNames metric_names;
py::array_t<unsigned long> emptyArray;
MetricsPtr emptyMetrics;
explicit ParserClass() {
pParser = new FTDCParser();
};
int parseFile(std::string file, bool lazy=true) {
fileList.emplace_back(file);
int n = pParser->parseFiles(&fileList, false, false, lazy);
if (n == 0) {
// Timestamps, metric names, and metadata as fields in python
metric_names = pParser->getMetricsNames();
metadata = pParser->getMetadata();
}
return n;
}
void setVerbose(bool verbose) {
pParser->setVerbose(verbose);
}
int parseDir(std::string dir, bool lazy=true) {
// if it exists, and it a directory, pop and push contents
if (std::filesystem::exists(dir) && std::filesystem::is_directory(dir)) {
for (auto&& fileInPath : std::filesystem::directory_iterator(dir))
fileList.push_back(fileInPath.path().string());
// Not really necessary.
std::sort(fileList.begin(), fileList.end());
int n = pParser->parseFiles(&fileList, false, false, lazy);
if (n == 0) {
// metric names and metadata as fields in python
metric_names = pParser->getMetricsNames();
metadata = pParser->getMetadata();
}
return n;
}
return -1;
}
int dumpFileAsJson(std::string input, std::string output) {
return pParser->dumpDocsAsJsonTimestamps(input, output, INVALID_TIMESTAMP, INVALID_TIMESTAMP);
}
int dumpFileAsCsv(std::string input, std::string output) {
return pParser->dumpDocsAsCsvTimestamps(input, output, INVALID_TIMESTAMP, INVALID_TIMESTAMP);
}
py::list
getParsedFileInfo() {
auto fi = pParser->getParsedFileInfo();
py::list parsedFiles;
for (auto f : fi) {
auto msg = str(boost::format("{ \"abs_path\" : %1%, \"samples\" : %2%, \"start\" : %3%, \"end\" : %4% }") %
f->getFileAbsolute() %
f->getSamplesCount() %
f->getStart() %
f->getEnd()
);
auto fileInfo = py::dict("abs_path"_a=f->getFileAbsolute(),
"samples"_a=f->getSamplesCount(),
"start"_a=f->getStart(),
"end"_a=f->getEnd()
);
parsedFiles.append(fileInfo);
}
return parsedFiles;
}
MetricsPtr get_timestamps(size_t start =INVALID_TIMESTAMP, size_t end = INVALID_TIMESTAMP) {
return pParser->getMetric( "start", start, end);
}
MetricsPtr getMetric(std::string metric_name,
size_t start = INVALID_TIMESTAMP, size_t end =INVALID_TIMESTAMP,
bool rated_metric = false) {
return pParser->getMetric(metric_name, start, end, rated_metric);
}
std::vector<MetricsPtr> getMetricList(const std::vector<std::string> metric_names,
size_t start = INVALID_TIMESTAMP,
size_t end = INVALID_TIMESTAMP,
bool rated_metric = false) {
auto m = pParser->getMetric(std::move(metric_names), start, end, rated_metric);
std::vector<MetricsPtr> metricList;
for(int i=0;i<m.size();++i) {
// How to handle metric names that are not found?
if (m[i] != nullptr) {
metricList.emplace_back(m[i]);
}
else
metricList.emplace_back(emptyMetrics);
}
return metricList;
}
uint64_t getMetricSampleCount() { //TODO: may or may not be valid in lazy parsing mode
return pParser->getMetricLength();
}
py::array_t<unsigned long> getMetricAsNumpyArray(std::string metric_name,
size_t start = INVALID_TIMESTAMP,
size_t end = INVALID_TIMESTAMP,
bool rated_metric = false) {
auto m = pParser->getMetric(metric_name, start, end, rated_metric);
return as_pyarray(m);
}
std::vector<py::array_t<unsigned long>> getMetricListAsNumpyArray(const std::vector<std::string> metric_names,
size_t start = INVALID_TIMESTAMP,
size_t end = INVALID_TIMESTAMP,
bool rated_metric = false) {
auto m = pParser->getMetric(std::move(metric_names), start, end, rated_metric);
std::vector<py::array_t<unsigned long>> metricList;
for(int i=0;i<m.size();++i) {
// How to handle metric names that are not found?
if (m[i] != nullptr) {
auto element = as_pyarray(m[i]);
metricList.emplace_back(element);
}
else
metricList.emplace_back(emptyArray);
}
return metricList;
}
py::array_t<uint64_t> getMetricListAsNumpyMatrix(const std::vector<std::string> metric_names,
size_t start = INVALID_TIMESTAMP,
size_t end = INVALID_TIMESTAMP,
bool rated_metric = false,
bool transpose = false) {
size_t stride = 0;
auto m = pParser->getMetricMatrix( metric_names, &stride, start, end, rated_metric);
if (stride !=0) {
int metricNamesSize = metric_names.size();
if (!transpose) {
return py::array_t<uint64_t>({ metricNamesSize, (int)stride}, m->data());
}
else {
py::array_t<uint64_t> a = py::array_t<uint64_t>( {(int)stride, metricNamesSize});
uint64_t *p = m->data();
auto r = a.mutable_unchecked();
//printf("dimensions %zd x %zd\n", r.shape(0), r.shape(1));
//printf("Element (0,0)=%ld\nElement (%ld,0)=%ld\n", p[0], r.shape(0), p[r.shape(0)]);
for (int i=0; i<r.shape(0); ++i) {
for (int j=0; j<r.shape(1); ++j)
r(i,j) = p[i + (j*r.shape(0))];
}
return a;
}
}
else {
// err
return py::array_t<uint64_t>({ 0, 0 }, { 4, 8 });
}
}
};
PYBIND11_MODULE(_core, m) {
m.doc() = R"pbdoc(
MongoDB FTDC files parser library.
-----------------------
.. currentmodule:: pyftdc
.. autosummary::
:toctree: _generate
parse_dir
parse_file
get_metric
get_timestamps
get_metric_sample_count
get_metric_names
timestamps
metadata
get_metric_numpy
get_metrics_list_numpy
get_metrics_list_numpy_matrix
)pbdoc";
py::class_<ParserClass>(m, "FTDCParser")
.def(py::init<>())
.def("set_verbose", &ParserClass::setVerbose,
"Set verbose flag",
py::arg("verbose"))
.def("parse_dir", &ParserClass::parseDir,
"Parses all files in a directory",
py::arg("dir"),
py::arg("lazy") = true)
.def("parse_file", &ParserClass::parseFile,
"Parses one file",
py::arg("file"),
py::arg("lazy") = true)
.def("get_parsed_file_info", &ParserClass::getParsedFileInfo,
"Returns information on parsed files")
.def("dump_file_as_json", &ParserClass::dumpFileAsJson,
"Dumps a file contents to a file as JSON structures.",
py::arg("input"),
py::arg("output"))
.def("dump_file_as_csv", &ParserClass::dumpFileAsCsv,
"Dumps a file contents to a file as CSV file.",
py::arg("input"),
py::arg("output"))
.def("get_metric", &ParserClass::getMetric,
"Returns a list of values from the metrics, using starting and ending timestamps if specified",
py::arg("metric_name"),
py::arg("start") = ::INVALID_TIMESTAMP,
py::arg("end") = ::INVALID_TIMESTAMP,
py::arg("rated_metric") = false)
.def("get_metrics_list", &ParserClass::getMetricList,
"Returns a list of values from the metrics list, using starting and ending timestamps if specified",
py::arg("metric_name"),
py::arg("start") = ::INVALID_TIMESTAMP,
py::arg("end") = ::INVALID_TIMESTAMP,
py::arg("rated_metric") = false)
.def("get_timestamps", &ParserClass::get_timestamps,
"Returns timestamps",
py::arg("start") = ::INVALID_TIMESTAMP,
py::arg("end") = ::INVALID_TIMESTAMP)
.def("get_metric_sample_count", &ParserClass::getMetricSampleCount)
.def_readonly("metric_names", &ParserClass::metric_names)
.def_readonly("metadata", &ParserClass::metadata)
.def("get_metric_numpy", &ParserClass::getMetricAsNumpyArray,
"Returns a metric as a numpy array.",
py::arg("metric_name"),
py::arg("start") = ::INVALID_TIMESTAMP,
py::arg("end") = ::INVALID_TIMESTAMP,
py::arg("rated_metric") = false)
.def("get_metrics_list_numpy", &ParserClass::getMetricListAsNumpyArray,
"Returns a list of metrics as numpy arrays.",
py::arg("metric_names"),
py::arg("start") = ::INVALID_TIMESTAMP,
py::arg("end") = ::INVALID_TIMESTAMP,
py::arg("rated_metric") = false)
.def("get_metrics_list_numpy_matrix", &ParserClass::getMetricListAsNumpyMatrix,
"Returns a matrix of metrics.",
py::arg("metric_names"),
py::arg("start") = ::INVALID_TIMESTAMP,
py::arg("end") = ::INVALID_TIMESTAMP,
py::arg("rated_metric") = false,
py::arg("transpose") = false)
;
#ifdef VERSION_INFO
m.attr("__version__") = MACRO_STRINGIFY(VERSION_INFO);
#else
m.attr("__version__") = "dev";
#endif
} // PYBIND11_MODULE
| 12,428 | 3,758 |
/**
* Project Untitled
*/
#include "Stewart.h"
/**
* Stewart implementation
*/
/**
* @param boardingCard
* @return bool
*/
bool Stewart::checkBoardingCard(void boardingCard) {
return false;
}
/**
* @return void
*/
void Stewart::sellFood() {
return;
} | 273 | 96 |
/*
* Copyright 2020 McGraw-Hill Education. All rights reserved. No reproduction or distribution without the prior written consent of McGraw-Hill Education.
*/
#include "decoder.h"
#include "isa.h"
#include "state.h"
#include "uop.h"
using namespace lc3::core;
PIMicroOp IMicroOp::insert(PIMicroOp new_next)
{
if(next == nullptr) {
next = new_next;
} else {
PIMicroOp cur = next;
while(cur->next != nullptr) {
cur = cur->next;
}
cur->next = new_next;
}
return next;
}
std::string IMicroOp::regToString(uint16_t reg_id) const
{
if(reg_id < 8) {
return lc3::utils::ssprintf("R%d", reg_id);
} else {
return lc3::utils::ssprintf("T%d", reg_id - 8);
}
}
void FetchMicroOp::handleMicroOp(MachineState & state)
{
if(isAccessViolation(state.readPC(), state)) {
PIMicroOp msg = std::make_shared<PrintMessageMicroOp>("illegal memory access (ACV)");
std::pair<PIMicroOp, PIMicroOp> handle_exception_chain = buildSystemModeEnter(INTEX_TABLE_START, 0x2,
lc3::utils::getBits(state.readPSR(), 10, 8));
PIMicroOp callback = std::make_shared<CallbackMicroOp>(CallbackType::EX_ENTER);
PIMicroOp func_trace = std::make_shared<PushFuncTypeMicroOp>(FuncType::EXCEPTION);
msg->insert(handle_exception_chain.first);
handle_exception_chain.second->insert(callback);
callback->insert(func_trace);
next = msg;
} else {
uint16_t value = std::get<0>(state.readMem(state.readPC()));
state.writeIR(value);
}
}
std::string FetchMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("IR:0x%0.4hx <= M[0x%0.4hx]:0x%0.4hx", state.readIR(), state.readPC(),
std::get<0>(state.readMem(state.readPC())));
}
void DecodeMicroOp::handleMicroOp(MachineState & state)
{
lc3::optional<PIInstruction> inst = decoder.decode(state.readIR());
if(inst) {
insert((*inst)->buildMicroOps(state));
state.writeDecodedIR(*inst);
} else {
PIMicroOp msg = std::make_shared<PrintMessageMicroOp>("unknown opcode");
PIMicroOp dec_pc = std::make_shared<PCAddImmMicroOp>(-1);
std::pair<PIMicroOp, PIMicroOp> handle_exception_chain = buildSystemModeEnter(INTEX_TABLE_START, 0x1,
lc3::utils::getBits(state.readPSR(), 10, 8));
PIMicroOp callback = std::make_shared<CallbackMicroOp>(CallbackType::EX_ENTER);
PIMicroOp func_trace = std::make_shared<PushFuncTypeMicroOp>(FuncType::EXCEPTION);
msg->insert(dec_pc);
dec_pc->insert(handle_exception_chain.first);
handle_exception_chain.second->insert(callback);
callback->insert(func_trace);
next = msg;
}
}
std::string DecodeMicroOp::toString(MachineState const & state) const
{
lc3::optional<PIInstruction> inst = decoder.decode(state.readIR());
if(inst) {
(*inst)->buildMicroOps(state);
return lc3::utils::ssprintf("dIR <= %s", (*inst)->toValueString().c_str());
} else {
return "dIR <= Illegal instruction";
}
}
void PCWriteRegMicroOp::handleMicroOp(MachineState & state)
{
uint16_t value = state.readReg(reg_id);
state.writePC(value);
}
std::string PCWriteRegMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("PC:0x%0.4hx <= %s:0x%0.4hx", state.readPC(), regToString(reg_id).c_str(),
state.readReg(reg_id));
}
void PSRWriteRegMicroOp::handleMicroOp(MachineState & state)
{
uint16_t value = state.readReg(reg_id);
state.writePSR(value);
}
std::string PSRWriteRegMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("PSR:0x%0.4hx <= %s:0x%0.4hx", state.readPSR(), regToString(reg_id).c_str(),
state.readReg(reg_id));
}
void PCAddImmMicroOp::handleMicroOp(MachineState & state)
{
uint16_t value = state.readPC() + amnt;
state.writePC(value);
}
std::string PCAddImmMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("PC:0x%0.4hx <= (PC:0x%0.4hx + #%d):0x%0.4hx", state.readPC(), state.readPC(), amnt,
state.readPC() + amnt);
}
void RegWriteImmMicroOp::handleMicroOp(MachineState & state)
{
state.writeReg(reg_id, value);
}
std::string RegWriteImmMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= 0x%0.4hx", regToString(reg_id).c_str(), state.readReg(reg_id), value);
}
void RegWriteRegMicroOp::handleMicroOp(MachineState & state)
{
state.writeReg(dst_id, state.readReg(src_id));
}
std::string RegWriteRegMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= %s:0x%0.4hx", regToString(dst_id).c_str(), state.readReg(dst_id),
regToString(src_id).c_str(), state.readReg(src_id));
}
void RegWritePCMicroOp::handleMicroOp(MachineState & state)
{
state.writeReg(reg_id, state.readPC());
}
std::string RegWritePCMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= PC:0x%0.4hx", regToString(reg_id).c_str(), state.readReg(reg_id),
state.readPC());
}
void RegWritePSRMicroOp::handleMicroOp(MachineState & state)
{
state.writeReg(reg_id, state.readPSR());
}
std::string RegWritePSRMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= PSR:0x%0.4hx", regToString(reg_id).c_str(), state.readReg(reg_id),
state.readPSR());
}
void RegWriteSSPMicroOp::handleMicroOp(MachineState & state)
{
state.writeReg(reg_id, state.readSSP());
}
std::string RegWriteSSPMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= SSP:0x%0.4hx", regToString(reg_id).c_str(), state.readReg(reg_id),
state.readSSP());
}
void SSPWriteRegMicroOp::handleMicroOp(MachineState & state)
{
state.writeSSP(state.readReg(reg_id));
}
std::string SSPWriteRegMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("SSP:0x%0.4hx <= %s:0x%0.4hx", state.readSSP(), regToString(reg_id).c_str(),
state.readReg(reg_id));
}
void RegAddImmMicroOp::handleMicroOp(MachineState & state)
{
uint16_t value = state.readReg(src_id) + amnt;
state.writeReg(dst_id, value);
}
std::string RegAddImmMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= (%s:0x%0.4hx + #%d):0x%0.4hx", regToString(dst_id).c_str(),
state.readReg(dst_id), regToString(src_id).c_str(), state.readReg(src_id), amnt, state.readReg(src_id) + amnt);
}
void RegAddRegMicroOp::handleMicroOp(MachineState & state)
{
uint16_t value = state.readReg(src_id1) + state.readReg(src_id2);
state.writeReg(dst_id, value);
}
std::string RegAddRegMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= (%s:0x%0.4hx + %s:0x%0.4hx):0x%0.4hx", regToString(dst_id).c_str(),
state.readReg(dst_id), regToString(src_id1).c_str(), state.readReg(src_id1), regToString(src_id2).c_str(),
state.readReg(src_id2), state.readReg(src_id1) + state.readReg(src_id2));
}
void RegAndImmMicroOp::handleMicroOp(MachineState & state)
{
uint16_t value = state.readReg(src_id) & amnt;
state.writeReg(dst_id, value);
}
std::string RegAndImmMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= (%s:0x%0.4hx & #%d):0x%0.4hx", regToString(dst_id).c_str(),
state.readReg(dst_id), regToString(src_id).c_str(), state.readReg(src_id), amnt, state.readReg(src_id) & amnt);
}
void RegAndRegMicroOp::handleMicroOp(MachineState & state)
{
uint16_t value = state.readReg(src_id1) & state.readReg(src_id2);
state.writeReg(dst_id, value);
}
std::string RegAndRegMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= (%s:0x%0.4hx & %s:0x%0.4hx):0x%0.4hx", regToString(dst_id).c_str(),
state.readReg(dst_id), regToString(src_id1).c_str(), state.readReg(src_id1), regToString(src_id2).c_str(),
state.readReg(src_id2), state.readReg(src_id1) & state.readReg(src_id2));
}
void RegNotMicroOp::handleMicroOp(MachineState & state)
{
uint16_t value = ~state.readReg(src_id);
state.writeReg(dst_id, value);
}
std::string RegNotMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= (~%s:0x%0.4hx):0x%0.4hx", regToString(dst_id).c_str(),
state.readReg(dst_id), regToString(src_id).c_str(), state.readReg(src_id),
~state.readReg(src_id));
}
void MemReadMicroOp::handleMicroOp(MachineState & state)
{
uint16_t addr = state.readReg(addr_reg_id);
if(isAccessViolation(addr, state)) {
PIMicroOp msg = std::make_shared<PrintMessageMicroOp>("illegal memory access (ACV)");
PIMicroOp dec_pc = std::make_shared<PCAddImmMicroOp>(-1);
std::pair<PIMicroOp, PIMicroOp> handle_exception_chain = buildSystemModeEnter(INTEX_TABLE_START, 0x2,
lc3::utils::getBits(state.readPSR(), 10, 8));
PIMicroOp callback = std::make_shared<CallbackMicroOp>(CallbackType::EX_ENTER);
PIMicroOp func_trace = std::make_shared<PushFuncTypeMicroOp>(FuncType::EXCEPTION);
msg->insert(dec_pc);
dec_pc->insert(handle_exception_chain.first);
handle_exception_chain.second->insert(callback);
callback->insert(func_trace);
next = msg;
} else {
std::pair<uint16_t, PIMicroOp> read_result = state.readMem(addr);
uint16_t value = std::get<0>(read_result);
PIMicroOp op = std::get<1>(read_result);
if(op) {
insert(op);
}
state.writeReg(dst_id, value);
}
}
std::string MemReadMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("%s:0x%0.4hx <= MEM[%s:0x%0.4hx]:0x%0.4hx", regToString(dst_id).c_str(),
state.readReg(dst_id), regToString(addr_reg_id).c_str(), state.readReg(addr_reg_id),
std::get<0>(state.readMem(state.readReg(addr_reg_id))));
}
void MemWriteImmMicroOp::handleMicroOp(MachineState & state)
{
uint16_t addr = state.readReg(addr_reg_id);
if(isAccessViolation(addr, state)) {
PIMicroOp msg = std::make_shared<PrintMessageMicroOp>("illegal memory access (ACV)");
PIMicroOp dec_pc = std::make_shared<PCAddImmMicroOp>(-1);
std::pair<PIMicroOp, PIMicroOp> handle_exception_chain = buildSystemModeEnter(INTEX_TABLE_START, 0x2,
lc3::utils::getBits(state.readPSR(), 10, 8));
PIMicroOp callback = std::make_shared<CallbackMicroOp>(CallbackType::EX_ENTER);
PIMicroOp func_trace = std::make_shared<PushFuncTypeMicroOp>(FuncType::EXCEPTION);
msg->insert(dec_pc);
dec_pc->insert(handle_exception_chain.first);
handle_exception_chain.second->insert(callback);
callback->insert(func_trace);
next = msg;
} else {
PIMicroOp op = state.writeMem(addr, value);
if(op) {
insert(op);
}
}
}
std::string MemWriteImmMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("MEM[%s:0x%0.4hx]:0x%0.4hx <= 0x%0.4hx", regToString(addr_reg_id).c_str(),
state.readReg(addr_reg_id), std::get<0>(state.readMem(state.readReg(addr_reg_id))), value);
}
void MemWriteRegMicroOp::handleMicroOp(MachineState & state)
{
uint16_t addr = state.readReg(addr_reg_id);
if(isAccessViolation(addr, state)) {
PIMicroOp msg = std::make_shared<PrintMessageMicroOp>("illegal memory access (ACV)");
PIMicroOp dec_pc = std::make_shared<PCAddImmMicroOp>(-1);
std::pair<PIMicroOp, PIMicroOp> handle_exception_chain = buildSystemModeEnter(INTEX_TABLE_START, 0x2,
lc3::utils::getBits(state.readPSR(), 10, 8));
PIMicroOp callback = std::make_shared<CallbackMicroOp>(CallbackType::EX_ENTER);
PIMicroOp func_trace = std::make_shared<PushFuncTypeMicroOp>(FuncType::EXCEPTION);
msg->insert(dec_pc);
dec_pc->insert(handle_exception_chain.first);
handle_exception_chain.second->insert(callback);
callback->insert(func_trace);
next = msg;
} else {
PIMicroOp op = state.writeMem(addr, state.readReg(src_id));
if(op) {
insert(op);
}
}
}
std::string MemWriteRegMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("MEM[%s:0x%0.4hx]:0x%0.4hx <= %s:0x%0.4hx", regToString(addr_reg_id).c_str(),
state.readReg(addr_reg_id), std::get<0>(state.readMem(state.readReg(addr_reg_id))), regToString(src_id).c_str(),
state.readReg(src_id));
}
void CCUpdateRegMicroOp::handleMicroOp(MachineState & state)
{
uint16_t psr_value = state.readPSR();
char cc_char = getCCChar(state.readReg(reg_id));
if(cc_char == 'N') {
state.writePSR((psr_value & 0xFFF8) | 0x0004);
} else if(cc_char == 'Z') {
state.writePSR((psr_value & 0xFFF8) | 0x0002);
} else {
state.writePSR((psr_value & 0xFFF8) | 0x0001);
}
}
std::string CCUpdateRegMicroOp::toString(MachineState const & state) const
{
char cur_cc_char;
uint16_t psr_value = state.readPSR();
if((psr_value & 0x0004) != 0) {
cur_cc_char = 'N';
} else if((psr_value & 0x0002) != 0) {
cur_cc_char = 'Z';
} else {
cur_cc_char = 'P';
}
return lc3::utils::ssprintf("CC:%c <= ComputeCC(0x%0.4hx):%c", cur_cc_char, state.readReg(reg_id),
getCCChar(state.readReg(reg_id)));
}
char CCUpdateRegMicroOp::getCCChar(uint16_t value) const
{
if((value & 0x8000) != 0) {
return 'N';
} else if(value == 0) {
return 'Z';
} else {
return 'P';
}
}
void BranchMicroOp::handleMicroOp(MachineState & state)
{
bool result = pred(state);
if(result) {
next = true_next;
} else {
next = false_next;
}
}
std::string BranchMicroOp::toString(MachineState const & state) const
{
return lc3::utils::ssprintf("uBEN <= (%s):%s", msg.c_str(), pred(state) ? "true" : "false");
}
PIMicroOp BranchMicroOp::insert(PIMicroOp new_next)
{
if(true_next) { true_next->insert(new_next); }
if(false_next) { false_next->insert(new_next); }
return new_next;
}
void CallbackMicroOp::handleMicroOp(MachineState & state)
{
state.addPendingCallback(type);
}
std::string CallbackMicroOp::toString(MachineState const & state) const
{
(void) state;
return lc3::utils::ssprintf("callbacks <= %s", callbackTypeToString(type).c_str());
}
void PushInterruptTypeMicroOp::handleMicroOp(MachineState & state)
{
state.enqueueInterrupt(type);
}
std::string PushInterruptTypeMicroOp::toString(MachineState const & state) const
{
(void) state;
return lc3::utils::ssprintf("interrupts <= %s", interruptTypeToString(type).c_str());
}
void PopInterruptTypeMicroOp::handleMicroOp(MachineState & state)
{
state.dequeueInterrupt();
}
std::string PopInterruptTypeMicroOp::toString(MachineState const & state) const
{
(void) state;
return lc3::utils::ssprintf("interrupts <= interrupts.removeFront()");
}
void PushFuncTypeMicroOp::handleMicroOp(MachineState & state)
{
state.pushFuncTraceType(type);
}
std::string PushFuncTypeMicroOp::toString(MachineState const & state) const
{
(void) state;
return lc3::utils::ssprintf("traceStack <= %s", funcTypeToString(type).c_str());
}
void PopFuncTypeMicroOp::handleMicroOp(MachineState & state)
{
state.popFuncTraceType();
}
std::string PopFuncTypeMicroOp::toString(MachineState const & state) const
{
(void) state;
return lc3::utils::ssprintf("traceStack <= traceStack.removeTop()");
}
void PrintMessageMicroOp::handleMicroOp(MachineState & state)
{
(void) state;
}
std::string PrintMessageMicroOp::toString(MachineState const & state) const
{
(void) state;
return msg;
}
| 15,980 | 6,050 |
#include <cassert>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <memory>
#include <utility>
#include <map>
#include <unordered_map>
#include <functional>
#include <algorithm>
#include <chrono>
#include <sg14/fixed_point>
#include <EASTL/vector.h>
#include <EASTL/array.h>
using sg14::fixed_point;
using eastl::vector;
using eastl::array;
using namespace std::chrono;
#include "NativeBitmap.h"
#include "ETextures.h"
#include "IFileLoaderDelegate.h"
#include "NativeBitmap.h"
#include "Vec2i.h"
#include "IMapElement.h"
#include "CTeam.h"
#include "CItem.h"
#include "CStorageItem.h"
#include "CActor.h"
#include "CGameDelegate.h"
#include "MapWithCharKey.h"
#include "CMap.h"
#include "IRenderer.h"
#include "RasterizerCommon.h"
#include "IFileLoaderDelegate.h"
#include "CGame.h"
#include "CRenderer.h"
#include "LoadPNG.h"
#include "VisibilityStrategy.h"
namespace odb {
const static bool kShouldDrawOutline = false;
const static bool kShouldDrawTextures = true;
const static auto kMinZCull = FixP{1};
void CRenderer::projectAllVertices( uint8_t count ) {
const static FixP halfWidth{HALF_XRES};
const static FixP halfHeight{HALF_YRES};
const static FixP two{2};
for ( auto& vertex : mVertices ) {
if ( count-- == 0 ) {
return;
}
const FixP oneOver = divide( halfHeight, divide(vertex.first.mZ, two) );
vertex.second.mX = halfWidth + multiply(vertex.first.mX, oneOver);
vertex.second.mY = halfHeight - multiply(vertex.first.mY, oneOver);
}
}
void CRenderer::drawCubeAt(const Vec3& center, TexturePair texture) {
if (center.mZ <= kMinZCull) {
return;
}
const static FixP one{ 1 };
mVertices[ 0 ].first = ( center + Vec3{ -one, -one, -one });
mVertices[ 1 ].first = ( center + Vec3{ one, -one, -one });
mVertices[ 2 ].first = ( center + Vec3{ -one, one, -one });
mVertices[ 3 ].first = ( center + Vec3{ one, one, -one });
mVertices[ 4 ].first = ( center + Vec3{ -one, -one, one });
mVertices[ 5 ].first = ( center + Vec3{ one, -one, one });
mVertices[ 6 ].first = ( center + Vec3{ -one, one, one });
mVertices[ 7 ].first = ( center + Vec3{ one, one, one });
projectAllVertices(8);
const auto ulz0 = mVertices[0].second;
const auto urz0 = mVertices[1].second;
const auto llz0 = mVertices[2].second;
const auto lrz0 = mVertices[3].second;
const auto ulz1 = mVertices[4].second;
const auto urz1 = mVertices[5].second;
const auto llz1 = mVertices[6].second;
const auto lrz1 = mVertices[7].second;
if (static_cast<int>(center.mX) <= 0 ) {
drawWall( urz0.mX, urz1.mX,
urz0.mY, lrz0.mY,
urz1.mY, lrz1.mY,
texture.second, one);
}
if (static_cast<int>(center.mY) >= 0 ) {
drawFloor(ulz1.mY, urz0.mY,
ulz1.mX, urz1.mX,
ulz0.mX, urz0.mX,
texture.first);
}
if (static_cast<int>(center.mY) <= 0 ) {
drawFloor(llz1.mY, lrz0.mY,
llz1.mX, lrz1.mX,
llz0.mX, lrz0.mX,
texture.first);
}
if (static_cast<int>(center.mX) >= 0 ) {
drawWall(ulz1.mX, ulz0.mX,
ulz1.mY, llz1.mY,
urz0.mY, lrz0.mY,
texture.second, one);
}
drawWall( ulz0.mX, urz0.mX,
ulz0.mY, llz0.mY,
urz0.mY, lrz0.mY,
texture.second, one );
}
void CRenderer::drawBillboardAt(const Vec3 ¢er, std::shared_ptr<odb::NativeTexture> texture ) {
if (center.mZ <= kMinZCull) {
return;
}
const static FixP one{ 1 };
const static FixP two{ 2 };
const auto textureScale = one / two;
const auto scaledCenter = Vec3{ center.mX, multiply(center.mY, one), center.mZ };
mVertices[ 0 ].first = ( scaledCenter + Vec3{ -one, two, 0 });
mVertices[ 1 ].first = ( scaledCenter + Vec3{ one, two, 0 });
mVertices[ 2 ].first = ( scaledCenter + Vec3{ -one, 0, 0 });
mVertices[ 3 ].first = ( scaledCenter + Vec3{ one, 0, 0 });
projectAllVertices(4);
const auto ulz0 = mVertices[0].second;
const auto urz0 = mVertices[1].second;
const auto llz0 = mVertices[2].second;
const auto lrz0 = mVertices[3].second;
if (kShouldDrawTextures) {
drawFrontWall( ulz0.mX, ulz0.mY,
lrz0.mX, lrz0.mY,
texture, (textureScale * two), true );
}
if (kShouldDrawOutline) {
drawLine( ulz0, urz0 );
drawLine( ulz0, llz0 );
drawLine( urz0, lrz0 );
drawLine( llz0, lrz0 );
}
}
void CRenderer::drawColumnAt(const Vec3 ¢er, const FixP &scale, TexturePair texture, bool mask[3],bool enableAlpha) {
if (center.mZ <= kMinZCull) {
return;
}
const static FixP one{ 1 };
const static FixP two{ 2 };
const auto halfScale = scale;
const auto textureScale = halfScale / two;
const auto scaledCenter = Vec3{ center.mX, multiply(center.mY, one), center.mZ };
// |\4 /|5
// | \ center / |
// | \ * / |
// | \0__|__1/ |7
// |6 | | | /
// \ | X | /
// \ | | /
// \|2____3|/
mVertices[ 0 ].first = ( scaledCenter + Vec3{ -one, halfScale, -one });
mVertices[ 1 ].first = ( scaledCenter + Vec3{ one, halfScale, -one });
mVertices[ 2 ].first = ( scaledCenter + Vec3{ -one, -halfScale, -one });
mVertices[ 3 ].first = ( scaledCenter + Vec3{ one, -halfScale, -one });
mVertices[ 4 ].first = ( scaledCenter + Vec3{ -one, halfScale, one });
mVertices[ 5 ].first = ( scaledCenter + Vec3{ one, halfScale, one });
mVertices[ 6 ].first = ( scaledCenter + Vec3{ -one, -halfScale, one });
mVertices[ 7 ].first = ( scaledCenter + Vec3{ one, -halfScale, one });
projectAllVertices(8);
const auto ulz0 = mVertices[0].second;
const auto urz0 = mVertices[1].second;
const auto llz0 = mVertices[2].second;
const auto lrz0 = mVertices[3].second;
const auto ulz1 = mVertices[4].second;
const auto urz1 = mVertices[5].second;
const auto llz1 = mVertices[6].second;
const auto lrz1 = mVertices[7].second;
if (kShouldDrawTextures) {
if ( enableAlpha && mask[ 1 ] ) {
drawFrontWall( ulz1.mX, ulz1.mY,
lrz1.mX, lrz1.mY,
texture.first, (textureScale * two), enableAlpha );
}
if ( mask[0] && static_cast<int>(center.mX) < 0 ) {
drawWall( urz0.mX, urz1.mX,
urz0.mY, lrz0.mY,
urz1.mY, lrz1.mY,
texture.second, (textureScale * two));
}
if ( mask[2] && static_cast<int>(center.mX) > 0 ) {
drawWall(ulz1.mX, ulz0.mX,
ulz1.mY, llz1.mY,
urz0.mY, lrz0.mY,
texture.second, (textureScale * two));
}
if ( mask[ 1 ] ) {
drawFrontWall( ulz0.mX, ulz0.mY,
lrz0.mX, lrz0.mY,
texture.first, (textureScale * two), enableAlpha );
}
if ( mask[ 3 ] ) {
drawMask( ulz0.mX, ulz0.mY,
lrz0.mX, lrz0.mY);
}
}
if (kShouldDrawOutline) {
drawLine( ulz0, urz0 );
drawLine( ulz0, llz0 );
drawLine( urz0, lrz0 );
drawLine( llz0, lrz0 );
drawLine( ulz0, ulz1 );
drawLine( llz0, llz1 );
drawLine( ulz1, llz1 );
drawLine( urz0, urz1 );
drawLine( lrz0, lrz1 );
drawLine( urz1, lrz1 );
}
}
void CRenderer::drawFloorAt(const Vec3& center, TexturePair texture) {
if (center.mZ <= kMinZCull) {
return;
}
const static FixP one{ 1 };
mVertices[ 0 ].first = ( center + Vec3{ -one, 0, -one });
mVertices[ 1 ].first = ( center + Vec3{ one, 0, -one });
mVertices[ 2 ].first = ( center + Vec3{ -one, 0, one });
mVertices[ 3 ].first = ( center + Vec3{ one, 0, one });
projectAllVertices(4);
const auto llz0 = mVertices[0].second;
const auto lrz0 = mVertices[1].second;
const auto llz1 = mVertices[2].second;
const auto lrz1 = mVertices[3].second;
if ( kShouldDrawTextures && static_cast<int>(center.mY) <= 0 ) {
drawFloor(llz1.mY, lrz0.mY,
llz1.mX, lrz1.mX,
llz0.mX, lrz0.mX,
texture.first);
}
if ( kShouldDrawOutline) {
drawLine( llz0, lrz0 );
drawLine( llz0, llz1 );
drawLine( lrz0, lrz1 );
drawLine( llz1, lrz1 );
}
}
void CRenderer::drawCeilingAt(const Vec3& center, TexturePair texture) {
if (center.mZ <= kMinZCull) {
return;
}
const static FixP one{ 1 };
mVertices[ 0 ].first = ( center + Vec3{ -one, 0, -one });
mVertices[ 1 ].first = ( center + Vec3{ one, 0, -one });
mVertices[ 2 ].first = ( center + Vec3{ -one, 0, one });
mVertices[ 3 ].first = ( center + Vec3{ one, 0, one });
projectAllVertices(4);
const auto llz0 = mVertices[0].second;
const auto lrz0 = mVertices[1].second;
const auto llz1 = mVertices[2].second;
const auto lrz1 = mVertices[3].second;
if ( kShouldDrawTextures && static_cast<int>(center.mY) >= 0 ) {
drawFloor(llz1.mY, lrz0.mY,
llz1.mX, lrz1.mX,
llz0.mX, lrz0.mX,
texture.first);
}
if (kShouldDrawOutline) {
drawLine( llz0, lrz0 );
drawLine( llz0, llz1 );
drawLine( lrz0, lrz1 );
drawLine( llz1, lrz1 );
}
}
void CRenderer::drawLeftNear(const Vec3& center, const FixP &scale, std::shared_ptr<odb::NativeTexture> texture, bool mask[4]) {
if (center.mZ <= kMinZCull) {
return;
}
const static FixP one{ 1 };
const static FixP two{ 2 };
const auto halfScale = scale;
const auto textureScale = halfScale;
FixP depth{1};
if (mCameraDirection == Knights::EDirection::kWest || mCameraDirection == Knights::EDirection::kEast ) {
depth = FixP{-1};
}
mVertices[ 0 ].first = ( center + Vec3{ -one, halfScale, -depth });
mVertices[ 1 ].first = ( center + Vec3{ one, halfScale, depth });
mVertices[ 2 ].first = ( center + Vec3{ -one, -halfScale, -depth });
mVertices[ 3 ].first = ( center + Vec3{ one, -halfScale, depth });
projectAllVertices(4);
const auto ulz0 = mVertices[0].second;
const auto urz0 = mVertices[1].second;
const auto llz0 = mVertices[2].second;
const auto lrz0 = mVertices[3].second;
if (kShouldDrawTextures) {
drawWall( ulz0.mX, urz0.mX,
ulz0.mY, llz0.mY,
urz0.mY, lrz0.mY,
texture, textureScale );
if (mask[3]) {
mVertices[ 0 ].first = ( center + Vec3{ -one, -halfScale, -one });
mVertices[ 1 ].first = ( center + Vec3{ one, halfScale, -one });
projectAllVertices(2);
drawMask( mVertices[ 0 ].second.mX, mVertices[ 0 ].second.mY,
mVertices[ 1 ].second.mX, mVertices[ 1 ].second.mY);
}
}
if (kShouldDrawOutline){
drawLine( ulz0, urz0 );
drawLine( llz0, ulz0 );
drawLine( llz0, lrz0 );
drawLine( urz0, lrz0 );
}
}
void CRenderer::drawRightNear(const Vec3& center, const FixP &scale, std::shared_ptr<odb::NativeTexture> texture, bool mask[4]) {
if (center.mZ <= kMinZCull) {
return;
}
const static FixP one{ 1 };
const static FixP two{ 2 };
const auto halfScale = scale;
const auto textureScale = halfScale ;
FixP depth{1};
if (mCameraDirection == Knights::EDirection::kWest || mCameraDirection == Knights::EDirection::kEast ) {
depth = FixP{-1};
}
mVertices[ 0 ].first = ( center + Vec3{ -one, halfScale, depth });
mVertices[ 1 ].first = ( center + Vec3{ one, halfScale, -depth });
mVertices[ 2 ].first = ( center + Vec3{ -one, -halfScale, depth });
mVertices[ 3 ].first = ( center + Vec3{ one, -halfScale, -depth });
projectAllVertices(4);
const auto ulz0 = mVertices[0].second;
const auto urz0 = mVertices[1].second;
const auto llz0 = mVertices[2].second;
const auto lrz0 = mVertices[3].second;
if (kShouldDrawTextures) {
drawWall( ulz0.mX, urz0.mX,
ulz0.mY, llz0.mY,
urz0.mY, lrz0.mY,
texture, textureScale );
if (mask[3]) {
mVertices[ 0 ].first = ( center + Vec3{ -one, -halfScale, -one });
mVertices[ 1 ].first = ( center + Vec3{ one, halfScale, -one });
projectAllVertices(2);
drawMask( mVertices[ 0 ].second.mX, mVertices[ 0 ].second.mY,
mVertices[ 1 ].second.mX, mVertices[ 1 ].second.mY);
}
}
if (kShouldDrawOutline) {
drawLine( ulz0, urz0 );
drawLine( llz0, ulz0 );
drawLine( llz0, lrz0 );
drawLine( urz0, lrz0 );
}
}
void CRenderer::drawLine(const Vec2& p0, const Vec2& p1) {
drawLine(static_cast<int16_t >(p0.mX),
static_cast<int16_t >(p0.mY),
static_cast<int16_t >(p1.mX),
static_cast<int16_t >(p1.mY)
);
}
}
| 14,755 | 5,238 |
// Copyright 2017 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 <stdlib.h>
#include "src/v8.h"
#include "src/heap/concurrent-marking.h"
#include "src/heap/heap-inl.h"
#include "src/heap/heap.h"
#include "src/heap/mark-compact.h"
#include "src/heap/worklist.h"
#include "test/cctest/cctest.h"
#include "test/cctest/heap/heap-utils.h"
namespace v8 {
namespace internal {
namespace heap {
void PublishSegment(ConcurrentMarking::MarkingWorklist* worklist,
HeapObject* object) {
for (size_t i = 0; i <= ConcurrentMarking::MarkingWorklist::kSegmentCapacity;
i++) {
worklist->Push(0, object);
}
CHECK(worklist->Pop(0, &object));
}
TEST(ConcurrentMarking) {
if (!i::FLAG_concurrent_marking) return;
CcTest::InitializeVM();
Heap* heap = CcTest::heap();
CcTest::CollectAllGarbage();
if (!heap->incremental_marking()->IsStopped()) return;
MarkCompactCollector* collector = CcTest::heap()->mark_compact_collector();
if (collector->sweeping_in_progress()) {
collector->EnsureSweepingCompleted();
}
ConcurrentMarking::MarkingWorklist shared, bailout, on_hold;
WeakObjects weak_objects;
ConcurrentMarking* concurrent_marking =
new ConcurrentMarking(heap, &shared, &bailout, &on_hold, &weak_objects);
PublishSegment(&shared, ReadOnlyRoots(heap).undefined_value());
concurrent_marking->ScheduleTasks();
concurrent_marking->Stop(
ConcurrentMarking::StopRequest::COMPLETE_TASKS_FOR_TESTING);
delete concurrent_marking;
}
TEST(ConcurrentMarkingReschedule) {
if (!i::FLAG_concurrent_marking) return;
CcTest::InitializeVM();
Heap* heap = CcTest::heap();
CcTest::CollectAllGarbage();
if (!heap->incremental_marking()->IsStopped()) return;
MarkCompactCollector* collector = CcTest::heap()->mark_compact_collector();
if (collector->sweeping_in_progress()) {
collector->EnsureSweepingCompleted();
}
ConcurrentMarking::MarkingWorklist shared, bailout, on_hold;
WeakObjects weak_objects;
ConcurrentMarking* concurrent_marking =
new ConcurrentMarking(heap, &shared, &bailout, &on_hold, &weak_objects);
PublishSegment(&shared, ReadOnlyRoots(heap).undefined_value());
concurrent_marking->ScheduleTasks();
concurrent_marking->Stop(
ConcurrentMarking::StopRequest::COMPLETE_ONGOING_TASKS);
PublishSegment(&shared, ReadOnlyRoots(heap).undefined_value());
concurrent_marking->RescheduleTasksIfNeeded();
concurrent_marking->Stop(
ConcurrentMarking::StopRequest::COMPLETE_TASKS_FOR_TESTING);
delete concurrent_marking;
}
TEST(ConcurrentMarkingPreemptAndReschedule) {
if (!i::FLAG_concurrent_marking) return;
CcTest::InitializeVM();
Heap* heap = CcTest::heap();
CcTest::CollectAllGarbage();
if (!heap->incremental_marking()->IsStopped()) return;
MarkCompactCollector* collector = CcTest::heap()->mark_compact_collector();
if (collector->sweeping_in_progress()) {
collector->EnsureSweepingCompleted();
}
ConcurrentMarking::MarkingWorklist shared, bailout, on_hold;
WeakObjects weak_objects;
ConcurrentMarking* concurrent_marking =
new ConcurrentMarking(heap, &shared, &bailout, &on_hold, &weak_objects);
for (int i = 0; i < 5000; i++)
PublishSegment(&shared, ReadOnlyRoots(heap).undefined_value());
concurrent_marking->ScheduleTasks();
concurrent_marking->Stop(ConcurrentMarking::StopRequest::PREEMPT_TASKS);
for (int i = 0; i < 5000; i++)
PublishSegment(&shared, ReadOnlyRoots(heap).undefined_value());
concurrent_marking->RescheduleTasksIfNeeded();
concurrent_marking->Stop(
ConcurrentMarking::StopRequest::COMPLETE_TASKS_FOR_TESTING);
delete concurrent_marking;
}
TEST(ConcurrentMarkingMarkedBytes) {
if (!i::FLAG_concurrent_marking) return;
CcTest::InitializeVM();
Isolate* isolate = CcTest::i_isolate();
Heap* heap = CcTest::heap();
HandleScope sc(isolate);
Handle<FixedArray> root = isolate->factory()->NewFixedArray(1000000);
CcTest::CollectAllGarbage();
if (!heap->incremental_marking()->IsStopped()) return;
heap::SimulateIncrementalMarking(heap, false);
heap->concurrent_marking()->Stop(
ConcurrentMarking::StopRequest::COMPLETE_TASKS_FOR_TESTING);
CHECK_GE(heap->concurrent_marking()->TotalMarkedBytes(), root->Size());
}
UNINITIALIZED_TEST(ConcurrentMarkingStoppedOnTeardown) {
if (!i::FLAG_concurrent_marking) return;
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
v8::Isolate* isolate = v8::Isolate::New(create_params);
{
Isolate* i_isolate = reinterpret_cast<Isolate*>(isolate);
Factory* factory = i_isolate->factory();
v8::Isolate::Scope isolate_scope(isolate);
v8::HandleScope handle_scope(isolate);
v8::Context::New(isolate)->Enter();
for (int i = 0; i < 10000; i++) {
factory->NewJSWeakMap();
}
Heap* heap = i_isolate->heap();
heap::SimulateIncrementalMarking(heap, false);
}
isolate->Dispose();
}
} // namespace heap
} // namespace internal
} // namespace v8
| 5,127 | 1,820 |