<commit_before>//
// TODO:
// - testy danych - te z kontynuacją wyłączalne w konf.
//		- dorobić dla tabfaktura
// - dialog do edycji stawek vat
// - drukowanie przez printjob
// - wpisanie nieistniejącego kontr/towaru na fakture -> uaktualnienie bazy
//		(kontrola w tabfaktura)
// - layout w tabach: setdivider na maksimum z kolumny zamiast sztywno
// - dialog konfiguracji wydruku (liczba kopii, tekst/grafika/?)
// - usunąć duplikat execSQL()
// - prawdziwe validateDate
// - nrfaktury (ostatniej) - wyrzucić z konfiguracji? działa bez tego
// - pole 'uwagi' w towar/faktura nie reaguje na zmiany
// - guzik kalendarza
// - guzik importu
// - DECROUND zaimplementować jako hook i userfunction, nie jako patch na sqlite
// - dummy menu ze statystykami
// - trzymanie stanu magazynu, info magazynowe
// - na koniec - usunac printfy z debugiem
// - przy włączonej optymalizacji dialAbout ma segfault
// zmiana curtab i przełączanie jest brzydkie, może cały beFakTab powinien
// dziedziczyć z btab?

#include "mainwindow.h"
#include "dialabout.h"
#include "dialfirma.h"
#include "sqlschema.h"
#include "tabfirma.h"
#include "tabtowar.h"
#include "tabfaktura.h"

#include <Alert.h>
#include <Application.h>
#include <File.h>
#include <View.h>
#include <Menu.h>
#include <MenuBar.h>
#include <MenuItem.h>
#include <TabView.h>

#include <stdio.h>

const uint32 MENU_PRINTO	= 'MPOR';
const uint32 MENU_PRINTC	= 'MPKO';
const uint32 MENU_PRINTD	= 'MPKD';
const uint32 MENU_CONFFIRMA	= 'MKOF';
const uint32 MENU_CONFVAT	= 'MKOV';
const uint32 MENU_PRINTT80	= 'MPT8';
const uint32 MENU_PRINTT136 = 'MPT1';
const uint32 MENU_PRINTHTML = 'MPHT';
const uint32 MENU_ABOUT		= 'MABO';

BeFAKMainWindow::BeFAKMainWindow(const char *windowTitle) : BWindow(
	BRect(100, 100, 900, 700), windowTitle, B_DOCUMENT_WINDOW, B_OUTLINE_RESIZE, B_CURRENT_WORKSPACE ) {

	BView *mainView = new BView(this->Bounds(), "mainView", B_FOLLOW_ALL_SIDES, 0);

	if (mainView == NULL) {
		AppReturnValue = B_NO_MEMORY;
		be_app->PostMessage(B_QUIT_REQUESTED);
		return;
	}

	mainView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
	this->AddChild(mainView);

	BRect r;
	r = mainView->Bounds();
	r.bottom = 20;
	menuBar = new BMenuBar(r, "menuBar");
	mainView->AddChild(menuBar);

	menu = new BMenu("Plik", B_ITEMS_IN_COLUMN);
	menu->AddItem(new BMenuItem("Zamknij", new BMessage(B_QUIT_REQUESTED), 'Q'));
	menuBar->AddItem(menu);

	menu = new BMenu("Dokument", B_ITEMS_IN_COLUMN);
	menu->AddItem(pmenuo = new BMenuItem("Oryginał", new BMessage(MENU_PRINTO)));
	menu->AddItem(pmenuc = new BMenuItem("Kopia", new BMessage(MENU_PRINTC)));
	menu->AddItem(pmenud = new BMenuItem("Duplikat", new BMessage(MENU_PRINTD)));
	menuBar->AddItem(menu);

	menu = new BMenu("Opcje", B_ITEMS_IN_COLUMN);
	menu->AddItem(new BMenuItem("Dane firmy", new BMessage(MENU_CONFFIRMA)));
	BMenu *printmenu = new BMenu("Rodzaj wydruku", B_ITEMS_IN_COLUMN);
	menu->AddItem(printmenu);
	menu->AddItem(new BMenuItem("Stawki VAT", new BMessage(MENU_CONFVAT)));
	menuBar->AddItem(menu);

	printmenu->AddItem(pmenut80  = new BMenuItem("Tekst (80 kol.)", new BMessage(MENU_PRINTT80)));
	printmenu->AddItem(pmenut136 = new BMenuItem("Tekst (136 kol.)", new BMessage(MENU_PRINTT136)));
	printmenu->AddItem(pmenuhtml = new BMenuItem("HTML", new BMessage(MENU_PRINTHTML)));

	menu = new BMenu("Pomoc", B_ITEMS_IN_COLUMN);
	menu->AddItem(new BMenuItem("O programie", new BMessage(MENU_ABOUT)));
	menuBar->AddItem(menu);

	// tabview
	r = mainView->Bounds();
	r.top = 20;
	tabView = new BTabView(r, "tabView");
	mainView->AddChild(tabView);

	// initialize database
	int ret = OpenDatabase();
	if (ret < 0)
		exit(1);

	// check if configuration is there
	DoCheckConfig();
	// initialize datawidgets
	initTabs(tabView);
	tabView->Select(0);
	curTab = tabs[0];
	updateMenus();	// sends PRINTCONF message - initial config is passed down
}

BeFAKMainWindow::~BeFAKMainWindow() {
	CloseDatabase();
}

void BeFAKMainWindow::initTabs(BTabView *tv) {
	tabs[0] = new tabFaktura(tv, dbData, this);
	tabs[1] = new tabTowar(tv, dbData, this);
	tabs[2] = new tabFirma(tv, dbData, this);
}

void BeFAKMainWindow::DoAbout(void) {
	aboutDialog = new dialAbout(APP_NAME "  " APP_VERSION);
}

void BeFAKMainWindow::DoConfigFirma(bool cancancel) {
	firmaDialog = new dialFirma(APP_NAME, dbData, cancancel);
}

void BeFAKMainWindow::DoConfigVAT(void) {
	// XXX a new db dialog here
	BAlert *vatalert = new BAlert(APP_NAME, "Tutaj dialog do edycji stawek VAT", "OK", NULL, NULL, B_WIDTH_AS_USUAL, B_INFO_ALERT);
	vatalert->Go();
}

void BeFAKMainWindow::DoCheckConfig(void) {
	int nRows, nCols;
	char **result;
	BString sql;
	// select NAZWA and all config data
	sql = "SELECT nazwa, liczbakopii, ostatni_nr, num_prosta FROM konfiguracja WHERE zrobiona = 1";
//printf("sql:%s\n",sql.String());
	sqlite_get_table(dbData, sql.String(), &result, &nRows, &nCols, &dbErrMsg);
//printf ("got:%ix%i\n", nRows, nCols);
	if (nRows < 1) {
		DoConfigFirma(false);	// should never happen
	} else {
		int i = nCols;
		sql = result[i++];	// test for 'nazwa' not ""
		if (sql.Length() == 0)
			DoConfigFirma(false);
		// read other config data from result
		liczbakopii = toint(result[i++]);
		ostatni_nr = toint(result[i++]);
//		printf("ostatninr = %i\n",ostatni_nr);
		num_prosta = toint(result[i++]);
	}
	/// XXX store these in config?
	ptyp = 0;
	pmode = 1;
	pwide = 0;
}

void BeFAKMainWindow::updateMenus(void) {
	pmenuo->SetMarked(ptyp == 0);
	pmenuc->SetMarked(ptyp == 1);
	pmenud->SetMarked(ptyp == 2);
	pmenut80->SetMarked( (pmode==1) && (pwide==0) );
	pmenut136->SetMarked( (pmode==1) && (pwide==1) );
	pmenuhtml->SetMarked(pmode == 2);
	BMessage *msg;
	msg = new BMessage(MSG_PRINTCONF);
	msg->AddInt32("_ptyp", ptyp);
	msg->AddInt32("_pmode", pmode);
	msg->AddInt32("_pwide", pwide);
	if (curTab!=NULL)
		curTab->MessageReceived(msg);
// needed?
	delete msg;
}

void BeFAKMainWindow::MessageReceived(BMessage *Message) {
	BString title;
	const char *tmp;

	this->DisableUpdates();
	switch (Message->what) {
		case MENU_PRINTO:
			ptyp = 0;
			updateMenus();
			break;
		case MENU_PRINTC:
			ptyp = 1;
			updateMenus();
			break;
		case MENU_PRINTD:
			ptyp = 2;
			updateMenus();
			break;
		case MENU_PRINTT80:
			pmode = 1;
			pwide = 0;
			updateMenus();
			break;
		case MENU_PRINTT136:
			pmode = 1;
			pwide = 1;
			updateMenus();
			break;
		case MENU_PRINTHTML:
			pmode = 2;
			updateMenus();
			break;
		case MENU_ABOUT:
			DoAbout();
			break;
		case MENU_CONFFIRMA:
			DoConfigFirma();
			break;
		case MENU_CONFVAT:
			DoConfigVAT();
			break;
		case MSG_NAMECHANGE:
			if (Message->FindString("_newtitle", &tmp) == B_OK) {
				title = APP_NAME; title += " : "; title += tmp;
				this->SetTitle(title.String());
			}
			break;
		case MSG_REQFIRMAUP:
		case MSG_REQTOWARUP:
			// XXX tab 0 is faktura, make it defined constant
			tabs[0]->MessageReceived(Message);
			break;
		default:
			curTab = tabs[tabView->Selection()];
			curTab->MessageReceived(Message);
			BWindow::MessageReceived(Message);
			break;
	}
	this->EnableUpdates();
}

bool BeFAKMainWindow::QuitRequested() {
//	config->position = this->Frame();
//	config->save();
	curTab->CommitCurdata(false);
	be_app->PostMessage(B_QUIT_REQUESTED);
	return BWindow::QuitRequested();
}

//--------------------
// database stuff, abstract it?

int BeFAKMainWindow::OpenDatabase(void) {
	// BFile test wouldn't be necessary if sqlite_open retured file not found
	// error as advertised
	BFile fData;
	int fResult = fData.SetTo(DATABASE_PATHNAME, B_READ_ONLY);
	// open database anyway - new or existing
	dbData = sqlite_open(DATABASE_PATHNAME, 0666, &dbErrMsg);
	if ((dbData==0)||(dbErrMsg!=0)) {
		// due to sqlite problems - this code is never reached; pity
//		printf("database not found\n");
		return -1;
	}
	if (fResult != B_OK) {
		// file wasn't there - new database has been created
		// populate it with schema and default configuration
		InitDatabase();
	}
	// if VACUUM fails on DB there is another error, we can't handle it
	return sqlite_exec(dbData, "VACUUM", 0, 0, &dbErrMsg);
}

void BeFAKMainWindow::CloseDatabase(void) {
	sqlite_exec(dbData, "VACUUM", 0, 0, &dbErrMsg);
	sqlite_close(dbData);
}

