<commit_before>// Copyright (c) 2016 Greenheart Games Pty. Ltd. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "nan.h"
#include "steam/steam_api.h"
#include "steam/steamencryptedappticket.h"
#include "v8.h"

#include "greenworks_async_workers.h"
#include "steam_api_registry.h"

namespace greenworks {
namespace api {
namespace {

NAN_METHOD(GetAuthSessionTicket) {
  Nan::HandleScope scope;
  if (info.Length() < 1 || !info[0]->IsFunction()) {
    THROW_BAD_ARGS("Bad arguments");
  }
  Nan::Callback* success_callback =
      new Nan::Callback(info[0].As<v8::Function>());
  Nan::Callback* error_callback = NULL;
  if (info.Length() > 1 && info[1]->IsFunction())
    error_callback = new Nan::Callback(info[1].As<v8::Function>());
  Nan::AsyncQueueWorker(new greenworks::GetAuthSessionTicketWorker(
    success_callback, error_callback));
  info.GetReturnValue().Set(Nan::Undefined());
}

NAN_METHOD(CancelAuthTicket) {
  Nan::HandleScope scope;
  if (info.Length() < 1 || !info[0]->IsNumber()) {
    THROW_BAD_ARGS("Bad arguments");
  }
  HAuthTicket h = info[1].As<v8::Number>()->Int32Value();
  SteamUser()->CancelAuthTicket(h);
  info.GetReturnValue().Set(Nan::Undefined());
}

NAN_METHOD(GetEncryptedAppTicket) {
  Nan::HandleScope scope;
  if (info.Length() < 2 || !info[0]->IsString() || !info[1]->IsFunction()) {
    THROW_BAD_ARGS("Bad arguments");
  }
  char* user_data = *(static_cast<v8::String::Utf8Value>(info[0]->ToString()));
  if (!user_data) {
    THROW_BAD_ARGS("Bad arguments");
  }
  Nan::Callback* success_callback =
      new Nan::Callback(info[1].As<v8::Function>());
  Nan::Callback* error_callback = NULL;
  if (info.Length() > 2 && info[2]->IsFunction())
    error_callback = new Nan::Callback(info[2].As<v8::Function>());
  Nan::AsyncQueueWorker(new greenworks::RequestEncryptedAppTicketWorker(
    user_data, success_callback, error_callback));
  info.GetReturnValue().Set(Nan::Undefined());
}

NAN_METHOD(DecryptAppTicket) {
  Nan::HandleScope scope;
  if (info.Length() < 2 || !node::Buffer::HasInstance(info[0]) ||
      !node::Buffer::HasInstance(info[1])) {
    THROW_BAD_ARGS("Bad arguments");
  }
  char* encrypted_ticket_buf = node::Buffer::Data(info[0]);
  size_t encrypted_ticket_buf_size = node::Buffer::Length(info[0]);
  char* key_buf = node::Buffer::Data(info[1]);
  if (node::Buffer::Length(info[1]) !=
      k_nSteamEncryptedAppTicketSymmetricKeyLen) {
    THROW_BAD_ARGS("The key length is not matched");
  }
  uint8 key[k_nSteamEncryptedAppTicketSymmetricKeyLen];
  memcpy(key, key_buf, k_nSteamEncryptedAppTicketSymmetricKeyLen);

  uint8 decrypted_ticket[1024];
  uint32 decrypted_ticket_size = 1024;
  bool is_success = SteamEncryptedAppTicket_BDecryptTicket(
      reinterpret_cast<const uint8*>(encrypted_ticket_buf),
      encrypted_ticket_buf_size, decrypted_ticket, &decrypted_ticket_size, key,
      k_nSteamEncryptedAppTicketSymmetricKeyLen);

  if (!is_success) {
    info.GetReturnValue().Set(Nan::Undefined());
    return;
  }
  info.GetReturnValue().Set(
      Nan::CopyBuffer(reinterpret_cast<const char *>(decrypted_ticket),
                      decrypted_ticket_size)
          .ToLocalChecked());
}

void RegisterAPIs(v8::Handle<v8::Object> target) {
  Nan::Set(target,
           Nan::New("getAuthSessionTicket").ToLocalChecked(),
           Nan::New<v8::FunctionTemplate>(GetAuthSessionTicket)->GetFunction());
  Nan::Set(target,
           Nan::New("getEncryptedAppTicket").ToLocalChecked(),
           Nan::New<v8::FunctionTemplate>(
               GetEncryptedAppTicket)->GetFunction());
  Nan::Set(target,
           Nan::New("decryptAppTicket").ToLocalChecked(),
           Nan::New<v8::FunctionTemplate>(
               DecryptAppTicket)->GetFunction());
  Nan::Set(target,
           Nan::New("cancelAuthTicket").ToLocalChecked(),
           Nan::New<v8::FunctionTemplate>(CancelAuthTicket)->GetFunction());
}

SteamAPIRegistry::Add X(RegisterAPIs);

}  // namespace
}  // namespace api
}  // namespace greenworks
<commit_msg>Implement IsTicketForApp() API.<commit_after>// Copyright (c) 2016 Greenheart Games Pty. Ltd. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "nan.h"
#include "steam/steam_api.h"
#include "steam/steamencryptedappticket.h"
#include "v8.h"

#include "greenworks_async_workers.h"
#include "steam_api_registry.h"

namespace greenworks {
namespace api {
namespace {

NAN_METHOD(GetAuthSessionTicket) {
  Nan::HandleScope scope;
  if (info.Length() < 1 || !info[0]->IsFunction()) {
    THROW_BAD_ARGS("Bad arguments");
  }
  Nan::Callback* success_callback =
      new Nan::Callback(info[0].As<v8::Function>());
  Nan::Callback* error_callback = NULL;
  if (info.Length() > 1 && info[1]->IsFunction())
    error_callback = new Nan::Callback(info[1].As<v8::Function>());
  Nan::AsyncQueueWorker(new greenworks::GetAuthSessionTicketWorker(
    success_callback, error_callback));
  info.GetReturnValue().Set(Nan::Undefined());
}

NAN_METHOD(CancelAuthTicket) {
  Nan::HandleScope scope;
  if (info.Length() < 1 || !info[0]->IsNumber()) {
    THROW_BAD_ARGS("Bad arguments");
  }
  HAuthTicket h = info[1].As<v8::Number>()->Int32Value();
  SteamUser()->CancelAuthTicket(h);
  info.GetReturnValue().Set(Nan::Undefined());
}

NAN_METHOD(GetEncryptedAppTicket) {
  Nan::HandleScope scope;
  if (info.Length() < 2 || !info[0]->IsString() || !info[1]->IsFunction()) {
    THROW_BAD_ARGS("Bad arguments");
  }
  char* user_data = *(static_cast<v8::String::Utf8Value>(info[0]->ToString()));
  if (!user_data) {
    THROW_BAD_ARGS("Bad arguments");
  }
  Nan::Callback* success_callback =
      new Nan::Callback(info[1].As<v8::Function>());
  Nan::Callback* error_callback = NULL;
  if (info.Length() > 2 && info[2]->IsFunction())
    error_callback = new Nan::Callback(info[2].As<v8::Function>());
  Nan::AsyncQueueWorker(new greenworks::RequestEncryptedAppTicketWorker(
    user_data, success_callback, error_callback));
  info.GetReturnValue().Set(Nan::Undefined());
}

NAN_METHOD(DecryptAppTicket) {
  Nan::HandleScope scope;
  if (info.Length() < 2 || !node::Buffer::HasInstance(info[0]) ||
      !node::Buffer::HasInstance(info[1])) {
    THROW_BAD_ARGS("Bad arguments");
  }
  char* encrypted_ticket_buf = node::Buffer::Data(info[0]);
  size_t encrypted_ticket_buf_size = node::Buffer::Length(info[0]);
  char* key_buf = node::Buffer::Data(info[1]);
  if (node::Buffer::Length(info[1]) !=
      k_nSteamEncryptedAppTicketSymmetricKeyLen) {
    THROW_BAD_ARGS("The key length is not matched");
  }
  uint8 key[k_nSteamEncryptedAppTicketSymmetricKeyLen];
  memcpy(key, key_buf, k_nSteamEncryptedAppTicketSymmetricKeyLen);

  uint8 decrypted_ticket[1024];
  uint32 decrypted_ticket_size = 1024;
  bool is_success = SteamEncryptedAppTicket_BDecryptTicket(
      reinterpret_cast<const uint8*>(encrypted_ticket_buf),
      encrypted_ticket_buf_size, decrypted_ticket, &decrypted_ticket_size, key,
      k_nSteamEncryptedAppTicketSymmetricKeyLen);

  if (!is_success) {
    info.GetReturnValue().Set(Nan::Undefined());
    return;
  }
  info.GetReturnValue().Set(
      Nan::CopyBuffer(reinterpret_cast<const char *>(decrypted_ticket),
                      decrypted_ticket_size)
          .ToLocalChecked());
}

NAN_METHOD(IsTicketForApp) {
  Nan::HandleScope scope;
  if (info.Length() < 2 || !node::Buffer::HasInstance(info[0]) ||
      info[1]->IsUint32()) {
    THROW_BAD_ARGS("Bad arguments");
  }

  char* decrypted_ticket_buf = node::Buffer::Data(info[0]);
  size_t decrypted_ticket_buf_size = node::Buffer::Length(info[0]);
  uint32 app_id = info[1]->Uint32Value();
  bool result = SteamEncryptedAppTicket_BIsTicketForApp(
      reinterpret_cast<uint8*>(decrypted_ticket_buf), decrypted_ticket_buf_size,
      app_id);
  info.GetReturnValue().Set(result);
}

void RegisterAPIs(v8::Handle<v8::Object> target) {
  Nan::Set(target,
           Nan::New("getAuthSessionTicket").ToLocalChecked(),
           Nan::New<v8::FunctionTemplate>(GetAuthSessionTicket)->GetFunction());
  Nan::Set(target,
           Nan::New("getEncryptedAppTicket").ToLocalChecked(),
           Nan::New<v8::FunctionTemplate>(
               GetEncryptedAppTicket)->GetFunction());
  Nan::Set(target,
           Nan::New("decryptAppTicket").ToLocalChecked(),
           Nan::New<v8::FunctionTemplate>(
               DecryptAppTicket)->GetFunction());
  Nan::Set(target,
           Nan::New("isTicketForApp").ToLocalChecked(),
           Nan::New<v8::FunctionTemplate>(
               IsTicketForApp)->GetFunction());
  Nan::Set(target,
           Nan::New("cancelAuthTicket").ToLocalChecked(),
           Nan::New<v8::FunctionTemplate>(CancelAuthTicket)->GetFunction());
}

SteamAPIRegistry::Add X(RegisterAPIs);

}  // namespace
}  // namespace api
}  // namespace greenworks
<|endoftext|>