void BeFAKMainWindow::InitDatabase(void) {
//	printf("new database, fill with schema\n");
	sqlite_exec(dbData, sql_schema, 0, 0, &dbErrMsg);
}
<commit_msg>- updated todo<commit_after>//
// TODO:
// - testy danych - te z kontynuacją wyłączalne w konf.
//		- dorobić dla tabfaktura
// - dialog do edycji stawek vat
// - drukowanie przez printjob
// - wpisanie nieistniejącego kontr/towaru na fakture -> uaktualnienie bazy
//		(kontrola w tabfaktura)
// - layout w tabach: setdivider na maksimum z kolumny zamiast sztywno
// - dialog konfiguracji wydruku (liczba kopii, tekst/grafika/?)
// - usunąć duplikat execSQL()
// - prawdziwe validateDate
// - nrfaktury (ostatniej) - wyrzucić z konfiguracji? działa bez tego
// - numeracja uproszczona - konfig/menu? uzywac? (wtedy bez miesiaca)
// - pole 'uwagi' w towar/faktura nie reaguje na zmiany
// - guzik kalendarza
// - guzik importu
// - DECROUND zaimplementować jako hook i userfunction, nie jako patch na sqlite
// - dummy menu ze statystykami
// - trzymanie stanu magazynu, info magazynowe
// - na koniec - usunac printfy z debugiem
// - przy włączonej optymalizacji dialAbout ma segfault
// zmiana curtab i przełączanie jest brzydkie, może cały beFakTab powinien
// dziedziczyć z btab?

#include "mainwindow.h"
#include "dialabout.h"
#include "dialfirma.h"
#include "sqlschema.h"
#include "tabfirma.h"
#include "tabtowar.h"
#include "tabfaktura.h"

#include <Alert.h>
#include <Application.h>
#include <File.h>
#include <View.h>
#include <Menu.h>
#include <MenuBar.h>
#include <MenuItem.h>
#include <TabView.h>

#include <stdio.h>

const uint32 MENU_PRINTO	= 'MPOR';
const uint32 MENU_PRINTC	= 'MPKO';
const uint32 MENU_PRINTD	= 'MPKD';
const uint32 MENU_CONFFIRMA	= 'MKOF';
const uint32 MENU_CONFVAT	= 'MKOV';
const uint32 MENU_PRINTT80	= 'MPT8';
const uint32 MENU_PRINTT136 = 'MPT1';
const uint32 MENU_PRINTHTML = 'MPHT';
const uint32 MENU_ABOUT		= 'MABO';

BeFAKMainWindow::BeFAKMainWindow(const char *windowTitle) : BWindow(
	BRect(100, 100, 900, 700), windowTitle, B_DOCUMENT_WINDOW, B_OUTLINE_RESIZE, B_CURRENT_WORKSPACE ) {

	BView *mainView = new BView(this->Bounds(), "mainView", B_FOLLOW_ALL_SIDES, 0);

	if (mainView == NULL) {
		AppReturnValue = B_NO_MEMORY;
		be_app->PostMessage(B_QUIT_REQUESTED);
		return;
	}

	mainView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
	this->AddChild(mainView);

	BRect r;
	r = mainView->Bounds();
	r.bottom = 20;
	menuBar = new BMenuBar(r, "menuBar");
	mainView->AddChild(menuBar);

	menu = new BMenu("Plik", B_ITEMS_IN_COLUMN);
	menu->AddItem(new BMenuItem("Zamknij", new BMessage(B_QUIT_REQUESTED), 'Q'));
	menuBar->AddItem(menu);

	menu = new BMenu("Dokument", B_ITEMS_IN_COLUMN);
	menu->AddItem(pmenuo = new BMenuItem("Oryginał", new BMessage(MENU_PRINTO)));
	menu->AddItem(pmenuc = new BMenuItem("Kopia", new BMessage(MENU_PRINTC)));
	menu->AddItem(pmenud = new BMenuItem("Duplikat", new BMessage(MENU_PRINTD)));
	menuBar->AddItem(menu);

	menu = new BMenu("Opcje", B_ITEMS_IN_COLUMN);
	menu->AddItem(new BMenuItem("Dane firmy", new BMessage(MENU_CONFFIRMA)));
	BMenu *printmenu = new BMenu("Rodzaj wydruku", B_ITEMS_IN_COLUMN);
	menu->AddItem(printmenu);
	menu->AddItem(new BMenuItem("Stawki VAT", new BMessage(MENU_CONFVAT)));
	menuBar->AddItem(menu);

	printmenu->AddItem(pmenut80  = new BMenuItem("Tekst (80 kol.)", new BMessage(MENU_PRINTT80)));
	printmenu->AddItem(pmenut136 = new BMenuItem("Tekst (136 kol.)", new BMessage(MENU_PRINTT136)));
	printmenu->AddItem(pmenuhtml = new BMenuItem("HTML", new BMessage(MENU_PRINTHTML)));

	menu = new BMenu("Pomoc", B_ITEMS_IN_COLUMN);
	menu->AddItem(new BMenuItem("O programie", new BMessage(MENU_ABOUT)));
	menuBar->AddItem(menu);

	// tabview
	r = mainView->Bounds();
	r.top = 20;
	tabView = new BTabView(r, "tabView");
	mainView->AddChild(tabView);

	// initialize database
	int ret = OpenDatabase();
	if (ret < 0)
		exit(1);

	// check if configuration is there
	DoCheckConfig();
	// initialize datawidgets
	initTabs(tabView);
	tabView->Select(0);
	curTab = tabs[0];
	updateMenus();	// sends PRINTCONF message - initial config is passed down
}

BeFAKMainWindow::~BeFAKMainWindow() {
	CloseDatabase();
}

void BeFAKMainWindow::initTabs(BTabView *tv) {
	tabs[0] = new tabFaktura(tv, dbData, this);
	tabs[1] = new tabTowar(tv, dbData, this);
	tabs[2] = new tabFirma(tv, dbData, this);
}

void BeFAKMainWindow::DoAbout(void) {
	aboutDialog = new dialAbout(APP_NAME "  " APP_VERSION);
}

void BeFAKMainWindow::DoConfigFirma(bool cancancel) {
	firmaDialog = new dialFirma(APP_NAME, dbData, cancancel);
}

void BeFAKMainWindow::DoConfigVAT(void) {
	// XXX a new db dialog here
	BAlert *vatalert = new BAlert(APP_NAME, "Tutaj dialog do edycji stawek VAT", "OK", NULL, NULL, B_WIDTH_AS_USUAL, B_INFO_ALERT);
	vatalert->Go();
}

void BeFAKMainWindow::DoCheckConfig(void) {
	int nRows, nCols;
	char **result;
	BString sql;
	// select NAZWA and all config data
	sql = "SELECT nazwa, liczbakopii, ostatni_nr, num_prosta FROM konfiguracja WHERE zrobiona = 1";
//printf("sql:%s\n",sql.String());
	sqlite_get_table(dbData, sql.String(), &result, &nRows, &nCols, &dbErrMsg);
//printf ("got:%ix%i\n", nRows, nCols);
	if (nRows < 1) {
		DoConfigFirma(false);	// should never happen
	} else {
		int i = nCols;
		sql = result[i++];	// test for 'nazwa' not ""
		if (sql.Length() == 0)
			DoConfigFirma(false);
		// read other config data from result
		liczbakopii = toint(result[i++]);
		ostatni_nr = toint(result[i++]);
//		printf("ostatninr = %i\n",ostatni_nr);
		num_prosta = toint(result[i++]);
	}
	/// XXX store these in config?
	ptyp = 0;
	pmode = 1;
	pwide = 0;
}

void BeFAKMainWindow::updateMenus(void) {
	pmenuo->SetMarked(ptyp == 0);
	pmenuc->SetMarked(ptyp == 1);
	pmenud->SetMarked(ptyp == 2);
	pmenut80->SetMarked( (pmode==1) && (pwide==0) );
	pmenut136->SetMarked( (pmode==1) && (pwide==1) );
	pmenuhtml->SetMarked(pmode == 2);
	BMessage *msg;
	msg = new BMessage(MSG_PRINTCONF);
	msg->AddInt32("_ptyp", ptyp);
	msg->AddInt32("_pmode", pmode);
	msg->AddInt32("_pwide", pwide);
	if (curTab!=NULL)
		curTab->MessageReceived(msg);
// needed?
	delete msg;
}

void BeFAKMainWindow::MessageReceived(BMessage *Message) {
	BString title;
	const char *tmp;

	this->DisableUpdates();
	switch (Message->what) {
		case MENU_PRINTO:
			ptyp = 0;
			updateMenus();
			break;
		case MENU_PRINTC:
			ptyp = 1;
			updateMenus();
			break;
		case MENU_PRINTD:
			ptyp = 2;
			updateMenus();
			break;
		case MENU_PRINTT80:
			pmode = 1;
			pwide = 0;
			updateMenus();
			break;
		case MENU_PRINTT136:
			pmode = 1;
			pwide = 1;
			updateMenus();
			break;
		case MENU_PRINTHTML:
			pmode = 2;
			updateMenus();
			break;
		case MENU_ABOUT:
			DoAbout();
			break;
		case MENU_CONFFIRMA:
			DoConfigFirma();
			break;
		case MENU_CONFVAT:
			DoConfigVAT();
			break;
		case MSG_NAMECHANGE:
			if (Message->FindString("_newtitle", &tmp) == B_OK) {
				title = APP_NAME; title += " : "; title += tmp;
				this->SetTitle(title.String());
			}
			break;
		case MSG_REQFIRMAUP:
		case MSG_REQTOWARUP:
			// XXX tab 0 is faktura, make it defined constant
			tabs[0]->MessageReceived(Message);
			break;
		default:
			curTab = tabs[tabView->Selection()];
			curTab->MessageReceived(Message);
			BWindow::MessageReceived(Message);
			break;
	}
	this->EnableUpdates();
}

bool BeFAKMainWindow::QuitRequested() {
//	config->position = this->Frame();
//	config->save();
	curTab->CommitCurdata(false);
	be_app->PostMessage(B_QUIT_REQUESTED);
	return BWindow::QuitRequested();
}

//--------------------
// database stuff, abstract it?

int BeFAKMainWindow::OpenDatabase(void) {
	// BFile test wouldn't be necessary if sqlite_open retured file not found
	// error as advertised
	BFile fData;
	int fResult = fData.SetTo(DATABASE_PATHNAME, B_READ_ONLY);
	// open database anyway - new or existing
	dbData = sqlite_open(DATABASE_PATHNAME, 0666, &dbErrMsg);
	if ((dbData==0)||(dbErrMsg!=0)) {
		// due to sqlite problems - this code is never reached; pity
//		printf("database not found\n");
		return -1;
	}
	if (fResult != B_OK) {
		// file wasn't there - new database has been created
		// populate it with schema and default configuration
		InitDatabase();
	}
	// if VACUUM fails on DB there is another error, we can't handle it
	return sqlite_exec(dbData, "VACUUM", 0, 0, &dbErrMsg);
}

void BeFAKMainWindow::CloseDatabase(void) {
	sqlite_exec(dbData, "VACUUM", 0, 0, &dbErrMsg);
	sqlite_close(dbData);
}

void BeFAKMainWindow::InitDatabase(void) {
//	printf("new database, fill with schema\n");
	sqlite_exec(dbData, sql_schema, 0, 0, &dbErrMsg);
}
<|endoftext|>


<commit_before>#include "UASQuickViewTextLabel.h"
#include <QDebug>
UASQuickViewTextLabel::UASQuickViewTextLabel(QWidget *parent) : QLabel(parent)
{
    m_styleSheetString = "UASQuickViewTextLabel{color:%1;font:%2;}";
}
void UASQuickViewTextLabel::setFontColor(QColor color)
{
    m_fontColor = color;
    this->setStyleSheet(m_styleSheetString.arg(m_fontColor.name(),QString::number(m_fontSize) + "px"));
    qDebug() << "Stylesheet:" << m_styleSheetString.arg(m_fontColor.name(),QString::number(m_fontSize) + "px");
}

void UASQuickViewTextLabel::setFontSize(int pixelsize)
{
    m_fontSize = pixelsize;
    this->setStyleSheet(m_styleSheetString.arg(m_fontColor.name(),QString::number(m_fontSize) + "px"));
}
<commit_msg>Removed extra debug output<commit_after>#include "UASQuickViewTextLabel.h"
#include <QDebug>
UASQuickViewTextLabel::UASQuickViewTextLabel(QWidget *parent) : QLabel(parent)
{
    m_styleSheetString = "UASQuickViewTextLabel{color:%1;font:%2;}";
}
void UASQuickViewTextLabel::setFontColor(QColor color)
{
    m_fontColor = color;
    this->setStyleSheet(m_styleSheetString.arg(m_fontColor.name(),QString::number(m_fontSize) + "px"));
}

void UASQuickViewTextLabel::setFontSize(int pixelsize)
{
    m_fontSize = pixelsize;
    this->setStyleSheet(m_styleSheetString.arg(m_fontColor.name(),QString::number(m_fontSize) + "px"));
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/attn/common/attnbits.C $                         */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2014,2016                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 * @file attnbits.C
 *
 * @brief HBATTN register addresses, bits of interest.
 */

#include "common/attnfwd.H"
#include "common/attnbits.H"

using namespace PRDF;
using namespace std;

namespace ATTN
{

/**
 * @brief RegAssoc Associate register data with a key.
 *
 * Typically used to associate an attention type or MCS position
 * with register addresses or masks.
 */
struct RegAssoc
{
    uint64_t key;

    uint64_t data;
};

bool getCheckbits(
        const RegAssoc * i_first,
        const RegAssoc * i_last,
        uint64_t i_key,
        uint64_t & o_bits)
{
    while(i_first != i_last)
    {
        if(i_first->key == i_key)
        {
            o_bits = i_first->data;
            break;
        }

        ++i_first;
    }

    return i_first != i_last;
}

void forEach(
        const RegAssoc * i_first,
        const RegAssoc * i_last,
        uint64_t i_scomData,
        void * i_data,
        void (*i_func)(uint64_t, void *))
{
    while(i_first != i_last)
    {
        if(i_first->data & i_scomData)
        {
            (*i_func)(i_first->key, i_data);
        }

        ++i_first;
    }
}

namespace IPOLL
{

const uint64_t address = IPOLL_MASK_REG;

// NOTE: This reg should get flushed to zeroes.
//       Hence, the 'routing to host' and
//       'routing to FSP' should be enabled.
//      (along with all interrupt types to FSP)
//  ---------------------------------------------
//    {ROUTE_TO_HOST,    0x0400000000000000ull},
//
//    {TOSP_CHECK_STOP,  0x0200000000000000ull},
//    {TOSP_RECOVERABLE, 0x0100000000000000ull},
//    {TOSP_SPECIAL,     0x0080000000000000ull},
//    {TOSP_UNIT_CS,     0x0040000000000000ull},
//    {TOSP_HOST,        0x0020000000000000ull},
//    {ROUTE_TO_SP,      0x0010000000000000ull},
//  ---------------------------------------------

void getCheckbitsAssociations(
        const RegAssoc * & o_first,
        const RegAssoc * & o_last)
{
    static const RegAssoc first[] = {

        {CHECK_STOP,  0x8000000000000000ull},
        {RECOVERABLE, 0x4000000000000000ull},
        {SPECIAL,     0x2000000000000000ull},
        {UNIT_CS,     0x1000000000000000ull},
        {HOST_ATTN,   0x0800000000000000ull},
    };

    static const RegAssoc * last = first +
        sizeof(first)/sizeof(*first);

    o_first = first;
    o_last = last;
}

bool getCheckbits(
        uint64_t i_type,
        uint64_t & o_bits)
{
    const RegAssoc * first, * last;

    getCheckbitsAssociations(first, last);

    return getCheckbits(first, last, i_type, o_bits);
}

void forEach(
        uint64_t i_scomData,
        void * i_data,
        void (*i_func)(uint64_t, void *))
{
    const RegAssoc * first, * last;

    getCheckbitsAssociations(first, last);

    forEach(first, last, i_scomData, i_data, i_func);
}
}

namespace GFIR
{

bool getAddress(
        uint64_t i_type,
        uint64_t & o_address)
{
    static const RegAssoc first[] = {

        {CHECK_STOP,  0x570f001c},
        {RECOVERABLE, 0x570f001b},
        {SPECIAL,     0x570f001a},
        {UNIT_CS,     0x57040018},
        {HOST_ATTN,   0x57040009},
    };

    static const RegAssoc * last = first +
        sizeof(first)/sizeof(*first);

    return getCheckbits(first, last, i_type, o_address);
}

bool getCheckbits(
        uint64_t i_type,
        uint64_t & o_bits)
{
    static const RegAssoc first[] = {

        {CHECK_STOP,  0xffffffffffffffffull},
        {RECOVERABLE, 0xffffffffffffffffull},
        {SPECIAL,     0xffffffffffffffffull},
        {UNIT_CS,     0xffffffffffffffffull},
        {HOST_ATTN,   0xffffffffffffffffull},
    };

    static const RegAssoc * last = first +
        sizeof(first)/sizeof(*first);

    return getCheckbits(first, last, i_type, o_bits);
}
}

namespace MCI
{
// Not valid / used for now on P9
const uint64_t address = 0x2011840;

void getCheckbitsAssociations(
        const RegAssoc * & o_first,
        const RegAssoc * & o_last)
{
    static const RegAssoc first[] = {

        {RECOVERABLE, 0x0009000000000000ull},
        {SPECIAL,     0x0000C00000000000ull},
    };

    static const RegAssoc * last = first +
        sizeof(first)/sizeof(*first);

    o_first = first;
    o_last = last;
}

bool getCheckbits(
        uint64_t i_type,
        uint64_t & o_bits)
{
    const RegAssoc * first, * last;

    getCheckbitsAssociations(first, last);

    return getCheckbits(first, last, i_type, o_bits);
}

void forEach(
        uint64_t i_scomData,
        void * i_data,
        void (*i_func)(uint64_t, void *))
{
    const RegAssoc * first, * last;

    getCheckbitsAssociations(first, last);

    forEach(first, last, i_scomData, i_data, i_func);
}
}

namespace GP1
{
// Not valid / used for now on P9
const uint64_t address = 0x2000001ull;

void getCheckbitsAssociations(
        const RegAssoc * & o_first,
        const RegAssoc * & o_last)
{
    static const RegAssoc first[] = {
        {0, 0x0100000000000000ull},
        {1, 0x0080000000000000ull},
        {2, 0x0040000000000000ull},
        {3, 0x0020000000000000ull},
        {4, 0x0010000000000000ull},
        {5, 0x0008000000000000ull},
        {6, 0x0004000000000000ull},
        {7, 0x0002000000000000ull},
    };

    static const RegAssoc * last = first +
        sizeof(first)/sizeof(*first);

    o_first = first;
    o_last = last;
}

bool getCheckbits(
        uint64_t i_pos,
        uint64_t & o_bits)
{
    const RegAssoc * first, * last;

    getCheckbitsAssociations(first, last);

    return getCheckbits(first, last, i_pos, o_bits);
}

void forEach(
        uint64_t i_scomData,
        void * i_data,
        void (*i_func)(uint64_t, void *))
{
    const RegAssoc * first, * last;

    getCheckbitsAssociations(first, last);

    forEach(first, last, i_scomData, i_data, i_func);
}
}
}
<commit_msg>ATTN: Use Multicast group 0<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/diag/attn/common/attnbits.C $                         */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2014,2016                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 * @file attnbits.C
 *
 * @brief HBATTN register addresses, bits of interest.
 */

#include "common/attnfwd.H"
#include "common/attnbits.H"

using namespace PRDF;
using namespace std;

namespace ATTN
{

/**
 * @brief RegAssoc Associate register data with a key.
 *
 * Typically used to associate an attention type or MCS position
 * with register addresses or masks.
 */
struct RegAssoc
{
    uint64_t key;

    uint64_t data;
};

bool getCheckbits(
        const RegAssoc * i_first,
        const RegAssoc * i_last,
        uint64_t i_key,
        uint64_t & o_bits)
{
    while(i_first != i_last)
    {
        if(i_first->key == i_key)
        {
            o_bits = i_first->data;
            break;
        }

        ++i_first;
    }

    return i_first != i_last;
}

void forEach(
        const RegAssoc * i_first,
        const RegAssoc * i_last,
        uint64_t i_scomData,
        void * i_data,
        void (*i_func)(uint64_t, void *))
{
    while(i_first != i_last)
    {
        if(i_first->data & i_scomData)
        {
            (*i_func)(i_first->key, i_data);
        }

        ++i_first;
    }
}

namespace IPOLL
{

const uint64_t address = IPOLL_MASK_REG;

// NOTE: This reg should get flushed to zeroes.
//       Hence, the 'routing to host' and
//       'routing to FSP' should be enabled.
//      (along with all interrupt types to FSP)
//  ---------------------------------------------
//    {ROUTE_TO_HOST,    0x0400000000000000ull},
//
//    {TOSP_CHECK_STOP,  0x0200000000000000ull},
//    {TOSP_RECOVERABLE, 0x0100000000000000ull},
//    {TOSP_SPECIAL,     0x0080000000000000ull},
//    {TOSP_UNIT_CS,     0x0040000000000000ull},
//    {TOSP_HOST,        0x0020000000000000ull},
//    {ROUTE_TO_SP,      0x0010000000000000ull},
//  ---------------------------------------------

void getCheckbitsAssociations(
        const RegAssoc * & o_first,
        const RegAssoc * & o_last)
{
    static const RegAssoc first[] = {

        {CHECK_STOP,  0x8000000000000000ull},
        {RECOVERABLE, 0x4000000000000000ull},
        {SPECIAL,     0x2000000000000000ull},
        {UNIT_CS,     0x1000000000000000ull},
        {HOST_ATTN,   0x0800000000000000ull},
    };

    static const RegAssoc * last = first +
        sizeof(first)/sizeof(*first);

    o_first = first;
    o_last = last;
}

bool getCheckbits(
        uint64_t i_type,
        uint64_t & o_bits)
{
    const RegAssoc * first, * last;

    getCheckbitsAssociations(first, last);

    return getCheckbits(first, last, i_type, o_bits);
}

void forEach(
        uint64_t i_scomData,
        void * i_data,
        void (*i_func)(uint64_t, void *))
{
    const RegAssoc * first, * last;

    getCheckbitsAssociations(first, last);

    forEach(first, last, i_scomData, i_data, i_func);
}
}

namespace GFIR
{

bool getAddress(
        uint64_t i_type,
        uint64_t & o_address)
{
    static const RegAssoc first[] = {

        {CHECK_STOP,  0x500f001c},
        {RECOVERABLE, 0x500f001b},
        {SPECIAL,     0x500f001a},
        {UNIT_CS,     0x50040018},
        {HOST_ATTN,   0x50040009},
    };

    static const RegAssoc * last = first +
        sizeof(first)/sizeof(*first);

    return getCheckbits(first, last, i_type, o_address);
}

bool getCheckbits(
        uint64_t i_type,
        uint64_t & o_bits)
{
    static const RegAssoc first[] = {

        {CHECK_STOP,  0xffffffffffffffffull},
        {RECOVERABLE, 0xffffffffffffffffull},
        {SPECIAL,     0xffffffffffffffffull},
        {UNIT_CS,     0xffffffffffffffffull},
        {HOST_ATTN,   0xffffffffffffffffull},
    };

    static const RegAssoc * last = first +
        sizeof(first)/sizeof(*first);

    return getCheckbits(first, last, i_type, o_bits);
}
}

namespace MCI
{
// Not valid / used for now on P9
const uint64_t address = 0x2011840;

void getCheckbitsAssociations(
        const RegAssoc * & o_first,
        const RegAssoc * & o_last)
{
    static const RegAssoc first[] = {

        {RECOVERABLE, 0x0009000000000000ull},
        {SPECIAL,     0x0000C00000000000ull},
    };

    static const RegAssoc * last = first +
        sizeof(first)/sizeof(*first);

    o_first = first;
    o_last = last;
}

bool getCheckbits(
        uint64_t i_type,
        uint64_t & o_bits)
{
    const RegAssoc * first, * last;

    getCheckbitsAssociations(first, last);

    return getCheckbits(first, last, i_type, o_bits);
}

void forEach(
        uint64_t i_scomData,
        void * i_data,
        void (*i_func)(uint64_t, void *))
{
    const RegAssoc * first, * last;

    getCheckbitsAssociations(first, last);

    forEach(first, last, i_scomData, i_data, i_func);
}
}

namespace GP1
{
// Not valid / used for now on P9
const uint64_t address = 0x2000001ull;

void getCheckbitsAssociations(
        const RegAssoc * & o_first,
        const RegAssoc * & o_last)
{
    static const RegAssoc first[] = {
        {0, 0x0100000000000000ull},
        {1, 0x0080000000000000ull},
        {2, 0x0040000000000000ull},
        {3, 0x0020000000000000ull},
        {4, 0x0010000000000000ull},
        {5, 0x0008000000000000ull},
        {6, 0x0004000000000000ull},
        {7, 0x0002000000000000ull},
    };

    static const RegAssoc * last = first +
        sizeof(first)/sizeof(*first);

    o_first = first;
    o_last = last;
}

bool getCheckbits(
        uint64_t i_pos,
        uint64_t & o_bits)
{
    const RegAssoc * first, * last;

    getCheckbitsAssociations(first, last);

    return getCheckbits(first, last, i_pos, o_bits);
}

void forEach(
        uint64_t i_scomData,
        void * i_data,
        void (*i_func)(uint64_t, void *))
{
    const RegAssoc * first, * last;

    getCheckbitsAssociations(first, last);

    forEach(first, last, i_scomData, i_data, i_func);
}
}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: UStringDescription_Impl.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: oj $ $Date: 2001-03-30 14:01:49 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef CONNECTIVITY_USTRINGDESCRIPTION_IMPL_HXX
#define CONNECTIVITY_USTRINGDESCRIPTION_IMPL_HXX

#define IMPLEMENT_CONSTASCII_USTRING(name)  \
UStringDescription name(connectivity::dbtools::get##name)

UStringDescription::UStringDescription(PVFN _fCharFkt)
{
    pZeroTerminatedName = (*_fCharFkt)();
    nLength = 0;
    const sal_Char* pIter = pZeroTerminatedName;
    while((*pIter++) != '\0')
        ++nLength;
}
// -------------------------------------------------------------------------
UStringDescription::~UStringDescription()
{
}

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_QUERYTIMEOUT          );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_MAXFIELDSIZE          );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_MAXROWS               );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_CURSORNAME            );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_RESULTSETCONCURRENCY  );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_RESULTSETTYPE         );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_FETCHDIRECTION        );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_FETCHSIZE             );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ESCAPEPROCESSING      );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_USEBOOKMARKS          );

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_NAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_TYPE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_TYPENAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_PRECISION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_SCALE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISNULLABLE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISAUTOINCREMENT);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISROWVERSION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_DESCRIPTION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_DEFAULTVALUE);

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_REFERENCEDTABLE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_UPDATERULE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_DELETERULE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_CATALOG);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISUNIQUE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISPRIMARYKEYINDEX);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISCLUSTERED);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISASCENDING);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_SCHEMANAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_CATALOGNAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_COMMAND);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_CHECKOPTION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_PASSWORD);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_RELATEDCOLUMN);