<commit_before>/*******************************************************
 * Copyright (c) 2015, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <af/array.h>
#include <af/image.h>
#include "symbol_manager.hpp"

af_err af_gradient(af_array *dx, af_array *dy, const af_array in)
{
    return CALL(dx, dy, in);
}

af_err af_load_image(af_array *out, const char* filename, const bool isColor)
{
    return CALL(out, filename, isColor);
}

af_err af_save_image(const char* filename, const af_array in)
{
    return CALL(in);
}

af_err af_load_image_memory(af_array *out, const void* ptr)
{
    return CALL(out, ptr);
}

af_err af_save_image_memory(void** ptr, const af_array in, const af_image_format format)
{
    return CALL(ptr, in, format);
}

af_err af_delete_image_memory(void* ptr)
{
    return CALL(ptr);
}

af_err af_resize(af_array *out, const af_array in, const dim_t odim0, const dim_t odim1, const af_interp_type method)
{
    return CALL(out, in, odim0, odim1, method);
}

af_err af_transform(af_array *out, const af_array in, const af_array transform,
        const dim_t odim0, const dim_t odim1,
        const af_interp_type method, const bool inverse)
{
    return CALL(out, in, transform, odim0, odim1, method, inverse);
}

af_err af_rotate(af_array *out, const af_array in, const float theta,
        const bool crop, const af_interp_type method)
{
    return CALL(out, in, theta, crop, method);
}

af_err af_translate(af_array *out, const af_array in, const float trans0, const float trans1,
        const dim_t odim0, const dim_t odim1, const af_interp_type method)
{
    return CALL(out, in, trans0, trans1, odim0, odim1, method);
}

af_err af_scale(af_array *out, const af_array in, const float scale0, const float scale1,
        const dim_t odim0, const dim_t odim1, const af_interp_type method)
{
    return CALL(out, in, scale0, scale1, odim0, odim1, method);
}

af_err af_skew(af_array *out, const af_array in, const float skew0, const float skew1,
        const dim_t odim0, const dim_t odim1, const af_interp_type method,
        const bool inverse)
{
    return CALL(out, in, skew0, skew1, odim0, odim1, method, inverse);
}

af_err af_histogram(af_array *out, const af_array in, const unsigned nbins, const double minval, const double maxval)
{
    return CALL(out, in, nbins, minval, maxval);
}

af_err af_dilate(af_array *out, const af_array in, const af_array mask)
{
    return CALL(out, in, mask);
}

af_err af_dilate3(af_array *out, const af_array in, const af_array mask)
{
    return CALL(out, in, mask);
}

af_err af_erode(af_array *out, const af_array in, const af_array mask)
{
    return CALL(out, in, mask);
}

af_err af_erode3(af_array *out, const af_array in, const af_array mask)
{
    return CALL(out, in, mask);
}

af_err af_bilateral(af_array *out, const af_array in, const float spatial_sigma, const float chromatic_sigma, const bool isColor)
{
    return CALL(out, in, spatial_sigma, chromatic_sigma, isColor);
}

af_err af_mean_shift(af_array *out, const af_array in, const float spatial_sigma, const float chromatic_sigma, const unsigned iter, const bool is_color)
{
    return CALL(out, in, spatial_sigma, chromatic_sigma, iter, is_color);
}

af_err af_medfilt(af_array *out, const af_array in, const dim_t wind_length, const dim_t wind_width, const af_border_type edge_pad)
{
    return CALL(out, in, wind_length, wind_width, edge_pad);
}

af_err af_minfilt(af_array *out, const af_array in, const dim_t wind_length, const dim_t wind_width, const af_border_type edge_pad)
{
    return CALL(out, in, wind_length, wind_width, edge_pad);
}

af_err af_maxfilt(af_array *out, const af_array in, const dim_t wind_length, const dim_t wind_width, const af_border_type edge_pad)
{
    return CALL(out, in, wind_length, wind_width, edge_pad);
}

af_err af_regions(af_array *out, const af_array in, const af_connectivity connectivity, const af_dtype ty)
{
    return CALL(out, in, connectivity, ty);
}

af_err af_sobel_operator(af_array *dx, af_array *dy, const af_array img, const unsigned ker_size)
{
    return CALL(dx, dy, img, ker_size);
}

af_err af_rgb2gray(af_array* out, const af_array in, const float rPercent, const float gPercent, const float bPercent)
{
    return CALL(out, in, rPercent, gPercent, bPercent);
}

af_err af_gray2rgb(af_array* out, const af_array in, const float rFactor, const float gFactor, const float bFactor)
{
    return CALL(out, in, rFactor, gFactor, bFactor);
}

af_err af_hist_equal(af_array *out, const af_array in, const af_array hist)
{
    return CALL(out, in, hist);
}

af_err af_gaussian_kernel(af_array *out,
        const int rows, const int cols,
        const double sigma_r, const double sigma_c)
{
    return CALL(out, rows, cols, sigma_r, sigma_c);
}

af_err af_hsv2rgb(af_array* out, const af_array in)
{
    return CALL(out, in);
}

af_err af_rgb2hsv(af_array* out, const af_array in)
{
    return CALL(out, in);
}

af_err af_color_space(af_array *out, const af_array image, const af_cspace_t to, const af_cspace_t from)
{
    return CALL(out, image, to, from);
}

af_err af_unwrap(af_array *out, const af_array in, const dim_t wx, const dim_t wy,
        const dim_t sx, const dim_t sy, const dim_t px, const dim_t py,
        const bool is_column)
{
    return CALL(out, in, wx, wy, sx, sy, px, py, is_column);
}

af_err af_wrap(af_array *out,
        const af_array in,
        const dim_t ox, const dim_t oy,
        const dim_t wx, const dim_t wy,
        const dim_t sx, const dim_t sy,
        const dim_t px, const dim_t py,
        const bool is_column)
{
    return CALL(out, in, ox, oy, wx, wy, sx, sy, px, py, is_column);
}

af_err af_sat(af_array *out, const af_array in)
{
    return CALL(out, in);
}

af_err af_ycbcr2rgb(af_array* out, const af_array in, const af_ycc_std standard)
{
    return CALL(out, in, standard);
}

af_err af_rgb2ycbcr(af_array* out, const af_array in, const af_ycc_std standard)
{
    return CALL(out, in, standard);
}
<commit_msg>fix in unified api for af_save_image<commit_after>/*******************************************************
 * Copyright (c) 2015, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <af/array.h>
#include <af/image.h>
#include "symbol_manager.hpp"

af_err af_gradient(af_array *dx, af_array *dy, const af_array in)
{
    return CALL(dx, dy, in);
}

af_err af_load_image(af_array *out, const char* filename, const bool isColor)
{
    return CALL(out, filename, isColor);
}

af_err af_save_image(const char* filename, const af_array in)
{
    return CALL(filename, in);
}

af_err af_load_image_memory(af_array *out, const void* ptr)
{
    return CALL(out, ptr);
}

af_err af_save_image_memory(void** ptr, const af_array in, const af_image_format format)
{
    return CALL(ptr, in, format);
}

af_err af_delete_image_memory(void* ptr)
{
    return CALL(ptr);
}

af_err af_resize(af_array *out, const af_array in, const dim_t odim0, const dim_t odim1, const af_interp_type method)
{
    return CALL(out, in, odim0, odim1, method);
}

af_err af_transform(af_array *out, const af_array in, const af_array transform,
        const dim_t odim0, const dim_t odim1,
        const af_interp_type method, const bool inverse)
{
    return CALL(out, in, transform, odim0, odim1, method, inverse);
}

af_err af_rotate(af_array *out, const af_array in, const float theta,
        const bool crop, const af_interp_type method)
{
    return CALL(out, in, theta, crop, method);
}

af_err af_translate(af_array *out, const af_array in, const float trans0, const float trans1,
        const dim_t odim0, const dim_t odim1, const af_interp_type method)
{
    return CALL(out, in, trans0, trans1, odim0, odim1, method);
}

af_err af_scale(af_array *out, const af_array in, const float scale0, const float scale1,
        const dim_t odim0, const dim_t odim1, const af_interp_type method)
{
    return CALL(out, in, scale0, scale1, odim0, odim1, method);
}

af_err af_skew(af_array *out, const af_array in, const float skew0, const float skew1,
        const dim_t odim0, const dim_t odim1, const af_interp_type method,
        const bool inverse)
{
    return CALL(out, in, skew0, skew1, odim0, odim1, method, inverse);
}

af_err af_histogram(af_array *out, const af_array in, const unsigned nbins, const double minval, const double maxval)
{
    return CALL(out, in, nbins, minval, maxval);
}

af_err af_dilate(af_array *out, const af_array in, const af_array mask)
{
    return CALL(out, in, mask);
}

af_err af_dilate3(af_array *out, const af_array in, const af_array mask)
{
    return CALL(out, in, mask);
}

af_err af_erode(af_array *out, const af_array in, const af_array mask)
{
    return CALL(out, in, mask);
}

af_err af_erode3(af_array *out, const af_array in, const af_array mask)
{
    return CALL(out, in, mask);
}

af_err af_bilateral(af_array *out, const af_array in, const float spatial_sigma, const float chromatic_sigma, const bool isColor)
{
    return CALL(out, in, spatial_sigma, chromatic_sigma, isColor);
}

af_err af_mean_shift(af_array *out, const af_array in, const float spatial_sigma, const float chromatic_sigma, const unsigned iter, const bool is_color)
{
    return CALL(out, in, spatial_sigma, chromatic_sigma, iter, is_color);
}

af_err af_medfilt(af_array *out, const af_array in, const dim_t wind_length, const dim_t wind_width, const af_border_type edge_pad)
{
    return CALL(out, in, wind_length, wind_width, edge_pad);
}

af_err af_minfilt(af_array *out, const af_array in, const dim_t wind_length, const dim_t wind_width, const af_border_type edge_pad)
{
    return CALL(out, in, wind_length, wind_width, edge_pad);
}

af_err af_maxfilt(af_array *out, const af_array in, const dim_t wind_length, const dim_t wind_width, const af_border_type edge_pad)
{
    return CALL(out, in, wind_length, wind_width, edge_pad);
}

af_err af_regions(af_array *out, const af_array in, const af_connectivity connectivity, const af_dtype ty)
{
    return CALL(out, in, connectivity, ty);
}

af_err af_sobel_operator(af_array *dx, af_array *dy, const af_array img, const unsigned ker_size)
{
    return CALL(dx, dy, img, ker_size);
}

af_err af_rgb2gray(af_array* out, const af_array in, const float rPercent, const float gPercent, const float bPercent)
{
    return CALL(out, in, rPercent, gPercent, bPercent);
}

af_err af_gray2rgb(af_array* out, const af_array in, const float rFactor, const float gFactor, const float bFactor)
{
    return CALL(out, in, rFactor, gFactor, bFactor);
}

af_err af_hist_equal(af_array *out, const af_array in, const af_array hist)
{
    return CALL(out, in, hist);
}

af_err af_gaussian_kernel(af_array *out,
        const int rows, const int cols,
        const double sigma_r, const double sigma_c)
{
    return CALL(out, rows, cols, sigma_r, sigma_c);
}

af_err af_hsv2rgb(af_array* out, const af_array in)
{
    return CALL(out, in);
}

af_err af_rgb2hsv(af_array* out, const af_array in)
{
    return CALL(out, in);
}

af_err af_color_space(af_array *out, const af_array image, const af_cspace_t to, const af_cspace_t from)
{
    return CALL(out, image, to, from);
}

af_err af_unwrap(af_array *out, const af_array in, const dim_t wx, const dim_t wy,
        const dim_t sx, const dim_t sy, const dim_t px, const dim_t py,
        const bool is_column)
{
    return CALL(out, in, wx, wy, sx, sy, px, py, is_column);
}

af_err af_wrap(af_array *out,
        const af_array in,
        const dim_t ox, const dim_t oy,
        const dim_t wx, const dim_t wy,
        const dim_t sx, const dim_t sy,
        const dim_t px, const dim_t py,
        const bool is_column)
{
    return CALL(out, in, ox, oy, wx, wy, sx, sy, px, py, is_column);
}

af_err af_sat(af_array *out, const af_array in)
{
    return CALL(out, in);
}

af_err af_ycbcr2rgb(af_array* out, const af_array in, const af_ycc_std standard)
{
    return CALL(out, in, standard);
}

af_err af_rgb2ycbcr(af_array* out, const af_array in, const af_ycc_std standard)
{
    return CALL(out, in, standard);
}
<|endoftext|>


<commit_before>#include "player.h"
#include <iostream>

Player::Player():
	jetpack(false)
{
	image = al_load_bitmap("data/char.png");
	x = 0;
	y = 0;
	move_left = false;
	move_right = false;
	jump = false;
}

void Player::Set_position(float ix, float iy)
{
	x = ix;
	y = iy - al_get_bitmap_height(image);
}

void Player::Event(ALLEGRO_EVENT& event)
{
	if(ALLEGRO_EVENT_KEY_DOWN == event.type)
	{
		if(ALLEGRO_KEY_LEFT == event.keyboard.keycode)
		{
			move_left = true;
		}
		if(ALLEGRO_KEY_RIGHT == event.keyboard.keycode)
		{
			move_right = true;
		}
		if(ALLEGRO_KEY_LCTRL == event.keyboard.keycode)
		{
			jetpack = true;
			jump = false;
		}
		else if(ALLEGRO_KEY_UP == event.keyboard.keycode)
		{
			jump = true;
		}
	}
	if(ALLEGRO_EVENT_KEY_UP == event.type)
	{
		if(ALLEGRO_KEY_LEFT == event.keyboard.keycode)
		{
			move_left = false;
		}
		if(ALLEGRO_KEY_RIGHT == event.keyboard.keycode)
		{
			move_right = false;
		}
		if(ALLEGRO_KEY_LCTRL == event.keyboard.keycode)
		{
			jetpack = false;
		}
		if(ALLEGRO_KEY_UP == event.keyboard.keycode)
		{
			jump = false;
		}
	}
}

void Player::Update(float dt)
{
	//Accellerating
	float max_speed = 100;
	if(move_left)
	{
		float mdiff = max_speed + xs;
		xs -= mdiff*10*dt;
	}
	if(move_right)
	{
		float mdiff = max_speed - xs;
		xs += mdiff*10*dt;
	}

	//Jumping
	bool touching_ground = y>=600-al_get_bitmap_height(image); //Placeholder
	if(jump && touching_ground)
	{
		jump = false;
		ys -= 250;
	}

	//Stopping
	if(!(move_right || move_left))
	{
		xs -= 10*xs*dt;
	}

	//Gravity
	if(!touching_ground)
	{
		ys += 1000*dt;
	}

	//Thrust
	if(jetpack)
	{
		ys -= 3000*dt;
	}

	x += xs*dt;
	y += ys*dt;

	touching_ground = y>=600-al_get_bitmap_height(image); //Placeholder
	if(touching_ground)
	{
		ys = 0;
		y = 600 - al_get_bitmap_height(image);
	}
}

void Player::Draw()
{
	al_draw_bitmap(image, x, y, 0);
}
<commit_msg>Making variable initialization constant<commit_after>#include "player.h"
#include <iostream>

Player::Player():
	jetpack(false),
	image(al_load_bitmap("data/char.png")),
	x(0),
	y(0),
	move_left(false),
	move_right(false),
	jump(false)
{
}

void Player::Set_position(float ix, float iy)
{
	x = ix;
	y = iy - al_get_bitmap_height(image);
}

void Player::Event(ALLEGRO_EVENT& event)
{
	if(ALLEGRO_EVENT_KEY_DOWN == event.type)
	{
		if(ALLEGRO_KEY_LEFT == event.keyboard.keycode)
		{
			move_left = true;
		}
		if(ALLEGRO_KEY_RIGHT == event.keyboard.keycode)
		{
			move_right = true;
		}
		if(ALLEGRO_KEY_LCTRL == event.keyboard.keycode)
		{
			jetpack = true;
			jump = false;
		}
		else if(ALLEGRO_KEY_UP == event.keyboard.keycode)
		{
			jump = true;
		}
	}
	if(ALLEGRO_EVENT_KEY_UP == event.type)
	{
		if(ALLEGRO_KEY_LEFT == event.keyboard.keycode)
		{
			move_left = false;
		}
		if(ALLEGRO_KEY_RIGHT == event.keyboard.keycode)
		{
			move_right = false;
		}
		if(ALLEGRO_KEY_LCTRL == event.keyboard.keycode)
		{
			jetpack = false;
		}
		if(ALLEGRO_KEY_UP == event.keyboard.keycode)
		{
			jump = false;
		}
	}
}

void Player::Update(float dt)
{
	//Accellerating
	float max_speed = 100;
	if(move_left)
	{
		float mdiff = max_speed + xs;
		xs -= mdiff*10*dt;
	}
	if(move_right)
	{
		float mdiff = max_speed - xs;
		xs += mdiff*10*dt;
	}

	//Jumping
	bool touching_ground = y>=600-al_get_bitmap_height(image); //Placeholder
	if(jump && touching_ground)
	{
		jump = false;
		ys -= 250;
	}

	//Stopping
	if(!(move_right || move_left))
	{
		xs -= 10*xs*dt;
	}

	//Gravity
	if(!touching_ground)
	{
		ys += 1000*dt;
	}

	//Thrust
	if(jetpack)
	{
		ys -= 3000*dt;
	}

	x += xs*dt;
	y += ys*dt;

	touching_ground = y>=600-al_get_bitmap_height(image); //Placeholder
	if(touching_ground)
	{
		ys = 0;
		y = 600 - al_get_bitmap_height(image);
	}
}

void Player::Draw()
{
	al_draw_bitmap(image, x, y, 0);
}
<|endoftext|>


<commit_before>#include "vector.h"
#include "unitizedmath.h"
#include "segmentparseexception.h"

#include <iostream>

namespace dewalls {

void Vector::deriveCtFromRect()
{
    ULength ne2 = usq(north()) + usq(east());
    ULength ne = usqrt(ne2); // horizontal offset
    ULength up = rectUp();
    if (!up.isValid()) up = ULength(0, Length::Meters);

    setDistance(usqrt(ne2 + usq(up)).in(units().dUnit()) - units().incd());
    UAngle azm = uatan2(east(), north()).in(units().aUnit()) - units().inca();
    if (azm < UAngle(0, Angle::Degrees))
    {
        azm += UAngle(360.0, Angle::Degrees);
    }
    setFrontAzimuth(azm);
    setFrontInclination(uatan2(up, ne).in(units().vUnit()) - units().incv());
}

bool Vector::isVertical()
{
    return units().isVertical(frontInclination(), frontAzimuth());
}

void Vector::applyHeightCorrections()
{
    if (!isVertical() && (units().inch().isNonzero() || instHeight().isNonzero() || targetHeight().isNonzero()))
    {
        UAngle inc = units().avgInc(frontInclination() + units().incv(), backInclination() + units().incvb());
        if (!inc.isValid()) inc = UAngle(0, Angle::Degrees);
        double sini = usin(inc);
        double cosi = ucos(inc);

        ULength tapeDist = distance() + units().incd();
        ULength _instHeight = instHeight();
        if (!_instHeight.isValid()) _instHeight = ULength(0, tapeDist.unit());
        ULength _targetHeight = targetHeight();
        if (!_targetHeight.isValid()) _targetHeight = ULength(0, tapeDist.unit());
        ULength tapeFromHeight = units().tape()[0] == TapingMethodMeasurement::Station ? ULength(0, tapeDist.unit()) : _instHeight;
        ULength tapeToHeight   = units().tape()[1] == TapingMethodMeasurement::Station ? ULength(0, tapeDist.unit()) : _targetHeight;
        ULength delta = (tapeToHeight - tapeFromHeight) - (_targetHeight - _instHeight);

        ULength unAdjusted = usqrt(usq(tapeDist) - usq(delta * cosi));
        if ((-unAdjusted - delta * sini).isPositive())
        {
            throw SegmentParseException(sourceSegment(), "vector is ambiguous; there are two possible vectors that satisfy the constraints imposed by the instrument/target heights, INCH and taping method");
        }

        ULength distAlongInc = unAdjusted - delta * sini;

        ULength totalDelta = _instHeight - _targetHeight + units().inch();

        ULength stationToStationDist = usqrt(usq(distAlongInc) + 2 * sini * umul(totalDelta, distAlongInc) + usq(totalDelta));
        unAdjusted = usqrt(usq(stationToStationDist) - usq(totalDelta * cosi));
        if ((-unAdjusted - totalDelta * sini).isPositive())
        {
            throw SegmentParseException(sourceSegment(), "vector is ambiguous; there are two possible vectors that satisfy the constraints imposed by the instrument/target heights, INCH and taping method");
        }

        UAngle  stationToStationInc  = inc + uatan(totalDelta * cosi / (distAlongInc + totalDelta * sini));

        setDistance(stationToStationDist - units().incd());

        UAngle dInc = stationToStationInc - inc;

        if (!frontInclination().isValid() && !backInclination().isValid())
        {
            setFrontInclination(stationToStationInc - units().incv());
        }
        else
        {
            setFrontInclination(frontInclination() + dInc - units().incv());
            setBackInclination (backInclination () + dInc - units().incvb());
        }
    }
}

} // namespace dewalls
<commit_msg>don't uncorrect when moving front/back inc<commit_after>#include "vector.h"
#include "unitizedmath.h"
#include "segmentparseexception.h"

#include <iostream>

namespace dewalls {

void Vector::deriveCtFromRect()
{
    ULength ne2 = usq(north()) + usq(east());
    ULength ne = usqrt(ne2); // horizontal offset
    ULength up = rectUp();
    if (!up.isValid()) up = ULength(0, Length::Meters);

    setDistance(usqrt(ne2 + usq(up)).in(units().dUnit()) - units().incd());
    UAngle azm = uatan2(east(), north()).in(units().aUnit()) - units().inca();
    if (azm < UAngle(0, Angle::Degrees))
    {
        azm += UAngle(360.0, Angle::Degrees);
    }
    setFrontAzimuth(azm);
    setFrontInclination(uatan2(up, ne).in(units().vUnit()) - units().incv());
}

bool Vector::isVertical()
{
    return units().isVertical(frontInclination(), frontAzimuth());
}

void Vector::applyHeightCorrections()
{
    if (!isVertical() && (units().inch().isNonzero() || instHeight().isNonzero() || targetHeight().isNonzero()))
    {
        UAngle inc = units().avgInc(frontInclination() + units().incv(), backInclination() + units().incvb());
        if (!inc.isValid()) inc = UAngle(0, Angle::Degrees);
        double sini = usin(inc);
        double cosi = ucos(inc);

        ULength tapeDist = distance() + units().incd();
        ULength _instHeight = instHeight();
        if (!_instHeight.isValid()) _instHeight = ULength(0, tapeDist.unit());
        ULength _targetHeight = targetHeight();
        if (!_targetHeight.isValid()) _targetHeight = ULength(0, tapeDist.unit());
        ULength tapeFromHeight = units().tape()[0] == TapingMethodMeasurement::Station ? ULength(0, tapeDist.unit()) : _instHeight;
        ULength tapeToHeight   = units().tape()[1] == TapingMethodMeasurement::Station ? ULength(0, tapeDist.unit()) : _targetHeight;
        ULength delta = (tapeToHeight - tapeFromHeight) - (_targetHeight - _instHeight);

        ULength unAdjusted = usqrt(usq(tapeDist) - usq(delta * cosi));
        if ((-unAdjusted - delta * sini).isPositive())
        {
            throw SegmentParseException(sourceSegment(), "vector is ambiguous; there are two possible vectors that satisfy the constraints imposed by the instrument/target heights, INCH and taping method");
        }

        ULength distAlongInc = unAdjusted - delta * sini;

        ULength totalDelta = _instHeight - _targetHeight + units().inch();

        ULength stationToStationDist = usqrt(usq(distAlongInc) + 2 * sini * umul(totalDelta, distAlongInc) + usq(totalDelta));
        unAdjusted = usqrt(usq(stationToStationDist) - usq(totalDelta * cosi));
        if ((-unAdjusted - totalDelta * sini).isPositive())
        {
            throw SegmentParseException(sourceSegment(), "vector is ambiguous; there are two possible vectors that satisfy the constraints imposed by the instrument/target heights, INCH and taping method");
        }

        UAngle  stationToStationInc  = inc + uatan(totalDelta * cosi / (distAlongInc + totalDelta * sini));

        setDistance(stationToStationDist - units().incd());

        if (!frontInclination().isValid() && !backInclination().isValid())
        {
            setFrontInclination(stationToStationInc - units().incv());
        }
        else
        {
            UAngle dInc = stationToStationInc - inc;
            setFrontInclination(frontInclination() + dInc);
            setBackInclination (backInclination () + dInc);
        }
    }
}

} // namespace dewalls
<|endoftext|>


<commit_before>//===- lib/Driver/GnuLdDriver.cpp -----------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// Concrete instance of the Driver for GNU's ld.
///
//===----------------------------------------------------------------------===//

#include "lld/Driver/Driver.h"
#include "lld/Driver/GnuLdInputGraph.h"

#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"

using namespace lld;

namespace {

// Create enum with OPT_xxx values for each option in GnuLdOptions.td
enum {
  OPT_INVALID = 0,
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
               HELP, META) \
          OPT_##ID,
#include "GnuLdOptions.inc"
#undef OPTION
};

// Create prefix string literals used in GnuLdOptions.td
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "GnuLdOptions.inc"
#undef PREFIX

// Create table mapping all options defined in GnuLdOptions.td
static const llvm::opt::OptTable::Info infoTable[] = {
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
               HELPTEXT, METAVAR)   \
  { PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, llvm::opt::Option::KIND##Class, \
    PARAM, FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS },
#include "GnuLdOptions.inc"
#undef OPTION
};

// Create OptTable class for parsing actual command line arguments
class GnuLdOptTable : public llvm::opt::OptTable {
public:
  GnuLdOptTable() : OptTable(infoTable, llvm::array_lengthof(infoTable)){}
};

} // namespace

llvm::ErrorOr<StringRef> ELFFileNode::getPath(const LinkingContext &) const {
  if (!_isDashlPrefix)
    return _path;
  return _elfLinkingContext.searchLibrary(_path, _libraryPaths);
}

std::string ELFFileNode::errStr(error_code errc) {
  if (errc == llvm::errc::no_such_file_or_directory) {
    if (_isDashlPrefix)
      return (Twine("Unable to find library -l") + _path).str();
    return (Twine("Unable to find file ") + _path).str();
  }
  return FileNode::errStr(errc);
}

bool GnuLdDriver::linkELF(int argc, const char *argv[],
                          raw_ostream &diagnostics) {
  std::unique_ptr<ELFLinkingContext> options;
  if (!parse(argc, argv, options, diagnostics))
    return false;
  if (!options)
    return true;

  return link(*options, diagnostics);
}

bool GnuLdDriver::parse(int argc, const char *argv[],
                        std::unique_ptr<ELFLinkingContext> &context,
                        raw_ostream &diagnostics) {
  // Parse command line options using GnuLdOptions.td
  std::unique_ptr<llvm::opt::InputArgList> parsedArgs;
  GnuLdOptTable table;
  unsigned missingIndex;
  unsigned missingCount;

  parsedArgs.reset(
      table.ParseArgs(&argv[1], &argv[argc], missingIndex, missingCount));
  if (missingCount) {
    diagnostics << "error: missing arg value for '"
                << parsedArgs->getArgString(missingIndex) << "' expected "
                << missingCount << " argument(s).\n";
    return false;
  }

  // Handle --help
  if (parsedArgs->getLastArg(OPT_help)) {
    table.PrintHelp(llvm::outs(), argv[0], "LLVM Linker", false);
    return true;
  }

  // Use -target or use default target triple to instantiate LinkingContext
  llvm::Triple triple;
  if (llvm::opt::Arg *trip = parsedArgs->getLastArg(OPT_target))
    triple = llvm::Triple(trip->getValue());
  else
    triple = getDefaultTarget(argv[0]);
  std::unique_ptr<ELFLinkingContext> ctx(ELFLinkingContext::create(triple));

  if (!ctx) {
    diagnostics << "unknown target triple\n";
    return false;
  }

  std::unique_ptr<InputGraph> inputGraph(new InputGraph());
  std::stack<InputElement *> controlNodeStack;

  // Positional options for an Input File
  std::vector<StringRef> searchPath;
  bool isWholeArchive = false;
  bool asNeeded = false;
  bool _outputOptionSet = false;

  // Create a dynamic executable by default
  ctx->setOutputELFType(llvm::ELF::ET_EXEC);
  ctx->setIsStaticExecutable(false);
  ctx->setAllowShlibUndefines(false);
  ctx->setUseShlibUndefines(true);

  int index = 0;

  // Process all the arguments and create Input Elements
  for (auto inputArg : *parsedArgs) {
    switch (inputArg->getOption().getID()) {
    case OPT_mllvm:
      ctx->appendLLVMOption(inputArg->getValue());
      break;
    case OPT_relocatable:
      ctx->setOutputELFType(llvm::ELF::ET_REL);
      ctx->setPrintRemainingUndefines(false);
      ctx->setAllowRemainingUndefines(true);
      break;
    case OPT_static:
      ctx->setOutputELFType(llvm::ELF::ET_EXEC);
      ctx->setIsStaticExecutable(true);
      break;
    case OPT_shared:
      ctx->setOutputELFType(llvm::ELF::ET_DYN);
      ctx->setAllowShlibUndefines(true);
      ctx->setUseShlibUndefines(false);
      break;
    case OPT_e:
      ctx->setEntrySymbolName(inputArg->getValue());
      break;

    case OPT_output:
      _outputOptionSet = true;
      ctx->setOutputPath(inputArg->getValue());
      break;

    case OPT_noinhibit_exec:
      ctx->setAllowRemainingUndefines(true);
      break;

    case OPT_merge_strings:
      ctx->setMergeCommonStrings(true);
      break;

    case OPT_t:
      ctx->setLogInputFiles(true);
      break;

    case OPT_no_allow_shlib_undefs:
      ctx->setAllowShlibUndefines(false);
      break;

    case OPT_allow_shlib_undefs:
      ctx->setAllowShlibUndefines(true);
      break;

    case OPT_use_shlib_undefs:
      ctx->setUseShlibUndefines(true);
      break;

    case OPT_dynamic_linker:
      ctx->setInterpreter(inputArg->getValue());
      break;

    case OPT_nmagic:
      ctx->setOutputMagic(ELFLinkingContext::OutputMagic::NMAGIC);
      ctx->setIsStaticExecutable(true);
      break;

    case OPT_omagic:
      ctx->setOutputMagic(ELFLinkingContext::OutputMagic::OMAGIC);
      ctx->setIsStaticExecutable(true);
      break;

    case OPT_no_omagic:
      ctx->setOutputMagic(ELFLinkingContext::OutputMagic::DEFAULT);
      ctx->setNoAllowDynamicLibraries();
      break;

    case OPT_u:
      ctx->addInitialUndefinedSymbol(inputArg->getValue());
      break;

    case OPT_init:
      ctx->addInitFunction(inputArg->getValue());
      break;

    case OPT_fini:
      ctx->addFiniFunction(inputArg->getValue());
      break;

    case OPT_output_filetype:
      ctx->setOutputFileType(inputArg->getValue());
      break;

    case OPT_no_whole_archive:
      isWholeArchive = false;
      break;
    case OPT_whole_archive:
      isWholeArchive = true;
      break;
    case OPT_as_needed:
      asNeeded = true;
      break;
    case OPT_no_as_needed:
      asNeeded = false;
      break;
    case OPT_L:
      searchPath.push_back(inputArg->getValue());
      break;

    case OPT_start_group: {
      std::unique_ptr<InputElement> controlStart(new ELFGroup(*ctx, index++));
      controlNodeStack.push(controlStart.get());
      (dyn_cast<ControlNode>)(controlNodeStack.top())
          ->processControlEnter();
      inputGraph->addInputElement(std::move(controlStart));
      break;
    }

    case OPT_end_group:
      (dyn_cast<ControlNode>)(controlNodeStack.top())
          ->processControlExit();
      controlNodeStack.pop();
      break;

    case OPT_INPUT:
    case OPT_l: {
      std::unique_ptr<InputElement> inputFile(new ELFFileNode(
          *ctx, inputArg->getValue(), searchPath, index++, isWholeArchive,
          asNeeded, inputArg->getOption().getID() == OPT_l));
      if (controlNodeStack.empty())
        inputGraph->addInputElement(std::move(inputFile));
      else
        (dyn_cast<ControlNode>)(controlNodeStack.top())
            ->processInputElement(std::move(inputFile));
      break;
    }

    case OPT_rpath: {
      SmallVector<StringRef, 2> rpaths;
      StringRef(inputArg->getValue()).split(rpaths, ":");
      for (auto path : rpaths)
        ctx->addRpath(path);
      break;
    }

    case OPT_rpath_link: {
      SmallVector<StringRef, 2> rpaths;
      StringRef(inputArg->getValue()).split(rpaths, ":");
      for (auto path : rpaths)
        ctx->addRpathLink(path);
      break;
    }

    case OPT_sysroot:
      ctx->setSysroot(inputArg->getValue());
      break;

    case OPT_soname:
      ctx->setSharedObjectName(inputArg->getValue());
      break;

    default:
      break;
    } // end switch on option ID
  }   // end for

  if (!inputGraph->size()) {
    diagnostics << "No input files\n";
    return false;
  }

  // Set default output file name if the output file was not
  // specified.
  if (!_outputOptionSet) {
    switch (ctx->outputFileType()) {
    case LinkingContext::OutputFileType::YAML:
      ctx->setOutputPath("-");
      break;
    case LinkingContext::OutputFileType::Native:
      ctx->setOutputPath("a.native");
      break;
    default:
      ctx->setOutputPath("a.out");
      break;
    }
  }

  if (ctx->outputFileType() == LinkingContext::OutputFileType::YAML)
    inputGraph->dump(diagnostics);

  // Validate the combination of options used.
  if (!ctx->validate(diagnostics))
    return false;

  ctx->setInputGraph(std::move(inputGraph));

  context.swap(ctx);

  return true;
}

/// Get the default target triple based on either the program name
/// (e.g. "x86-ibm-linux-lld") or the primary target llvm was configured for.
llvm::Triple GnuLdDriver::getDefaultTarget(const char *progName) {
  SmallVector<StringRef, 4> components;
  llvm::SplitString(llvm::sys::path::stem(progName), components, "-");
  // If has enough parts to be start with a triple.
  if (components.size() >= 4) {
    llvm::Triple triple(components[0], components[1], components[2],
                        components[3]);
    // If first component looks like an arch.
    if (triple.getArch() != llvm::Triple::UnknownArch)
      return triple;
  }

  // Fallback to use whatever default triple llvm was configured for.
  return llvm::Triple(llvm::sys::getDefaultTargetTriple());
}
<commit_msg>Remove extraneous parentheses.<commit_after>//===- lib/Driver/GnuLdDriver.cpp -----------------------------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// Concrete instance of the Driver for GNU's ld.
///
//===----------------------------------------------------------------------===//

#include "lld/Driver/Driver.h"
#include "lld/Driver/GnuLdInputGraph.h"

#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Signals.h"

using namespace lld;

namespace {

// Create enum with OPT_xxx values for each option in GnuLdOptions.td
enum {
  OPT_INVALID = 0,
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
               HELP, META) \
          OPT_##ID,
#include "GnuLdOptions.inc"
#undef OPTION
};

// Create prefix string literals used in GnuLdOptions.td
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "GnuLdOptions.inc"
#undef PREFIX

// Create table mapping all options defined in GnuLdOptions.td
static const llvm::opt::OptTable::Info infoTable[] = {
#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
               HELPTEXT, METAVAR)   \
  { PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, llvm::opt::Option::KIND##Class, \
    PARAM, FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS },
#include "GnuLdOptions.inc"
#undef OPTION
};

// Create OptTable class for parsing actual command line arguments
class GnuLdOptTable : public llvm::opt::OptTable {
public:
  GnuLdOptTable() : OptTable(infoTable, llvm::array_lengthof(infoTable)){}
};

} // namespace

llvm::ErrorOr<StringRef> ELFFileNode::getPath(const LinkingContext &) const {
  if (!_isDashlPrefix)
    return _path;
  return _elfLinkingContext.searchLibrary(_path, _libraryPaths);
}

std::string ELFFileNode::errStr(error_code errc) {
  if (errc == llvm::errc::no_such_file_or_directory) {
    if (_isDashlPrefix)
      return (Twine("Unable to find library -l") + _path).str();
    return (Twine("Unable to find file ") + _path).str();
  }
  return FileNode::errStr(errc);
}

bool GnuLdDriver::linkELF(int argc, const char *argv[],
                          raw_ostream &diagnostics) {
  std::unique_ptr<ELFLinkingContext> options;
  if (!parse(argc, argv, options, diagnostics))
    return false;
  if (!options)
    return true;

  return link(*options, diagnostics);
}

bool GnuLdDriver::parse(int argc, const char *argv[],
                        std::unique_ptr<ELFLinkingContext> &context,
                        raw_ostream &diagnostics) {
  // Parse command line options using GnuLdOptions.td
  std::unique_ptr<llvm::opt::InputArgList> parsedArgs;
  GnuLdOptTable table;
  unsigned missingIndex;
  unsigned missingCount;

  parsedArgs.reset(
      table.ParseArgs(&argv[1], &argv[argc], missingIndex, missingCount));
  if (missingCount) {
    diagnostics << "error: missing arg value for '"
                << parsedArgs->getArgString(missingIndex) << "' expected "
                << missingCount << " argument(s).\n";
    return false;
  }

  // Handle --help
  if (parsedArgs->getLastArg(OPT_help)) {
    table.PrintHelp(llvm::outs(), argv[0], "LLVM Linker", false);
    return true;
  }

  // Use -target or use default target triple to instantiate LinkingContext
  llvm::Triple triple;
  if (llvm::opt::Arg *trip = parsedArgs->getLastArg(OPT_target))
    triple = llvm::Triple(trip->getValue());
  else
    triple = getDefaultTarget(argv[0]);
  std::unique_ptr<ELFLinkingContext> ctx(ELFLinkingContext::create(triple));

  if (!ctx) {
    diagnostics << "unknown target triple\n";
    return false;
  }

  std::unique_ptr<InputGraph> inputGraph(new InputGraph());
  std::stack<InputElement *> controlNodeStack;

  // Positional options for an Input File
  std::vector<StringRef> searchPath;
  bool isWholeArchive = false;
  bool asNeeded = false;
  bool _outputOptionSet = false;

  // Create a dynamic executable by default
  ctx->setOutputELFType(llvm::ELF::ET_EXEC);
  ctx->setIsStaticExecutable(false);
  ctx->setAllowShlibUndefines(false);
  ctx->setUseShlibUndefines(true);

  int index = 0;

  // Process all the arguments and create Input Elements
  for (auto inputArg : *parsedArgs) {
    switch (inputArg->getOption().getID()) {
    case OPT_mllvm:
      ctx->appendLLVMOption(inputArg->getValue());
      break;
    case OPT_relocatable:
      ctx->setOutputELFType(llvm::ELF::ET_REL);
      ctx->setPrintRemainingUndefines(false);
      ctx->setAllowRemainingUndefines(true);
      break;
    case OPT_static:
      ctx->setOutputELFType(llvm::ELF::ET_EXEC);
      ctx->setIsStaticExecutable(true);
      break;
    case OPT_shared:
      ctx->setOutputELFType(llvm::ELF::ET_DYN);
      ctx->setAllowShlibUndefines(true);
      ctx->setUseShlibUndefines(false);
      break;
    case OPT_e:
      ctx->setEntrySymbolName(inputArg->getValue());
      break;

    case OPT_output:
      _outputOptionSet = true;
      ctx->setOutputPath(inputArg->getValue());
      break;

    case OPT_noinhibit_exec:
      ctx->setAllowRemainingUndefines(true);
      break;

    case OPT_merge_strings:
      ctx->setMergeCommonStrings(true);
      break;

    case OPT_t:
      ctx->setLogInputFiles(true);
      break;

    case OPT_no_allow_shlib_undefs:
      ctx->setAllowShlibUndefines(false);
      break;

    case OPT_allow_shlib_undefs:
      ctx->setAllowShlibUndefines(true);
      break;

    case OPT_use_shlib_undefs:
      ctx->setUseShlibUndefines(true);
      break;

    case OPT_dynamic_linker:
      ctx->setInterpreter(inputArg->getValue());
      break;

    case OPT_nmagic:
      ctx->setOutputMagic(ELFLinkingContext::OutputMagic::NMAGIC);
      ctx->setIsStaticExecutable(true);
      break;

    case OPT_omagic:
      ctx->setOutputMagic(ELFLinkingContext::OutputMagic::OMAGIC);
      ctx->setIsStaticExecutable(true);
      break;

    case OPT_no_omagic:
      ctx->setOutputMagic(ELFLinkingContext::OutputMagic::DEFAULT);
      ctx->setNoAllowDynamicLibraries();
      break;

    case OPT_u:
      ctx->addInitialUndefinedSymbol(inputArg->getValue());
      break;

    case OPT_init:
      ctx->addInitFunction(inputArg->getValue());
      break;

    case OPT_fini:
      ctx->addFiniFunction(inputArg->getValue());
      break;

    case OPT_output_filetype:
      ctx->setOutputFileType(inputArg->getValue());
      break;

    case OPT_no_whole_archive:
      isWholeArchive = false;
      break;
    case OPT_whole_archive:
      isWholeArchive = true;
      break;
    case OPT_as_needed:
      asNeeded = true;
      break;
    case OPT_no_as_needed:
      asNeeded = false;
      break;
    case OPT_L:
      searchPath.push_back(inputArg->getValue());
      break;

    case OPT_start_group: {
      std::unique_ptr<InputElement> controlStart(new ELFGroup(*ctx, index++));
      controlNodeStack.push(controlStart.get());
      dyn_cast<ControlNode>(controlNodeStack.top())->processControlEnter();
      inputGraph->addInputElement(std::move(controlStart));
      break;
    }

    case OPT_end_group:
      dyn_cast<ControlNode>(controlNodeStack.top())->processControlExit();
      controlNodeStack.pop();
      break;

    case OPT_INPUT:
    case OPT_l: {
      std::unique_ptr<InputElement> inputFile(new ELFFileNode(
          *ctx, inputArg->getValue(), searchPath, index++, isWholeArchive,
          asNeeded, inputArg->getOption().getID() == OPT_l));
      if (controlNodeStack.empty())
        inputGraph->addInputElement(std::move(inputFile));
      else
        dyn_cast<ControlNode>(controlNodeStack.top())
            ->processInputElement(std::move(inputFile));
      break;
    }

    case OPT_rpath: {
      SmallVector<StringRef, 2> rpaths;
      StringRef(inputArg->getValue()).split(rpaths, ":");
      for (auto path : rpaths)
        ctx->addRpath(path);
      break;
    }

    case OPT_rpath_link: {
      SmallVector<StringRef, 2> rpaths;
      StringRef(inputArg->getValue()).split(rpaths, ":");
      for (auto path : rpaths)
        ctx->addRpathLink(path);
      break;
    }

    case OPT_sysroot:
      ctx->setSysroot(inputArg->getValue());
      break;

    case OPT_soname:
      ctx->setSharedObjectName(inputArg->getValue());
      break;

    default:
      break;
    } // end switch on option ID
  }   // end for

  if (!inputGraph->size()) {
    diagnostics << "No input files\n";
    return false;
  }

  // Set default output file name if the output file was not
  // specified.
  if (!_outputOptionSet) {
    switch (ctx->outputFileType()) {
    case LinkingContext::OutputFileType::YAML:
      ctx->setOutputPath("-");
      break;
    case LinkingContext::OutputFileType::Native:
      ctx->setOutputPath("a.native");
      break;
    default:
      ctx->setOutputPath("a.out");
      break;
    }
  }

  if (ctx->outputFileType() == LinkingContext::OutputFileType::YAML)
    inputGraph->dump(diagnostics);

  // Validate the combination of options used.
  if (!ctx->validate(diagnostics))
    return false;

  ctx->setInputGraph(std::move(inputGraph));

  context.swap(ctx);

  return true;
}

/// Get the default target triple based on either the program name
/// (e.g. "x86-ibm-linux-lld") or the primary target llvm was configured for.
llvm::Triple GnuLdDriver::getDefaultTarget(const char *progName) {
  SmallVector<StringRef, 4> components;
  llvm::SplitString(llvm::sys::path::stem(progName), components, "-");
  // If has enough parts to be start with a triple.
  if (components.size() >= 4) {
    llvm::Triple triple(components[0], components[1], components[2],
                        components[3]);
    // If first component looks like an arch.
    if (triple.getArch() != llvm::Triple::UnknownArch)
      return triple;
  }

  // Fallback to use whatever default triple llvm was configured for.
  return llvm::Triple(llvm::sys::getDefaultTargetTriple());
}
<|endoftext|>


<commit_before>// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/v8.h"

#include "src/version.h"

// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION     4
#define MINOR_VERSION     2
#define BUILD_NUMBER      0
#define PATCH_LEVEL       0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1

// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME            ""

#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif

#define SX(x) #x
#define S(x) SX(x)

#if PATCH_LEVEL > 0
#define VERSION_STRING                                                         \
  S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." S(PATCH_LEVEL) \
      CANDIDATE_STRING
#else
#define VERSION_STRING \
  S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) CANDIDATE_STRING
#endif

namespace v8 {
namespace internal {

int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;

// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
  const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
  const char* is_simulator = " SIMULATOR";
#else
  const char* is_simulator = "";
#endif  // USE_SIMULATOR
  if (GetPatch() > 0) {
    SNPrintF(str, "%d.%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
             is_simulator);
  } else {
    SNPrintF(str, "%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), candidate,
             is_simulator);
  }
}

// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
  if (soname_ == NULL || *soname_ == '\0') {
    // Generate generic SONAME if no specific SONAME is defined.
    const char* candidate = IsCandidate() ? "-candidate" : "";
    if (GetPatch() > 0) {
      SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
    } else {
      SNPrintF(str, "libv8-%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), candidate);
    }
  } else {
    // Use specific SONAME.
    SNPrintF(str, "%s", soname_);
  }
}

} }  // namespace v8::internal
<commit_msg>Bump up version for 4.3 candidate.<commit_after>// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/v8.h"

#include "src/version.h"

// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION     4
#define MINOR_VERSION     3
#define BUILD_NUMBER      0
#define PATCH_LEVEL       0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1

// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME            ""

#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif

#define SX(x) #x
#define S(x) SX(x)

#if PATCH_LEVEL > 0
#define VERSION_STRING                                                         \
  S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." S(PATCH_LEVEL) \
      CANDIDATE_STRING
#else
#define VERSION_STRING \
  S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) CANDIDATE_STRING
#endif

namespace v8 {
namespace internal {

int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;

// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
  const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
  const char* is_simulator = " SIMULATOR";
#else
  const char* is_simulator = "";
#endif  // USE_SIMULATOR
  if (GetPatch() > 0) {
    SNPrintF(str, "%d.%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
             is_simulator);
  } else {
    SNPrintF(str, "%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), candidate,
             is_simulator);
  }
}

// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
  if (soname_ == NULL || *soname_ == '\0') {
    // Generate generic SONAME if no specific SONAME is defined.
    const char* candidate = IsCandidate() ? "-candidate" : "";
    if (GetPatch() > 0) {
      SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
    } else {
      SNPrintF(str, "libv8-%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), candidate);
    }
  } else {
    // Use specific SONAME.
    SNPrintF(str, "%s", soname_);
  }
}

} }  // namespace v8::internal
<|endoftext|>


<commit_before>// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/v8.h"

#include "src/version.h"

// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION     3
#define MINOR_VERSION     29
#define BUILD_NUMBER      5
#define PATCH_LEVEL       0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1

// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME            ""

#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif

#define SX(x) #x
#define S(x) SX(x)

#if PATCH_LEVEL > 0
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "."              \
        S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER)                  \
        CANDIDATE_STRING
#endif

namespace v8 {
namespace internal {

int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;

// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
  const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
  const char* is_simulator = " SIMULATOR";
#else
  const char* is_simulator = "";
#endif  // USE_SIMULATOR
  if (GetPatch() > 0) {
    SNPrintF(str, "%d.%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
             is_simulator);
  } else {
    SNPrintF(str, "%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), candidate,
             is_simulator);
  }
}

// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
  if (soname_ == NULL || *soname_ == '\0') {
    // Generate generic SONAME if no specific SONAME is defined.
    const char* candidate = IsCandidate() ? "-candidate" : "";
    if (GetPatch() > 0) {
      SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
    } else {
      SNPrintF(str, "libv8-%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), candidate);
    }
  } else {
    // Use specific SONAME.
    SNPrintF(str, "%s", soname_);
  }
}

} }  // namespace v8::internal
<commit_msg>[Auto-roll] Bump up version to 3.29.6.0<commit_after>// Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/v8.h"

#include "src/version.h"

// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION     3
#define MINOR_VERSION     29
#define BUILD_NUMBER      6
#define PATCH_LEVEL       0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1

// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME            ""

#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif

#define SX(x) #x
#define S(x) SX(x)

#if PATCH_LEVEL > 0
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "."              \
        S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING                                                         \
    S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER)                  \
        CANDIDATE_STRING
#endif

namespace v8 {
namespace internal {

int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;

// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
  const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
  const char* is_simulator = " SIMULATOR";
#else
  const char* is_simulator = "";
#endif  // USE_SIMULATOR
  if (GetPatch() > 0) {
    SNPrintF(str, "%d.%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
             is_simulator);
  } else {
    SNPrintF(str, "%d.%d.%d%s%s",
             GetMajor(), GetMinor(), GetBuild(), candidate,
             is_simulator);
  }
}

// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
  if (soname_ == NULL || *soname_ == '\0') {
    // Generate generic SONAME if no specific SONAME is defined.
    const char* candidate = IsCandidate() ? "-candidate" : "";
    if (GetPatch() > 0) {
      SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
    } else {
      SNPrintF(str, "libv8-%d.%d.%d%s.so",
               GetMajor(), GetMinor(), GetBuild(), candidate);
    }
  } else {
    // Use specific SONAME.
    SNPrintF(str, "%s", soname_);
  }
}

} }  // namespace v8::internal
<|endoftext|>


<commit_before>//===- LLVMContextImpl.cpp - Implement LLVMContextImpl --------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements the opaque LLVMContextImpl.
//
//===----------------------------------------------------------------------===//

#include "LLVMContextImpl.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/OptBisect.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/ManagedStatic.h"
#include <cassert>
#include <utility>

using namespace llvm;

LLVMContextImpl::LLVMContextImpl(LLVMContext &C)
  : DiagHandler(llvm::make_unique<DiagnosticHandler>()),
    VoidTy(C, Type::VoidTyID),
    LabelTy(C, Type::LabelTyID),
    HalfTy(C, Type::HalfTyID),
    FloatTy(C, Type::FloatTyID),
    DoubleTy(C, Type::DoubleTyID),
    MetadataTy(C, Type::MetadataTyID),
    TokenTy(C, Type::TokenTyID),
    X86_FP80Ty(C, Type::X86_FP80TyID),
    FP128Ty(C, Type::FP128TyID),
    PPC_FP128Ty(C, Type::PPC_FP128TyID),
    X86_MMXTy(C, Type::X86_MMXTyID),
    Int1Ty(C, 1),
    Int8Ty(C, 8),
    Int16Ty(C, 16),
    Int32Ty(C, 32),
    Int64Ty(C, 64),
    Int128Ty(C, 128) {}

LLVMContextImpl::~LLVMContextImpl() {
  // NOTE: We need to delete the contents of OwnedModules, but Module's dtor
  // will call LLVMContextImpl::removeModule, thus invalidating iterators into
  // the container. Avoid iterators during this operation:
  while (!OwnedModules.empty())
    delete *OwnedModules.begin();

  // Drop references for MDNodes.  Do this before Values get deleted to avoid
  // unnecessary RAUW when nodes are still unresolved.
  for (auto *I : DistinctMDNodes)
    I->dropAllReferences();
#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS)                                    \
  for (auto *I : CLASS##s)                                                     \
    I->dropAllReferences();
#include "llvm/IR/Metadata.def"

  // Also drop references that come from the Value bridges.
  for (auto &Pair : ValuesAsMetadata)
    Pair.second->dropUsers();
  for (auto &Pair : MetadataAsValues)
    Pair.second->dropUse();

  // Destroy MDNodes.
  for (MDNode *I : DistinctMDNodes)
    I->deleteAsSubclass();
#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS)                                    \
  for (CLASS * I : CLASS##s)                                                   \
    delete I;
#include "llvm/IR/Metadata.def"

  // Free the constants.
  for (auto *I : ExprConstants)
    I->dropAllReferences();
  for (auto *I : ArrayConstants)
    I->dropAllReferences();
  for (auto *I : StructConstants)
    I->dropAllReferences();
  for (auto *I : VectorConstants)
    I->dropAllReferences();
  ExprConstants.freeConstants();
  ArrayConstants.freeConstants();
  StructConstants.freeConstants();
  VectorConstants.freeConstants();
  InlineAsms.freeConstants();

  CAZConstants.clear();
  CPNConstants.clear();
  UVConstants.clear();
  IntConstants.clear();
  FPConstants.clear();

  for (auto &CDSConstant : CDSConstants)
    delete CDSConstant.second;
  CDSConstants.clear();

  // Destroy attributes.
  for (FoldingSetIterator<AttributeImpl> I = AttrsSet.begin(),
         E = AttrsSet.end(); I != E; ) {
    FoldingSetIterator<AttributeImpl> Elem = I++;
    delete &*Elem;
  }

  // Destroy attribute lists.
  for (FoldingSetIterator<AttributeListImpl> I = AttrsLists.begin(),
                                             E = AttrsLists.end();
       I != E;) {
    FoldingSetIterator<AttributeListImpl> Elem = I++;
    delete &*Elem;
  }

  // Destroy attribute node lists.
  for (FoldingSetIterator<AttributeSetNode> I = AttrsSetNodes.begin(),
         E = AttrsSetNodes.end(); I != E; ) {
    FoldingSetIterator<AttributeSetNode> Elem = I++;
    delete &*Elem;
  }

  // Destroy MetadataAsValues.
  {
    SmallVector<MetadataAsValue *, 8> MDVs;
    MDVs.reserve(MetadataAsValues.size());
    for (auto &Pair : MetadataAsValues)
      MDVs.push_back(Pair.second);
    MetadataAsValues.clear();
    for (auto *V : MDVs)
      delete V;
  }

  // Destroy ValuesAsMetadata.
  for (auto &Pair : ValuesAsMetadata)
    delete Pair.second;
}

void LLVMContextImpl::dropTriviallyDeadConstantArrays() {
  bool Changed;
  do {
    Changed = false;

    for (auto I = ArrayConstants.begin(), E = ArrayConstants.end(); I != E;) {
      auto *C = *I++;
      if (C->use_empty()) {
        Changed = true;
        C->destroyConstant();
      }
    }
  } while (Changed);
}

void Module::dropTriviallyDeadConstantArrays() {
  Context.pImpl->dropTriviallyDeadConstantArrays();
}

namespace llvm {

/// Make MDOperand transparent for hashing.
///
/// This overload of an implementation detail of the hashing library makes
/// MDOperand hash to the same value as a \a Metadata pointer.
///
/// Note that overloading \a hash_value() as follows:
///
/// \code
///     size_t hash_value(const MDOperand &X) { return hash_value(X.get()); }
/// \endcode
///
/// does not cause MDOperand to be transparent.  In particular, a bare pointer
/// doesn't get hashed before it's combined, whereas \a MDOperand would.
static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }

} // end namespace llvm

unsigned MDNodeOpsKey::calculateHash(MDNode *N, unsigned Offset) {
  unsigned Hash = hash_combine_range(N->op_begin() + Offset, N->op_end());
#ifndef NDEBUG
  {
    SmallVector<Metadata *, 8> MDs(N->op_begin() + Offset, N->op_end());
    unsigned RawHash = calculateHash(MDs);
    assert(Hash == RawHash &&
           "Expected hash of MDOperand to equal hash of Metadata*");
  }
#endif
  return Hash;
}

unsigned MDNodeOpsKey::calculateHash(ArrayRef<Metadata *> Ops) {
  return hash_combine_range(Ops.begin(), Ops.end());
}

StringMapEntry<uint32_t> *LLVMContextImpl::getOrInsertBundleTag(StringRef Tag) {
  uint32_t NewIdx = BundleTagCache.size();
  return &*(BundleTagCache.insert(std::make_pair(Tag, NewIdx)).first);
}

void LLVMContextImpl::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
  Tags.resize(BundleTagCache.size());
  for (const auto &T : BundleTagCache)
    Tags[T.second] = T.first();
}

uint32_t LLVMContextImpl::getOperandBundleTagID(StringRef Tag) const {
  auto I = BundleTagCache.find(Tag);
  assert(I != BundleTagCache.end() && "Unknown tag!");
  return I->second;
}

SyncScope::ID LLVMContextImpl::getOrInsertSyncScopeID(StringRef SSN) {
  auto NewSSID = SSC.size();
  assert(NewSSID < std::numeric_limits<SyncScope::ID>::max() &&
         "Hit the maximum number of synchronization scopes allowed!");
  return SSC.insert(std::make_pair(SSN, SyncScope::ID(NewSSID))).first->second;
}

void LLVMContextImpl::getSyncScopeNames(
    SmallVectorImpl<StringRef> &SSNs) const {
  SSNs.resize(SSC.size());
  for (const auto &SSE : SSC)
    SSNs[SSE.second] = SSE.first();
}

/// Singleton instance of the OptBisect class.
///
/// This singleton is accessed via the LLVMContext::getOptPassGate() function.
/// It provides a mechanism to disable passes and individual optimizations at
/// compile time based on a command line option (-opt-bisect-limit) in order to
/// perform a bisecting search for optimization-related problems.
///
/// Even if multiple LLVMContext objects are created, they will all return the
/// same instance of OptBisect in order to provide a single bisect count.  Any
/// code that uses the OptBisect object should be serialized when bisection is
/// enabled in order to enable a consistent bisect count.
static ManagedStatic<OptBisect> OptBisector;

OptPassGate &LLVMContextImpl::getOptPassGate() const {
  if (!OPG)
    OPG = &(*OptBisector);
  return *OPG;
}

void LLVMContextImpl::setOptPassGate(OptPassGate& OPG) {
  this->OPG = &OPG;
}
<commit_msg>[LLVMContext] Detecting leaked instructions with metadata<commit_after>//===- LLVMContextImpl.cpp - Implement LLVMContextImpl --------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements the opaque LLVMContextImpl.
//
//===----------------------------------------------------------------------===//

#include "LLVMContextImpl.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/OptBisect.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/ManagedStatic.h"
#include <cassert>
#include <utility>

using namespace llvm;

LLVMContextImpl::LLVMContextImpl(LLVMContext &C)
  : DiagHandler(llvm::make_unique<DiagnosticHandler>()),
    VoidTy(C, Type::VoidTyID),
    LabelTy(C, Type::LabelTyID),
    HalfTy(C, Type::HalfTyID),
    FloatTy(C, Type::FloatTyID),
    DoubleTy(C, Type::DoubleTyID),
    MetadataTy(C, Type::MetadataTyID),
    TokenTy(C, Type::TokenTyID),
    X86_FP80Ty(C, Type::X86_FP80TyID),
    FP128Ty(C, Type::FP128TyID),
    PPC_FP128Ty(C, Type::PPC_FP128TyID),
    X86_MMXTy(C, Type::X86_MMXTyID),
    Int1Ty(C, 1),
    Int8Ty(C, 8),
    Int16Ty(C, 16),
    Int32Ty(C, 32),
    Int64Ty(C, 64),
    Int128Ty(C, 128) {}

LLVMContextImpl::~LLVMContextImpl() {
  // NOTE: We need to delete the contents of OwnedModules, but Module's dtor
  // will call LLVMContextImpl::removeModule, thus invalidating iterators into
  // the container. Avoid iterators during this operation:
  while (!OwnedModules.empty())
    delete *OwnedModules.begin();

#ifndef NDEBUG
  // Check for metadata references from leaked Instructions.
  for (auto &Pair : InstructionMetadata)
    Pair.first->dump();
  assert(InstructionMetadata.empty() &&
         "Instructions with metadata have been leaked");
#endif

  // Drop references for MDNodes.  Do this before Values get deleted to avoid
  // unnecessary RAUW when nodes are still unresolved.
  for (auto *I : DistinctMDNodes)
    I->dropAllReferences();
#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS)                                    \
  for (auto *I : CLASS##s)                                                     \
    I->dropAllReferences();
#include "llvm/IR/Metadata.def"

  // Also drop references that come from the Value bridges.
  for (auto &Pair : ValuesAsMetadata)
    Pair.second->dropUsers();
  for (auto &Pair : MetadataAsValues)
    Pair.second->dropUse();

  // Destroy MDNodes.
  for (MDNode *I : DistinctMDNodes)
    I->deleteAsSubclass();
#define HANDLE_MDNODE_LEAF_UNIQUABLE(CLASS)                                    \
  for (CLASS * I : CLASS##s)                                                   \
    delete I;
#include "llvm/IR/Metadata.def"

  // Free the constants.
  for (auto *I : ExprConstants)
    I->dropAllReferences();
  for (auto *I : ArrayConstants)
    I->dropAllReferences();
  for (auto *I : StructConstants)
    I->dropAllReferences();
  for (auto *I : VectorConstants)
    I->dropAllReferences();
  ExprConstants.freeConstants();
  ArrayConstants.freeConstants();
  StructConstants.freeConstants();
  VectorConstants.freeConstants();
  InlineAsms.freeConstants();

  CAZConstants.clear();
  CPNConstants.clear();
  UVConstants.clear();
  IntConstants.clear();
  FPConstants.clear();

  for (auto &CDSConstant : CDSConstants)
    delete CDSConstant.second;
  CDSConstants.clear();

  // Destroy attributes.
  for (FoldingSetIterator<AttributeImpl> I = AttrsSet.begin(),
         E = AttrsSet.end(); I != E; ) {
    FoldingSetIterator<AttributeImpl> Elem = I++;
    delete &*Elem;
  }

  // Destroy attribute lists.
  for (FoldingSetIterator<AttributeListImpl> I = AttrsLists.begin(),
                                             E = AttrsLists.end();
       I != E;) {
    FoldingSetIterator<AttributeListImpl> Elem = I++;
    delete &*Elem;
  }

  // Destroy attribute node lists.
  for (FoldingSetIterator<AttributeSetNode> I = AttrsSetNodes.begin(),
         E = AttrsSetNodes.end(); I != E; ) {
    FoldingSetIterator<AttributeSetNode> Elem = I++;
    delete &*Elem;
  }

  // Destroy MetadataAsValues.
  {
    SmallVector<MetadataAsValue *, 8> MDVs;
    MDVs.reserve(MetadataAsValues.size());
    for (auto &Pair : MetadataAsValues)
      MDVs.push_back(Pair.second);
    MetadataAsValues.clear();
    for (auto *V : MDVs)
      delete V;
  }

  // Destroy ValuesAsMetadata.
  for (auto &Pair : ValuesAsMetadata)
    delete Pair.second;
}

void LLVMContextImpl::dropTriviallyDeadConstantArrays() {
  bool Changed;
  do {
    Changed = false;

    for (auto I = ArrayConstants.begin(), E = ArrayConstants.end(); I != E;) {
      auto *C = *I++;
      if (C->use_empty()) {
        Changed = true;
        C->destroyConstant();
      }
    }
  } while (Changed);
}

void Module::dropTriviallyDeadConstantArrays() {
  Context.pImpl->dropTriviallyDeadConstantArrays();
}

namespace llvm {

/// Make MDOperand transparent for hashing.
///
/// This overload of an implementation detail of the hashing library makes
/// MDOperand hash to the same value as a \a Metadata pointer.
///
/// Note that overloading \a hash_value() as follows:
///
/// \code
///     size_t hash_value(const MDOperand &X) { return hash_value(X.get()); }
/// \endcode
///
/// does not cause MDOperand to be transparent.  In particular, a bare pointer
/// doesn't get hashed before it's combined, whereas \a MDOperand would.
static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }

} // end namespace llvm

unsigned MDNodeOpsKey::calculateHash(MDNode *N, unsigned Offset) {
  unsigned Hash = hash_combine_range(N->op_begin() + Offset, N->op_end());
#ifndef NDEBUG
  {
    SmallVector<Metadata *, 8> MDs(N->op_begin() + Offset, N->op_end());
    unsigned RawHash = calculateHash(MDs);
    assert(Hash == RawHash &&
           "Expected hash of MDOperand to equal hash of Metadata*");
  }
#endif
  return Hash;
}

unsigned MDNodeOpsKey::calculateHash(ArrayRef<Metadata *> Ops) {
  return hash_combine_range(Ops.begin(), Ops.end());
}

StringMapEntry<uint32_t> *LLVMContextImpl::getOrInsertBundleTag(StringRef Tag) {
  uint32_t NewIdx = BundleTagCache.size();
  return &*(BundleTagCache.insert(std::make_pair(Tag, NewIdx)).first);
}

void LLVMContextImpl::getOperandBundleTags(SmallVectorImpl<StringRef> &Tags) const {
  Tags.resize(BundleTagCache.size());
  for (const auto &T : BundleTagCache)
    Tags[T.second] = T.first();
}

uint32_t LLVMContextImpl::getOperandBundleTagID(StringRef Tag) const {
  auto I = BundleTagCache.find(Tag);
  assert(I != BundleTagCache.end() && "Unknown tag!");
  return I->second;
}

SyncScope::ID LLVMContextImpl::getOrInsertSyncScopeID(StringRef SSN) {
  auto NewSSID = SSC.size();
  assert(NewSSID < std::numeric_limits<SyncScope::ID>::max() &&
         "Hit the maximum number of synchronization scopes allowed!");
  return SSC.insert(std::make_pair(SSN, SyncScope::ID(NewSSID))).first->second;
}

void LLVMContextImpl::getSyncScopeNames(
    SmallVectorImpl<StringRef> &SSNs) const {
  SSNs.resize(SSC.size());
  for (const auto &SSE : SSC)
    SSNs[SSE.second] = SSE.first();
}

/// Singleton instance of the OptBisect class.
///
/// This singleton is accessed via the LLVMContext::getOptPassGate() function.
/// It provides a mechanism to disable passes and individual optimizations at
/// compile time based on a command line option (-opt-bisect-limit) in order to
/// perform a bisecting search for optimization-related problems.
///
/// Even if multiple LLVMContext objects are created, they will all return the
/// same instance of OptBisect in order to provide a single bisect count.  Any
/// code that uses the OptBisect object should be serialized when bisection is
/// enabled in order to enable a consistent bisect count.
static ManagedStatic<OptBisect> OptBisector;

OptPassGate &LLVMContextImpl::getOptPassGate() const {
  if (!OPG)
    OPG = &(*OptBisector);
  return *OPG;
}

void LLVMContextImpl::setOptPassGate(OptPassGate& OPG) {
  this->OPG = &OPG;
}
<|endoftext|>


<commit_before>//==-LTOInternalize.cpp - LLVM Link Time Optimizer Internalization Utility -==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a helper to run the internalization part of LTO.
//
//===----------------------------------------------------------------------===//

#include "LTOInternalize.h"

#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Mangler.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/TargetSubtargetInfo.h"
#include "llvm/Transforms/IPO.h"

using namespace llvm;

namespace {

class ComputePreserveList {
public:
  ComputePreserveList(const StringSet<> &MustPreserveSymbols,
                      const StringSet<> &AsmUndefinedRefs,
                      const TargetMachine &TM, const Module &TheModule,
                      StringMap<GlobalValue::LinkageTypes> *ExternalSymbols,
                      std::vector<const char *> &MustPreserveList,
                      SmallPtrSetImpl<const GlobalValue *> &AsmUsed)
      : MustPreserveSymbols(MustPreserveSymbols),
        AsmUndefinedRefs(AsmUndefinedRefs), TM(TM),
        ExternalSymbols(ExternalSymbols), MustPreserveList(MustPreserveList),
        AsmUsed(AsmUsed) {
    accumulateAndSortLibcalls(TheModule);
    for (const Function &F : TheModule)
      applyRestriction(F);
    for (const GlobalVariable &GV : TheModule.globals())
      applyRestriction(GV);
    for (const GlobalAlias &GA : TheModule.aliases())
      applyRestriction(GA);
  }

private:
  // Inputs
  const StringSet<> &MustPreserveSymbols;
  const StringSet<> AsmUndefinedRefs;
  const TargetMachine &TM;

  // Temps
  llvm::Mangler Mangler;
  std::vector<StringRef> Libcalls;

  // Output
  StringMap<GlobalValue::LinkageTypes> *ExternalSymbols;
  std::vector<const char *> &MustPreserveList;
  SmallPtrSetImpl<const GlobalValue *> &AsmUsed;

  // Collect names of runtime library functions. User-defined functions with the
  // same names are added to llvm.compiler.used to prevent them from being
  // deleted by optimizations.
  void accumulateAndSortLibcalls(const Module &TheModule) {
    TargetLibraryInfoImpl TLII(Triple(TM.getTargetTriple()));
    TargetLibraryInfo TLI(TLII);

    // TargetLibraryInfo has info on C runtime library calls on the current
    // target.
    for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
         I != E; ++I) {
      LibFunc::Func F = static_cast<LibFunc::Func>(I);
      if (TLI.has(F))
        Libcalls.push_back(TLI.getName(F));
    }

    SmallPtrSet<const TargetLowering *, 1> TLSet;

    for (const Function &F : TheModule) {
      const TargetLowering *Lowering =
          TM.getSubtargetImpl(F)->getTargetLowering();

      if (Lowering && TLSet.insert(Lowering).second)
        // TargetLowering has info on library calls that CodeGen expects to be
        // available, both from the C runtime and compiler-rt.
        for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
             I != E; ++I)
          if (const char *Name =
                  Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
            Libcalls.push_back(Name);
    }

    array_pod_sort(Libcalls.begin(), Libcalls.end());
    Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
                   Libcalls.end());
  }

  void applyRestriction(const GlobalValue &GV) {
    // There are no restrictions to apply to declarations.
    if (GV.isDeclaration())
      return;

    // There is nothing more restrictive than private linkage.
    if (GV.hasPrivateLinkage())
      return;

    SmallString<64> Buffer;
    TM.getNameWithPrefix(Buffer, &GV, Mangler);

    if (MustPreserveSymbols.count(Buffer))
      MustPreserveList.push_back(GV.getName().data());
    if (AsmUndefinedRefs.count(Buffer))
      AsmUsed.insert(&GV);

    // Conservatively append user-supplied runtime library functions to
    // llvm.compiler.used.  These could be internalized and deleted by
    // optimizations like -globalopt, causing problems when later optimizations
    // add new library calls (e.g., llvm.memset => memset and printf => puts).
    // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
    if (isa<Function>(GV) &&
        std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
      AsmUsed.insert(&GV);

    // Record the linkage type of non-local symbols so they can be restored
    // prior
    // to module splitting.
    if (ExternalSymbols && !GV.hasAvailableExternallyLinkage() &&
        !GV.hasLocalLinkage() && GV.hasName())
      ExternalSymbols->insert(std::make_pair(GV.getName(), GV.getLinkage()));
  }
};

} // namespace anonymous

static void findUsedValues(GlobalVariable *LLVMUsed,
                           SmallPtrSetImpl<const GlobalValue *> &UsedValues) {
  if (!LLVMUsed)
    return;

  ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
  for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
    if (GlobalValue *GV =
            dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
      UsedValues.insert(GV);
}

void llvm::LTOInternalize(
    Module &TheModule, const TargetMachine &TM,
    const StringSet<> &MustPreserveSymbols, const StringSet<> &AsmUndefinedRefs,
    StringMap<GlobalValue::LinkageTypes> *ExternalSymbols) {
  legacy::PassManager passes;
  // mark which symbols can not be internalized
  Mangler Mangler;
  std::vector<const char *> MustPreserveList;
  SmallPtrSet<const GlobalValue *, 8> AsmUsed;

  ComputePreserveList(MustPreserveSymbols, AsmUndefinedRefs, TM, TheModule,
                      ExternalSymbols, MustPreserveList, AsmUsed);

  GlobalVariable *LLVMCompilerUsed =
      TheModule.getGlobalVariable("llvm.compiler.used");
  findUsedValues(LLVMCompilerUsed, AsmUsed);
  if (LLVMCompilerUsed)
    LLVMCompilerUsed->eraseFromParent();

  if (!AsmUsed.empty()) {
    llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(TheModule.getContext());
    std::vector<Constant *> asmUsed2;
    for (const auto *GV : AsmUsed) {
      Constant *c =
          ConstantExpr::getBitCast(const_cast<GlobalValue *>(GV), i8PTy);
      asmUsed2.push_back(c);
    }

    llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
    LLVMCompilerUsed = new llvm::GlobalVariable(
        TheModule, ATy, false, llvm::GlobalValue::AppendingLinkage,
        llvm::ConstantArray::get(ATy, asmUsed2), "llvm.compiler.used");

    LLVMCompilerUsed->setSection("llvm.metadata");
  }

  passes.add(createInternalizePass(MustPreserveList));

  // apply scope restrictions
  passes.run(TheModule);
}
<commit_msg>LTOInternalize: Fix member type, should be a reference and not a copy<commit_after>//==-LTOInternalize.cpp - LLVM Link Time Optimizer Internalization Utility -==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a helper to run the internalization part of LTO.
//
//===----------------------------------------------------------------------===//

#include "LTOInternalize.h"

#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Mangler.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/TargetSubtargetInfo.h"
#include "llvm/Transforms/IPO.h"

using namespace llvm;

namespace {

class ComputePreserveList {
public:
  ComputePreserveList(const StringSet<> &MustPreserveSymbols,
                      const StringSet<> &AsmUndefinedRefs,
                      const TargetMachine &TM, const Module &TheModule,
                      StringMap<GlobalValue::LinkageTypes> *ExternalSymbols,
                      std::vector<const char *> &MustPreserveList,
                      SmallPtrSetImpl<const GlobalValue *> &AsmUsed)
      : MustPreserveSymbols(MustPreserveSymbols),
        AsmUndefinedRefs(AsmUndefinedRefs), TM(TM),
        ExternalSymbols(ExternalSymbols), MustPreserveList(MustPreserveList),
        AsmUsed(AsmUsed) {
    accumulateAndSortLibcalls(TheModule);
    for (const Function &F : TheModule)
      applyRestriction(F);
    for (const GlobalVariable &GV : TheModule.globals())
      applyRestriction(GV);
    for (const GlobalAlias &GA : TheModule.aliases())
      applyRestriction(GA);
  }

private:
  // Inputs
  const StringSet<> &MustPreserveSymbols;
  const StringSet<> &AsmUndefinedRefs;
  const TargetMachine &TM;

  // Temps
  llvm::Mangler Mangler;
  std::vector<StringRef> Libcalls;

  // Output
  StringMap<GlobalValue::LinkageTypes> *ExternalSymbols;
  std::vector<const char *> &MustPreserveList;
  SmallPtrSetImpl<const GlobalValue *> &AsmUsed;

  // Collect names of runtime library functions. User-defined functions with the
  // same names are added to llvm.compiler.used to prevent them from being
  // deleted by optimizations.
  void accumulateAndSortLibcalls(const Module &TheModule) {
    TargetLibraryInfoImpl TLII(Triple(TM.getTargetTriple()));
    TargetLibraryInfo TLI(TLII);

    // TargetLibraryInfo has info on C runtime library calls on the current
    // target.
    for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs);
         I != E; ++I) {
      LibFunc::Func F = static_cast<LibFunc::Func>(I);
      if (TLI.has(F))
        Libcalls.push_back(TLI.getName(F));
    }

    SmallPtrSet<const TargetLowering *, 1> TLSet;

    for (const Function &F : TheModule) {
      const TargetLowering *Lowering =
          TM.getSubtargetImpl(F)->getTargetLowering();

      if (Lowering && TLSet.insert(Lowering).second)
        // TargetLowering has info on library calls that CodeGen expects to be
        // available, both from the C runtime and compiler-rt.
        for (unsigned I = 0, E = static_cast<unsigned>(RTLIB::UNKNOWN_LIBCALL);
             I != E; ++I)
          if (const char *Name =
                  Lowering->getLibcallName(static_cast<RTLIB::Libcall>(I)))
            Libcalls.push_back(Name);
    }

    array_pod_sort(Libcalls.begin(), Libcalls.end());
    Libcalls.erase(std::unique(Libcalls.begin(), Libcalls.end()),
                   Libcalls.end());
  }

  void applyRestriction(const GlobalValue &GV) {
    // There are no restrictions to apply to declarations.
    if (GV.isDeclaration())
      return;

    // There is nothing more restrictive than private linkage.
    if (GV.hasPrivateLinkage())
      return;

    SmallString<64> Buffer;
    TM.getNameWithPrefix(Buffer, &GV, Mangler);

    if (MustPreserveSymbols.count(Buffer))
      MustPreserveList.push_back(GV.getName().data());
    if (AsmUndefinedRefs.count(Buffer))
      AsmUsed.insert(&GV);

    // Conservatively append user-supplied runtime library functions to
    // llvm.compiler.used.  These could be internalized and deleted by
    // optimizations like -globalopt, causing problems when later optimizations
    // add new library calls (e.g., llvm.memset => memset and printf => puts).
    // Leave it to the linker to remove any dead code (e.g. with -dead_strip).
    if (isa<Function>(GV) &&
        std::binary_search(Libcalls.begin(), Libcalls.end(), GV.getName()))
      AsmUsed.insert(&GV);

    // Record the linkage type of non-local symbols so they can be restored
    // prior
    // to module splitting.
    if (ExternalSymbols && !GV.hasAvailableExternallyLinkage() &&
        !GV.hasLocalLinkage() && GV.hasName())
      ExternalSymbols->insert(std::make_pair(GV.getName(), GV.getLinkage()));
  }
};

} // namespace anonymous

static void findUsedValues(GlobalVariable *LLVMUsed,
                           SmallPtrSetImpl<const GlobalValue *> &UsedValues) {
  if (!LLVMUsed)
    return;

  ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
  for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i)
    if (GlobalValue *GV =
            dyn_cast<GlobalValue>(Inits->getOperand(i)->stripPointerCasts()))
      UsedValues.insert(GV);
}

void llvm::LTOInternalize(
    Module &TheModule, const TargetMachine &TM,
    const StringSet<> &MustPreserveSymbols, const StringSet<> &AsmUndefinedRefs,
    StringMap<GlobalValue::LinkageTypes> *ExternalSymbols) {
  legacy::PassManager passes;
  // mark which symbols can not be internalized
  Mangler Mangler;
  std::vector<const char *> MustPreserveList;
  SmallPtrSet<const GlobalValue *, 8> AsmUsed;

  ComputePreserveList(MustPreserveSymbols, AsmUndefinedRefs, TM, TheModule,
                      ExternalSymbols, MustPreserveList, AsmUsed);

  GlobalVariable *LLVMCompilerUsed =
      TheModule.getGlobalVariable("llvm.compiler.used");
  findUsedValues(LLVMCompilerUsed, AsmUsed);
  if (LLVMCompilerUsed)
    LLVMCompilerUsed->eraseFromParent();

  if (!AsmUsed.empty()) {
    llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(TheModule.getContext());
    std::vector<Constant *> asmUsed2;
    for (const auto *GV : AsmUsed) {
      Constant *c =
          ConstantExpr::getBitCast(const_cast<GlobalValue *>(GV), i8PTy);
      asmUsed2.push_back(c);
    }

    llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
    LLVMCompilerUsed = new llvm::GlobalVariable(
        TheModule, ATy, false, llvm::GlobalValue::AppendingLinkage,
        llvm::ConstantArray::get(ATy, asmUsed2), "llvm.compiler.used");

    LLVMCompilerUsed->setSection("llvm.metadata");
  }

  passes.add(createInternalizePass(MustPreserveList));

  // apply scope restrictions
  passes.run(TheModule);
}
<|endoftext|>