IMPLEMENT_CONSTASCII_USTRING(STAT_INVALID_INDEX);

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_FUNCTION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_TABLENAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_REALNAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_DBASEPRECISIONCHANGED);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISCURRENCY);

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISBOOKMARKABLE);
//============================================================
//= error messages
//============================================================
IMPLEMENT_CONSTASCII_USTRING(ERRORMSG_SEQUENCE);
IMPLEMENT_CONSTASCII_USTRING(SQLSTATE_SEQUENCE);
IMPLEMENT_CONSTASCII_USTRING(SQLSTATE_GENERAL);
//============================================================
//= different
//============================================================
IMPLEMENT_CONSTASCII_USTRING(STR_DELIMITER);

#endif // CONNECTIVITY_USTRINGDESCRIPTION_IMPL_HXX

<commit_msg>INTEGRATION: CWS ooo19126 (1.3.352); FILE MERGED 2005/09/05 17:24:51 rt 1.3.352.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: UStringDescription_Impl.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:40:43 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef CONNECTIVITY_USTRINGDESCRIPTION_IMPL_HXX
#define CONNECTIVITY_USTRINGDESCRIPTION_IMPL_HXX

#define IMPLEMENT_CONSTASCII_USTRING(name)  \
UStringDescription name(connectivity::dbtools::get##name)

UStringDescription::UStringDescription(PVFN _fCharFkt)
{
    pZeroTerminatedName = (*_fCharFkt)();
    nLength = 0;
    const sal_Char* pIter = pZeroTerminatedName;
    while((*pIter++) != '\0')
        ++nLength;
}
// -------------------------------------------------------------------------
UStringDescription::~UStringDescription()
{
}

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_QUERYTIMEOUT          );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_MAXFIELDSIZE          );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_MAXROWS               );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_CURSORNAME            );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_RESULTSETCONCURRENCY  );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_RESULTSETTYPE         );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_FETCHDIRECTION        );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_FETCHSIZE             );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ESCAPEPROCESSING      );
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_USEBOOKMARKS          );

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_NAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_TYPE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_TYPENAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_PRECISION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_SCALE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISNULLABLE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISAUTOINCREMENT);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISROWVERSION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_DESCRIPTION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_DEFAULTVALUE);

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_REFERENCEDTABLE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_UPDATERULE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_DELETERULE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_CATALOG);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISUNIQUE);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISPRIMARYKEYINDEX);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISCLUSTERED);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISASCENDING);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_SCHEMANAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_CATALOGNAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_COMMAND);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_CHECKOPTION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_PASSWORD);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_RELATEDCOLUMN);

IMPLEMENT_CONSTASCII_USTRING(STAT_INVALID_INDEX);

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_FUNCTION);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_TABLENAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_REALNAME);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_DBASEPRECISIONCHANGED);
IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISCURRENCY);

IMPLEMENT_CONSTASCII_USTRING(PROPERTY_ISBOOKMARKABLE);
//============================================================
//= error messages
//============================================================
IMPLEMENT_CONSTASCII_USTRING(ERRORMSG_SEQUENCE);
IMPLEMENT_CONSTASCII_USTRING(SQLSTATE_SEQUENCE);
IMPLEMENT_CONSTASCII_USTRING(SQLSTATE_GENERAL);
//============================================================
//= different
//============================================================
IMPLEMENT_CONSTASCII_USTRING(STR_DELIMITER);

#endif // CONNECTIVITY_USTRINGDESCRIPTION_IMPL_HXX

<|endoftext|>


<commit_before>/*!
 * \file hyo_utilities_tests.cpp
 * \author Robert 'Bob' Caddy (rvc@pitt.edu), Helena Richie (helenarichie@pitt.edu)
 * \brief Tests for the contents of hydro_utilities.h and hydro_utilities.cpp
 *
 */

// STL Includes
#include <vector>
#include <string>
#include <iostream>

// External Includes
#include <gtest/gtest.h>    // Include GoogleTest and related libraries/headers

// Local Includes
#include "../utils/testing_utilities.h"
#include "../utils/hydro_utilities.h"
#include "../global/global.h"

// =============================================================================
// Local helper functions

/*!
* INDEX OF VARIABLES
* p : pressure
* vx, vy, vz : x, y, and z velocity
* d : density
* E : energy
* T : temperature
* px, py, pz : x, y, and z momentum
* n : number density
*/

namespace
{
    struct TestParams
    {
        double gamma = 5./3.;
        std::vector<double> d {8.4087201154e-100, 1.6756968986e2, 5.4882403847e100};
        std::vector<double> vx {7.0378624601e-100, 7.0829278656e2, 1.8800514112e100};
        std::vector<double> vy {7.3583469014e-100, 5.9283073464e2, 5.2725717864e100};
        std::vector<double> vz {1.7182972216e-100, 8.8417748226e2, 1.5855352639e100};
        std::vector<double> px {8.2340416681e-100, 8.1019429453e2, 5.5062596954e100};
        std::vector<double> py {4.9924582299e-100, 7.1254780684e2, 6.5939640992e100};
        std::vector<double> pz {3.6703192739e-100, 7.5676716066e2, 7.2115881803e100};
        std::vector<double> E {3.0342082433e-100, 7.6976906577e2, 1.9487120853e100};
        std::vector<double> p {2.2244082909e-100, 8.6772951021e2, 6.7261085663e100};
        std::vector<std::string> names{"Small number case", "Medium number case", "Large number case"};
    };
}

TEST(tHydroUtilsCalcPressureConserved, CorrectInputExpectCorrectOutput) {
    TestParams parameters;
    std::vector<double> fiducial_pressures{3.3366124363499995e-100,
                                         137786230.15630624,
                                         9.2884430880010847e+301};

    for (size_t i = 0; i < parameters.names.size(); i++)
    {
        Real test_p= hydro_utilites::Calc_Pressure_Conserved(parameters.p.at(i), parameters.d.at(i), parameters.vx.at(i), parameters.vy.at(i), parameters.vz.at(i), parameters.gamma);

        testingUtilities::checkResults(fiducial_pressures.at(i), test_p, parameters.names.at(i));
    }
}<commit_msg>add hydro utility function testing<commit_after>/*!
 * \file hyo_utilities_tests.cpp
 * \author Robert 'Bob' Caddy (rvc@pitt.edu), Helena Richie (helenarichie@pitt.edu)
 * \brief Tests for the contents of hydro_utilities.h and hydro_utilities.cpp
 *
 */

// STL Includes
#include <vector>
#include <string>
#include <iostream>

// External Includes
#include <gtest/gtest.h>    // Include GoogleTest and related libraries/headers

// Local Includes
#include "../utils/testing_utilities.h"
#include "../utils/hydro_utilities.h"
#include "../global/global.h"

// =============================================================================
// Local helper functions

/*!
* INDEX OF VARIABLES
* p : pressure
* vx, vy, vz : x, y, and z velocity
* d : density
* E : energy
* T : temperature
* px, py, pz : x, y, and z momentum
* n : number density
*/

namespace
{
    struct TestParams
    {
        double gamma = 5./3.;
        std::vector<double> d {8.4087201154e-100, 1.6756968986e2, 5.4882403847e100};
        std::vector<double> vx {7.0378624601e-100, 7.0829278656e2, 1.8800514112e100};
        std::vector<double> vy {7.3583469014e-100, 5.9283073464e2, 5.2725717864e100};
        std::vector<double> vz {1.7182972216e-100, 8.8417748226e2, 1.5855352639e100};
        std::vector<double> px {8.2340416681e-100, 8.1019429453e2, 5.5062596954e100};
        std::vector<double> py {4.9924582299e-100, 7.1254780684e2, 6.5939640992e100};
        std::vector<double> pz {3.6703192739e-100, 7.5676716066e2, 7.2115881803e100};
        std::vector<double> E {3.0342082433e-100, 7.6976906577e2, 1.9487120853e100};
        std::vector<double> p {2.2244082909e-100, 8.6772951021e2, 6.7261085663e100};
        std::vector<std::string> names{"Small number case", "Medium number case", "Large number case"};
    };
}

TEST(tHydroUtilsCalcPressureConserved, CorrectInputExpectCorrectOutput) {
    TestParams parameters;
    std::vector<double> fiducial_pressures{3.3366124363499995e-100,
                                         137786230.15630624,
                                         9.2884430880010847e+301};

    for (size_t i = 0; i < parameters.names.size(); i++)
    {
        Real test_p = hydro_utilities::Calc_Pressure_Conserved(parameters.p.at(i), parameters.d.at(i), parameters.vx.at(i), parameters.vy.at(i), parameters.vz.at(i), parameters.gamma);

        testingUtilities::checkResults(fiducial_pressures.at(i), test_p, parameters.names.at(i));
    }
}<|endoftext|>


<commit_before>//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the llc code generator driver. It provides a convenient
// command-line interface for generating native assembly-language code
// or C code, given LLVM bitcode.
//
//===----------------------------------------------------------------------===//

#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Support/IRReader.h"
#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
#include "llvm/CodeGen/LinkAllCodegenComponents.h"
#include "llvm/Config/config.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/System/Host.h"
#include "llvm/System/Signals.h"
#include "llvm/Target/SubtargetFeature.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Target/TargetSelect.h"
#include <memory>
using namespace llvm;

// General options for llc.  Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));

static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));

// Determine optimization level.
static cl::opt<char>
OptLevel("O",
         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
                  "(default = '-O2')"),
         cl::Prefix,
         cl::ZeroOrMore,
         cl::init(' '));

static cl::opt<std::string>
TargetTriple("mtriple", cl::desc("Override target triple for module"));

static cl::opt<std::string>
MArch("march", cl::desc("Architecture to generate code for (see --version)"));

static cl::opt<std::string>
MCPU("mcpu",
  cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  cl::value_desc("cpu-name"),
  cl::init(""));

static cl::list<std::string>
MAttrs("mattr",
  cl::CommaSeparated,
  cl::desc("Target specific attributes (-mattr=help for details)"),
  cl::value_desc("a1,+a2,-a3,..."));

static cl::opt<bool>
RelaxAll("mc-relax-all",
  cl::desc("When used with filetype=obj, "
           "relax all fixups in the emitted object file"));

cl::opt<TargetMachine::CodeGenFileType>
FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
  cl::desc("Choose a file type (not all types are supported by all targets):"),
  cl::values(
       clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
                  "Emit an assembly ('.s') file"),
       clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
                  "Emit a native object ('.o') file [experimental]"),
       clEnumValN(TargetMachine::CGFT_Null, "null",
                  "Emit nothing, for performance testing"),
       clEnumValEnd));

cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
                       cl::desc("Do not verify input module"));

static cl::opt<bool>
DisableRedZone("disable-red-zone",
  cl::desc("Do not emit code that uses the red zone."),
  cl::init(false));

static cl::opt<bool>
NoImplicitFloats("no-implicit-float",
  cl::desc("Don't generate implicit floating point instructions (x86-only)"),
  cl::init(false));

// GetFileNameRoot - Helper function to get the basename of a filename.
static inline std::string
GetFileNameRoot(const std::string &InputFilename) {
  std::string IFN = InputFilename;
  std::string outputFilename;
  int Len = IFN.length();
  if ((Len > 2) &&
      IFN[Len-3] == '.' &&
      ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
       (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
    outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
  } else {
    outputFilename = IFN;
  }
  return outputFilename;
}

static formatted_raw_ostream *GetOutputStream(const char *TargetName,
                                              Triple::OSType OS,
                                              const char *ProgName) {
  if (!OutputFilename.empty()) {
    // Make sure that the Out file gets unlinked from the disk if we get a
    // SIGINT
    if (OutputFilename != "-")
      sys::RemoveFileOnSignal(sys::Path(OutputFilename));

    std::string error;
    raw_fd_ostream *FDOut =
      new raw_fd_ostream(OutputFilename.c_str(), error,
                         raw_fd_ostream::F_Binary);
    if (!error.empty()) {
      errs() << error << '\n';
      delete FDOut;
      return 0;
    }
    formatted_raw_ostream *Out =
      new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);

    return Out;
  }

  if (InputFilename == "-") {
    OutputFilename = "-";
    return new formatted_raw_ostream(outs(),
                                     formatted_raw_ostream::PRESERVE_STREAM);
  }

  OutputFilename = GetFileNameRoot(InputFilename);

  bool Binary = false;
  switch (FileType) {
  default: assert(0 && "Unknown file type");
  case TargetMachine::CGFT_AssemblyFile:
    if (TargetName[0] == 'c') {
      if (TargetName[1] == 0)
        OutputFilename += ".cbe.c";
      else if (TargetName[1] == 'p' && TargetName[2] == 'p')
        OutputFilename += ".cpp";
      else
        OutputFilename += ".s";
    } else
      OutputFilename += ".s";
    break;
  case TargetMachine::CGFT_ObjectFile:
    if (OS == Triple::Win32)
      OutputFilename += ".obj";
    else
      OutputFilename += ".o";
    Binary = true;
    break;
  case TargetMachine::CGFT_Null:
    OutputFilename += ".null";
    Binary = true;
    break;
  }

  // Make sure that the Out file gets unlinked from the disk if we get a
  // SIGINT
  sys::RemoveFileOnSignal(sys::Path(OutputFilename));

  std::string error;
  unsigned OpenFlags = 0;
  if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
  raw_fd_ostream *FDOut = new raw_fd_ostream(OutputFilename.c_str(), error,
                                             OpenFlags);
  if (!error.empty()) {
    errs() << error << '\n';
    delete FDOut;
    return 0;
  }

  formatted_raw_ostream *Out =
    new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);

  return Out;
}

// main - Entry point for the llc compiler.
//
int main(int argc, char **argv) {
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);

  // Enable debug stream buffering.
  EnableDebugBuffering = true;

  LLVMContext &Context = getGlobalContext();
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.

  // Initialize targets first, so that --version shows registered targets.
  InitializeAllTargets();
  InitializeAllAsmPrinters();
  InitializeAllAsmParsers();

  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");

  // Load the module to be compiled...
  SMDiagnostic Err;
  std::auto_ptr<Module> M;

  M.reset(ParseIRFile(InputFilename, Err, Context));
  if (M.get() == 0) {
    Err.Print(argv[0], errs());
    return 1;
  }
  Module &mod = *M.get();

  // If we are supposed to override the target triple, do so now.
  if (!TargetTriple.empty())
    mod.setTargetTriple(TargetTriple);

  Triple TheTriple(mod.getTargetTriple());
  if (TheTriple.getTriple().empty())
    TheTriple.setTriple(sys::getHostTriple());

  // Allocate target machine.  First, check whether the user has explicitly
  // specified an architecture to compile for. If so we have to look it up by
  // name, because it might be a backend that has no mapping to a target triple.
  const Target *TheTarget = 0;
  if (!MArch.empty()) {
    for (TargetRegistry::iterator it = TargetRegistry::begin(),
           ie = TargetRegistry::end(); it != ie; ++it) {
      if (MArch == it->getName()) {
        TheTarget = &*it;
        break;
      }
    }

    if (!TheTarget) {
      errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
      return 1;
    }

    // Adjust the triple to match (if known), otherwise stick with the
    // module/host triple.
    Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
    if (Type != Triple::UnknownArch)
      TheTriple.setArch(Type);
  } else {
    std::string Err;
    TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
    if (TheTarget == 0) {
      errs() << argv[0] << ": error auto-selecting target for module '"
             << Err << "'.  Please use the -march option to explicitly "
             << "pick a target.\n";
      return 1;
    }
  }

  // Package up features to be passed to target/subtarget
  std::string FeaturesStr;
  if (MCPU.size() || MAttrs.size()) {
    SubtargetFeatures Features;
    Features.setCPU(MCPU);
    for (unsigned i = 0; i != MAttrs.size(); ++i)
      Features.AddFeature(MAttrs[i]);
    FeaturesStr = Features.getString();
  }

  std::auto_ptr<TargetMachine>
    target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
  assert(target.get() && "Could not allocate target machine!");
  TargetMachine &Target = *target.get();

  // Figure out where we are going to send the output...
  formatted_raw_ostream *Out = GetOutputStream(TheTarget->getName(),
                                               TheTriple.getOS(), argv[0]);
  if (Out == 0) return 1;

  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  switch (OptLevel) {
  default:
    errs() << argv[0] << ": invalid optimization level.\n";
    return 1;
  case ' ': break;
  case '0': OLvl = CodeGenOpt::None; break;
  case '1': OLvl = CodeGenOpt::Less; break;
  case '2': OLvl = CodeGenOpt::Default; break;
  case '3': OLvl = CodeGenOpt::Aggressive; break;
  }

  // Request that addPassesToEmitFile run the Verifier after running
  // passes which modify the IR.
#ifndef NDEBUG
  bool DisableVerify = false;
#else
  bool DisableVerify = true;
#endif

  // Build up all of the passes that we want to do to the module.
  PassManager PM;

  // Add the target data from the target machine, if it exists, or the module.
  if (const TargetData *TD = Target.getTargetData())
    PM.add(new TargetData(*TD));
  else
    PM.add(new TargetData(&mod));

  if (!NoVerify)
    PM.add(createVerifierPass());

  // Override default to generate verbose assembly.
  Target.setAsmVerbosityDefault(true);

  if (RelaxAll) {
    if (FileType != TargetMachine::CGFT_ObjectFile)
      errs() << argv[0]
             << ": warning: ignoring -mc-relax-all because filetype != obj";
    else
      Target.setMCRelaxAll(true);
  }

  // Ask the target to add backend passes as necessary.
  if (Target.addPassesToEmitFile(PM, *Out, FileType, OLvl,
                                 DisableVerify)) {
    errs() << argv[0] << ": target does not support generation of this"
           << " file type!\n";
    delete Out;
    // And the Out file is empty and useless, so remove it now.
    sys::Path(OutputFilename).eraseFromDisk();
    return 1;
  }

  PM.run(mod);

  // Delete the ostream.
  delete Out;

  return 0;
}
<commit_msg>Eliminate some redundancy by relying on raw_fd_ostream to handle "-" properly.<commit_after>//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the llc code generator driver. It provides a convenient
// command-line interface for generating native assembly-language code
// or C code, given LLVM bitcode.
//
//===----------------------------------------------------------------------===//

#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Support/IRReader.h"
#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
#include "llvm/CodeGen/LinkAllCodegenComponents.h"
#include "llvm/Config/config.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/System/Host.h"
#include "llvm/System/Signals.h"
#include "llvm/Target/SubtargetFeature.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Target/TargetSelect.h"
#include <memory>
using namespace llvm;

// General options for llc.  Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));

static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));

// Determine optimization level.
static cl::opt<char>
OptLevel("O",
         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
                  "(default = '-O2')"),
         cl::Prefix,
         cl::ZeroOrMore,
         cl::init(' '));

static cl::opt<std::string>
TargetTriple("mtriple", cl::desc("Override target triple for module"));

static cl::opt<std::string>
MArch("march", cl::desc("Architecture to generate code for (see --version)"));

static cl::opt<std::string>
MCPU("mcpu",
  cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  cl::value_desc("cpu-name"),
  cl::init(""));

static cl::list<std::string>
MAttrs("mattr",
  cl::CommaSeparated,
  cl::desc("Target specific attributes (-mattr=help for details)"),
  cl::value_desc("a1,+a2,-a3,..."));

static cl::opt<bool>
RelaxAll("mc-relax-all",
  cl::desc("When used with filetype=obj, "
           "relax all fixups in the emitted object file"));

cl::opt<TargetMachine::CodeGenFileType>
FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
  cl::desc("Choose a file type (not all types are supported by all targets):"),
  cl::values(
       clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
                  "Emit an assembly ('.s') file"),
       clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
                  "Emit a native object ('.o') file [experimental]"),
       clEnumValN(TargetMachine::CGFT_Null, "null",
                  "Emit nothing, for performance testing"),
       clEnumValEnd));

cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
                       cl::desc("Do not verify input module"));

static cl::opt<bool>
DisableRedZone("disable-red-zone",
  cl::desc("Do not emit code that uses the red zone."),
  cl::init(false));

static cl::opt<bool>
NoImplicitFloats("no-implicit-float",
  cl::desc("Don't generate implicit floating point instructions (x86-only)"),
  cl::init(false));

// GetFileNameRoot - Helper function to get the basename of a filename.
static inline std::string
GetFileNameRoot(const std::string &InputFilename) {
  std::string IFN = InputFilename;
  std::string outputFilename;
  int Len = IFN.length();
  if ((Len > 2) &&
      IFN[Len-3] == '.' &&
      ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
       (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
    outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
  } else {
    outputFilename = IFN;
  }
  return outputFilename;
}

static formatted_raw_ostream *GetOutputStream(const char *TargetName,
                                              Triple::OSType OS,
                                              const char *ProgName) {
  // If we don't yet have an output filename, make one.
  if (OutputFilename.empty()) {
    if (InputFilename == "-")
      OutputFilename = "-";
    else {
      OutputFilename = GetFileNameRoot(InputFilename);

      switch (FileType) {
      default: assert(0 && "Unknown file type");
      case TargetMachine::CGFT_AssemblyFile:
        if (TargetName[0] == 'c') {
          if (TargetName[1] == 0)
            OutputFilename += ".cbe.c";
          else if (TargetName[1] == 'p' && TargetName[2] == 'p')
            OutputFilename += ".cpp";
          else
            OutputFilename += ".s";
        } else
          OutputFilename += ".s";
        break;
      case TargetMachine::CGFT_ObjectFile:
        if (OS == Triple::Win32)
          OutputFilename += ".obj";
        else
          OutputFilename += ".o";
        break;
      case TargetMachine::CGFT_Null:
        OutputFilename += ".null";
        break;
      }
    }
  }

  // Decide if we need "binary" output.
  bool Binary = false;
  switch (FileType) {
  default: assert(0 && "Unknown file type");
  case TargetMachine::CGFT_AssemblyFile:
    break;
  case TargetMachine::CGFT_ObjectFile:
  case TargetMachine::CGFT_Null:
    Binary = true;
    break;
  }

  // Make sure that the Out file gets unlinked from the disk if we get a
  // SIGINT
  if (OutputFilename != "-")
    sys::RemoveFileOnSignal(sys::Path(OutputFilename));

  // Open the file.
  std::string error;
  unsigned OpenFlags = 0;
  if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
  raw_fd_ostream *FDOut = new raw_fd_ostream(OutputFilename.c_str(), error,
                                             OpenFlags);
  if (!error.empty()) {
    errs() << error << '\n';
    delete FDOut;
    return 0;
  }

  formatted_raw_ostream *Out =
    new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);

  return Out;
}

// main - Entry point for the llc compiler.
//
int main(int argc, char **argv) {
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);

  // Enable debug stream buffering.
  EnableDebugBuffering = true;

  LLVMContext &Context = getGlobalContext();
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.

  // Initialize targets first, so that --version shows registered targets.
  InitializeAllTargets();
  InitializeAllAsmPrinters();
  InitializeAllAsmParsers();

  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");

  // Load the module to be compiled...
  SMDiagnostic Err;
  std::auto_ptr<Module> M;

  M.reset(ParseIRFile(InputFilename, Err, Context));
  if (M.get() == 0) {
    Err.Print(argv[0], errs());
    return 1;
  }
  Module &mod = *M.get();

  // If we are supposed to override the target triple, do so now.
  if (!TargetTriple.empty())
    mod.setTargetTriple(TargetTriple);

  Triple TheTriple(mod.getTargetTriple());
  if (TheTriple.getTriple().empty())
    TheTriple.setTriple(sys::getHostTriple());

  // Allocate target machine.  First, check whether the user has explicitly
  // specified an architecture to compile for. If so we have to look it up by
  // name, because it might be a backend that has no mapping to a target triple.
  const Target *TheTarget = 0;
  if (!MArch.empty()) {
    for (TargetRegistry::iterator it = TargetRegistry::begin(),
           ie = TargetRegistry::end(); it != ie; ++it) {
      if (MArch == it->getName()) {
        TheTarget = &*it;
        break;
      }
    }

    if (!TheTarget) {
      errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
      return 1;
    }

    // Adjust the triple to match (if known), otherwise stick with the
    // module/host triple.
    Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
    if (Type != Triple::UnknownArch)
      TheTriple.setArch(Type);
  } else {
    std::string Err;
    TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
    if (TheTarget == 0) {
      errs() << argv[0] << ": error auto-selecting target for module '"
             << Err << "'.  Please use the -march option to explicitly "
             << "pick a target.\n";
      return 1;
    }
  }

  // Package up features to be passed to target/subtarget
  std::string FeaturesStr;
  if (MCPU.size() || MAttrs.size()) {
    SubtargetFeatures Features;
    Features.setCPU(MCPU);
    for (unsigned i = 0; i != MAttrs.size(); ++i)
      Features.AddFeature(MAttrs[i]);
    FeaturesStr = Features.getString();
  }

  std::auto_ptr<TargetMachine>
    target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
  assert(target.get() && "Could not allocate target machine!");
  TargetMachine &Target = *target.get();

  // Figure out where we are going to send the output...
  formatted_raw_ostream *Out = GetOutputStream(TheTarget->getName(),
                                               TheTriple.getOS(), argv[0]);
  if (Out == 0) return 1;

  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  switch (OptLevel) {
  default:
    errs() << argv[0] << ": invalid optimization level.\n";
    return 1;
  case ' ': break;
  case '0': OLvl = CodeGenOpt::None; break;
  case '1': OLvl = CodeGenOpt::Less; break;
  case '2': OLvl = CodeGenOpt::Default; break;
  case '3': OLvl = CodeGenOpt::Aggressive; break;
  }

  // Request that addPassesToEmitFile run the Verifier after running
  // passes which modify the IR.
#ifndef NDEBUG
  bool DisableVerify = false;
#else
  bool DisableVerify = true;
#endif

  // Build up all of the passes that we want to do to the module.
  PassManager PM;

  // Add the target data from the target machine, if it exists, or the module.
  if (const TargetData *TD = Target.getTargetData())
    PM.add(new TargetData(*TD));
  else
    PM.add(new TargetData(&mod));

  if (!NoVerify)
    PM.add(createVerifierPass());

  // Override default to generate verbose assembly.
  Target.setAsmVerbosityDefault(true);

  if (RelaxAll) {
    if (FileType != TargetMachine::CGFT_ObjectFile)
      errs() << argv[0]
             << ": warning: ignoring -mc-relax-all because filetype != obj";
    else
      Target.setMCRelaxAll(true);
  }

  // Ask the target to add backend passes as necessary.
  if (Target.addPassesToEmitFile(PM, *Out, FileType, OLvl,
                                 DisableVerify)) {
    errs() << argv[0] << ": target does not support generation of this"
           << " file type!\n";
    delete Out;
    // And the Out file is empty and useless, so remove it now.
    sys::Path(OutputFilename).eraseFromDisk();
    return 1;
  }

  PM.run(mod);

  // Delete the ostream.
  delete Out;

  return 0;
}
<|endoftext|>


<commit_before>//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the llc code generator driver. It provides a convenient
// command-line interface for generating native assembly-language code
// or C code, given LLVM bitcode.
//
//===----------------------------------------------------------------------===//

#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Support/IRReader.h"
#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
#include "llvm/CodeGen/LinkAllCodegenComponents.h"
#include "llvm/Config/config.h"
#include "llvm/LinkAllVMCore.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/System/Host.h"
#include "llvm/System/Signals.h"
#include "llvm/Target/SubtargetFeature.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Target/TargetSelect.h"
#include "llvm/Transforms/Scalar.h"
#include <memory>
using namespace llvm;

// General options for llc.  Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));

static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));

static cl::opt<bool>
Force("f", cl::desc("Enable binary output on terminals"));

// Determine optimization level.
static cl::opt<char>
OptLevel("O",
         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
                  "(default = '-O2')"),
         cl::Prefix,
         cl::ZeroOrMore,
         cl::init(' '));

static cl::opt<std::string>
TargetTriple("mtriple", cl::desc("Override target triple for module"));

static cl::opt<std::string>
MArch("march", cl::desc("Architecture to generate code for (see --version)"));

static cl::opt<std::string>
MCPU("mcpu",
  cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  cl::value_desc("cpu-name"),
  cl::init(""));

static cl::list<std::string>
MAttrs("mattr",
  cl::CommaSeparated,
  cl::desc("Target specific attributes (-mattr=help for details)"),
  cl::value_desc("a1,+a2,-a3,..."));

cl::opt<TargetMachine::CodeGenFileType>
FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
  cl::desc("Choose a file type (not all types are supported by all targets):"),
  cl::values(
       clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
                  "Emit an assembly ('.s') file"),
       clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
                  "Emit a native object ('.o') file [experimental]"),
       clEnumValN(TargetMachine::CGFT_Null, "null",
                  "Emit nothing, for performance testing"),
       clEnumValEnd));

cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
                       cl::desc("Do not verify input module"));

static cl::opt<bool>
DisableRedZone("disable-red-zone",
  cl::desc("Do not emit code that uses the red zone."),
  cl::init(false));

static cl::opt<bool>
NoImplicitFloats("no-implicit-float",
  cl::desc("Don't generate implicit floating point instructions (x86-only)"),
  cl::init(false));

// GetFileNameRoot - Helper function to get the basename of a filename.
static inline std::string
GetFileNameRoot(const std::string &InputFilename) {
  std::string IFN = InputFilename;
  std::string outputFilename;
  int Len = IFN.length();
  if ((Len > 2) &&
      IFN[Len-3] == '.' &&
      ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
       (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
    outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
  } else {
    outputFilename = IFN;
  }
  return outputFilename;
}

static formatted_raw_ostream *GetOutputStream(const char *TargetName,
                                              const char *ProgName) {
  if (OutputFilename != "") {
    if (OutputFilename == "-")
      return &fouts();

    // Make sure that the Out file gets unlinked from the disk if we get a
    // SIGINT
    sys::RemoveFileOnSignal(sys::Path(OutputFilename));

    std::string error;
    raw_fd_ostream *FDOut =
      new raw_fd_ostream(OutputFilename.c_str(), error,
                         raw_fd_ostream::F_Binary);
    if (!error.empty()) {
      errs() << error << '\n';
      delete FDOut;
      return 0;
    }
    formatted_raw_ostream *Out =
      new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);

    return Out;
  }

  if (InputFilename == "-") {
    OutputFilename = "-";
    return &fouts();
  }

  OutputFilename = GetFileNameRoot(InputFilename);

  bool Binary = false;
  switch (FileType) {
  default: assert(0 && "Unknown file type");
  case TargetMachine::CGFT_AssemblyFile:
    if (TargetName[0] == 'c') {
      if (TargetName[1] == 0)
        OutputFilename += ".cbe.c";
      else if (TargetName[1] == 'p' && TargetName[2] == 'p')
        OutputFilename += ".cpp";
      else
        OutputFilename += ".s";
    } else
      OutputFilename += ".s";
    break;
  case TargetMachine::CGFT_ObjectFile:
    OutputFilename += ".o";
    Binary = true;
    break;
  case TargetMachine::CGFT_Null:
    OutputFilename += ".null";
    Binary = true;
    break;
  }

  // Make sure that the Out file gets unlinked from the disk if we get a
  // SIGINT
  sys::RemoveFileOnSignal(sys::Path(OutputFilename));

  std::string error;
  unsigned OpenFlags = 0;
  if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
  raw_fd_ostream *FDOut = new raw_fd_ostream(OutputFilename.c_str(), error,
                                             OpenFlags);
  if (!error.empty()) {
    errs() << error << '\n';
    delete FDOut;
    return 0;
  }

  formatted_raw_ostream *Out =
    new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);

  return Out;
}

// main - Entry point for the llc compiler.
//
int main(int argc, char **argv) {
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);

  // Enable debug stream buffering.
  EnableDebugBuffering = true;

  LLVMContext &Context = getGlobalContext();
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.

  // Initialize targets first, so that --version shows registered targets.
  InitializeAllTargets();
  InitializeAllAsmPrinters();

  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");

  // Load the module to be compiled...
  SMDiagnostic Err;
  std::auto_ptr<Module> M;

  M.reset(ParseIRFile(InputFilename, Err, Context));
  if (M.get() == 0) {
    Err.Print(argv[0], errs());
    return 1;
  }
  Module &mod = *M.get();

  // If we are supposed to override the target triple, do so now.
  if (!TargetTriple.empty())
    mod.setTargetTriple(TargetTriple);

  Triple TheTriple(mod.getTargetTriple());
  if (TheTriple.getTriple().empty())
    TheTriple.setTriple(sys::getHostTriple());

  // Allocate target machine.  First, check whether the user has explicitly
  // specified an architecture to compile for. If so we have to look it up by
  // name, because it might be a backend that has no mapping to a target triple.
  const Target *TheTarget = 0;
  if (!MArch.empty()) {
    for (TargetRegistry::iterator it = TargetRegistry::begin(),
           ie = TargetRegistry::end(); it != ie; ++it) {
      if (MArch == it->getName()) {
        TheTarget = &*it;
        break;
      }
    }

    if (!TheTarget) {
      errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
      return 1;
    }

    // Adjust the triple to match (if known), otherwise stick with the
    // module/host triple.
    Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
    if (Type != Triple::UnknownArch)
      TheTriple.setArch(Type);
  } else {
    std::string Err;
    TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
    if (TheTarget == 0) {
      errs() << argv[0] << ": error auto-selecting target for module '"
             << Err << "'.  Please use the -march option to explicitly "
             << "pick a target.\n";
      return 1;
    }
  }

  // Package up features to be passed to target/subtarget
  std::string FeaturesStr;
  if (MCPU.size() || MAttrs.size()) {
    SubtargetFeatures Features;
    Features.setCPU(MCPU);
    for (unsigned i = 0; i != MAttrs.size(); ++i)
      Features.AddFeature(MAttrs[i]);
    FeaturesStr = Features.getString();
  }

  std::auto_ptr<TargetMachine>
    target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
  assert(target.get() && "Could not allocate target machine!");
  TargetMachine &Target = *target.get();

  // Figure out where we are going to send the output...
  formatted_raw_ostream *Out = GetOutputStream(TheTarget->getName(), argv[0]);
  if (Out == 0) return 1;

  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  switch (OptLevel) {
  default:
    errs() << argv[0] << ": invalid optimization level.\n";
    return 1;
  case ' ': break;
  case '0': OLvl = CodeGenOpt::None; break;
  case '1': OLvl = CodeGenOpt::Less; break;
  case '2': OLvl = CodeGenOpt::Default; break;
  case '3': OLvl = CodeGenOpt::Aggressive; break;
  }

  // Request that addPassesToEmitFile run the Verifier after running
  // passes which modify the IR.
#ifndef NDEBUG
  bool DisableVerify = false;
#else
  bool DisableVerify = true;
#endif

  // If this target requires addPassesToEmitWholeFile, do it now.  This is
  // used by strange things like the C backend.
  if (Target.WantsWholeFile()) {
    PassManager PM;

    // Add the target data from the target machine, if it exists, or the module.
    if (const TargetData *TD = Target.getTargetData())
      PM.add(new TargetData(*TD));
    else
      PM.add(new TargetData(&mod));

    if (!NoVerify)
      PM.add(createVerifierPass());

    // Ask the target to add backend passes as necessary.
    if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, OLvl,
                                        DisableVerify)) {
      errs() << argv[0] << ": target does not support generation of this"
             << " file type!\n";
      if (Out != &fouts()) delete Out;
      // And the Out file is empty and useless, so remove it now.
      sys::Path(OutputFilename).eraseFromDisk();
      return 1;
    }
    PM.run(mod);
  } else {
    // Build up all of the passes that we want to do to the module.
    FunctionPassManager Passes(M.get());

    // Add the target data from the target machine, if it exists, or the module.
    if (const TargetData *TD = Target.getTargetData())
      Passes.add(new TargetData(*TD));
    else
      Passes.add(new TargetData(&mod));

#ifndef NDEBUG
    if (!NoVerify)
      Passes.add(createVerifierPass());
#endif

    // Override default to generate verbose assembly.
    Target.setAsmVerbosityDefault(true);

    if (Target.addPassesToEmitFile(Passes, *Out, FileType, OLvl,
                                   DisableVerify)) {
      errs() << argv[0] << ": target does not support generation of this"
             << " file type!\n";
      if (Out != &fouts()) delete Out;
      // And the Out file is empty and useless, so remove it now.
      sys::Path(OutputFilename).eraseFromDisk();
      return 1;
    }

    Passes.doInitialization();

    // Run our queue of passes all at once now, efficiently.
    // TODO: this could lazily stream functions out of the module.
    for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I)
      if (!I->isDeclaration()) {
        if (DisableRedZone)
          I->addFnAttr(Attribute::NoRedZone);
        if (NoImplicitFloats)
          I->addFnAttr(Attribute::NoImplicitFloat);
        Passes.run(*I);
      }

    Passes.doFinalization();
  }

  // Delete the ostream if it's not a stdout stream
  if (Out != &fouts()) delete Out;

  return 0;
}
<commit_msg>llc doesn't need LinkAllVMCore.<commit_after>//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the llc code generator driver. It provides a convenient
// command-line interface for generating native assembly-language code
// or C code, given LLVM bitcode.
//
//===----------------------------------------------------------------------===//

#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/PassManager.h"
#include "llvm/Pass.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Support/IRReader.h"
#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
#include "llvm/CodeGen/LinkAllCodegenComponents.h"
#include "llvm/Config/config.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PluginLoader.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/System/Host.h"
#include "llvm/System/Signals.h"
#include "llvm/Target/SubtargetFeature.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegistry.h"
#include "llvm/Target/TargetSelect.h"
#include "llvm/Transforms/Scalar.h"
#include <memory>
using namespace llvm;

// General options for llc.  Other pass-specific options are specified
// within the corresponding llc passes, and target-specific options
// and back-end code generation options are specified with the target machine.
//
static cl::opt<std::string>
InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));

static cl::opt<std::string>
OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));

static cl::opt<bool>
Force("f", cl::desc("Enable binary output on terminals"));

// Determine optimization level.
static cl::opt<char>
OptLevel("O",
         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
                  "(default = '-O2')"),
         cl::Prefix,
         cl::ZeroOrMore,
         cl::init(' '));

static cl::opt<std::string>
TargetTriple("mtriple", cl::desc("Override target triple for module"));

static cl::opt<std::string>
MArch("march", cl::desc("Architecture to generate code for (see --version)"));

static cl::opt<std::string>
MCPU("mcpu",
  cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  cl::value_desc("cpu-name"),
  cl::init(""));

static cl::list<std::string>
MAttrs("mattr",
  cl::CommaSeparated,
  cl::desc("Target specific attributes (-mattr=help for details)"),
  cl::value_desc("a1,+a2,-a3,..."));

cl::opt<TargetMachine::CodeGenFileType>
FileType("filetype", cl::init(TargetMachine::CGFT_AssemblyFile),
  cl::desc("Choose a file type (not all types are supported by all targets):"),
  cl::values(
       clEnumValN(TargetMachine::CGFT_AssemblyFile, "asm",
                  "Emit an assembly ('.s') file"),
       clEnumValN(TargetMachine::CGFT_ObjectFile, "obj",
                  "Emit a native object ('.o') file [experimental]"),
       clEnumValN(TargetMachine::CGFT_Null, "null",
                  "Emit nothing, for performance testing"),
       clEnumValEnd));

cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
                       cl::desc("Do not verify input module"));

static cl::opt<bool>
DisableRedZone("disable-red-zone",
  cl::desc("Do not emit code that uses the red zone."),
  cl::init(false));

static cl::opt<bool>
NoImplicitFloats("no-implicit-float",
  cl::desc("Don't generate implicit floating point instructions (x86-only)"),
  cl::init(false));

// GetFileNameRoot - Helper function to get the basename of a filename.
static inline std::string
GetFileNameRoot(const std::string &InputFilename) {
  std::string IFN = InputFilename;
  std::string outputFilename;
  int Len = IFN.length();
  if ((Len > 2) &&
      IFN[Len-3] == '.' &&
      ((IFN[Len-2] == 'b' && IFN[Len-1] == 'c') ||
       (IFN[Len-2] == 'l' && IFN[Len-1] == 'l'))) {
    outputFilename = std::string(IFN.begin(), IFN.end()-3); // s/.bc/.s/
  } else {
    outputFilename = IFN;
  }
  return outputFilename;
}

static formatted_raw_ostream *GetOutputStream(const char *TargetName,
                                              const char *ProgName) {
  if (OutputFilename != "") {
    if (OutputFilename == "-")
      return &fouts();

    // Make sure that the Out file gets unlinked from the disk if we get a
    // SIGINT
    sys::RemoveFileOnSignal(sys::Path(OutputFilename));

    std::string error;
    raw_fd_ostream *FDOut =
      new raw_fd_ostream(OutputFilename.c_str(), error,
                         raw_fd_ostream::F_Binary);
    if (!error.empty()) {
      errs() << error << '\n';
      delete FDOut;
      return 0;
    }
    formatted_raw_ostream *Out =
      new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);

    return Out;
  }

  if (InputFilename == "-") {
    OutputFilename = "-";
    return &fouts();
  }

  OutputFilename = GetFileNameRoot(InputFilename);

  bool Binary = false;
  switch (FileType) {
  default: assert(0 && "Unknown file type");
  case TargetMachine::CGFT_AssemblyFile:
    if (TargetName[0] == 'c') {
      if (TargetName[1] == 0)
        OutputFilename += ".cbe.c";
      else if (TargetName[1] == 'p' && TargetName[2] == 'p')
        OutputFilename += ".cpp";
      else
        OutputFilename += ".s";
    } else
      OutputFilename += ".s";
    break;
  case TargetMachine::CGFT_ObjectFile:
    OutputFilename += ".o";
    Binary = true;
    break;
  case TargetMachine::CGFT_Null:
    OutputFilename += ".null";
    Binary = true;
    break;
  }

  // Make sure that the Out file gets unlinked from the disk if we get a
  // SIGINT
  sys::RemoveFileOnSignal(sys::Path(OutputFilename));

  std::string error;
  unsigned OpenFlags = 0;
  if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
  raw_fd_ostream *FDOut = new raw_fd_ostream(OutputFilename.c_str(), error,
                                             OpenFlags);
  if (!error.empty()) {
    errs() << error << '\n';
    delete FDOut;
    return 0;
  }

  formatted_raw_ostream *Out =
    new formatted_raw_ostream(*FDOut, formatted_raw_ostream::DELETE_STREAM);

  return Out;
}

// main - Entry point for the llc compiler.
//
int main(int argc, char **argv) {
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);

  // Enable debug stream buffering.
  EnableDebugBuffering = true;

  LLVMContext &Context = getGlobalContext();
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.

  // Initialize targets first, so that --version shows registered targets.
  InitializeAllTargets();
  InitializeAllAsmPrinters();

  cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");

  // Load the module to be compiled...
  SMDiagnostic Err;
  std::auto_ptr<Module> M;

  M.reset(ParseIRFile(InputFilename, Err, Context));
  if (M.get() == 0) {
    Err.Print(argv[0], errs());
    return 1;
  }
  Module &mod = *M.get();

  // If we are supposed to override the target triple, do so now.
  if (!TargetTriple.empty())
    mod.setTargetTriple(TargetTriple);

  Triple TheTriple(mod.getTargetTriple());
  if (TheTriple.getTriple().empty())
    TheTriple.setTriple(sys::getHostTriple());

  // Allocate target machine.  First, check whether the user has explicitly
  // specified an architecture to compile for. If so we have to look it up by
  // name, because it might be a backend that has no mapping to a target triple.
  const Target *TheTarget = 0;
  if (!MArch.empty()) {
    for (TargetRegistry::iterator it = TargetRegistry::begin(),
           ie = TargetRegistry::end(); it != ie; ++it) {
      if (MArch == it->getName()) {
        TheTarget = &*it;
        break;
      }
    }

    if (!TheTarget) {
      errs() << argv[0] << ": error: invalid target '" << MArch << "'.\n";
      return 1;
    }

    // Adjust the triple to match (if known), otherwise stick with the
    // module/host triple.
    Triple::ArchType Type = Triple::getArchTypeForLLVMName(MArch);
    if (Type != Triple::UnknownArch)
      TheTriple.setArch(Type);
  } else {
    std::string Err;
    TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Err);
    if (TheTarget == 0) {
      errs() << argv[0] << ": error auto-selecting target for module '"
             << Err << "'.  Please use the -march option to explicitly "
             << "pick a target.\n";
      return 1;
    }
  }

  // Package up features to be passed to target/subtarget
  std::string FeaturesStr;
  if (MCPU.size() || MAttrs.size()) {
    SubtargetFeatures Features;
    Features.setCPU(MCPU);
    for (unsigned i = 0; i != MAttrs.size(); ++i)
      Features.AddFeature(MAttrs[i]);
    FeaturesStr = Features.getString();
  }

  std::auto_ptr<TargetMachine>
    target(TheTarget->createTargetMachine(TheTriple.getTriple(), FeaturesStr));
  assert(target.get() && "Could not allocate target machine!");
  TargetMachine &Target = *target.get();

  // Figure out where we are going to send the output...
  formatted_raw_ostream *Out = GetOutputStream(TheTarget->getName(), argv[0]);
  if (Out == 0) return 1;

  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  switch (OptLevel) {
  default:
    errs() << argv[0] << ": invalid optimization level.\n";
    return 1;
  case ' ': break;
  case '0': OLvl = CodeGenOpt::None; break;
  case '1': OLvl = CodeGenOpt::Less; break;
  case '2': OLvl = CodeGenOpt::Default; break;
  case '3': OLvl = CodeGenOpt::Aggressive; break;
  }

  // Request that addPassesToEmitFile run the Verifier after running
  // passes which modify the IR.
#ifndef NDEBUG
  bool DisableVerify = false;
#else
  bool DisableVerify = true;
#endif

  // If this target requires addPassesToEmitWholeFile, do it now.  This is
  // used by strange things like the C backend.
  if (Target.WantsWholeFile()) {
    PassManager PM;

    // Add the target data from the target machine, if it exists, or the module.
    if (const TargetData *TD = Target.getTargetData())
      PM.add(new TargetData(*TD));
    else
      PM.add(new TargetData(&mod));

    if (!NoVerify)
      PM.add(createVerifierPass());

    // Ask the target to add backend passes as necessary.
    if (Target.addPassesToEmitWholeFile(PM, *Out, FileType, OLvl,
                                        DisableVerify)) {
      errs() << argv[0] << ": target does not support generation of this"
             << " file type!\n";
      if (Out != &fouts()) delete Out;
      // And the Out file is empty and useless, so remove it now.
      sys::Path(OutputFilename).eraseFromDisk();
      return 1;
    }
    PM.run(mod);
  } else {
    // Build up all of the passes that we want to do to the module.
    FunctionPassManager Passes(M.get());

    // Add the target data from the target machine, if it exists, or the module.
    if (const TargetData *TD = Target.getTargetData())
      Passes.add(new TargetData(*TD));
    else
      Passes.add(new TargetData(&mod));

#ifndef NDEBUG
    if (!NoVerify)
      Passes.add(createVerifierPass());
#endif

    // Override default to generate verbose assembly.
    Target.setAsmVerbosityDefault(true);

    if (Target.addPassesToEmitFile(Passes, *Out, FileType, OLvl,
                                   DisableVerify)) {
      errs() << argv[0] << ": target does not support generation of this"
             << " file type!\n";
      if (Out != &fouts()) delete Out;
      // And the Out file is empty and useless, so remove it now.
      sys::Path(OutputFilename).eraseFromDisk();
      return 1;
    }

    Passes.doInitialization();

    // Run our queue of passes all at once now, efficiently.
    // TODO: this could lazily stream functions out of the module.
    for (Module::iterator I = mod.begin(), E = mod.end(); I != E; ++I)
      if (!I->isDeclaration()) {
        if (DisableRedZone)
          I->addFnAttr(Attribute::NoRedZone);
        if (NoImplicitFloats)
          I->addFnAttr(Attribute::NoImplicitFloat);
        Passes.run(*I);
      }

    Passes.doFinalization();
  }

  // Delete the ostream if it's not a stdout stream
  if (Out != &fouts()) delete Out;

  return 0;
}
<|endoftext|>