repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
josephlewis42/personal_codebase
|
xc/HW09-FinalVehicle/src/DistanceControlHelper.h
|
#ifndef HELPER_H
#define HELPER_H
int find_pulse_duration_ms(int width, int dist_mm);
#endif
|
josephlewis42/personal_codebase
|
xc/HW02-HotPotato/.build_Debug/XK-1A.h
|
<filename>xc/HW02-HotPotato/.build_Debug/XK-1A.h
#ifndef HAVE_PLATFORM_H
#define HAVE_PLATFORM_H
#include <xs1.h>
/*
* Platform description header file.
* Automatically generated from ".././XK-1A.xn".
*/
#ifdef __XC__
/* Core array declaration. */
extern core stdcore[1];
#endif
#ifdef __XC__
/* Service prototypes. */
/* none */
#endif
#if !defined(__ASSEMBLER__)
#define PORT_UART_RX on stdcore[0]: XS1_PORT_1I
#define PORT_UART_TX on stdcore[0]: XS1_PORT_1J
#define PORT_BUT_1 on stdcore[0]: XS1_PORT_1K
#define PORT_BUT_2 on stdcore[0]: XS1_PORT_1L
#define PORT_SPI_MISO on stdcore[0]: XS1_PORT_1M
#define PORT_SPI_SS on stdcore[0]: XS1_PORT_1N
#define PORT_SPI_CLK on stdcore[0]: XS1_PORT_1O
#define PORT_SPI_MOSI on stdcore[0]: XS1_PORT_1P
#define PORT_LED on stdcore[0]: XS1_PORT_4F
#else
#define PORT_UART_RX XS1_PORT_1I
#define PORT_UART_TX XS1_PORT_1J
#define PORT_BUT_1 XS1_PORT_1K
#define PORT_BUT_2 XS1_PORT_1L
#define PORT_SPI_MISO XS1_PORT_1M
#define PORT_SPI_SS XS1_PORT_1N
#define PORT_SPI_CLK XS1_PORT_1O
#define PORT_SPI_MOSI XS1_PORT_1P
#define PORT_LED XS1_PORT_4F
#endif
/* Reference frequency definition. */
#define PLATFORM_REFERENCE_HZ 100000000
#define PLATFORM_REFERENCE_KHZ 100000
#define PLATFORM_REFERENCE_MHZ 100
#endif /* HAVE_PLATFORM_H */
|
josephlewis42/personal_codebase
|
xc/HW09-FinalVehicle/src/common_cmds.h
|
<filename>xc/HW09-FinalVehicle/src/common_cmds.h
/*
* common_cmds.h - Useful commands that are used everywhere.
*
* Created on: May 28, 2012
* Author: joseph
*/
#ifndef COMMON_CMDS_H_
#define COMMON_CMDS_H_
#include <xs1.h>
#define TICKS_PER_SEC XS1_TIMER_HZ
#define TICKS_PER_MS (XS1_TIMER_HZ/1000)
#define TICKS_PER_US (XS1_TIMER_HZ/1000000)
#define TIMER_MAX_VALUE 0x7FFFFFFF
// Waits the given number of ticks.
void wait_time(unsigned int time, timer tmr);
// Converts numbers to wherever they are on a circle, even negative and those over 360*
int normalize_heading(int heading);
#endif /* COMMON_CMDS_H_ */
|
josephlewis42/personal_codebase
|
xc/HW09-FinalVehicle/src/director.h
|
<filename>xc/HW09-FinalVehicle/src/director.h
/*
* director.h - There are no small roles.
*
* Created on: May 28, 2012
* Author: <NAME> <<EMAIL>>
*/
#ifndef DIRECTOR_H_
#define DIRECTOR_H_
#define GO_FORWARD 0
#define TURN_NINETY_LEFT 1
#define TURN_NINETY_RIGHT 2
#define STOP 3
enum driving_commands{
forward,
left_ninety,
right_ninety,
stop
};
struct direction_t;
typedef struct direction_t {
int command; // GO_FORWARD, TURN_NINETY_LEFT, etc.
int param; // PARAM, GO_FORWARD = num mm to go
} direction;
void directions_thread( chanend direction_output, int start_rank, int goal_rank, const int obstacles[]);
void director_test( chanend direction_input);
#endif /* DIRECTOR_H_ */
|
josephlewis42/personal_codebase
|
cpp/tinybasic/io.h
|
/**
A TinyBASIC derivative originally built for the Arduino.
Copyright 2012-04-07 <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The classes in this file are used for displaying stdio, if you wanted
to port this to something, like say an Arduino, you'd need to create
one of these to handle all the keyboard and display stuff. This makes
the BASIC system very portable.
**/
#ifndef IO_H
#define IO_H
#include <iostream>
/**
* The IOHandler is used for fetching/displaying user input/output.
*/
class IOHandler
{
public:
virtual void output(const char* strout) = 0;
virtual void output(int i) = 0;
virtual void output(char c) = 0;
virtual int inputInt() = 0; // Read an int from a keyboard.
virtual void clear_output() = 0; // Clear the screen.
};
/**
* A handler that uses stdout and stdin.
*/
class STDIOHandler : public IOHandler
{
public:
void output(const char* strout)
{
std::cout << strout;
}
void output(int strout)
{
std::cout << strout;
}
void output(char strout)
{
std::cout << strout;
}
void clear_output()
{
for(int i = 0; i < 50; ++i)
std::cout << std::endl;
}
int inputInt()
{
int j = 0;
std::cin >> j;
return j;
}
};
#endif
|
josephlewis42/personal_codebase
|
xc/HW09-FinalVehicle/src/bumper.h
|
<gh_stars>1-10
/*
* buttons.h - Don't push mine.
*
* Created on: May 28, 2012
* Author: <NAME> <<EMAIL>>
*/
#ifndef BUMPER_H
#define BUMPER_H
void wait_left_bumper_press();
void wait_right_bumper_press();
void wait_either_bumper_press();
void wait_left_bumper_release();
void wait_right_bumper_release();
void wait_all_bumper_release();
void test_bumpers();
int left_is_hit();
int right_is_hit();
int bumper_is_hit();
#endif /* BUTTONS_H_ */
|
josephlewis42/personal_codebase
|
xc/HW03-Ping/src/utility.c
|
<reponame>josephlewis42/personal_codebase<gh_stars>1-10
/*
* utility.c
*
* Created on: Apr 12, 2012
* Author: joseph
*/
#include "utility.h"
int ticks_to_mm(unsigned int ticks, unsigned int mm_per_sec, unsigned int ticks_per_sec)
{
double tks = ticks;
//double seconds = ticks;
// How many seconds did this last?
tks /= ticks_per_sec;
// How many mm are there in the sec?
tks *= mm_per_sec;
// Being we're doing sonar, the wave must travel there *and* back, so divide by 2
tks /= 2;
return (int) tks;
}
|
josephlewis42/personal_codebase
|
c/monty_hall.c
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define true 1
#define false 0
#define SWITCH_DOORS 1
#define ROUNDS 1000000000
//#define PRINTOUT = 1 //Define for printout of text
/* Seed the random with a random value the clock doesn't work because
* it only gets updated once per second, and rand is called multiple hundreds
* of times per second.
*/
static int get_rand()
{
srand(rand());
return rand();
}
static int choose_door_to_open(int one, int two)
{
if( one || two ) //If either door actually has the prize
{
return (one) ? 2 : 1; //Open the other one
}
//If neither door has the prize, just return a random door.
return get_rand() % 2 + 1;
}
int choose_door_to_switch(int opens, int chosen_door)
{
if(opens == 1)
return (chosen_door == 2) ? 3 : 2;
if(opens == 2)
return (chosen_door == 1) ? 3 : 1;
//Opens must be 3, no need for that extra compairison.
return (chosen_door == 1) ? 2 : 1;
}
int main(int argc, char *argv[])
{
unsigned int wins = 0;
unsigned int losses = 0;
unsigned int i = 1;
int door_one, door_two, door_three;
/*Seed the random generator with the time*/
srand(time(NULL));
for (i = 1 ; i < ROUNDS + 1; i++)
{
//Set up doors
door_one = false;
door_two = false;
door_three = false;
int door_with_prize = get_rand() % 3 + 1;
if (door_with_prize == 1)
{
door_one = true;
}
else
{
if (door_with_prize == 2)
door_two = true;
else
door_three = true;
}
#ifdef PRINTOUT
printf("Doors\n");
printf("One: %i \n", door_one);
printf("Two: %i\n", door_two);
printf("Three: %i\n", door_three);
#endif
//Have the program randomly choose a start door
unsigned int chosen_door = get_rand() % 3 + 1;
#ifdef PRINTOUT
printf("Chosen Door: %i\n", chosen_door);
#endif
//Have the program randomly choose which door to open.
unsigned int opens;
if( chosen_door == 1 )
{
opens = choose_door_to_open(door_two, door_three);
opens = (opens == 1) ? 2 : 3;
}
else
{
if( chosen_door == 2 )
{
opens = choose_door_to_open(door_one, door_three);
opens = (opens == 1) ? 1 : 3;
}
else //Chosen door must be 3
{
opens = choose_door_to_open(door_one, door_two);
opens = (opens == 1) ? 1 : 2;
}
}
#ifdef PRINTOUT
printf("Door Opened: %i\n", opens);
#endif
//Have the program switch doors
if (SWITCH_DOORS == true)
{
chosen_door = choose_door_to_switch(opens, chosen_door);
#ifdef PRINTOUT
printf("Change door to: %i \n", chosen_door);
#endif
}
//Increment the proper number so we can do stats at the end.
if (chosen_door == door_with_prize)
{
#ifdef PRINTOUT
printf( "Win\n" );
#endif
wins++;
}
else
{
#ifdef PRINTOUT
printf ("Lose\n");
#endif
losses++;
}
#ifdef PRINTOUT
printf("===End of round: %i ===\n", i);
#endif
}
printf( "===RESULTS===\n" );
printf( "Wins: %i\n", wins);
printf( "%f %% \n",(wins / (ROUNDS * 1.0))*100);
printf( "Losses: %i\n", losses);
printf( "%f %% \n",(losses / (ROUNDS * 1.0))*100);
return 0;
}
|
josephlewis42/personal_codebase
|
xc/Lab07-Rotate90/src/uart.h
|
#ifndef uart_h
#define uart_h
void debug(const char values[], unsigned int n);
#endif
|
josephlewis42/personal_codebase
|
cpp/lib/Configuration.h
|
/*
* Configuration.h
*
* A simple configuration manager that looks up arbitrary key:value pairs.
*
* Copyright (c) 2013 <NAME> <<EMAIL>> | <<EMAIL>>
* Licensed under the GPL 3
*
*/
#ifndef CONFIGURATION_H_
#define CONFIGURATION_H_
#include <string>
#include <mutex>
#include <boost/property_tree/ptree_fwd.hpp>
#include <vector>
#include <map>
#include "Singleton.h"
class Configuration : public Singleton<Configuration>
{
friend class Singleton<Configuration>;
public:
// Loads the values from the given properties file.
void loadProperties(std::string path);
// Returns a string from the configuration.
std::string gets(const std::string &key, const std::string &alt="");
// Returns a bool from the configuration
bool getb(const std::string &key, bool alt=false);
// Returns an int from the configuration.
int geti(const std::string &key, int alt=0);
// Returns a float from the configuration
float getf(const std::string &key, float alt=0.0f);
// Returns a double from the configuration
double getd(const std::string &key, double alt=0.0);
/**
* Sets a path to be a value.
*/
void set(const std::string &key, const std::string& value);
/**
* Sets a path to be a double value
*
* @param key - the key to store the value under
* @param value - the value of the param
*/
void setd(const std::string &key, const double value);
/**
* Sets a path to be an int value
*
* @param key - the key to store the value under
* @param value - the value of the param
*/
void seti(const std::string &key, const int value);
/**
* Sets a description for the given key. Note that basic markdown can be used
* when setting these descriptions.
*
* @param key - the key to set the description for
* @param domain - the domain of the key (e.g. 1-100 or non-negative integers)
* @param usage - how the key is used internally
* @param units - the units of this value (optional)
* @param note - a note about the key (optional)
**/
void describe(const std::string &key,
const std::string &domain,
const std::string &usage,
const std::string &units="",
const std::string ¬e="");
/**
* Returns the description for the whole configuration file.
**/
std::string getDescription();
private:
boost::property_tree::ptree* _properties;
static std::mutex _propertiesLock;
std::map<std::string, std::string> _descriptions;
std::mutex _descriptionsLock;
Configuration();
virtual ~Configuration();
void save();
};
/**
* Allows you to perform configuration operations on a sub-tree of the main
* configuration as if it were an independent configuration tree.
*
*/
class ConfigurationSubTree
{
private:
std::string _prefix;
public:
ConfigurationSubTree(std::string prefix)
:_prefix(prefix + ".") {}
virtual ~ConfigurationSubTree() {};
/// Returns a string from the configuration.
std::string configGets(const std::string &key, const std::string &alt="")
{
return Configuration::getInstance()->gets(_prefix + key, alt);
}
/// Returns a bool from the configuration
bool configGetb(const std::string &key, bool alt=false)
{
return Configuration::getInstance()->getb(_prefix + key, alt);
}
/// Returns an int from the configuration.
int configGeti(const std::string &key, int alt=0)
{
return Configuration::getInstance()->geti(_prefix + key, alt);
}
/// Returns a float from the configuration
float configGetf(const std::string &key, float alt=0.0f)
{
return Configuration::getInstance()->getf(_prefix + key, alt);
}
/// Returns a double from the configuration
double configGetd(const std::string &key, double alt=0.0)
{
return Configuration::getInstance()->getd(_prefix + key, alt);
}
/**
* Sets a path to be a value.
*/
void configSet(const std::string &key, const std::string& value)
{
Configuration::getInstance()->set(_prefix + key, value);
}
/**
* Sets a path to be a double value
*
* @param key - the key to store the value under
* @param value - the value of the param
*/
void configSetd(const std::string &key, const double value)
{
return Configuration::getInstance()->setd(_prefix + key, value);
}
/**
* Sets a path to be an int value
*
* @param key - the key to store the value under
* @param value - the value of the param
*/
void configSeti(const std::string &key, const int value)
{
Configuration::getInstance()->seti(_prefix + key, value);
}
/**
* Sets a description for the given key. Note that basic HTML can be used
* when setting these descriptions.
*
* @param key - the key to set the description for
* @param domain - the domain of the key (e.g. 1-100 or non-negative integers)
* @param usage - how the key is used internally
* @param units - the units of this value (optional)
* @param note - a note about the key (optional)
**/
void configDescribe(const std::string &key,
const std::string &domain,
const std::string &usage,
const std::string &units="",
const std::string ¬e="")
{
Configuration::getInstance()->describe(_prefix + key, domain, usage, units, note);
}
};
#endif /* CONFIGURATION_H_ */
|
josephlewis42/personal_codebase
|
xc/Lab09-DrivingStraight/src/servo.h
|
<gh_stars>1-10
#ifndef SERVO_H_
#define SERVO_H_
// constants
#define MIN_SERVO_PULSE_US 1000
#define MID_SERVO_PULSE_US 1500
#define MAX_SERVO_PULSE_US 2000
#define MAX_NUM_SERVOS 8
// types
typedef struct {
unsigned int pulse_width_us[MAX_NUM_SERVOS];
} servo_cmd_t;
// prototypes
servo_cmd_t default_servo_cmd();
void servo_task_multi(
unsigned int nServos,
out port oServos[],
const int servo_offsets[],
chanend in_servo_cmd_chan);
#endif
|
josephlewis42/personal_codebase
|
cpp/tinybasic/tokenizer.h
|
<gh_stars>1-10
/**
A TinyBASIC derivative originally built for the Arduino.
Copyright 2012-04-07 <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
#ifndef TOKENIZER_H
#define TOKENIZER_H
#include "program_reader.h"
enum TOKEN
{
PRINT = 'P',
IF = 'I',
THEN = 't',
GOTO = 'G',
INPUT = 'N',
LET = 'L',
GOSUB = 'S',
RETURN = 'R',
CLEAR = 'C',
LIST = 'T',
RUN = 'U',
END = 'E',
COMMA = ',',
NUMBER = '#',
STRING = 's',
VARIABLE = 'v',
END_STATEMENT = 'e',
BEGIN_STATEMENT = 'b',
END_PROGRAM = 'q',
CHAR = 'c',
PLUS = '+',
MINUS = '-',
MULTIPLY = '*',
DIVIDE = '/',
EQUALS = '=',
ERROR = 'X',
LPAREN = '(',
RPAREN = ')',
GREATER_THAN = '>',
LESS_THAN = '<'
};
class Tokenizer
{
public:
Tokenizer(ProgramReader* pgm);
~Tokenizer()
{
delete[] curr_str;
delete[] current_line;
}
void parse_next_token(); // Parses the next token.
TOKEN getToken(); // Gets the current token.
bool isFinished(); // Gets whether or not the program has ended.
int getInt(); // Gets the value of the current chunk as an int.
const char* getString();
char get_variable_name();
void reset(); // Resets all vars and restarts the file.
private:
TOKEN current_token;
const char* current_line;
int current_line_position;
ProgramReader* m_file;
void read_next_token();
const char* curr_str;
int curr_int;
char varname;
};
#endif
|
josephlewis42/personal_codebase
|
cpp/lib/Path.h
|
/**
* Copyright 2014 <NAME> <<EMAIL>>
*
* This file is part of University of Denver Autopilot.
* Dual licensed under the GPL v 3 and the Apache 2.0 License
*
**/
#ifndef PATH_H_
#define PATH_H_
#include <string>
/** This class handles filesystem paths.
**/
class Path
{
private:
std::string _path;
int remove_all(const char* path);
public:
/// Constructs a path in the current working directory
Path();
/// Constructs a path with the given initial file
Path(std::string initial)
:_path(initial)
{};
Path(const char* initial)
:_path(initial)
{};
bool has_extension();
/// Check if the path exists
bool exists();
/// Reinitialize path
bool clear();
/// Recursively removes a directory.
int remove_all();
/// Returns the extension of the path or a blank string if none exists
std::string get_extension();
/** Recursively makes a directory.
* src: http://nion.modprobe.de/blog/archives/357-Recursive-directory-creation.html
**/
void create_directories();
std::string toString() const;
const char* c_str() const;
friend Path operator/(const Path &p, const char* toappend);
friend Path operator/(const Path &p, const std::string toappend);
Path& operator/=(const char* right);
Path& operator/=(const std::string right);
};
#endif // PATH_H_
|
josephlewis42/personal_codebase
|
cpp/tinybasic/basic.h
|
/**
A TinyBASIC derivative originally built for the Arduino.
Copyright 2012-04-07 <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
#ifndef BASIC_H
#define BASIC_H
/**
* Configuration definitions
*/
// Enable to show debugging info
//#define DEBUGGING 1
// Enable to allow reading from a file (using stdlib, increases size)
#define FILE_READ
#include <iostream>
#include "program_reader.h"
#include "io.h"
// Run a BASIC program with the given environment.
void run_bas(IOHandler*, ProgramReader*);
#endif
|
josephlewis42/personal_codebase
|
xc/Lab08-LinkedList/src/bfs.c
|
<reponame>josephlewis42/personal_codebase
/*
* bfs.c
*
* A breadth first search algorithm
*
* Created on: May 17, 2012
* Author: <NAME> <<EMAIL>>
*/
#include <stdlib.h>
#include "bfs.h"
#include <assert.h>
// definitions
#define NORTH 0
#define EAST 1
#define SOUTH 2
#define WEST 3
// declarations
struct list_t;
struct list_element_t_struct;
struct list_element_t_struct
{
int rank ;
struct list_element_t_struct* next ;
};
typedef struct list_element_t_struct list_element_t;
typedef struct
{
list_element_t* head;
list_element_t* tail;
} list_t;
// prototypes
void push_back(list_t* list, int rank);
list_t init_list();
void free_list(list_t* list);
int remove_front(list_t* list);
void push_front(list_t* list, int rank);
void fill_neighbors(int neighbors[], int rank);
/** Functions **/
int test_main()
{
// test init_list()
list_t l1;
l1 = init_list();
assert(l1.head == l1.tail && l1.head == NULL);
// test push_back;
push_back(&l1, 10);
assert(l1.head != NULL);
assert(l1.tail == l1.head);
assert(l1.head->rank == 10);
assert(l1.head->next == NULL);
push_back(&l1, 20);
assert(l1.head != l1.tail);
assert(l1.head->rank == 10);
assert(l1.head->next == l1.tail);
assert(l1.tail->rank == 20);
assert(l1.tail->next == NULL);
// test remove_front
assert(remove_front(&l1) == 10);
assert(l1.head != NULL);
assert(l1.tail == l1.head);
assert(l1.head->rank == 20);
assert(l1.head->next == NULL);
assert(remove_front(&l1) == 20);
assert(l1.head == l1.tail && l1.head == NULL);
// test free_list
free_list(&l1);
assert(l1.head == l1.tail && l1.head == NULL);
// test push_front;
push_front(&l1, 10);
assert(l1.head != NULL);
assert(l1.tail == l1.head);
assert(l1.head->rank == 10);
assert(l1.head->next == NULL);
push_front(&l1, 20);
assert(l1.head != l1.tail);
assert(l1.head->rank == 20);
assert(l1.head->next == l1.tail);
assert(l1.tail->rank == 10);
assert(l1.tail->next == NULL);
// fill_neighbors
int init[4];
fill_neighbors(init, 0); // NW
assert(init[NORTH] == -1);
assert(init[EAST] != -1);
assert(init[SOUTH] != -1);
assert(init[WEST] == -1);
return 0;
}
/**
This function should declare a new list t variable, ensure that both the head and tail ele-
ments are NULL, and return it.
**/
list_t init_list()
{
list_t a;
a.head = NULL;
a.tail = NULL;
return a;
}
void push_back(list_t* list, int rank)
{
list_element_t* tmp = (list_element_t*) malloc (sizeof(list_element_t));
assert(tmp != NULL); // if out of heap, we'll be null
tmp->rank = rank;
tmp->next = NULL;
if(list->tail == NULL)
{
list->head = tmp;
list->tail = tmp;
return;
}
list->tail->next = tmp;
list->tail = tmp;
}
void free_list(list_t* list)
{
list_element_t* tmp = list->head;
list_element_t* last;
while(tmp != NULL)
{
last = tmp;
tmp = tmp->next;
free(last);
}
*list = init_list();
}
int remove_front(list_t* list)
{
list_element_t* tmp = list->head;
int val;
if(tmp == NULL)
return -1;
val = tmp->rank;
// fix up the head
list->head = tmp->next;
// fix up the tail (if needed)
if(list->tail == tmp)
*list = init_list();
free(tmp);
return val;
}
void push_front(list_t* list, int rank)
{
list_element_t* tmp = (list_element_t*) malloc (sizeof(list_element_t));
assert(tmp != NULL); // if out of heap, we'll be null
tmp->rank = rank;
tmp->next = list->head;
list->head = tmp;
if(list->tail == NULL)
list->tail = tmp;
}
void fill_neighbors(int neighbors[], int rank)
{
int row = ROW(rank);
int col = COL(rank);
// FILL NORTH
if(row - 1 >= 0)
neighbors[NORTH] = RANK(row - 1, col);
else
neighbors[NORTH] = -1;
// FILL WEST
if(col - 1 >= 0)
neighbors[WEST] = RANK(row, col - 1);
else
neighbors[WEST] = -1;
// FILL SOUTH
if(row + 1 < MAZE_WIDTH)
neighbors[SOUTH] = RANK(row + 1, col);
else
neighbors[SOUTH] = -1;
// FILL EAST
if(col + 1 < MAZE_WIDTH)
neighbors[EAST] = RANK(row, col + 1);
else
neighbors[EAST] = -1;
}
|
josephlewis42/personal_codebase
|
xc/HW09-FinalVehicle/src/bfs.h
|
/*
* bfs.h - Not to be confused with BFF
*
* Created on: May 17, 2012
* Author: <NAME> <<EMAIL>>
*/
#ifndef BFS_H_
#define BFS_H_
#include <xs1.h>
#include "platform.h"
#define MAZE_WIDTH 6
# define ELEMENT_COUNT (MAZE_WIDTH * MAZE_WIDTH)
# define RANK(row, col) ((row) * MAZE_WIDTH + (col))
# define ROW(rank) ((rank) / MAZE_WIDTH)
# define COL(rank) ((rank) % MAZE_WIDTH)
int init_path(int start_rank, int goal_rank, const int obstacles[]);
int next_rank();
int has_next();
int test_bfs();
#endif /* BFS_H_ */
|
josephlewis42/personal_codebase
|
xc/HW03-Ping/src/utility.h
|
/*
* utility.h
*
* Created on: Apr 12, 2012
* Author: joseph
*/
#ifndef UTILITY_H_
#define UTILITY_H_
int ticks_to_mm(unsigned int ticks, unsigned int mm_per_sec, unsigned int ticks_per_sec);
#endif /* UTILITY_H_ */
|
josephlewis42/personal_codebase
|
cpp/tinybasic/program_reader.h
|
<reponame>josephlewis42/personal_codebase<gh_stars>1-10
/**
A TinyBASIC derivative originally built for the Arduino.
Copyright 2012-04-07 <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
These classes are used for "reading" the program from different sources,
stdio, files, etc. If you wanted something to run on an embedded system
you'd just implement a ProgramReader that would accept data from say,
EEPROM.
**/
#ifndef READER_H
#define READER_H
#include <iostream>
#include <string>
#include <list>
#include <fstream>
class ProgramReader
{
public:
ProgramReader()
{
}
virtual const char* read_line() = 0;
virtual bool has_next() = 0;
virtual void seek_begin() = 0;
};
class InputProgramReader : public ProgramReader {
public:
const char* read_line()
{
std::string line;
std::getline(std::cin,line);
return (char*)line.c_str();
}
bool has_next()
{
return true;
}
void seek_begin()
{
}
};
class FileProgramReader : public ProgramReader {
public:
FileProgramReader(const char* filename)
{
std::ifstream infile;
infile.open(filename); // open file
if(infile)
{
std::string s = "";
while(getline(infile, s))
{
lines.push_back(s);
}
}
seek_begin();
}
const char* read_line()
{
std::string tmp = *it;
it++;
return tmp.c_str();
}
bool has_next()
{
return it != lines.end();
}
void seek_begin()
{
it = lines.begin();
}
private:
std::list<std::string> lines;
std::list<std::string>::iterator it;
};
#endif
|
josephlewis42/personal_codebase
|
xc/HW05-HMC6352/src/servos.h
|
#ifndef SERVOS_H_FILE
#define SERVOS_H_FILE
void servo_task(unsigned int timeout_ticks); // launches the servo task, timeout turns it off timeout=0 for continueous.
void left_forward(int pct);
void left_reverse(int pct);
void right_forward(int pct);
void right_reverse(int pct);
void right_stop();
void left_stop();
#endif
|
josephlewis42/personal_codebase
|
cpp/tinybasic/stringutils.h
|
<gh_stars>1-10
/**
A TinyBASIC derivative originally built for the Arduino.
Copyright 2012-04-07 <NAME> <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
#ifndef STRINGUTILS_H
#define STRINGUTILS_H
// Converts an a-z character to upper case.
char toUpper(char c);
/**
* Determines if a string, orig, starting at offset, starts with the
* given string. e.g.
* starts_with_ignore_case("Hello World",7,"world") would be true.
*/
bool starts_with_ignore_case(const char* orig, int offset, const char* test);
/**
* Returns true if the given character is a whitespace char.
*/
bool is_whitespace(char c);
/**
* True if the given char is an ASCII digit.
**/
bool is_digit(char c);
/**
* Converts the given char to a digit, assumes it is 0-9.
**/
int to_digit(char c);
/**
* Tests if the character after this is a-zA-Z.
*/
bool is_alpha(char c);
/**
* Returns a substring of another string.
**/
char* substring(const char* orig, int offset, int length);
#endif
|
josephlewis42/personal_codebase
|
cpp/lib/RateLimiter.h
|
<reponame>josephlewis42/personal_codebase
/*
* RateLimiter.h
*
* Created on: Sep 27, 2013
* Author: <NAME> <<EMAIL>>
*/
#ifndef RATELIMITER_H_
#define RATELIMITER_H_
#include <thread>
#include <chrono>
class RateLimiter
{
private:
std::chrono::milliseconds _msToWait;
std::chrono::time_point<std::chrono::high_resolution_clock> _nextTime;
bool _checkload;
float _msPerLoop;
public:
/**
* Provides a limiting mechanism to functions
*
* @param hz - the number of hertz to run this function.
* @param loadcheck - whether or not to record the load of the RateLImiter between
* wait() and finishedCriticalSection()
*/
RateLimiter(int hz, bool loadcheck=false);
virtual ~RateLimiter();
/**
* This function should be called within loops to slow them down if necessary
* it will return when it is time to "wake up"
*
* if load checking is enabled, returns the proportion of time used to time
* allotted for each loop, a number > 1 means that the time taken is
* exceeding the time allotted.
*/
float wait();
/**
* This function is called when the loop is finished with one iteration,
* it gives the OS an opportunity to do some cleanup and go about doing other
* things.
*
*
*/
void finishedCriticalSection();
};
#endif /* RATELIMITER_H_ */
|
josephlewis42/personal_codebase
|
xc/HW09-FinalVehicle/src/lights.h
|
<reponame>josephlewis42/personal_codebase
/*
* lights.h - Pretty Lights
*
* Created on: May 28, 2012
* Author: <NAME> <<EMAIL>>
*/
#ifndef LIGHTS_H_
#define LIGHTS_H_
// chanend c takes an int as the number of hz to flash at, 0 is off, < 0 is full on
void lights_thread(chanend c);
// Blinks at 0 hz for 1 sec, 2 hz for 1 sec, 3 hz for 1 sec, then 4 hz for 1 sec
void lights_test(chanend c);
#endif /* LIGHTS_H_ */
|
josephlewis42/personal_codebase
|
xc/Lab05-BasicCompass/src/i2c.h
|
#ifndef I2C_H_INCLUDED
#define I2C_H_INCLUDED
#include <xs1.h>
typedef struct
{
port scl; // clock port
port sda; // data port
unsigned t; // timestamp
timer tmr; // timer
unsigned delay; // delay on clock edges (in ticks)
} i2c_p;
void i2c_delay(i2c_p &i2c); // delays by i2c_p.delay ticks
void i2c_init(i2c_p &i2c); // sets the initial state on the SCL and SDA lines
void i2c_start(i2c_p &i2c); // sends the start bit sequence
void i2c_stop(i2c_p &i2c); // sends the stop bit sequence
int i2c_read(i2c_p &i2c, int ack); // reads a byte from the slave, the 'ack' flag determines if a master->slave is sent. This should be 1 after bytes in the middle of a multi-byte response, 0 otherwise
int i2c_write(i2c_p &i2c, unsigned data); // writes a byte to the slave.
#endif
|
josephlewis42/personal_codebase
|
xc/Lab02-SimSetup/utility.h
|
<filename>xc/Lab02-SimSetup/utility.h
/*
* utility.h
*
* Created on: Apr 5, 2012
* Author: joseph
*/
#ifndef UTILITY_H_
#define UTILITY_H_
void format_message(char buffer[], unsigned int t0, unsigned int t1);
#endif /* UTILITY_H_ */
|
josephlewis42/personal_codebase
|
xc/Lab02-SimSetup/utility.c
|
<reponame>josephlewis42/personal_codebase
/*
* utility.c
*
* Created on: Apr 5, 2012
* Author: joseph
*/
#include <xs1.h>
#include "utility.h"
#include <stdio.h>
float timer_diff(unsigned int t0, unsigned int t1)
{
if(t1 < t0)
{
return ((float)((XS1_TIMER_HZ - t0) + t1)) / XS1_TIMER_HZ;
}
return ((float)(t1 - t0)) / XS1_TIMER_HZ;
}
void format_message(char buffer[], unsigned int t0, unsigned int t1)
{
sprintf(buffer, "Difference was %f seconds\n", timer_diff(t0,t1));
}
|
josephlewis42/personal_codebase
|
xc/HW06-DistanceControl/src/DistanceControlHelper.h
|
<filename>xc/HW06-DistanceControl/src/DistanceControlHelper.h
#ifndef HELPER_H
#define HELPER_H
int find_pulse_duration_ms(int width, int dist_mm);
#endif
|
josephlewis42/personal_codebase
|
xc/HW09-FinalVehicle/src/americus.h
|
<filename>xc/HW09-FinalVehicle/src/americus.h
/*
* americus.h - The head of the navigator.
*
* Created on: May 29, 2012
* Author: joseph
*/
#ifndef AMERICUS_H_
#define AMERICUS_H_
void navigate_maze(chanend lightschan, chanend directions, chanend out_servo_cmd_chan, i2c_p& i2c);
void test_navigation(chanend lightschan, chanend directions, chanend out_servo_cmd_chan, i2c_p& i2c);
#endif /* AMERICUS_H_ */
|
josephlewis42/personal_codebase
|
xc/HW09-FinalVehicle/src/buttons.h
|
<reponame>josephlewis42/personal_codebase<gh_stars>1-10
/*
* buttons.h - Don't push mine.
*
* Created on: May 28, 2012
* Author: <NAME> <<EMAIL>>
*/
#ifndef BUTTONS_H_
#define BUTTONS_H_
void wait_left_button_press();
void wait_right_button_press();
void wait_either_button_press();
void wait_left_button_release();
void wait_right_button_release();
void wait_all_button_release();
void test_buttons();
#endif /* BUTTONS_H_ */
|
imaroger/walking_human_trajectory_models
|
include/OptimalControlModel.h
|
#ifndef OPTIMALCONTROLMODEL_H
#define OPTIMALCONTROLMODEL_H
#include "crocoddyl/core/actions/human.hpp"
#include "crocoddyl/core/optctrl/shooting.hpp"
#include "crocoddyl/core/solvers/ddp.hpp"
#include <iostream>
#include <cmath>
using namespace std;
using namespace crocoddyl;
class OptimalControlModel
{
private :
Eigen::Vector3d final_state;
Eigen::Vector3d init_state;
Eigen::Vector3d final_state_translated;
Eigen::VectorXd init_state_translated = Eigen::VectorXd(6);
Eigen::VectorXd cost_weights = Eigen::VectorXd(7);
int T_guess;
double alpha;
vector<boost::shared_ptr<ActionModelAbstract>> running_models;
ActionModelHuman model;
public :
int T_opt;
vector<double> x;
vector<double> y;
vector<double> theta;
OptimalControlModel(double x0, double y0, double theta0,
double xf, double yf, double thetaf,
Eigen::VectorXd costs,double a);
void optimizeT(boost::shared_ptr<ActionModelAbstract> model_ptr);
void solve();
};
#endif
|
imaroger/walking_human_trajectory_models
|
include/GeneralizedFresnel.h
|
#ifndef GENERALIZEDFRESNEL_H
#define GENERALIZEDFRESNEL_H
#include <iostream>
#include <boost/array.hpp>
#include <boost/numeric/odeint.hpp>
class GeneralizedFresnel
{
private:
double k0;
double k1;
double init_theta;
int n;
int i;
double S_i;
double C_i;
typedef boost::array< double , 3 > state_type;
double alpha;
public:
std::vector<double> S;
std::vector<double> C;
GeneralizedFresnel(double theta0, double k, double dk, int order, double slowing_coef);
void generalized_fresnel_ode_fct(const state_type &state , state_type &dstate , double t );
void build_generalized_fresnel(const state_type &state ,const double t);
void generalized_fresnel_fct_i();
void generalized_fresnel_fct();
};
#endif
|
imaroger/walking_human_trajectory_models
|
include/Clothoid.h
|
<filename>include/Clothoid.h
#ifndef CLOTHOID_H
#define CLOTHOID_H
#include <iostream>
#include <boost/array.hpp>
#include <cmath>
#include <boost/numeric/odeint.hpp>
#include <stdlib.h>
#include "GeneralizedFresnel.h"
class Clothoid
{
private:
double dt;
double epsilon = 1e-12;
double alpha;
typedef boost::array< double , 3 > state_type;
state_type init_state;
state_type final_state;
public:
std::vector<double> x;
std::vector<double> y;
std::vector<double> theta;
double L;
double k0;
double k1;
Clothoid(double x0, double y0, double theta0,
double xf, double yf, double thetaf, double step, double slowing_coef);
void build_clothoid_param();
void clothoid_ode_fct(const state_type &state , state_type &dstate , double t );
void build_clothoid( const state_type &state , const double t );
void clothoid_fct();
double normalizeAngle(double angle);
double guessA(double phi0,double phif);
double findA(double A_guess,double dphi,double phi0);
};
#endif
|
mohamedpop871/Telemetry-System
|
Embedded/Telemetry System/Telemetry System/Timer1.h
|
/*
* Timer_1.h
*
* Created: 10/14/2019 11:34:27 PM
* Author: Mohamed_Hassanin
*/
#ifndef TIMER1_H_
#define TIMER1_H_
#include <avr/io.h>
#include <avr/interrupt.h>
#include "USART.h"
/*
*Function Name: send_RPM
* Purpose : Sending RPM with precision xxx (0 -> 999)
* Input : RPM
* Output : None
*/
void send_RPM(uint32_t RPM);
/*
*Function Name: send_KMPH
* Purpose : Sending KMPH with precision xx.xx (0 -> 99.99)
* Input : KMPH
* Output : None
*/
void send_KMPH(float KMPH);
/*
*Function Name: send_Current
* Purpose : Sending current with precision xx.xxx (0 -> 99.999)
* Input : Current
* Output : None
*/
void send_Current(float current);
void Timer1_Init(void);
volatile uint16_t temp;
extern volatile uint8_t Send;
extern volatile uint8_t After_Send;
//Declaring external Variables sent in the package
extern volatile uint32_t RPM;
extern volatile float current;
extern volatile float KMPH;
#endif /* TIMER1_H_ */
|
mohamedpop871/Telemetry-System
|
Embedded/Telemetry System/Telemetry System/main.c
|
<gh_stars>0
/*
* main.h
*
* Created: 10/15/2019 6:01:05 PM
* Author: Mohamed_Hassanin
*
*Description:
*This code measure the RPM and KMPH of a BLDC motor and the current consumed by it.
*the current sensor used to measure the current is ACS712
*/
#include <avr/io.h>
#include <avr/interrupt.h>
#include <inttypes.h>
#include "USART.h"
#include "Timer1.h"
#include "Timer3.h"
volatile uint32_t RPM = 0;
volatile uint32_t Rotor_Freq;
volatile float KMPH = 0.00;
volatile uint8_t After_Send;
volatile uint16_t adc_val = 0;
volatile uint64_t acc = 0;
volatile float adcAvg = 0;
volatile float current = 0;
volatile uint8_t count = 0;
int main()
{
INIT_UART();
Timer1_Init();
Timer3_Init();
//==================[Configuring ADC to convert channel3 (A3 in Arduino Mega)]===============
ADMUX |= 1 << REFS0 | (1 << MUX0) | (1 << MUX1); //AVCC with external capacitor at AREF pin,
//MUX = 0011, ArduinoMega "A3"
ADCSRA |= 1 << ADEN | 1 << ADPS2 | 1 << ADPS1 | 1 << ADPS0; //N = 128 -> 125kHz sampling rate
//25 samples in 5kHz pulse
//enable end of conversion interrupt
ADCSRA |= 1 << ADIE;
//start first conversion
ADCSRA |= 1<< ADSC;
//===================[Configuring Interrupt]===================
EICRA |= 1 << ISC01 | 1 << ISC00; //Generate interrupt on rising edge.
EIMSK |= 1 << INT0; // INT0 -> pin 21 (Arduino Mega).
//enable global interrupt
sei();
DDRB |= 1 << PINB5;
PORTB &= ~(1 << PINB5);
while (1)
;
return 0;
}
ISR
(INT0_vect)
{
//source: hall sensor 50% duty -> half of the freq = elec. rev.
Rotor_Freq = TCNT3;
Rotor_Freq = (((unsigned long) 16000000) / 1024 / Rotor_Freq);
RPM = (Rotor_Freq/24.0) * 60;
KMPH = (RPM * .08859291283); //.08859291283 Hard-Coded for this conversion
adcAvg = (float)acc/count; //Getting Average
if (RPM <= 15)
{
//Set initial Values
RPM = 0;
KMPH = 0;
current = 0.12;
}
else
{
//5.33 is inverse slope (refer to current sensor DS)
adcAvg = (adcAvg / 1024.0) * 5.0 * 5.33;
current = adcAvg;
}
//Reset timer3, count, and accumulated value for next speed¤t measurement:
TCNT3 = 0;
count = 0;
acc = 0;
}
ISR
(ADC_vect)
{
count++;
adc_val = ADC - 505; //505 is Hard-coded, as the current sensor shifts current by 2.5V.
acc += adc_val;
ADCSRA |= 1<< ADSC;
}
|
mohamedpop871/Telemetry-System
|
Embedded/Telemetry System/Telemetry System/Timer3.h
|
/*
* Timer0.h
*
* Created: 10/15/2019 6:01:05 PM
* Author: Mohamed_Hassanin
*/
#ifndef TIMER3_H_
#define TIMER3_H_
#include <avr/io.h>
void Timer3_Init(void);
#endif /* TIMER3_H_ */
|
mohamedpop871/Telemetry-System
|
Embedded/Telemetry System/Telemetry System/Timer1.c
|
<reponame>mohamedpop871/Telemetry-System
/*
* Timer1.c
*
* Created: 10/14/2019 11:34:16 PM
* Author: Mohamed_Hassanin
*/
#include "Timer1.h"
void
Timer1_Init(void)
{
TIMSK1 |= 1 << OCIE1A; //interrupt enable at overflow
TCCR1B |= 1 << WGM12;
OCR1A = 2000;
TCCR1B |= 1 << CS10 | 1 << CS12;
}
ISR
(TIMER1_COMPA_vect)
{
//enable nested interrupts for Hall sensor
sei();
if (Send == 1)
{
After_Send = 1;
//byte 0x1B means the end of the frame
// so don't put it as a data and put it as a combination
send_RPM(RPM); //Sending the RPM value
send_KMPH(KMPH); //Sending the KMPH value
send_Current(current);//Sending the Current value
USART_TX(0x1B); //Send delimiter -> End of Package
}
}
void
send_RPM(uint32_t RPM)
{
uint8_t RPMDig3 = (RPM / 100) % 10; //Getting Digit X3
USART_TX( RPM % 10 + 0x30); //Send X0
USART_TX( (RPM / 10) - RPMDig3 * 10 + 0x30); //Send X1
USART_TX( RPMDig3 + 0x30); //Send X2
}
void
send_KMPH(float KMPH)
{
float KMPHDig10 = (KMPH - (int) KMPH) * 100; //Getting Digits X1 & X0 (e.g. : 35)
USART_TX( (uint8_t) KMPHDig10 % 10 + 0x30 ); //Send X0
USART_TX( (uint8_t) KMPHDig10 / 10 + 0x30 ); //Send X1
USART_TX( (uint8_t) KMPH % 10 + 0x30 ); //Send X2
USART_TX( ((uint8_t) KMPH / 10) % 10 + 0x30 ); //Send X3
}
void
send_Current(float current)
{
uint8_t currentDig43 = (int) current % 100; //Getting Digits X4 & X3 (e.g. : 35)
uint8_t currentDig4 = currentDig43 / 10;
uint16_t currentDig210 = (current - (int) current) * 1000; //Getting Digits X3 & X2 & X1 (e.g. : 143)
uint8_t currentDig1 = currentDig210 / 10 - (currentDig210 / 100) * 10;
USART_TX(( (currentDig210) %10 + 0x30 )); //Send X0
USART_TX(( (currentDig1) + 0x30 )); //Send X1
USART_TX(( (currentDig210 / 100) + 0x30 )); //Send X2
USART_TX(( (currentDig43 % 10 + 0x30 ))); //Send X3
USART_TX(( (currentDig4 + 0x30))); //Send X4
}
|
mohamedpop871/Telemetry-System
|
Embedded/Telemetry System/Telemetry System/Timer3.c
|
/*
* Timer0.c
*
* Created: 10/15/2019 6:00:53 PM
* Author: Mohamed_Hassanin
*/
#include "Timer3.h"
//for speed
void
Timer3_Init(void)
{
TCCR3B |= 1 << CS30 | 1 << CS32;
}
|
mohamedpop871/Telemetry-System
|
Embedded/Telemetry System/Telemetry System/USART.c
|
<reponame>mohamedpop871/Telemetry-System<gh_stars>0
#include "USART.h"
void
INIT_UART(void)
{
UBRR0 = (F_CPU/16UL/BAUD)-1;
UCSR0B |= 1 << TXEN0 | 1 << RXCIE0 | 1 << RXEN0;
UCSR0B &= ~(1 << UCSZ02);
UCSR0C |= 1 << UCSZ00 | 1 << UCSZ01;
Send = 0;
}
void
USART_TX(uint8_t data )
{
/* Wait for empty transmit buffer */
while ( !( UCSR0A & (1<<UDRE0)) )
;
/* Put data into buffer, sends the data */
UDR0 = data;
}
void
USART_PRINTF(const char *str)
{
int x = 0;
while (str[x]){
USART_TX(str[x]);
x++;
}
}
ISR
(USART0_RX_vect)
{
if (UDR0 == 1)
{
Send = 1;
}
else
{
Send = 0;
}
}
|
mohamedpop871/Telemetry-System
|
Embedded/Telemetry System/Telemetry System/USART.h
|
<reponame>mohamedpop871/Telemetry-System<filename>Embedded/Telemetry System/Telemetry System/USART.h
#ifndef _USART_H
#define _USART_H
#include <inttypes.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#define F_CPU 16000000ul
#define BAUD 9600
volatile uint8_t data_rx;
void INIT_UART(void);
void USART_TX(uint8_t ch);
void USART_PRINTF(const char *str);
volatile uint8_t Send;
#endif
|
juanpablofernandez/SwiftyFeedback
|
SwiftyFeedback/SwiftyFeedback.h
|
//
// SwiftyFeedback.h
// SwiftyFeedback
//
// Created by <NAME> on 6/29/18.
// Copyright © 2018 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for SwiftyFeedback.
FOUNDATION_EXPORT double SwiftyFeedbackVersionNumber;
//! Project version string for SwiftyFeedback.
FOUNDATION_EXPORT const unsigned char SwiftyFeedbackVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <SwiftyFeedback/PublicHeader.h>
|
jfbastien/pnacl-compiler-rt
|
lib/builtins/compilerrt_logbf.c
|
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* From newlib's newlib/libm/common/sf_logb.c */
#include "fdlibm_nacl.h"
float __compilerrt_logbf(float x)
{
__int32_t hx,ix;
GET_FLOAT_WORD(hx,x);
hx &= 0x7fffffff;
if(FLT_UWORD_IS_ZERO(hx)) {
float xx;
/* arg==0: return -inf and raise divide-by-zero exception */
SET_FLOAT_WORD(xx,hx); /* +0.0 */
return -1./xx; /* logbf(0) = -inf */
}
if(FLT_UWORD_IS_SUBNORMAL(hx)) {
for (ix = -126,hx<<=8; hx>0; hx<<=1) ix -=1;
return (float) ix;
}
else if (FLT_UWORD_IS_INFINITE(hx)) return HUGE_VALF; /* x==+|-inf */
else if (FLT_UWORD_IS_NAN(hx)) return x;
else return (float) ((hx>>23)-127);
}
|
jfbastien/pnacl-compiler-rt
|
lib/builtins/int_types.h
|
/* ===-- int_lib.h - configuration header for compiler-rt -----------------===
*
* The LLVM Compiler Infrastructure
*
* This file is dual licensed under the MIT and the University of Illinois Open
* Source Licenses. See LICENSE.TXT for details.
*
* ===----------------------------------------------------------------------===
*
* This file is not part of the interface of this library.
*
* This file defines various standard types, most importantly a number of unions
* used to access parts of larger types.
*
* ===----------------------------------------------------------------------===
*/
#ifndef INT_TYPES_H
#define INT_TYPES_H
#include "int_endianness.h"
typedef int si_int;
typedef unsigned su_int;
typedef long long di_int;
typedef unsigned long long du_int;
typedef union
{
di_int all;
struct
{
#if _YUGA_LITTLE_ENDIAN
su_int low;
si_int high;
#else
si_int high;
su_int low;
#endif /* _YUGA_LITTLE_ENDIAN */
}s;
} dwords;
typedef union
{
du_int all;
struct
{
#if _YUGA_LITTLE_ENDIAN
su_int low;
su_int high;
#else
su_int high;
su_int low;
#endif /* _YUGA_LITTLE_ENDIAN */
}s;
} udwords;
/* MIPS64 issue: PR 20098 */
// @LOCALMOD
#if (defined(__LP64__) || \
(defined(__native_client__) && defined(__x86_64__))) \
&& !(defined(__mips__) && defined(__clang__))
#define CRT_HAS_128BIT
#endif
#ifdef CRT_HAS_128BIT
typedef int ti_int __attribute__ ((mode (TI)));
typedef unsigned tu_int __attribute__ ((mode (TI)));
typedef union
{
ti_int all;
struct
{
#if _YUGA_LITTLE_ENDIAN
du_int low;
di_int high;
#else
di_int high;
du_int low;
#endif /* _YUGA_LITTLE_ENDIAN */
}s;
} twords;
typedef union
{
tu_int all;
struct
{
#if _YUGA_LITTLE_ENDIAN
du_int low;
du_int high;
#else
du_int high;
du_int low;
#endif /* _YUGA_LITTLE_ENDIAN */
}s;
} utwords;
static inline ti_int make_ti(di_int h, di_int l) {
twords r;
r.s.high = h;
r.s.low = l;
return r.all;
}
static inline tu_int make_tu(du_int h, du_int l) {
utwords r;
r.s.high = h;
r.s.low = l;
return r.all;
}
#endif /* CRT_HAS_128BIT */
typedef union
{
su_int u;
float f;
} float_bits;
typedef union
{
udwords u;
double f;
} double_bits;
typedef struct
{
#if _YUGA_LITTLE_ENDIAN
udwords low;
udwords high;
#else
udwords high;
udwords low;
#endif /* _YUGA_LITTLE_ENDIAN */
} uqwords;
typedef union
{
uqwords u;
long double f;
} long_double_bits;
#endif /* INT_TYPES_H */
|
jfbastien/pnacl-compiler-rt
|
lib/builtins/fdlibm_nacl.h
|
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* NaCl-specific defines and typedefs */
#define HUGE_VALF __builtin_huge_valf()
#define HUGE_VAL __builtin_huge_val()
typedef int __int32_t;
typedef unsigned int __uint32_t;
/* Excerpted from newlib's libm/common/fdlibm.h */
#define FLT_UWORD_IS_FINITE(x) ((x)<0x7f800000L)
#define FLT_UWORD_IS_NAN(x) ((x)>0x7f800000L)
#define FLT_UWORD_IS_INFINITE(x) ((x)==0x7f800000L)
#define FLT_UWORD_MAX 0x7f7fffffL
#define FLT_UWORD_EXP_MAX 0x43000000
#define FLT_UWORD_LOG_MAX 0x42b17217
#define FLT_UWORD_LOG_2MAX 0x42b2d4fc
#define HUGE ((float)3.40282346638528860e+38)
#define FLT_UWORD_IS_ZERO(x) ((x)==0)
#define FLT_UWORD_IS_SUBNORMAL(x) ((x)<0x00800000L)
#define FLT_UWORD_MIN 0x00000001
#define FLT_UWORD_EXP_MIN 0x43160000
#define FLT_UWORD_LOG_MIN 0x42cff1b5
#define FLT_SMALLEST_EXP -22
typedef union
{
double value;
struct
{
__uint32_t lsw;
__uint32_t msw;
} parts;
} ieee_double_shape_type;
/* Get two 32 bit ints from a double. */
#define EXTRACT_WORDS(ix0,ix1,d) \
do { \
ieee_double_shape_type ew_u; \
ew_u.value = (d); \
(ix0) = ew_u.parts.msw; \
(ix1) = ew_u.parts.lsw; \
} while (0)
/* Set a double from two 32 bit ints. */
#define INSERT_WORDS(d,ix0,ix1) \
do { \
ieee_double_shape_type iw_u; \
iw_u.parts.msw = (ix0); \
iw_u.parts.lsw = (ix1); \
(d) = iw_u.value; \
} while (0)
/* A union which permits us to convert between a float and a 32 bit
int. */
typedef union
{
float value;
__uint32_t word;
} ieee_float_shape_type;
/* Get a 32 bit int from a float. */
#define GET_FLOAT_WORD(i,d) \
do { \
ieee_float_shape_type gf_u; \
gf_u.value = (d); \
(i) = gf_u.word; \
} while (0)
/* Set a float from a 32 bit int. */
#define SET_FLOAT_WORD(d,i) \
do { \
ieee_float_shape_type sf_u; \
sf_u.word = (i); \
(d) = sf_u.value; \
} while (0)
|
jfbastien/pnacl-compiler-rt
|
lib/builtins/atomic64.c
|
<filename>lib/builtins/atomic64.c
/*===----- atomic64.c - Support functions for 64-bit atomic operations.-----===
*
* The LLVM Compiler Infrastructure
*
* This file is dual licensed under the MIT and the University of Illinois Open
* Source Licenses. See LICENSE.TXT for details.
*
*===-----------------------------------------------------------------------===
*
* atomic64.c defines a set of functions for performing atomic accesses on
* 64-bit memory locations. It also implements spinlock synchronization
* operations.
*
*===-----------------------------------------------------------------------===
*/
#include <stdint.h>
#include <stdbool.h>
#pragma redefine_extname __nacl_sync_fetch_and_add_8 __sync_fetch_and_add_8
#pragma redefine_extname __nacl_sync_fetch_and_sub_8 __sync_fetch_and_sub_8
#pragma redefine_extname __nacl_sync_fetch_and_and_8 __sync_fetch_and_and_8
#pragma redefine_extname __nacl_sync_fetch_and_or_8 __sync_fetch_and_or_8
#pragma redefine_extname __nacl_sync_fetch_and_xor_8 __sync_fetch_and_xor_8
#pragma redefine_extname __nacl_sync_add_and_fetch_8 __sync_add_and_fetch_8
#pragma redefine_extname __nacl_sync_sub_and_fetch_8 __sync_sub_and_fetch_8
#pragma redefine_extname __nacl_sync_and_and_fetch_8 __sync_and_and_fetch_8
#pragma redefine_extname __nacl_sync_or_and_fetch_8 __sync_or_and_fetch_8
#pragma redefine_extname __nacl_sync_xor_and_fetch_8 __sync_xor_and_fetch_8
#pragma redefine_extname __nacl_sync_bool_compare_and_swap_8 \
__sync_bool_compare_and_swap_8
#pragma redefine_extname __nacl_sync_val_compare_and_swap_8 \
__sync_val_compare_and_swap_8
#pragma redefine_extname __nacl_sync_lock_test_and_set_8 \
__sync_lock_test_and_set_8
#pragma redefine_extname __nacl_sync_lock_release_8 __sync_lock_release_8
static void __spin_lock(volatile int *lock) {
while (__sync_lock_test_and_set(lock, 1))
while (*lock) {}
}
static void __spin_unlock(volatile int *lock) {
__sync_lock_release(lock);
}
/*
* Make sure the lock is on its own cache line to prevent false sharing.
* Put it inside a struct that is aligned and padded to the typical MIPS
* cacheline which is 32 bytes.
*/
static struct {
int lock;
char pad[32 - sizeof(int)];
} __attribute__((aligned (32))) lock = { 0 };
uint64_t __nacl_sync_fetch_and_add_8(volatile uint64_t *ptr, uint64_t val) {
uint64_t ret;
__spin_lock(&lock.lock);
ret = *ptr;
*ptr = ret + val;
__spin_unlock(&lock.lock);
return ret;
}
uint64_t __nacl_sync_fetch_and_sub_8(volatile uint64_t *ptr, uint64_t val) {
uint64_t ret;
__spin_lock(&lock.lock);
ret = *ptr;
*ptr = ret - val;
__spin_unlock(&lock.lock);
return ret;
}
uint64_t __nacl_sync_fetch_and_and_8(volatile uint64_t *ptr, uint64_t val) {
uint64_t ret;
__spin_lock(&lock.lock);
ret = *ptr;
*ptr = ret & val;
__spin_unlock(&lock.lock);
return ret;
}
uint64_t __nacl_sync_fetch_and_or_8(volatile uint64_t *ptr, uint64_t val) {
uint64_t ret;
__spin_lock(&lock.lock);
ret = *ptr;
*ptr = ret | val;
__spin_unlock(&lock.lock);
return ret;
}
uint64_t __nacl_sync_fetch_and_xor_8(volatile uint64_t *ptr, uint64_t val) {
uint64_t ret;
__spin_lock(&lock.lock);
ret = *ptr;
*ptr = ret ^ val;
__spin_unlock(&lock.lock);
return ret;
}
uint64_t __nacl_sync_add_and_fetch_8(volatile uint64_t *ptr, uint64_t val) {
uint64_t ret;
__spin_lock(&lock.lock);
ret = *ptr + val;
*ptr = ret;
__spin_unlock(&lock.lock);
return ret;
}
uint64_t __nacl_sync_sub_and_fetch_8(volatile uint64_t *ptr, uint64_t val) {
uint64_t ret;
__spin_lock(&lock.lock);
ret = *ptr - val;
*ptr = ret;
__spin_unlock(&lock.lock);
return ret;
}
uint64_t __nacl_sync_and_and_fetch_8(volatile uint64_t *ptr, uint64_t val) {
uint64_t ret;
__spin_lock(&lock.lock);
ret = *ptr & val;
*ptr = ret;
__spin_unlock(&lock.lock);
return ret;
}
uint64_t __nacl_sync_or_and_fetch_8(volatile uint64_t *ptr, uint64_t val) {
uint64_t ret;
__spin_lock(&lock.lock);
ret = *ptr | val;
*ptr = ret;
__spin_unlock(&lock.lock);
return ret;
}
uint64_t __nacl_sync_xor_and_fetch_8(volatile uint64_t *ptr, uint64_t val) {
uint64_t ret;
__spin_lock(&lock.lock);
ret = *ptr ^ val;
*ptr = ret;
__spin_unlock(&lock.lock);
return ret;
}
bool __nacl_sync_bool_compare_and_swap_8(volatile uint64_t *ptr,
uint64_t oldval, uint64_t newval) {
bool ret = false;
__spin_lock(&lock.lock);
if (*ptr == oldval) {
*ptr = newval;
ret = true;
}
__spin_unlock(&lock.lock);
return ret;
}
uint64_t __nacl_sync_val_compare_and_swap_8(volatile uint64_t *ptr,
uint64_t oldval, uint64_t newval) {
uint64_t ret;
__spin_lock(&lock.lock);
ret = *ptr;
if (ret == oldval)
*ptr = newval;
__spin_unlock(&lock.lock);
return ret;
}
uint64_t __nacl_sync_lock_test_and_set_8(volatile uint64_t *ptr, uint64_t val) {
uint64_t ret;
__spin_lock(&lock.lock);
ret = *ptr;
*ptr = val;
__spin_unlock(&lock.lock);
return ret;
}
void __nacl_sync_lock_release_8(volatile uint64_t *ptr) {
__spin_lock(&lock.lock);
*ptr = 0;
__spin_unlock(&lock.lock);
}
|
jfbastien/pnacl-compiler-rt
|
lib/builtins/compilerrt_logb.c
|
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
/* From newlib's newlib/libm/common/s_logb.c */
#include "fdlibm_nacl.h"
double __compilerrt_logb(double x)
{
__int32_t hx,lx,ix;
EXTRACT_WORDS(hx,lx,x);
hx &= 0x7fffffff; /* high |x| */
if(hx<0x00100000) { /* 0 or subnormal */
if((hx|lx)==0) {
double xx;
/* arg==0: return -inf and raise divide-by-zero exception */
INSERT_WORDS(xx,hx,lx); /* +0.0 */
return -1./xx; /* logb(0) = -inf */
}
else /* subnormal x */
if(hx==0) {
for (ix = -1043; lx>0; lx<<=1) ix -=1;
} else {
for (ix = -1022,hx<<=11; hx>0; hx<<=1) ix -=1;
}
return (double) ix;
}
else if (hx<0x7ff00000) return (hx>>20)-1023; /* normal # */
else if (hx>0x7ff00000 || lx) return x; /* x==NaN */
else return HUGE_VAL; /* x==inf (+ or -) */
}
|
jfbastien/pnacl-compiler-rt
|
lib/builtins/compilerrt_fmaxf.c
|
/*
* Copyright (c) 2015 The Native Client 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 "int_math.h"
float __compilerrt_fmaxf(float x, float y)
{
if (crt_isnan(x))
return y;
if (crt_isnan(y))
return x;
return x > y ? x : y;
}
|
tanvir002700/kmp
|
ext/kmp/kmp.c
|
#include<ruby.h>
#include<kmp_string.h>
void Init_kmp()
{
VALUE mKmp = rb_define_module("Kmp");
Init_kmp_string(mKmp);
}
|
tanvir002700/kmp
|
ext/kmp/kmp_string.c
|
#include<ruby.h>
#include<string.h>
struct Str
{
char * ptr;
};
static void deallocate(struct Str *str)
{
if(str->ptr) free(str->ptr);
free(str);
}
static VALUE allocate(VALUE klass)
{
struct Str * str = (struct Str *)malloc(sizeof(struct Str));
VALUE obj = Data_Make_Struct(klass, struct Str, NULL, deallocate, str);
str->ptr = NULL;
return obj;
}
static VALUE initialize(VALUE self, VALUE rb_string)
{
struct Str * str;
Check_Type(rb_string, T_STRING);
Data_Get_Struct(self, struct Str, str);
str->ptr = calloc(RSTRING_LEN(rb_string) + 1 , sizeof(char));
memcpy(str->ptr, StringValuePtr(rb_string), RSTRING_LEN(rb_string));
rb_iv_set(self, "@str", rb_string);
rb_iv_set(self, "@length", INT2NUM(RSTRING_LEN(rb_string)));
return self;
}
static int* compute_prefix(const char *str)
{
int len = strlen(str);
int k = -1;
int * prefix;
prefix = (int *) calloc(len+1, sizeof(int));
prefix[0] = -1;
for(int i=1; i<len; i++)
{
while( k>-1 && str[k+1]!=str[i] ) k = prefix[k];
if( str[k+1] == str[i] ) k = k+1;
prefix[i] = k;
}
return prefix;
}
static VALUE match(VALUE self, VALUE rb_str)
{
VALUE positions = rb_ary_new();
struct Str * obj;
char * str;
char * ptrn;
int * prefix;
int n,m,q;
Check_Type(rb_str, T_STRING);
Data_Get_Struct(self, struct Str, obj);
str = calloc(strlen(obj->ptr) + 1, sizeof(char));
strcpy(str, obj->ptr);
ptrn = (char *) calloc(RSTRING_LEN(rb_str) + 1, sizeof(char));
memcpy(ptrn, StringValuePtr(rb_str), RSTRING_LEN(rb_str));
prefix = compute_prefix(ptrn);
n = strlen(str);
m = strlen(ptrn);
q = -1;
for(int i=0; i<n; i++)
{
while( q>-1 && ptrn[q+1]!=str[i] ) q = prefix[q];
if( ptrn[q+1]==str[i] ) q = q+1;
if( q==m-1 )
{
rb_ary_push(positions, INT2NUM(i-m+1));
q = prefix[q];
}
}
free(prefix);
free(ptrn);
free(str);
return positions;
}
static VALUE replace(VALUE self, VALUE rb_str, VALUE rb_string_sub)
{
struct Str * obj;
char * str;
char * new_str;
char * sub_str;
Check_Type(rb_str, T_STRING);
Check_Type(rb_string_sub, T_STRING);
Data_Get_Struct(self, struct Str, obj);
str = calloc(strlen(obj->ptr) + 1, sizeof(char));
strcpy(str, obj->ptr);
int current_str_len = strlen(str);
sub_str = (char *) calloc(RSTRING_LEN(rb_string_sub) + 1, sizeof(char));
memcpy(sub_str, StringValuePtr(rb_string_sub), RSTRING_LEN(rb_string_sub));
VALUE pos = match(self, rb_str);
VALUE * arr = rb_array_const_ptr(pos);
int replace_str_len, sub_string_len, occurance;
replace_str_len = RSTRING_LEN(rb_str);
sub_string_len = strlen(sub_str);
occurance = rb_array_len(pos);
int new_str_len = (current_str_len - (replace_str_len * occurance) + (sub_string_len * occurance));
new_str = (char *) calloc(new_str_len+1, sizeof(char));
int indx = 0;
int occurance_indx = occurance ? 0 : -1;
int str_indx = 0;
while(str_indx<=new_str_len)
{
if(occurance_indx != -1 && occurance_indx<occurance && RB_NUM2INT(arr[occurance_indx]) == indx)
{
int sub_indx = 0;
while(sub_indx<sub_string_len)
{
new_str[str_indx] = sub_str[sub_indx];
str_indx++;
sub_indx++;
}
indx += replace_str_len;
occurance_indx++;
}
else
{
new_str[str_indx++] = str[indx++];
}
}
VALUE rb_new_str = rb_str_new2(new_str);
free(new_str);
free(sub_str);
free(str);
return rb_new_str;
}
void Init_kmp_string(VALUE mKmp)
{
VALUE cKmpString = rb_define_class_under(mKmp, "String", rb_cObject);
rb_define_alloc_func(cKmpString, allocate);
rb_define_method(cKmpString, "initialize", initialize, 1);
rb_define_method(cKmpString, "match", match, 1);
rb_define_method(cKmpString, "replace", replace, 2);
rb_define_attr(cKmpString, "str", 1, 0);
rb_define_attr(cKmpString, "length", 1, 0);
}
|
tanvir002700/kmp
|
ext/kmp/kmp_string.h
|
<reponame>tanvir002700/kmp<filename>ext/kmp/kmp_string.h
#ifndef KMP_STRING
#define KMP_STRING
#include<ruby.h>
void Init_kmp_string(VALUE mKmp);
#endif
|
HorexC/CXExtension
|
CXExtension/CXExtension/CXType.h
|
<filename>CXExtension/CXExtension/CXType.h
//
// CXType.h
// CXExtension
//
// Created by Horex on 15/9/1.
// Copyright (c) 2015年 Horex. All rights reserved.
//
// 包装一种类型
#import <Foundation/Foundation.h>
@interface CXType : NSObject
/** 类型标识符 */
@property (nonatomic, strong) NSString *code;
/** 对象类型(如果是基本类型,此值为nil) */
@property (nonatomic, assign, readonly) Class typeClass;
/** 类型是否来自与Foundation框架,比如NSString、NSArray */
@property (nonatomic, assign, readonly, getter = isFromFoundation) BOOL fromFoundation;
/** 类型是否不支持KVC */
@property (nonatomic, assign, readonly, getter = isKVCDisabled) BOOL KVCDisabled;
/**
* 初始化一个类型对象
*
* @param code 类型标识符
*/
- (instancetype)initWithCode:(NSString *)code;
/**
* 获得缓存的类型对象
*/
+ (instancetype)cachedTypeWithCode:(NSString *)code;
@end
|
HorexC/CXExtension
|
CXExtension/CXExtension/NSObject+CXCoding.h
|
<reponame>HorexC/CXExtension<filename>CXExtension/CXExtension/NSObject+CXCoding.h
//
// NSObject+CXCoding.h
// CXExtension
//
// Created by Horex on 15/9/2.
// Copyright (c) 2015年 Horex. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSObject (CXCoding)
/** 解码 */
- (void)decode:(NSCoder *)decoder;
/** 编码 */
- (void)encode:(NSCoder *)encoder;
@end
/** 归档实现 */
#define CXCodingImplementation \
- (id)initWithCoder:(NSCoder *)decoder \
{ \
if (self = [super init]) { \
[self decode:decoder]; \
} \
return self; \
} \
\
- (void)encodeWithCoder:(NSCoder *)encoder \
{ \
[self encode:encoder]; \
}
|
HorexC/CXExtension
|
CXExtension/CXExtension/JustTest.h
|
//
// JustTest.h
// CXExtension
//
// Created by Horex on 16/3/28.
// Copyright © 2016年 Horex. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface JustTest : NSObject
@end
|
HorexC/CXExtension
|
CXExtension/CXExtension/NSObject+CXIvar.h
|
<gh_stars>0
//
// NSObject+CXIvar.h
// CXExtension
//
// Created by Horex on 15/9/2.
// Copyright (c) 2015年 Horex. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "CXIvar.h"
/**
* 遍历所有类的block(父类)
*/
typedef void (^CXClassesBlock)(Class c, BOOL *stop);
@interface NSObject (CXIvar)
/**
* 遍历所有的成员变量
*/
- (void)enumerateIvarsWithBlock:(CXIvarsBlock)block;
/**
* 遍历所有的类
*/
- (void)enumerateClassesWithBlock:(CXClassesBlock)block;
@end
|
HorexC/CXExtension
|
CXExtension/CXExtension/CXIvar.h
|
//
// CXIvar.h
// CXExtension
//
// Created by Horex on 15/9/1.
// Copyright (c) 2015年 Horex. All rights reserved.
// 包装一个成员变量
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import "CXType.h"
@interface CXIvar : NSObject
/** 成员变量 */
@property (nonatomic, assign) Ivar ivar;
/** 成员属性名 */
@property (nonatomic, copy, readonly) NSString *propertyName;
/** 成员变量值 */
@property (nonatomic) id value;
/** 成员变量类型 */
@property (nonatomic, strong, readonly) CXType *type;
/** 对应着字典中的key */
@property (nonatomic, copy) NSString *key;
/** 模型数组中的模型类型 */
@property (nonatomic, assign) Class objectClassInArray;
/** 成员来源于哪个类(可能是父类) */
@property (nonatomic, assign) Class srcClass;
/** 成员来源于哪个对象 */
@property (nonatomic, weak) id srcObject;
/** 成员名 */
@property (nonatomic, copy) NSString *name;
/**
* 初始化
*
* @param ivar 成员变量
* @param srcObject 哪个对象的成员变量
*
* @return 初始化好的对象
*/
- (instancetype)initWithIvar:(Ivar)ivar;
+ (instancetype)cachedIvarWithIvar:(Ivar)ivar;
@end
/**
* 遍历成员变量用的block
*
* @param ivar 成员变量的包装对象
* @param stop YES代表停止遍历,NO代表继续遍历
*/
typedef void (^CXIvarsBlock)(CXIvar *ivar, BOOL *stop);
|
HorexC/CXExtension
|
CXExtension/CXExtension/CXExtension.h
|
//
// CXExtension.h
// CXExtension
//
// Created by Horex on 15/9/1.
// Copyright (c) 2015年 Horex. All rights reserved.
//
#import "CXTypeEncoding.h"
#import "NSObject+CXKeyValue.h"
#import "NSObject+CXCoding.h"
#import "NSObject+CXIvar.h"
#define CXLogAllIvars \
- (NSString *)description \
{\
return [NSString string]; \
}
//[self keyValues].description
|
HorexC/CXExtension
|
CXExtension/CXExtension/CXConst.h
|
<reponame>HorexC/CXExtension
//
// CXConst.h
// CXExtension
//
// Created by Horex on 15/9/2.
// Copyright (c) 2015年 Horex. All rights reserved.
//
#ifdef DEBUG // 调试状态
// 打开LOG功能
#define CXLog(...) NSLog(__VA_ARGS__)
// 打开断言功能
#define CXAssert(condition, desc) NSAssert(condition, @"\n报错文件:%@\n报错行数:第%d行\n报错方法:%s\n错误描述:%@",[NSString stringWithUTF8String:__FILE__], __LINE__, __FUNCTION__, desc)
#define CXAssertParamsNoNil(param) CXAssert(param, [[NSString stringWithFormat:@#param] stringByAppendingString:@"参数不能为nil"])
#else // 发布状态
// 关闭LOG功能
#define CXLog(...)
// 关闭断言功能
#define CXAssert(condition, desc)
#define CXAssertParamsNoNil(param)
// 断言
#define MJAssert2(condition, desc, returnValue) \
if ((condition) == NO) { \
NSString *file = [NSString stringWithUTF8String:__FILE__]; \
MJLog(@"\n警告文件:%@\n警告行数:第%d行\n警告方法:%s\n警告描述:%@", file, __LINE__, __FUNCTION__, desc); \
return returnValue; \
}
#define MJAssert(condition, desc) MJAssert2(condition, desc, )
#define MJAssertParamNotNil2(param, returnValue) \
MJAssert2(param, [[NSString stringWithFormat:@#param] stringByAppendingString:@"参数不能为nil"], returnValue)
#define MJAssertParamNotNil(param) MJAssertParamNotNil2(param, )
#endif
|
HorexC/CXExtension
|
CXExtension/CXExtension/NSObject+CXKeyValue.h
|
//
// NSObject+CXKeyValue.h
// CXExtension
//
// Created by Horex on 15/9/2.
// Copyright (c) 2015年 Horex. All rights reserved.
//
#import <Foundation/Foundation.h>
/** KeyValue协议 */
@protocol CXKeyValue <NSObject>
@optional
/**
* 将属性名换为其他key去字典中取值
*
* @return 字典中的key是属性名,value是从字典中取值用的key
*/
- (NSDictionary *)replaceKeyFromPropertyName;
/**
* 数组中需要转换的模型类
*
* @return 字典中的key是数组属性名,value是数组中存放模型的Class
*/
- (NSDictionary *)objectClassInArray;
/**
* 字典转模型完毕时候调用
*/
- (void)keyValuesDidFinshConvertingToObject;
/**
* 模型转字典完毕时候调用
*/
- (void)objectDidFinshConvertingToKeyValues;
@end
@interface NSObject (CXKeyValue) <CXKeyValue>
/**
* 将字典的键值对转成模型属性
* @param keyValues 字典
*/
- (instancetype)setKeyValues:(NSDictionary *)keyValues;
/**
* 将模型转成字典
* @return 字典
*/
- (NSDictionary *)keyValues;
/**
* 通过模型数组来创建一个字典数组
* @param objectArray 模型数组
* @return 字典数组
*/
+ (NSArray *)keyValuesArrayWithObjectArray:(NSArray *)objectArray;
/**
* 通过JSON数据来创建一个模型
* @param data JSON数据
* @return 新建的对象
*/
+ (instancetype)objectWithJSONData:(NSData *)data;
#pragma mark - 字典转模型
/**
* 通过字典来创建一个模型
* @param keyValues 字典
* @return 新建的对象
*/
+ (instancetype)objectWithKeyValues:(NSDictionary *)keyValues;
/**
* 通过plist来创建一个模型
* @param filename 文件名(仅限于mainBundle中的文件)
* @return 新建的对象
*/
+ (instancetype)objectWithFilename:(NSString *)filename;
/**
* 通过plist来创建一个模型
* @param file 文件全路径
* @return 新建的对象
*/
+ (instancetype)objectWithFile:(NSString *)file;
#pragma mark - 字典数组转模型数组
/**
* 通过字典数组来创建一个模型数组
* @param keyValuesArray 字典数组
* @return 模型数组
*/
+ (NSArray *)objectArrayWithKeyValuesArray:(NSArray *)keyValuesArray;
/**
* 通过plist来创建一个模型数组
* @param filename 文件名(仅限于mainBundle中的文件)
* @return 模型数组
*/
+ (NSArray *)objectArrayWithFilename:(NSString *)filename;
/**
* 通过plist来创建一个模型数组
* @param file 文件全路径
* @return 模型数组
*/
+ (NSArray *)objectArrayWithFile:(NSString *)file;
#pragma mark - 其他方法
- (NSString *)keyWithPropertyName:(NSString *)propertyName;
@end
|
HorexC/CXExtension
|
CXExtension/CXExtension/CXFoundation.h
|
//
// CXFoundation.h
// CXExtension
//
// Created by Horex on 15/9/2.
// Copyright (c) 2015年 Horex. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface CXFoundation : NSObject
+ (BOOL)isClassFromFoundation:(Class)c;
@end
|
HorexC/CXExtension
|
CXExtension/CXExtension/CXTypeEncoding.h
|
//
// CXTypeEncoding.h
// CXExtension
//
// Created by Horex on 15/9/1.
// Copyright (c) 2015年 Horex. All rights reserved.
//
#import <Foundation/Foundation.h>
/** 属性类型 */
extern NSString *const CXTypeInt;
extern NSString *const CXTypeFloat;
extern NSString *const CXTypeDouble;
extern NSString *const CXTypeLong;
extern NSString *const CXTypeLongLong;
extern NSString *const CXTypeChar;
extern NSString *const CXTypeBOOL;
extern NSString *const CXTypePointer;
extern NSString *const CXTypeIvar;
extern NSString *const CXTypeMethod;
extern NSString *const CXTypeBlock;
extern NSString *const CXTypeClass;
extern NSString *const CXTypeSEL;
extern NSString *const CXTypeId;
/** 返回值类型 */
extern NSString *const CXReturnTypeVoid;
extern NSString *const CXReturnTypeObject;
|
Wilgnne/Pseudo-Kernel
|
src/kernel/kernel.c
|
#include <stdio.h>
#include <kernel/kstdio.h>
void main()
{
char command[100];
char args[50];
while (1)
{
printf("$ ");
scanf("%s", command);
scanf("%[^\n]", args);
flush_in();
printf("\t\tRUN %s with %s args\n", command, args);
}
}
|
Wilgnne/Pseudo-Kernel
|
include/kernel/kstdio.h
|
void flush_in();
|
Wilgnne/Pseudo-Kernel
|
include/kernel/process.h
|
<filename>include/kernel/process.h
// Estrutura de um processo
typedef struct
{
// exec=1; ready=0; blocked=-1;
int state;
} process;
|
Wilgnne/Pseudo-Kernel
|
src/kernel/kstdio.c
|
<reponame>Wilgnne/Pseudo-Kernel
#include <stdio.h>
#include <kernel/kstdio.h>
//Limpa o buffer do teclado
void flush_in()
{
int ch;
while ((ch = fgetc(stdin)) != EOF && ch != '\n')
{
}
}
|
JamesOrson/KomodoCPP
|
src/include/komodo/core/game.h
|
#pragma once
#include <memory>
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <string>
namespace komodo::core
{
class Game
{
public:
#pragma region Constructors
Game();
#pragma endregion
~Game();
#pragma region Static Members
//static ContentManager contentManager;
#pragma endregion
#pragma region Accessors
//weak_ptr<BehaviorSystem> getBehaviorSystem() const;
//weak_ptr<CameraSystem> getCameraSystem() const;
//weak_ptr<Shader> getDefaultSpriteShader() const;
float getFramesPerSecond() const;
//weak_ptr<GraphicsManager> getGraphicsManager() const;
bool getIsActive() const;
//vector<PhysicsSystem> getPhysicsSystem() const;
//vector<Render2DSystem> getRender2DSystem() const;
//vector<Render3DSystem> getRender3DSystem() const;
std::string getScreenDeviceName() const;
//weak_ptr<SoundSystem> getSoundSystem() const;
std::string getTitle() const;
#pragma endregion
#pragma region Mutators
//void setDefaultSpriteShader(Shader value);
void setIsActive(bool value);
void setTitle(std::string value);
#pragma endregion
#pragma region Member Methods
//std::shared_ptr<PhysicsSystem> createPhysicsSystem();
//std::shared_ptr<Render2DSystem> createRender2DSystem();
//std::shared_ptr<Render3DSystem> createRender3DSystem();
void draw(float dt, sf::Color clearColor = sf::Color(0.0f, 100.0f, 100.0f));
void exit();
void initialize();
void run();
void update(float dt);
#pragma region Event handlers
//int addExitingEvent(const std::shared_ptr<function<bool(ExitEventArgs args)>> handler);
//int addFocusGainedEvent(const std::shared_ptr<function<bool(FoxusGainedArgs args)>> handler);
//int addFocusLostEvent(const std::shared_ptr<function<bool(FocusLostArgs args)>> handler);
//int addKeyDownEvent(const std::shared_ptr<function<bool(KeyDownEventArgs args)>> handler);
//int addScreenDeviceNameChangedEvent(const std::shared_ptr<function<bool(KeyUpArgs args)>> handler);
//int addTextInputEvent(const std::shared_ptr<function<bool(TextInputEventArgs args)>> handler);
//int addWindowSizeChangedEvent(const std::shared_ptr<function<bool(WindowSizeChangedEventArgs args)>> handler);
//bool removeExitingEvent(const int handlerId);
//bool removeFocusGainedEvent(const int handlerId);
//bool removeFocusLostEvent(const int handlerId);
//bool removeKeyDownEvent(const int handlerId);
//bool removeScreenDeviceNameChangedEvent(const int handlerId);
//bool removeTextInputEvent(const int handlerId);
//bool removeWindowSizeChangedEvent(const int handlerId);
#pragma endregion
#pragma endregion Member Methods
private:
#pragma region Members
//BehaviorSystem behaviorSystem;
//CameraSystem cameraSystem;
std::shared_ptr<sf::Clock> clock;
//Shader defaultSpriteShader;
float framesPerSecond = 0.0;
//GraphicsManager graphicsManager;
bool isActive = true;
//vector<PhysicsSystem> physicsSystems;
//vector<Render2DSystem> render2DSystems;
//vector<Render2DSystem> render2DSystems;
std::string screenDeviceName;
bool shouldClose = false;
//SoundSystem soundSystem;
std::string title;
std::shared_ptr<sf::RenderWindow> window;
#pragma endregion
};
}
|
Randyninja/PhysXEngine
|
PhysicsForGamesvs2015_Start/PhysicsForGames/DIYPhysicsEngine/PhysicsObjects/BoxClass.h
|
#pragma once
#include "RigidBody.h"
class BoxClass : public RigidBody
{
public:
BoxClass(vec3 pos, vec3 bounds, vec3 vel, quat rot, float mass);
~BoxClass();
void MakeGizmo();
vec3 min, max;
vec3 centreOfGravity;
};
|
Randyninja/PhysXEngine
|
PhysicsForGamesvs2015_Start/PhysicsForGames/Physics.h
|
<reponame>Randyninja/PhysXEngine<gh_stars>0
#ifndef SOUND_PROGRAMMING_H_
#define SOUND_PROGRAMMING_H_
#include "Application.h"
#include "Camera.h"
#include "Render.h"
#include "DIYPhysicsEngine/DIYPhysicScene.h"
#include "DIYPhysicsEngine\PhysicsObjects\Plane.h"
#include "DIYPhysicsEngine\PhysicsObjects\SpringJoint.h"
#include <PxPhysicsAPI.h>
#include <PxScene.h>
#include <pvd/PxVisualDebugger.h>
using namespace physx;
class myAllocator : public PxAllocatorCallback
{
public:
virtual ~myAllocator() {}
virtual void* allocate(size_t size, const char* typeName, const char* filename, int line)
{
void* pointer = _aligned_malloc(size, 16);
return pointer;
}
virtual void deallocate(void* ptr)
{
_aligned_free(ptr);
}
};
class Physics : public Application
{
public:
virtual bool startup();
virtual void shutdown();
virtual bool update();
virtual void draw();
void SetUpPhysX();
void SetupVisualDebugger();
void UpdatePhysX(float deltaTime);
void DIYPhysicsSetup();
void SetupTutorial1();
void renderGizmos(PxScene* physics_scene);
Renderer* m_renderer;
FlyCamera m_camera;
float m_delta_time;
float dt;
private:
PxFoundation* m_PhysicsFoundation;
PxPhysics* m_Physics;
PxScene* m_PhysicsScene;
PxDefaultErrorCallback mDefaultErrorCallback;
PxDefaultAllocator mDefaultAllocatorCallback;
PxSimulationFilterShader mDefaultFilterShader = PxDefaultSimulationFilterShader;
PxMaterial* m_PhysicsMaterial;
PxMaterial* m_BoxMaterial;
PxCooking* m_PhysicsCooker;
DIYPhysicScene* physicsScene;
float counter = 0;
SphereClass* newBall;
SphereClass* newBall2;
Plane* plane;
float rocketTimer = 0;
float fireTimer = 0;
float boxTimer = 2;
float boxCounter = 0;
SpringJoint* joint;
SphereClass* ballList[10*10];
};
#endif //CAM_PROJ_H_
|
Randyninja/PhysXEngine
|
PhysicsForGamesvs2015_Start/PhysicsForGames/DIYPhysicsEngine/PhysicsObjects/SpringJoint.h
|
#pragma once
#include "PhysicsObject.h"
#include "RigidBody.h"
class SpringJoint : public PhysicsObject
{
public:
SpringJoint(RigidBody* connection1, RigidBody* connection2, float springCoefficient, float damping);
private:
void virtual Update(vec3 gravity, float timeStep);
void virtual Debug();
void virtual MakeGizmo();
RigidBody* m_connections[2];
float m_damping;
float m_restLength;
float m_springCoefficient;
};
|
Randyninja/PhysXEngine
|
PhysicsForGamesvs2015_Start/PhysicsForGames/DIYPhysicsEngine/PhysicsObjects/PhysicsObject.h
|
<reponame>Randyninja/PhysXEngine
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// <NAME>
// 5/02/16
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#pragma once
#include "../Gizmos.h"
#include <../glm/glm.hpp>
#include <../glm/ext.hpp>
#include <PxPhysicsAPI.h>
using namespace glm;
enum ShapeType
{
PLANE,
SPHERE,
BOX,
CAPSULE,
JOINT,
Last = JOINT
};
enum PhysicsType
{
DYNAMIC,
STATIC,
KINEMATIC
};
class PhysicsObject
{
public:
void virtual Update(vec3 gravity, float timeStep) = 0;
void virtual Debug() = 0;
void virtual MakeGizmo() = 0;
void virtual ResetPosition() {};
ShapeType m_shapeID;
PhysicsType m_physicsType;
bool m_isAwake = true;
};
|
Randyninja/PhysXEngine
|
PhysicsForGamesvs2015_Start/PhysicsForGames/DIYPhysicsEngine/PhysicsObjects/SphereClass.h
|
<gh_stars>1-10
#pragma once
#include "RigidBody.h"
class SphereClass : public RigidBody
{
public:
SphereClass(vec3 position, vec3 velocity, float mass, float radius, vec4 colour);
void virtual MakeGizmo();
float m_radius;
};
|
Randyninja/PhysXEngine
|
PhysicsForGamesvs2015_Start/PhysicsForGames/DIYPhysicsEngine/PhysicsObjects/RigidBody.h
|
<gh_stars>1-10
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// <NAME>
// 02/05/16
// Use Unity RigidBody as reference http://docs.unity3d.com/ScriptReference/Rigidbody.html
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#pragma once
#include "PhysicsObject.h"
enum ForceType
{
IMPULSE,
ACCELERATION
};
class RigidBody : public PhysicsObject
{
public:
RigidBody(vec3 position, vec3 velocity, quat rotation, float mass);
void virtual Update(vec3 gravity, float timeStep);
void virtual Debug();
void ApplyForce(vec3 force, ForceType type, float time = 0);
void ApplyForceToActor(RigidBody* actor2, vec3 force, ForceType type);
void ApplyTorque(float torque, vec3 direction);
void AddVelocity(vec3 velocity);
void AddMomentum(vec3 momentum);
vec3 GetMomentum();
vec3 m_position;
vec3 m_linearVelocity;
vec3 m_angularVelocity;
vec3 m_acceleration;
float m_mass;
vec3 m_rotation;
mat4 m_rotationMatrix;
float m_linearDrag;
float m_rotationalDrag;
float m_rotationalInertia;
float m_staticFriction;
float m_dynamicFriction;
float m_bounciness; // Coefficient of Restitution
float m_elasticity; // Collision restitution
vec4 m_color;
};
|
Randyninja/PhysXEngine
|
PhysicsForGamesvs2015_Start/PhysicsForGames/DIYPhysicsEngine/PhysicsObjects/Plane.h
|
<reponame>Randyninja/PhysXEngine
#pragma once
#include "PhysicsObject.h"
class Plane : public PhysicsObject
{
public:
Plane(vec3 normal, float distance);
void virtual Update(vec3 gravity, float timeStep) {};
void virtual Debug() {};
void virtual MakeGizmo();
vec3 m_normal;
float m_distance;
};
|
Randyninja/PhysXEngine
|
PhysicsForGamesvs2015_Start/PhysicsForGames/Application.h
|
#ifndef _APPLICATION_H_
#define _APPLICATION_H_
struct GLFWwindow;
class Application
{
public:
Application();
virtual ~Application();
virtual bool startup();
virtual void shutdown();
virtual bool update();
virtual void draw();
int window_width;
int window_height;
GLFWwindow* m_window;
};
#endif //_APPLICATION_H_
|
Randyninja/PhysXEngine
|
PhysicsForGamesvs2015_Start/PhysicsForGames/Gizmos.h
|
#pragma once
#include "glm/fwd.hpp"
class Gizmos
{
public:
static void create(unsigned int a_maxLines = 0xffff, unsigned int a_maxTris = 0xffff,
unsigned int a_max2DLines = 0xff, unsigned int a_max2DTris = 0xff);
static void destroy();
// removes all Gizmos
static void clear();
// draws current Gizmo buffers, either using a combined (projection * view) matrix, or separate matrices
static void draw(const glm::mat4& a_projectionView);
static void draw(const glm::mat4& a_projection, const glm::mat4& a_view);
// the projection matrix here should ideally be orthographic with a near of -1 and far of 1
static void draw2D(const glm::mat4& a_projection);
// Adds a single debug line
static void addLine(const glm::vec3& a_rv0, const glm::vec3& a_rv1,
const glm::vec4& a_colour);
// Adds a single debug line
static void addLine(const glm::vec3& a_rv0, const glm::vec3& a_rv1,
const glm::vec4& a_colour0, const glm::vec4& a_colour1);
// Adds a triangle.
static void addTri(const glm::vec3& a_rv0, const glm::vec3& a_rv1, const glm::vec3& a_rv2, const glm::vec4& a_colour);
// Adds 3 unit-length lines (red,green,blue) representing the 3 axis of a transform,
// at the transform's translation. Optional scale available.
static void addTransform(const glm::mat4& a_transform, float a_fScale = 1.0f);
// Adds a wireframe Axis-Aligned Bounding-Box with optional transform for rotation/translation.
static void addAABB(const glm::vec3& a_center, const glm::vec3& a_extents,
const glm::vec4& a_colour, const glm::mat4* a_transform = nullptr);
// Adds an Axis-Aligned Bounding-Box with optional transform for rotation.
static void addAABBFilled(const glm::vec3& a_center, const glm::vec3& a_extents,
const glm::vec4& a_fillColour, const glm::mat4* a_transform = nullptr);
// Adds a cylinder aligned to the Y-axis with optional transform for rotation.
static void addCylinderFilled(const glm::vec3& a_center, float a_radius, float a_fHalfLength,
unsigned int a_segments, const glm::vec4& a_fillColour, const glm::mat4* a_transform = nullptr);
// Adds a double-sided hollow ring in the XZ axis with optional transform for rotation.
// If a_rvFilLColour.w == 0 then only an outer and inner line is drawn.
static void addRing(const glm::vec3& a_center, float a_innerRadius, float a_outerRadius,
unsigned int a_segments, const glm::vec4& a_fillColour, const glm::mat4* a_transform = nullptr);
// Adds a double-sided disk in the XZ axis with optional transform for rotation.
// If a_rvFilLColour.w == 0 then only an outer line is drawn.
static void addDisk(const glm::vec3& a_center, float a_radius,
unsigned int a_segments, const glm::vec4& a_fillColour, const glm::mat4* a_transform = nullptr);
// Adds an arc, around the Y-axis
// If a_rvFilLColour.w == 0 then only an outer line is drawn.
static void addArc(const glm::vec3& a_center, float a_rotation,
float a_radius, float a_halfAngle,
unsigned int a_segments, const glm::vec4& a_fillColour, const glm::mat4* a_transform = nullptr);
// Adds an arc, around the Y-axis, starting at the inner radius and extending to the outer radius
// If a_rvFilLColour.w == 0 then only an outer line is drawn.
static void addArcRing(const glm::vec3& a_center, float a_rotation,
float a_innerRadius, float a_outerRadius, float a_arcHalfAngle,
unsigned int a_segments, const glm::vec4& a_fillColour, const glm::mat4* a_transform = nullptr);
// Adds a Sphere at a given position, with a given number of rows, and columns, radius and a max and min long and latitude
static void addSphere(const glm::vec3& a_center, float a_radius, int a_rows, int a_columns, const glm::vec4& a_fillColour,
const glm::mat4* a_transform = nullptr, float a_longMin = 0.f, float a_longMax = 360,
float a_latMin = -90, float a_latMax = 90 );
// Adds a Sphere at a given position, with a given number of rows, and columns, radius and a max and min long and latitude
static void addSphereFilled(const glm::vec3& a_center, float a_radius, int a_rows, int a_columns, const glm::vec4& a_fillColour,
const glm::mat4* a_transform = nullptr, float a_longMin = 0.f, float a_longMax = 360,
float a_latMin = -90, float a_latMax = 90);
// Adds a single Hermite spline curve
static void addHermiteSpline(const glm::vec3& a_start, const glm::vec3& a_end,
const glm::vec3& a_tangentStart, const glm::vec3& a_tangentEnd, unsigned int a_segments, const glm::vec4& a_colour);
static void addCapsule(const glm::vec3 center, const float length, const float radius, const int rows, const int cols, const glm::vec4 color, const glm::mat4* rotation = 0);
// 2-dimensional gizmos
static void add2DLine(const glm::vec2& a_start, const glm::vec2& a_end, const glm::vec4& a_colour);
static void add2DLine(const glm::vec2& a_start, const glm::vec2& a_end, const glm::vec4& a_colour0, const glm::vec4& a_colour1);
static void add2DTri(const glm::vec2& a_0, const glm::vec2& a_1, const glm::vec2& a_2, const glm::vec4& a_colour);
static void add2DAABB(const glm::vec2& a_center, const glm::vec2& a_extents, const glm::vec4& a_colour, const glm::mat4* a_transform = nullptr);
static void add2DAABBFilled(const glm::vec2& a_center, const glm::vec2& a_extents, const glm::vec4& a_colour, const glm::mat4* a_transform = nullptr);
static void add2DCircle(const glm::vec2& a_center, float a_radius, unsigned int a_segments, const glm::vec4& a_colour, const glm::mat4* a_transform = nullptr);
private:
Gizmos(unsigned int a_maxLines, unsigned int a_maxTris,
unsigned int a_max2DLines, unsigned int a_max2DTris);
~Gizmos();
struct GizmoVertex
{
float x, y, z, w;
float r, g, b, a;
};
struct GizmoLine
{
GizmoVertex v0;
GizmoVertex v1;
};
struct GizmoTri
{
GizmoVertex v0;
GizmoVertex v1;
GizmoVertex v2;
};
unsigned int m_shader;
// line data
unsigned int m_maxLines;
unsigned int m_lineCount;
GizmoLine* m_lines;
unsigned int m_lineVAO;
unsigned int m_lineVBO;
// triangle data
unsigned int m_maxTris;
unsigned int m_triCount;
GizmoTri* m_tris;
unsigned int m_triVAO;
unsigned int m_triVBO;
unsigned int m_transparentTriCount;
GizmoTri* m_transparentTris;
unsigned int m_transparentTriVAO;
unsigned int m_transparentTriVBO;
// 2D line data
unsigned int m_max2DLines;
unsigned int m_2DlineCount;
GizmoLine* m_2Dlines;
unsigned int m_2DlineVAO;
unsigned int m_2DlineVBO;
// 2D triangle data
unsigned int m_max2DTris;
unsigned int m_2DtriCount;
GizmoTri* m_2Dtris;
unsigned int m_2DtriVAO;
unsigned int m_2DtriVBO;
static Gizmos* sm_singleton;
};
|
Randyninja/PhysXEngine
|
PhysicsForGamesvs2015_Start/PhysicsForGames/DIYPhysicsEngine/DIYPhysicScene.h
|
#pragma once
#include "PhysicsObjects\SphereClass.h"
#include "PhysicsObjects\Plane.h"
#include "PhysicsObjects\BoxClass.h"
#include "PhysicsObjects\SpringJoint.h"
#include <vector>
class DIYPhysicScene
{
public:
DIYPhysicScene();
~DIYPhysicScene();
void AddActor(PhysicsObject* actorToAdd);
void RemoveActor(PhysicsObject* actorToRemove);
void Update(float deltaTime);
void DebugScene();
void AddGizmos();
vec3 ProjectileMotionPrediction(vec3 initialPos, vec3 initialVelocity, float time);
void CheckForCollision();
// CollsionChecks
static bool Plane2Plane(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Plane2Sphere(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Plane2Box(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Plane2Capsule(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Plane2Joint(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Sphere2Plane(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Sphere2Sphere(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Sphere2Box(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Sphere2Capsule(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Sphere2Joint(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Box2Plane(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Box2Sphere(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Box2Box(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Box2Capsule(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Box2Joint(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Capsule2Plane(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Capsule2Sphere(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Capsule2Box(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Capsule2Capsule(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Capsule2Joint(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Joint2Plane(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Joint2Sphere(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Joint2Box(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Joint2Capsule(PhysicsObject* obj1, PhysicsObject* obj2);
static bool Joint2Joint(PhysicsObject* obj1, PhysicsObject* obj2);
static void Response(RigidBody* obj1, RigidBody* obj2, float overlap, vec3 normal);
static void Seperate(RigidBody* obj1, RigidBody* obj2, float overlap, vec3 normal);
vec3 gravity;
float timeStep = 0;
std::vector<PhysicsObject*> actors;
};
|
Randyninja/PhysXEngine
|
PhysicsForGamesvs2015_Start/PhysicsForGames/Render.h
|
#ifndef _RENDER_H_
#define _RENDER_H_
#define GLM_SWIZZLE
#include "glm/glm.hpp"
#include <vector>
using glm::vec2;
using glm::vec3;
using glm::vec4;
using glm::mat4;
struct Material
{
int diffuse_texture;
int normal_texture;
int specular_texture;
vec3 diffuse_color;
vec3 specular_color;
};
struct SimpleVertex
{
vec3 pos;
vec3 normal;
vec2 uv;
};
struct SubMesh
{
Material material;
unsigned int ibo;
unsigned int vao;
unsigned int* index_data;
unsigned int index_count;
};
struct Mesh
{
unsigned int sub_mesh_count;
SubMesh* sub_meshes;
unsigned int vbo;
unsigned int vertex_count;
SimpleVertex* vertex_data;
};
struct Scene
{
Mesh* meshes;
unsigned int mesh_count;
};
Scene LoadSceneFromOBJ(char* dir, char* filename);
void FreeSceneFromOBJ(Scene* scene);
unsigned int LoadGLTextureBasic(const char * path);
Mesh *CreateMeshFromBuffers(SimpleVertex* vertex_data, unsigned int vertex_count, unsigned int *index_data, unsigned int index_count, Material material);
//NOTE(aidan): This should only be called on meshes created from the
//CreateMeshFromBuffers function. DO NOT call on the meshes in a scene
void FreeMesh(Mesh* mesh);
void RebuildVertexBuffer(Mesh* mesh);
class Renderer
{
public:
Renderer();
~Renderer();
void PushMesh(Mesh* mesh, mat4 transform);
void RenderAndClear(mat4 view_proj);
struct RenderItem
{
Mesh* mesh;
mat4 transform;
};
std::vector<RenderItem> render_queue;
unsigned int main_shader;
};
#endif
|
dev5tec/FBProgressView
|
FBProgressView/FBProgressViewAppDelegate.h
|
<filename>FBProgressView/FBProgressViewAppDelegate.h<gh_stars>1-10
//
// FBProgressViewAppDelegate.h
// FBProgressView
//
// Created by <NAME> on 11/03/30.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
@class FBProgressView;
@interface FBProgressViewAppDelegate : NSObject <UIApplicationDelegate> {
}
@property (nonatomic, strong) IBOutlet UIWindow *window;
@property (nonatomic, strong) IBOutlet FBProgressView* view1;
@property (nonatomic, strong) IBOutlet FBProgressView* view2;
@end
|
dev5tec/FBProgressView
|
FBProgressViewTests/FBProgressViewTests.h
|
//
// FBProgressViewTests.h
// FBProgressViewTests
//
// Created by <NAME> on 11/03/30.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import <SenTestingKit/SenTestingKit.h>
@interface FBProgressViewTests : SenTestCase {
@private
}
@end
|
hamzahamidi/v8
|
src/objects/lookup-inl.h
|
// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_OBJECTS_LOOKUP_INL_H_
#define V8_OBJECTS_LOOKUP_INL_H_
#include "src/objects/lookup.h"
#include "src/handles/handles-inl.h"
#include "src/heap/factory-inl.h"
#include "src/objects/api-callbacks.h"
#include "src/objects/map-inl.h"
#include "src/objects/name-inl.h"
#include "src/objects/objects-inl.h"
namespace v8 {
namespace internal {
LookupIterator::LookupIterator(Isolate* isolate, Handle<Object> receiver,
Handle<Name> name, Configuration configuration)
: LookupIterator(isolate, receiver, name, GetRoot(isolate, receiver),
configuration) {}
LookupIterator::LookupIterator(Handle<Object> receiver, Handle<Name> name,
Handle<JSReceiver> holder,
Configuration configuration)
: LookupIterator(holder->GetIsolate(), receiver, name, holder,
configuration) {}
LookupIterator::LookupIterator(Isolate* isolate, Handle<Object> receiver,
Handle<Name> name, Handle<JSReceiver> holder,
Configuration configuration)
: configuration_(ComputeConfiguration(isolate, configuration, name)),
interceptor_state_(InterceptorState::kUninitialized),
property_details_(PropertyDetails::Empty()),
isolate_(isolate),
name_(isolate_->factory()->InternalizeName(name)),
receiver_(receiver),
initial_holder_(holder),
// kMaxUInt32 isn't a valid index.
index_(kMaxUInt32),
number_(static_cast<uint32_t>(DescriptorArray::kNotFound)) {
#ifdef DEBUG
uint32_t index; // Assert that the name is not an array index.
DCHECK(!name->AsArrayIndex(&index));
#endif // DEBUG
Start<false>();
}
LookupIterator::LookupIterator(Isolate* isolate, Handle<Object> receiver,
uint32_t index, Configuration configuration)
: LookupIterator(isolate, receiver, index,
GetRoot(isolate, receiver, index), configuration) {}
LookupIterator LookupIterator::PropertyOrElement(Isolate* isolate,
Handle<Object> receiver,
Handle<Name> name,
Handle<JSReceiver> holder,
Configuration configuration) {
uint32_t index;
if (name->AsArrayIndex(&index)) {
LookupIterator it =
LookupIterator(isolate, receiver, index, holder, configuration);
it.name_ = name;
return it;
}
return LookupIterator(isolate, receiver, name, holder, configuration);
}
LookupIterator LookupIterator::PropertyOrElement(Isolate* isolate,
Handle<Object> receiver,
Handle<Name> name,
Configuration configuration) {
uint32_t index;
if (name->AsArrayIndex(&index)) {
LookupIterator it = LookupIterator(isolate, receiver, index, configuration);
it.name_ = name;
return it;
}
return LookupIterator(isolate, receiver, name, configuration);
}
Handle<Name> LookupIterator::GetName() {
if (name_.is_null()) {
DCHECK(IsElement());
name_ = factory()->Uint32ToString(index_);
}
return name_;
}
bool LookupIterator::is_dictionary_holder() const {
return !holder_->HasFastProperties(isolate_);
}
Handle<Map> LookupIterator::transition_map() const {
DCHECK_EQ(TRANSITION, state_);
return Handle<Map>::cast(transition_);
}
Handle<PropertyCell> LookupIterator::transition_cell() const {
DCHECK_EQ(TRANSITION, state_);
return Handle<PropertyCell>::cast(transition_);
}
template <class T>
Handle<T> LookupIterator::GetHolder() const {
DCHECK(IsFound());
return Handle<T>::cast(holder_);
}
bool LookupIterator::ExtendingNonExtensible(Handle<JSReceiver> receiver) {
DCHECK(receiver.is_identical_to(GetStoreTarget<JSReceiver>()));
return !receiver->map(isolate_).is_extensible() &&
(IsElement() || !name_->IsPrivate(isolate_));
}
bool LookupIterator::IsCacheableTransition() {
DCHECK_EQ(TRANSITION, state_);
return transition_->IsPropertyCell(isolate_) ||
(transition_map()->is_dictionary_map() &&
!GetStoreTarget<JSReceiver>()->HasFastProperties(isolate_)) ||
transition_map()->GetBackPointer(isolate_).IsMap(isolate_);
}
void LookupIterator::UpdateProtector() {
if (IsElement()) return;
// This list must be kept in sync with
// CodeStubAssembler::CheckForAssociatedProtector!
ReadOnlyRoots roots(isolate_);
if (*name_ == roots.is_concat_spreadable_symbol() ||
*name_ == roots.constructor_string() || *name_ == roots.next_string() ||
*name_ == roots.species_symbol() || *name_ == roots.iterator_symbol() ||
*name_ == roots.resolve_string() || *name_ == roots.then_string()) {
InternalUpdateProtector();
}
}
int LookupIterator::descriptor_number() const {
DCHECK(!IsElement());
DCHECK(has_property_);
DCHECK(holder_->HasFastProperties(isolate_));
return number_;
}
int LookupIterator::dictionary_entry() const {
DCHECK(!IsElement());
DCHECK(has_property_);
DCHECK(!holder_->HasFastProperties(isolate_));
return number_;
}
// static
LookupIterator::Configuration LookupIterator::ComputeConfiguration(
Isolate* isolate, Configuration configuration, Handle<Name> name) {
return name->IsPrivate(isolate) ? OWN_SKIP_INTERCEPTOR : configuration;
}
// static
Handle<JSReceiver> LookupIterator::GetRoot(Isolate* isolate,
Handle<Object> receiver,
uint32_t index) {
if (receiver->IsJSReceiver(isolate))
return Handle<JSReceiver>::cast(receiver);
return GetRootForNonJSReceiver(isolate, receiver, index);
}
template <class T>
Handle<T> LookupIterator::GetStoreTarget() const {
DCHECK(receiver_->IsJSReceiver(isolate_));
if (receiver_->IsJSGlobalProxy(isolate_)) {
HeapObject prototype =
JSGlobalProxy::cast(*receiver_).map(isolate_).prototype(isolate_);
if (prototype.IsJSGlobalObject(isolate_)) {
return handle(JSGlobalObject::cast(prototype), isolate_);
}
}
return Handle<T>::cast(receiver_);
}
// static
template <bool is_element>
InterceptorInfo LookupIterator::GetInterceptor(Isolate* isolate,
JSObject holder) {
return is_element ? holder.GetIndexedInterceptor(isolate)
: holder.GetNamedInterceptor(isolate);
}
inline Handle<InterceptorInfo> LookupIterator::GetInterceptor() const {
DCHECK_EQ(INTERCEPTOR, state_);
JSObject holder = JSObject::cast(*holder_);
InterceptorInfo result = IsElement()
? GetInterceptor<true>(isolate_, holder)
: GetInterceptor<false>(isolate_, holder);
return handle(result, isolate_);
}
} // namespace internal
} // namespace v8
#endif // V8_OBJECTS_LOOKUP_INL_H_
|
hamzahamidi/v8
|
src/objects/js-weak-refs-inl.h
|
<gh_stars>1000+
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_OBJECTS_JS_WEAK_REFS_INL_H_
#define V8_OBJECTS_JS_WEAK_REFS_INL_H_
#include "src/objects/js-weak-refs.h"
#include "src/api/api-inl.h"
#include "src/heap/heap-write-barrier-inl.h"
#include "src/objects/smi-inl.h"
// Has to be the last include (doesn't have include guards):
#include "src/objects/object-macros.h"
namespace v8 {
namespace internal {
OBJECT_CONSTRUCTORS_IMPL(WeakCell, HeapObject)
OBJECT_CONSTRUCTORS_IMPL(JSWeakRef, JSObject)
OBJECT_CONSTRUCTORS_IMPL(JSFinalizationGroup, JSObject)
OBJECT_CONSTRUCTORS_IMPL(JSFinalizationGroupCleanupIterator, JSObject)
ACCESSORS(JSFinalizationGroup, native_context, NativeContext,
kNativeContextOffset)
ACCESSORS(JSFinalizationGroup, cleanup, Object, kCleanupOffset)
ACCESSORS(JSFinalizationGroup, active_cells, Object, kActiveCellsOffset)
ACCESSORS(JSFinalizationGroup, cleared_cells, Object, kClearedCellsOffset)
ACCESSORS(JSFinalizationGroup, key_map, Object, kKeyMapOffset)
SMI_ACCESSORS(JSFinalizationGroup, flags, kFlagsOffset)
ACCESSORS(JSFinalizationGroup, next, Object, kNextOffset)
CAST_ACCESSOR(JSFinalizationGroup)
ACCESSORS(WeakCell, finalization_group, Object, kFinalizationGroupOffset)
ACCESSORS(WeakCell, target, HeapObject, kTargetOffset)
ACCESSORS(WeakCell, holdings, Object, kHoldingsOffset)
ACCESSORS(WeakCell, next, Object, kNextOffset)
ACCESSORS(WeakCell, prev, Object, kPrevOffset)
ACCESSORS(WeakCell, key, Object, kKeyOffset)
ACCESSORS(WeakCell, key_list_next, Object, kKeyListNextOffset)
ACCESSORS(WeakCell, key_list_prev, Object, kKeyListPrevOffset)
CAST_ACCESSOR(WeakCell)
CAST_ACCESSOR(JSWeakRef)
ACCESSORS(JSWeakRef, target, HeapObject, kTargetOffset)
ACCESSORS(JSFinalizationGroupCleanupIterator, finalization_group,
JSFinalizationGroup, kFinalizationGroupOffset)
CAST_ACCESSOR(JSFinalizationGroupCleanupIterator)
void JSFinalizationGroup::Register(
Handle<JSFinalizationGroup> finalization_group, Handle<JSReceiver> target,
Handle<Object> holdings, Handle<Object> key, Isolate* isolate) {
Handle<WeakCell> weak_cell = isolate->factory()->NewWeakCell();
weak_cell->set_finalization_group(*finalization_group);
weak_cell->set_target(*target);
weak_cell->set_holdings(*holdings);
weak_cell->set_prev(ReadOnlyRoots(isolate).undefined_value());
weak_cell->set_next(ReadOnlyRoots(isolate).undefined_value());
weak_cell->set_key(*key);
weak_cell->set_key_list_prev(ReadOnlyRoots(isolate).undefined_value());
weak_cell->set_key_list_next(ReadOnlyRoots(isolate).undefined_value());
// Add to active_cells.
weak_cell->set_next(finalization_group->active_cells());
if (finalization_group->active_cells().IsWeakCell()) {
WeakCell::cast(finalization_group->active_cells()).set_prev(*weak_cell);
}
finalization_group->set_active_cells(*weak_cell);
if (!key->IsUndefined(isolate)) {
Handle<ObjectHashTable> key_map;
if (finalization_group->key_map().IsUndefined(isolate)) {
key_map = ObjectHashTable::New(isolate, 1);
} else {
key_map =
handle(ObjectHashTable::cast(finalization_group->key_map()), isolate);
}
Object value = key_map->Lookup(key);
if (value.IsWeakCell()) {
WeakCell existing_weak_cell = WeakCell::cast(value);
existing_weak_cell.set_key_list_prev(*weak_cell);
weak_cell->set_key_list_next(existing_weak_cell);
} else {
DCHECK(value.IsTheHole(isolate));
}
key_map = ObjectHashTable::Put(key_map, key, weak_cell);
finalization_group->set_key_map(*key_map);
}
}
bool JSFinalizationGroup::Unregister(
Handle<JSFinalizationGroup> finalization_group,
Handle<JSReceiver> unregister_token, Isolate* isolate) {
// Iterate through the doubly linked list of WeakCells associated with the
// key. Each WeakCell will be in the "active_cells" or "cleared_cells" list of
// its FinalizationGroup; remove it from there.
if (!finalization_group->key_map().IsUndefined(isolate)) {
Handle<ObjectHashTable> key_map =
handle(ObjectHashTable::cast(finalization_group->key_map()), isolate);
Object value = key_map->Lookup(unregister_token);
Object undefined = ReadOnlyRoots(isolate).undefined_value();
while (value.IsWeakCell()) {
WeakCell weak_cell = WeakCell::cast(value);
weak_cell.RemoveFromFinalizationGroupCells(isolate);
value = weak_cell.key_list_next();
weak_cell.set_key_list_prev(undefined);
weak_cell.set_key_list_next(undefined);
}
bool was_present;
key_map = ObjectHashTable::Remove(isolate, key_map, unregister_token,
&was_present);
finalization_group->set_key_map(*key_map);
return was_present;
}
return false;
}
bool JSFinalizationGroup::NeedsCleanup() const {
return cleared_cells().IsWeakCell();
}
bool JSFinalizationGroup::scheduled_for_cleanup() const {
return ScheduledForCleanupField::decode(flags());
}
void JSFinalizationGroup::set_scheduled_for_cleanup(
bool scheduled_for_cleanup) {
set_flags(ScheduledForCleanupField::update(flags(), scheduled_for_cleanup));
}
Object JSFinalizationGroup::PopClearedCellHoldings(
Handle<JSFinalizationGroup> finalization_group, Isolate* isolate) {
Handle<WeakCell> weak_cell =
handle(WeakCell::cast(finalization_group->cleared_cells()), isolate);
DCHECK(weak_cell->prev().IsUndefined(isolate));
finalization_group->set_cleared_cells(weak_cell->next());
weak_cell->set_next(ReadOnlyRoots(isolate).undefined_value());
if (finalization_group->cleared_cells().IsWeakCell()) {
WeakCell cleared_cells_head =
WeakCell::cast(finalization_group->cleared_cells());
DCHECK_EQ(cleared_cells_head.prev(), *weak_cell);
cleared_cells_head.set_prev(ReadOnlyRoots(isolate).undefined_value());
} else {
DCHECK(finalization_group->cleared_cells().IsUndefined(isolate));
}
// Also remove the WeakCell from the key_map (if it's there).
if (!weak_cell->key().IsUndefined(isolate)) {
if (weak_cell->key_list_prev().IsUndefined(isolate) &&
weak_cell->key_list_next().IsUndefined(isolate)) {
// weak_cell is the only one associated with its key; remove the key
// from the hash table.
Handle<ObjectHashTable> key_map =
handle(ObjectHashTable::cast(finalization_group->key_map()), isolate);
Handle<Object> key = handle(weak_cell->key(), isolate);
bool was_present;
key_map = ObjectHashTable::Remove(isolate, key_map, key, &was_present);
DCHECK(was_present);
finalization_group->set_key_map(*key_map);
} else if (weak_cell->key_list_prev().IsUndefined()) {
// weak_cell is the list head for its key; we need to change the value of
// the key in the hash table.
Handle<ObjectHashTable> key_map =
handle(ObjectHashTable::cast(finalization_group->key_map()), isolate);
Handle<Object> key = handle(weak_cell->key(), isolate);
Handle<WeakCell> next =
handle(WeakCell::cast(weak_cell->key_list_next()), isolate);
DCHECK_EQ(next->key_list_prev(), *weak_cell);
next->set_key_list_prev(ReadOnlyRoots(isolate).undefined_value());
weak_cell->set_key_list_next(ReadOnlyRoots(isolate).undefined_value());
key_map = ObjectHashTable::Put(key_map, key, next);
finalization_group->set_key_map(*key_map);
} else {
// weak_cell is somewhere in the middle of its key list.
WeakCell prev = WeakCell::cast(weak_cell->key_list_prev());
prev.set_key_list_next(weak_cell->key_list_next());
if (!weak_cell->key_list_next().IsUndefined()) {
WeakCell next = WeakCell::cast(weak_cell->key_list_next());
next.set_key_list_prev(weak_cell->key_list_prev());
}
}
}
return weak_cell->holdings();
}
void WeakCell::Nullify(
Isolate* isolate,
std::function<void(HeapObject object, ObjectSlot slot, Object target)>
gc_notify_updated_slot) {
// Remove from the WeakCell from the "active_cells" list of its
// JSFinalizationGroup and insert it into the "cleared_cells" list. This is
// only called for WeakCells which haven't been unregistered yet, so they will
// be in the active_cells list. (The caller must guard against calling this
// for unregistered WeakCells by checking that the target is not undefined.)
DCHECK(target().IsJSReceiver());
set_target(ReadOnlyRoots(isolate).undefined_value());
JSFinalizationGroup fg = JSFinalizationGroup::cast(finalization_group());
if (prev().IsWeakCell()) {
DCHECK_NE(fg.active_cells(), *this);
WeakCell prev_cell = WeakCell::cast(prev());
prev_cell.set_next(next());
gc_notify_updated_slot(prev_cell, prev_cell.RawField(WeakCell::kNextOffset),
next());
} else {
DCHECK_EQ(fg.active_cells(), *this);
fg.set_active_cells(next());
gc_notify_updated_slot(
fg, fg.RawField(JSFinalizationGroup::kActiveCellsOffset), next());
}
if (next().IsWeakCell()) {
WeakCell next_cell = WeakCell::cast(next());
next_cell.set_prev(prev());
gc_notify_updated_slot(next_cell, next_cell.RawField(WeakCell::kPrevOffset),
prev());
}
set_prev(ReadOnlyRoots(isolate).undefined_value());
Object cleared_head = fg.cleared_cells();
if (cleared_head.IsWeakCell()) {
WeakCell cleared_head_cell = WeakCell::cast(cleared_head);
cleared_head_cell.set_prev(*this);
gc_notify_updated_slot(cleared_head_cell,
cleared_head_cell.RawField(WeakCell::kPrevOffset),
*this);
}
set_next(fg.cleared_cells());
gc_notify_updated_slot(*this, RawField(WeakCell::kNextOffset), next());
fg.set_cleared_cells(*this);
gc_notify_updated_slot(
fg, fg.RawField(JSFinalizationGroup::kClearedCellsOffset), *this);
}
void WeakCell::RemoveFromFinalizationGroupCells(Isolate* isolate) {
// Remove the WeakCell from the list it's in (either "active_cells" or
// "cleared_cells" of its JSFinalizationGroup).
// It's important to set_target to undefined here. This guards that we won't
// call Nullify (which assumes that the WeakCell is in active_cells).
DCHECK(target().IsUndefined() || target().IsJSReceiver());
set_target(ReadOnlyRoots(isolate).undefined_value());
JSFinalizationGroup fg = JSFinalizationGroup::cast(finalization_group());
if (fg.active_cells() == *this) {
DCHECK(prev().IsUndefined(isolate));
fg.set_active_cells(next());
} else if (fg.cleared_cells() == *this) {
DCHECK(!prev().IsWeakCell());
fg.set_cleared_cells(next());
} else {
DCHECK(prev().IsWeakCell());
WeakCell prev_cell = WeakCell::cast(prev());
prev_cell.set_next(next());
}
if (next().IsWeakCell()) {
WeakCell next_cell = WeakCell::cast(next());
next_cell.set_prev(prev());
}
set_prev(ReadOnlyRoots(isolate).undefined_value());
set_next(ReadOnlyRoots(isolate).undefined_value());
}
} // namespace internal
} // namespace v8
#include "src/objects/object-macros-undef.h"
#endif // V8_OBJECTS_JS_WEAK_REFS_INL_H_
|
hamzahamidi/v8
|
src/wasm/baseline/ppc/liftoff-assembler-ppc.h
|
<gh_stars>1000+
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_WASM_BASELINE_PPC_LIFTOFF_ASSEMBLER_PPC_H_
#define V8_WASM_BASELINE_PPC_LIFTOFF_ASSEMBLER_PPC_H_
#include "src/wasm/baseline/liftoff-assembler.h"
namespace v8 {
namespace internal {
namespace wasm {
int LiftoffAssembler::PrepareStackFrame() {
bailout(kUnsupportedArchitecture, "PrepareStackFrame");
return 0;
}
void LiftoffAssembler::PatchPrepareStackFrame(int offset,
uint32_t stack_slots) {
bailout(kUnsupportedArchitecture, "PatchPrepareStackFrame");
}
void LiftoffAssembler::FinishCode() { EmitConstantPool(); }
void LiftoffAssembler::AbortCompilation() { FinishCode(); }
void LiftoffAssembler::LoadConstant(LiftoffRegister reg, WasmValue value,
RelocInfo::Mode rmode) {
bailout(kUnsupportedArchitecture, "LoadConstant");
}
void LiftoffAssembler::LoadFromInstance(Register dst, uint32_t offset,
int size) {
bailout(kUnsupportedArchitecture, "LoadFromInstance");
}
void LiftoffAssembler::LoadTaggedPointerFromInstance(Register dst,
uint32_t offset) {
bailout(kUnsupportedArchitecture, "LoadTaggedPointerFromInstance");
}
void LiftoffAssembler::SpillInstance(Register instance) {
bailout(kUnsupportedArchitecture, "SpillInstance");
}
void LiftoffAssembler::FillInstanceInto(Register dst) {
bailout(kUnsupportedArchitecture, "FillInstanceInto");
}
void LiftoffAssembler::LoadTaggedPointer(Register dst, Register src_addr,
Register offset_reg,
uint32_t offset_imm,
LiftoffRegList pinned) {
bailout(kUnsupportedArchitecture, "LoadTaggedPointer");
}
void LiftoffAssembler::Load(LiftoffRegister dst, Register src_addr,
Register offset_reg, uint32_t offset_imm,
LoadType type, LiftoffRegList pinned,
uint32_t* protected_load_pc, bool is_load_mem) {
bailout(kUnsupportedArchitecture, "Load");
}
void LiftoffAssembler::Store(Register dst_addr, Register offset_reg,
uint32_t offset_imm, LiftoffRegister src,
StoreType type, LiftoffRegList pinned,
uint32_t* protected_store_pc, bool is_store_mem) {
bailout(kUnsupportedArchitecture, "Store");
}
void LiftoffAssembler::LoadCallerFrameSlot(LiftoffRegister dst,
uint32_t caller_slot_idx,
ValueType type) {
bailout(kUnsupportedArchitecture, "LoadCallerFrameSlot");
}
void LiftoffAssembler::MoveStackValue(uint32_t dst_index, uint32_t src_index,
ValueType type) {
bailout(kUnsupportedArchitecture, "MoveStackValue");
}
void LiftoffAssembler::Move(Register dst, Register src, ValueType type) {
bailout(kUnsupportedArchitecture, "Move Register");
}
void LiftoffAssembler::Move(DoubleRegister dst, DoubleRegister src,
ValueType type) {
bailout(kUnsupportedArchitecture, "Move DoubleRegister");
}
void LiftoffAssembler::Spill(uint32_t index, LiftoffRegister reg,
ValueType type) {
bailout(kUnsupportedArchitecture, "Spill register");
}
void LiftoffAssembler::Spill(uint32_t index, WasmValue value) {
bailout(kUnsupportedArchitecture, "Spill value");
}
void LiftoffAssembler::Fill(LiftoffRegister reg, uint32_t index,
ValueType type) {
bailout(kUnsupportedArchitecture, "Fill");
}
void LiftoffAssembler::FillI64Half(Register, uint32_t index, RegPairHalf) {
bailout(kUnsupportedArchitecture, "FillI64Half");
}
#define UNIMPLEMENTED_I32_BINOP(name) \
void LiftoffAssembler::emit_##name(Register dst, Register lhs, \
Register rhs) { \
bailout(kUnsupportedArchitecture, "i32 binop:: " #name); \
}
#define UNIMPLEMENTED_I32_BINOP_I(name) \
UNIMPLEMENTED_I32_BINOP(name) \
void LiftoffAssembler::emit_##name(Register dst, Register lhs, \
int32_t imm) { \
bailout(kUnsupportedArchitecture, "i32 binop_i: " #name); \
}
#define UNIMPLEMENTED_I64_BINOP(name) \
void LiftoffAssembler::emit_##name(LiftoffRegister dst, LiftoffRegister lhs, \
LiftoffRegister rhs) { \
bailout(kUnsupportedArchitecture, "i64 binop: " #name); \
}
#define UNIMPLEMENTED_I64_BINOP_I(name) \
UNIMPLEMENTED_I64_BINOP(name) \
void LiftoffAssembler::emit_##name(LiftoffRegister dst, LiftoffRegister lhs, \
int32_t imm) { \
bailout(kUnsupportedArchitecture, "i64_i binop: " #name); \
}
#define UNIMPLEMENTED_GP_UNOP(name) \
bool LiftoffAssembler::emit_##name(Register dst, Register src) { \
bailout(kUnsupportedArchitecture, "gp unop: " #name); \
return true; \
}
#define UNIMPLEMENTED_FP_BINOP(name) \
void LiftoffAssembler::emit_##name(DoubleRegister dst, DoubleRegister lhs, \
DoubleRegister rhs) { \
bailout(kUnsupportedArchitecture, "fp binop: " #name); \
}
#define UNIMPLEMENTED_FP_UNOP(name) \
void LiftoffAssembler::emit_##name(DoubleRegister dst, DoubleRegister src) { \
bailout(kUnsupportedArchitecture, "fp unop: " #name); \
}
#define UNIMPLEMENTED_FP_UNOP_RETURN_TRUE(name) \
bool LiftoffAssembler::emit_##name(DoubleRegister dst, DoubleRegister src) { \
bailout(kUnsupportedArchitecture, "fp unop: " #name); \
return true; \
}
#define UNIMPLEMENTED_I32_SHIFTOP(name) \
void LiftoffAssembler::emit_##name(Register dst, Register src, \
Register amount, LiftoffRegList pinned) { \
bailout(kUnsupportedArchitecture, "i32 shiftop: " #name); \
}
#define UNIMPLEMENTED_I64_SHIFTOP(name) \
void LiftoffAssembler::emit_##name(LiftoffRegister dst, LiftoffRegister src, \
Register amount, LiftoffRegList pinned) { \
bailout(kUnsupportedArchitecture, "i64 shiftop: " #name); \
}
UNIMPLEMENTED_I32_BINOP_I(i32_add)
UNIMPLEMENTED_I32_BINOP(i32_sub)
UNIMPLEMENTED_I32_BINOP(i32_mul)
UNIMPLEMENTED_I32_BINOP_I(i32_and)
UNIMPLEMENTED_I32_BINOP_I(i32_or)
UNIMPLEMENTED_I32_BINOP_I(i32_xor)
UNIMPLEMENTED_I32_SHIFTOP(i32_shl)
UNIMPLEMENTED_I32_SHIFTOP(i32_sar)
UNIMPLEMENTED_I32_SHIFTOP(i32_shr)
UNIMPLEMENTED_I64_BINOP_I(i64_add)
UNIMPLEMENTED_I64_BINOP(i64_sub)
UNIMPLEMENTED_I64_BINOP(i64_mul)
#ifdef V8_TARGET_ARCH_PPC64
UNIMPLEMENTED_I64_BINOP_I(i64_and)
UNIMPLEMENTED_I64_BINOP_I(i64_or)
UNIMPLEMENTED_I64_BINOP_I(i64_xor)
#endif
UNIMPLEMENTED_I64_SHIFTOP(i64_shl)
UNIMPLEMENTED_I64_SHIFTOP(i64_sar)
UNIMPLEMENTED_I64_SHIFTOP(i64_shr)
UNIMPLEMENTED_GP_UNOP(i32_clz)
UNIMPLEMENTED_GP_UNOP(i32_ctz)
UNIMPLEMENTED_GP_UNOP(i32_popcnt)
UNIMPLEMENTED_FP_BINOP(f32_add)
UNIMPLEMENTED_FP_BINOP(f32_sub)
UNIMPLEMENTED_FP_BINOP(f32_mul)
UNIMPLEMENTED_FP_BINOP(f32_div)
UNIMPLEMENTED_FP_BINOP(f32_min)
UNIMPLEMENTED_FP_BINOP(f32_max)
UNIMPLEMENTED_FP_BINOP(f32_copysign)
UNIMPLEMENTED_FP_UNOP(f32_abs)
UNIMPLEMENTED_FP_UNOP(f32_neg)
UNIMPLEMENTED_FP_UNOP_RETURN_TRUE(f32_ceil)
UNIMPLEMENTED_FP_UNOP_RETURN_TRUE(f32_floor)
UNIMPLEMENTED_FP_UNOP_RETURN_TRUE(f32_trunc)
UNIMPLEMENTED_FP_UNOP_RETURN_TRUE(f32_nearest_int)
UNIMPLEMENTED_FP_UNOP(f32_sqrt)
UNIMPLEMENTED_FP_BINOP(f64_add)
UNIMPLEMENTED_FP_BINOP(f64_sub)
UNIMPLEMENTED_FP_BINOP(f64_mul)
UNIMPLEMENTED_FP_BINOP(f64_div)
UNIMPLEMENTED_FP_BINOP(f64_min)
UNIMPLEMENTED_FP_BINOP(f64_max)
UNIMPLEMENTED_FP_BINOP(f64_copysign)
UNIMPLEMENTED_FP_UNOP(f64_abs)
UNIMPLEMENTED_FP_UNOP(f64_neg)
UNIMPLEMENTED_FP_UNOP_RETURN_TRUE(f64_ceil)
UNIMPLEMENTED_FP_UNOP_RETURN_TRUE(f64_floor)
UNIMPLEMENTED_FP_UNOP_RETURN_TRUE(f64_trunc)
UNIMPLEMENTED_FP_UNOP_RETURN_TRUE(f64_nearest_int)
UNIMPLEMENTED_FP_UNOP(f64_sqrt)
#undef UNIMPLEMENTED_I32_BINOP
#undef UNIMPLEMENTED_I32_BINOP_I
#undef UNIMPLEMENTED_I64_BINOP
#undef UNIMPLEMENTED_I64_BINOP_I
#undef UNIMPLEMENTED_GP_UNOP
#undef UNIMPLEMENTED_FP_BINOP
#undef UNIMPLEMENTED_FP_UNOP
#undef UNIMPLEMENTED_FP_UNOP_RETURN_TRUE
#undef UNIMPLEMENTED_I32_SHIFTOP
#undef UNIMPLEMENTED_I64_SHIFTOP
void LiftoffAssembler::emit_i32_divs(Register dst, Register lhs, Register rhs,
Label* trap_div_by_zero,
Label* trap_div_unrepresentable) {
bailout(kUnsupportedArchitecture, "i32_divs");
}
void LiftoffAssembler::emit_i32_divu(Register dst, Register lhs, Register rhs,
Label* trap_div_by_zero) {
bailout(kUnsupportedArchitecture, "i32_divu");
}
void LiftoffAssembler::emit_i32_rems(Register dst, Register lhs, Register rhs,
Label* trap_div_by_zero) {
bailout(kUnsupportedArchitecture, "i32_rems");
}
void LiftoffAssembler::emit_i32_remu(Register dst, Register lhs, Register rhs,
Label* trap_div_by_zero) {
bailout(kUnsupportedArchitecture, "i32_remu");
}
void LiftoffAssembler::emit_i32_shr(Register dst, Register lhs, int amount) {
bailout(kUnsupportedArchitecture, "i32_shr");
}
bool LiftoffAssembler::emit_i64_divs(LiftoffRegister dst, LiftoffRegister lhs,
LiftoffRegister rhs,
Label* trap_div_by_zero,
Label* trap_div_unrepresentable) {
bailout(kUnsupportedArchitecture, "i64_divs");
return true;
}
bool LiftoffAssembler::emit_i64_divu(LiftoffRegister dst, LiftoffRegister lhs,
LiftoffRegister rhs,
Label* trap_div_by_zero) {
bailout(kUnsupportedArchitecture, "i64_divu");
return true;
}
bool LiftoffAssembler::emit_i64_rems(LiftoffRegister dst, LiftoffRegister lhs,
LiftoffRegister rhs,
Label* trap_div_by_zero) {
bailout(kUnsupportedArchitecture, "i64_rems");
return true;
}
bool LiftoffAssembler::emit_i64_remu(LiftoffRegister dst, LiftoffRegister lhs,
LiftoffRegister rhs,
Label* trap_div_by_zero) {
bailout(kUnsupportedArchitecture, "i64_remu");
return true;
}
void LiftoffAssembler::emit_i64_shr(LiftoffRegister dst, LiftoffRegister lhs,
int amount) {
bailout(kUnsupportedArchitecture, "i64_shr");
}
void LiftoffAssembler::emit_i32_to_intptr(Register dst, Register src) {
#ifdef V8_TARGET_ARCH_PPC64
bailout(kUnsupportedArchitecture, "emit_i32_to_intptr");
#else
// This is a nop on ppc32.
#endif
}
bool LiftoffAssembler::emit_type_conversion(WasmOpcode opcode,
LiftoffRegister dst,
LiftoffRegister src, Label* trap) {
bailout(kUnsupportedArchitecture, "emit_type_conversion");
return true;
}
void LiftoffAssembler::emit_i32_signextend_i8(Register dst, Register src) {
bailout(kUnsupportedArchitecture, "emit_i32_signextend_i8");
}
void LiftoffAssembler::emit_i32_signextend_i16(Register dst, Register src) {
bailout(kUnsupportedArchitecture, "emit_i32_signextend_i16");
}
void LiftoffAssembler::emit_i64_signextend_i8(LiftoffRegister dst,
LiftoffRegister src) {
bailout(kUnsupportedArchitecture, "emit_i64_signextend_i8");
}
void LiftoffAssembler::emit_i64_signextend_i16(LiftoffRegister dst,
LiftoffRegister src) {
bailout(kUnsupportedArchitecture, "emit_i64_signextend_i16");
}
void LiftoffAssembler::emit_i64_signextend_i32(LiftoffRegister dst,
LiftoffRegister src) {
bailout(kUnsupportedArchitecture, "emit_i64_signextend_i32");
}
void LiftoffAssembler::emit_jump(Label* label) {
bailout(kUnsupportedArchitecture, "emit_jump");
}
void LiftoffAssembler::emit_jump(Register target) {
bailout(kUnsupportedArchitecture, "emit_jump");
}
void LiftoffAssembler::emit_cond_jump(Condition cond, Label* label,
ValueType type, Register lhs,
Register rhs) {
bailout(kUnsupportedArchitecture, "emit_cond_jump");
}
void LiftoffAssembler::emit_i32_eqz(Register dst, Register src) {
bailout(kUnsupportedArchitecture, "emit_i32_eqz");
}
void LiftoffAssembler::emit_i32_set_cond(Condition cond, Register dst,
Register lhs, Register rhs) {
bailout(kUnsupportedArchitecture, "emit_i32_set_cond");
}
void LiftoffAssembler::emit_i64_eqz(Register dst, LiftoffRegister src) {
bailout(kUnsupportedArchitecture, "emit_i64_eqz");
}
void LiftoffAssembler::emit_i64_set_cond(Condition cond, Register dst,
LiftoffRegister lhs,
LiftoffRegister rhs) {
bailout(kUnsupportedArchitecture, "emit_i64_set_cond");
}
void LiftoffAssembler::emit_f32_set_cond(Condition cond, Register dst,
DoubleRegister lhs,
DoubleRegister rhs) {
bailout(kUnsupportedArchitecture, "emit_f32_set_cond");
}
void LiftoffAssembler::emit_f64_set_cond(Condition cond, Register dst,
DoubleRegister lhs,
DoubleRegister rhs) {
bailout(kUnsupportedArchitecture, "emit_f64_set_cond");
}
void LiftoffAssembler::StackCheck(Label* ool_code, Register limit_address) {
bailout(kUnsupportedArchitecture, "StackCheck");
}
void LiftoffAssembler::CallTrapCallbackForTesting() {
bailout(kUnsupportedArchitecture, "CallTrapCallbackForTesting");
}
void LiftoffAssembler::AssertUnreachable(AbortReason reason) {
bailout(kUnsupportedArchitecture, "AssertUnreachable");
}
void LiftoffAssembler::PushRegisters(LiftoffRegList regs) {
bailout(kUnsupportedArchitecture, "PushRegisters");
}
void LiftoffAssembler::PopRegisters(LiftoffRegList regs) {
bailout(kUnsupportedArchitecture, "PopRegisters");
}
void LiftoffAssembler::DropStackSlotsAndRet(uint32_t num_stack_slots) {
bailout(kUnsupportedArchitecture, "DropStackSlotsAndRet");
}
void LiftoffAssembler::CallC(wasm::FunctionSig* sig,
const LiftoffRegister* args,
const LiftoffRegister* rets,
ValueType out_argument_type, int stack_bytes,
ExternalReference ext_ref) {
bailout(kUnsupportedArchitecture, "CallC");
}
void LiftoffAssembler::CallNativeWasmCode(Address addr) {
bailout(kUnsupportedArchitecture, "CallNativeWasmCode");
}
void LiftoffAssembler::CallIndirect(wasm::FunctionSig* sig,
compiler::CallDescriptor* call_descriptor,
Register target) {
bailout(kUnsupportedArchitecture, "CallIndirect");
}
void LiftoffAssembler::CallRuntimeStub(WasmCode::RuntimeStubId sid) {
bailout(kUnsupportedArchitecture, "CallRuntimeStub");
}
void LiftoffAssembler::AllocateStackSlot(Register addr, uint32_t size) {
bailout(kUnsupportedArchitecture, "AllocateStackSlot");
}
void LiftoffAssembler::DeallocateStackSlot(uint32_t size) {
bailout(kUnsupportedArchitecture, "DeallocateStackSlot");
}
void LiftoffStackSlots::Construct() {
asm_->bailout(kUnsupportedArchitecture, "LiftoffStackSlots::Construct");
}
} // namespace wasm
} // namespace internal
} // namespace v8
#undef BAILOUT
#endif // V8_WASM_BASELINE_PPC_LIFTOFF_ASSEMBLER_PPC_H_
|
hamzahamidi/v8
|
src/heap/store-buffer-inl.h
|
<filename>src/heap/store-buffer-inl.h
// Copyright 2011 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_HEAP_STORE_BUFFER_INL_H_
#define V8_HEAP_STORE_BUFFER_INL_H_
#include "src/heap/store-buffer.h"
#include "src/heap/heap-inl.h"
namespace v8 {
namespace internal {
void StoreBuffer::InsertIntoStoreBuffer(Address slot) {
if (top_ + sizeof(Address) > limit_[current_]) {
StoreBufferOverflow(heap_->isolate());
}
*top_ = slot;
top_++;
}
} // namespace internal
} // namespace v8
#endif // V8_HEAP_STORE_BUFFER_INL_H_
|
hamzahamidi/v8
|
src/heap/basic-memory-chunk.h
|
// Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_HEAP_BASIC_MEMORY_CHUNK_H_
#define V8_HEAP_BASIC_MEMORY_CHUNK_H_
#include <type_traits>
#include "src/base/atomic-utils.h"
#include "src/common/globals.h"
#include "src/heap/marking.h"
namespace v8 {
namespace internal {
class MemoryChunk;
class BasicMemoryChunk {
public:
enum Flag {
NO_FLAGS = 0u,
IS_EXECUTABLE = 1u << 0,
POINTERS_TO_HERE_ARE_INTERESTING = 1u << 1,
POINTERS_FROM_HERE_ARE_INTERESTING = 1u << 2,
// A page in the from-space or a young large page that was not scavenged
// yet.
FROM_PAGE = 1u << 3,
// A page in the to-space or a young large page that was scavenged.
TO_PAGE = 1u << 4,
LARGE_PAGE = 1u << 5,
EVACUATION_CANDIDATE = 1u << 6,
NEVER_EVACUATE = 1u << 7,
// Large objects can have a progress bar in their page header. These object
// are scanned in increments and will be kept black while being scanned.
// Even if the mutator writes to them they will be kept black and a white
// to grey transition is performed in the value.
HAS_PROGRESS_BAR = 1u << 8,
// |PAGE_NEW_OLD_PROMOTION|: A page tagged with this flag has been promoted
// from new to old space during evacuation.
PAGE_NEW_OLD_PROMOTION = 1u << 9,
// |PAGE_NEW_NEW_PROMOTION|: A page tagged with this flag has been moved
// within the new space during evacuation.
PAGE_NEW_NEW_PROMOTION = 1u << 10,
// This flag is intended to be used for testing. Works only when both
// FLAG_stress_compaction and FLAG_manual_evacuation_candidates_selection
// are set. It forces the page to become an evacuation candidate at next
// candidates selection cycle.
FORCE_EVACUATION_CANDIDATE_FOR_TESTING = 1u << 11,
// This flag is intended to be used for testing.
NEVER_ALLOCATE_ON_PAGE = 1u << 12,
// The memory chunk is already logically freed, however the actual freeing
// still has to be performed.
PRE_FREED = 1u << 13,
// |POOLED|: When actually freeing this chunk, only uncommit and do not
// give up the reservation as we still reuse the chunk at some point.
POOLED = 1u << 14,
// |COMPACTION_WAS_ABORTED|: Indicates that the compaction in this page
// has been aborted and needs special handling by the sweeper.
COMPACTION_WAS_ABORTED = 1u << 15,
// |COMPACTION_WAS_ABORTED_FOR_TESTING|: During stress testing evacuation
// on pages is sometimes aborted. The flag is used to avoid repeatedly
// triggering on the same page.
COMPACTION_WAS_ABORTED_FOR_TESTING = 1u << 16,
// |SWEEP_TO_ITERATE|: The page requires sweeping using external markbits
// to iterate the page.
SWEEP_TO_ITERATE = 1u << 17,
// |INCREMENTAL_MARKING|: Indicates whether incremental marking is currently
// enabled.
INCREMENTAL_MARKING = 1u << 18,
NEW_SPACE_BELOW_AGE_MARK = 1u << 19,
// The memory chunk freeing bookkeeping has been performed but the chunk has
// not yet been freed.
UNREGISTERED = 1u << 20,
// The memory chunk belongs to the read-only heap and does not participate
// in garbage collection. This is used instead of owner for identity
// checking since read-only chunks have no owner once they are detached.
READ_ONLY_HEAP = 1u << 21,
};
static const intptr_t kAlignment =
(static_cast<uintptr_t>(1) << kPageSizeBits);
static const intptr_t kAlignmentMask = kAlignment - 1;
BasicMemoryChunk(size_t size, Address area_start, Address area_end);
static Address BaseAddress(Address a) { return a & ~kAlignmentMask; }
Address address() const { return reinterpret_cast<Address>(this); }
size_t size() const { return size_; }
void set_size(size_t size) { size_ = size; }
Address area_start() const { return area_start_; }
Address area_end() const { return area_end_; }
void set_area_end(Address area_end) { area_end_ = area_end; }
size_t area_size() const {
return static_cast<size_t>(area_end() - area_start());
}
template <AccessMode access_mode = AccessMode::NON_ATOMIC>
void SetFlag(Flag flag) {
if (access_mode == AccessMode::NON_ATOMIC) {
flags_ |= flag;
} else {
base::AsAtomicWord::SetBits<uintptr_t>(&flags_, flag, flag);
}
}
template <AccessMode access_mode = AccessMode::NON_ATOMIC>
bool IsFlagSet(Flag flag) const {
return (GetFlags<access_mode>() & flag) != 0;
}
void ClearFlag(Flag flag) { flags_ &= ~flag; }
// Set or clear multiple flags at a time. The flags in the mask are set to
// the value in "flags", the rest retain the current value in |flags_|.
void SetFlags(uintptr_t flags, uintptr_t mask) {
flags_ = (flags_ & ~mask) | (flags & mask);
}
// Return all current flags.
template <AccessMode access_mode = AccessMode::NON_ATOMIC>
uintptr_t GetFlags() const {
if (access_mode == AccessMode::NON_ATOMIC) {
return flags_;
} else {
return base::AsAtomicWord::Relaxed_Load(&flags_);
}
}
bool InReadOnlySpace() const { return IsFlagSet(READ_ONLY_HEAP); }
// TODO(v8:7464): Add methods for down casting to MemoryChunk.
bool Contains(Address addr) const {
return addr >= area_start() && addr < area_end();
}
// Checks whether |addr| can be a limit of addresses in this page. It's a
// limit if it's in the page, or if it's just after the last byte of the page.
bool ContainsLimit(Address addr) const {
return addr >= area_start() && addr <= area_end();
}
V8_EXPORT_PRIVATE static bool HasHeaderSentinel(Address slot_addr);
void ReleaseMarkingBitmap();
static const intptr_t kSizeOffset = 0;
static const intptr_t kFlagsOffset = kSizeOffset + kSizetSize;
static const intptr_t kMarkBitmapOffset = kFlagsOffset + kUIntptrSize;
static const intptr_t kHeapOffset = kMarkBitmapOffset + kSystemPointerSize;
static const intptr_t kHeaderSentinelOffset =
kHeapOffset + kSystemPointerSize;
static const size_t kHeaderSize =
kSizeOffset + kSizetSize // size_t size
+ kUIntptrSize // uintptr_t flags_
+ kSystemPointerSize // Bitmap* marking_bitmap_
+ kSystemPointerSize // Heap* heap_
+ kSystemPointerSize // Address header_sentinel_
+ kSystemPointerSize // Address area_start_
+ kSystemPointerSize; // Address area_end_
protected:
// Overall size of the chunk, including the header and guards.
size_t size_;
uintptr_t flags_ = NO_FLAGS;
Bitmap* marking_bitmap_ = nullptr;
// TODO(v8:7464): Find a way to remove this.
// This goes against the spirit for the BasicMemoryChunk, but until C++14/17
// is the default it needs to live here because MemoryChunk is not standard
// layout under C++11.
Heap* heap_;
// This is used to distinguish the memory chunk header from the interior of a
// large page. The memory chunk header stores here an impossible tagged
// pointer: the tagger pointer of the page start. A field in a large object is
// guaranteed to not contain such a pointer.
Address header_sentinel_;
// Start and end of allocatable memory on this chunk.
Address area_start_;
Address area_end_;
friend class BasicMemoryChunkValidator;
};
STATIC_ASSERT(std::is_standard_layout<BasicMemoryChunk>::value);
class BasicMemoryChunkValidator {
// Computed offsets should match the compiler generated ones.
STATIC_ASSERT(BasicMemoryChunk::kSizeOffset ==
offsetof(BasicMemoryChunk, size_));
STATIC_ASSERT(BasicMemoryChunk::kFlagsOffset ==
offsetof(BasicMemoryChunk, flags_));
STATIC_ASSERT(BasicMemoryChunk::kMarkBitmapOffset ==
offsetof(BasicMemoryChunk, marking_bitmap_));
STATIC_ASSERT(BasicMemoryChunk::kHeapOffset ==
offsetof(BasicMemoryChunk, heap_));
STATIC_ASSERT(BasicMemoryChunk::kHeaderSentinelOffset ==
offsetof(BasicMemoryChunk, header_sentinel_));
};
} // namespace internal
} // namespace v8
#endif // V8_HEAP_BASIC_MEMORY_CHUNK_H_
|
hamzahamidi/v8
|
src/codegen/arm64/assembler-arm64.h
|
// Copyright 2013 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_CODEGEN_ARM64_ASSEMBLER_ARM64_H_
#define V8_CODEGEN_ARM64_ASSEMBLER_ARM64_H_
#include <deque>
#include <list>
#include <map>
#include <memory>
#include <vector>
#include "src/base/optional.h"
#include "src/codegen/arm64/constants-arm64.h"
#include "src/codegen/arm64/instructions-arm64.h"
#include "src/codegen/arm64/register-arm64.h"
#include "src/codegen/assembler.h"
#include "src/codegen/constant-pool.h"
#include "src/common/globals.h"
#include "src/utils/utils.h"
// Windows arm64 SDK defines mvn to NEON intrinsic neon_not which will not
// be used here.
#if defined(V8_OS_WIN) && defined(mvn)
#undef mvn
#endif
#if defined(V8_OS_WIN)
#include "src/diagnostics/unwinding-info-win64.h"
#endif // V8_OS_WIN
namespace v8 {
namespace internal {
class SafepointTableBuilder;
// -----------------------------------------------------------------------------
// Immediates.
class Immediate {
public:
template <typename T>
inline explicit Immediate(
Handle<T> handle, RelocInfo::Mode mode = RelocInfo::FULL_EMBEDDED_OBJECT);
// This is allowed to be an implicit constructor because Immediate is
// a wrapper class that doesn't normally perform any type conversion.
template <typename T>
inline Immediate(T value); // NOLINT(runtime/explicit)
template <typename T>
inline Immediate(T value, RelocInfo::Mode rmode);
int64_t value() const { return value_; }
RelocInfo::Mode rmode() const { return rmode_; }
private:
int64_t value_;
RelocInfo::Mode rmode_;
};
// -----------------------------------------------------------------------------
// Operands.
constexpr int kSmiShift = kSmiTagSize + kSmiShiftSize;
constexpr uint64_t kSmiShiftMask = (1ULL << kSmiShift) - 1;
// Represents an operand in a machine instruction.
class Operand {
// TODO(all): If necessary, study more in details which methods
// TODO(all): should be inlined or not.
public:
// rm, {<shift> {#<shift_amount>}}
// where <shift> is one of {LSL, LSR, ASR, ROR}.
// <shift_amount> is uint6_t.
// This is allowed to be an implicit constructor because Operand is
// a wrapper class that doesn't normally perform any type conversion.
inline Operand(Register reg, Shift shift = LSL,
unsigned shift_amount = 0); // NOLINT(runtime/explicit)
// rm, <extend> {#<shift_amount>}
// where <extend> is one of {UXTB, UXTH, UXTW, UXTX, SXTB, SXTH, SXTW, SXTX}.
// <shift_amount> is uint2_t.
inline Operand(Register reg, Extend extend, unsigned shift_amount = 0);
static Operand EmbeddedNumber(double number); // Smi or HeapNumber.
static Operand EmbeddedStringConstant(const StringConstantBase* str);
inline bool IsHeapObjectRequest() const;
inline HeapObjectRequest heap_object_request() const;
inline Immediate immediate_for_heap_object_request() const;
// Implicit constructor for all int types, ExternalReference, and Smi.
template <typename T>
inline Operand(T t); // NOLINT(runtime/explicit)
// Implicit constructor for int types.
template <typename T>
inline Operand(T t, RelocInfo::Mode rmode);
inline bool IsImmediate() const;
inline bool IsShiftedRegister() const;
inline bool IsExtendedRegister() const;
inline bool IsZero() const;
// This returns an LSL shift (<= 4) operand as an equivalent extend operand,
// which helps in the encoding of instructions that use the stack pointer.
inline Operand ToExtendedRegister() const;
// Returns new Operand adapted for using with W registers.
inline Operand ToW() const;
inline Immediate immediate() const;
inline int64_t ImmediateValue() const;
inline RelocInfo::Mode ImmediateRMode() const;
inline Register reg() const;
inline Shift shift() const;
inline Extend extend() const;
inline unsigned shift_amount() const;
// Relocation information.
bool NeedsRelocation(const Assembler* assembler) const;
private:
base::Optional<HeapObjectRequest> heap_object_request_;
Immediate immediate_;
Register reg_;
Shift shift_;
Extend extend_;
unsigned shift_amount_;
};
// MemOperand represents a memory operand in a load or store instruction.
class MemOperand {
public:
inline MemOperand();
inline explicit MemOperand(Register base, int64_t offset = 0,
AddrMode addrmode = Offset);
inline explicit MemOperand(Register base, Register regoffset,
Shift shift = LSL, unsigned shift_amount = 0);
inline explicit MemOperand(Register base, Register regoffset, Extend extend,
unsigned shift_amount = 0);
inline explicit MemOperand(Register base, const Operand& offset,
AddrMode addrmode = Offset);
const Register& base() const { return base_; }
const Register& regoffset() const { return regoffset_; }
int64_t offset() const { return offset_; }
AddrMode addrmode() const { return addrmode_; }
Shift shift() const { return shift_; }
Extend extend() const { return extend_; }
unsigned shift_amount() const { return shift_amount_; }
inline bool IsImmediateOffset() const;
inline bool IsRegisterOffset() const;
inline bool IsPreIndex() const;
inline bool IsPostIndex() const;
// For offset modes, return the offset as an Operand. This helper cannot
// handle indexed modes.
inline Operand OffsetAsOperand() const;
enum PairResult {
kNotPair, // Can't use a pair instruction.
kPairAB, // Can use a pair instruction (operandA has lower address).
kPairBA // Can use a pair instruction (operandB has lower address).
};
// Check if two MemOperand are consistent for stp/ldp use.
static PairResult AreConsistentForPair(const MemOperand& operandA,
const MemOperand& operandB,
int access_size_log2 = kXRegSizeLog2);
private:
Register base_;
Register regoffset_;
int64_t offset_;
AddrMode addrmode_;
Shift shift_;
Extend extend_;
unsigned shift_amount_;
};
// -----------------------------------------------------------------------------
// Assembler.
class V8_EXPORT_PRIVATE Assembler : public AssemblerBase {
public:
// Create an assembler. Instructions and relocation information are emitted
// into a buffer, with the instructions starting from the beginning and the
// relocation information starting from the end of the buffer. See CodeDesc
// for a detailed comment on the layout (globals.h).
//
// If the provided buffer is nullptr, the assembler allocates and grows its
// own buffer. Otherwise it takes ownership of the provided buffer.
explicit Assembler(const AssemblerOptions&,
std::unique_ptr<AssemblerBuffer> = {});
virtual ~Assembler();
virtual void AbortedCodeGeneration();
// System functions ---------------------------------------------------------
// Start generating code from the beginning of the buffer, discarding any code
// and data that has already been emitted into the buffer.
//
// In order to avoid any accidental transfer of state, Reset DCHECKs that the
// constant pool is not blocked.
void Reset();
// GetCode emits any pending (non-emitted) code and fills the descriptor desc.
static constexpr int kNoHandlerTable = 0;
static constexpr SafepointTableBuilder* kNoSafepointTable = nullptr;
void GetCode(Isolate* isolate, CodeDesc* desc,
SafepointTableBuilder* safepoint_table_builder,
int handler_table_offset);
// Convenience wrapper for code without safepoint or handler tables.
void GetCode(Isolate* isolate, CodeDesc* desc) {
GetCode(isolate, desc, kNoSafepointTable, kNoHandlerTable);
}
// Insert the smallest number of nop instructions
// possible to align the pc offset to a multiple
// of m. m must be a power of 2 (>= 4).
void Align(int m);
// Insert the smallest number of zero bytes possible to align the pc offset
// to a mulitple of m. m must be a power of 2 (>= 2).
void DataAlign(int m);
// Aligns code to something that's optimal for a jump target for the platform.
void CodeTargetAlign();
inline void Unreachable();
// Label --------------------------------------------------------------------
// Bind a label to the current pc. Note that labels can only be bound once,
// and if labels are linked to other instructions, they _must_ be bound
// before they go out of scope.
void bind(Label* label);
// RelocInfo and pools ------------------------------------------------------
// Record relocation information for current pc_.
enum ConstantPoolMode { NEEDS_POOL_ENTRY, NO_POOL_ENTRY };
void RecordRelocInfo(RelocInfo::Mode rmode, intptr_t data = 0,
ConstantPoolMode constant_pool_mode = NEEDS_POOL_ENTRY);
// Generate a B immediate instruction with the corresponding relocation info.
// 'offset' is the immediate to encode in the B instruction (so it is the
// difference between the target and the PC of the instruction, divided by
// the instruction size).
void near_jump(int offset, RelocInfo::Mode rmode);
// Generate a BL immediate instruction with the corresponding relocation info.
// As for near_jump, 'offset' is the immediate to encode in the BL
// instruction.
void near_call(int offset, RelocInfo::Mode rmode);
// Generate a BL immediate instruction with the corresponding relocation info
// for the input HeapObjectRequest.
void near_call(HeapObjectRequest request);
// Return the address in the constant pool of the code target address used by
// the branch/call instruction at pc.
inline static Address target_pointer_address_at(Address pc);
// Read/Modify the code target address in the branch/call instruction at pc.
// The isolate argument is unused (and may be nullptr) when skipping flushing.
inline static Address target_address_at(Address pc, Address constant_pool);
// Read/Modify the code target address in the branch/call instruction at pc.
inline static Tagged_t target_compressed_address_at(Address pc,
Address constant_pool);
inline static void set_target_address_at(
Address pc, Address constant_pool, Address target,
ICacheFlushMode icache_flush_mode = FLUSH_ICACHE_IF_NEEDED);
inline static void set_target_compressed_address_at(
Address pc, Address constant_pool, Tagged_t target,
ICacheFlushMode icache_flush_mode = FLUSH_ICACHE_IF_NEEDED);
// Returns the handle for the code object called at 'pc'.
// This might need to be temporarily encoded as an offset into code_targets_.
inline Handle<Code> code_target_object_handle_at(Address pc);
inline EmbeddedObjectIndex embedded_object_index_referenced_from(Address pc);
inline void set_embedded_object_index_referenced_from(
Address p, EmbeddedObjectIndex index);
// Returns the handle for the heap object referenced at 'pc'.
inline Handle<HeapObject> target_object_handle_at(Address pc);
// Returns the target address for a runtime function for the call encoded
// at 'pc'.
// Runtime entries can be temporarily encoded as the offset between the
// runtime function entrypoint and the code range start (stored in the
// code_range_start field), in order to be encodable as we generate the code,
// before it is moved into the code space.
inline Address runtime_entry_at(Address pc);
// This sets the branch destination. 'location' here can be either the pc of
// an immediate branch or the address of an entry in the constant pool.
// This is for calls and branches within generated code.
inline static void deserialization_set_special_target_at(Address location,
Code code,
Address target);
// Get the size of the special target encoded at 'location'.
inline static int deserialization_special_target_size(Address location);
// This sets the internal reference at the pc.
inline static void deserialization_set_target_internal_reference_at(
Address pc, Address target,
RelocInfo::Mode mode = RelocInfo::INTERNAL_REFERENCE);
// This value is used in the serialization process and must be zero for
// ARM64, as the code target is split across multiple instructions and does
// not exist separately in the code, so the serializer should not step
// forwards in memory after a target is resolved and written.
static constexpr int kSpecialTargetSize = 0;
// Size of the generated code in bytes
uint64_t SizeOfGeneratedCode() const {
DCHECK((pc_ >= buffer_start_) && (pc_ < (buffer_start_ + buffer_->size())));
return pc_ - buffer_start_;
}
// Return the code size generated from label to the current position.
uint64_t SizeOfCodeGeneratedSince(const Label* label) {
DCHECK(label->is_bound());
DCHECK_GE(pc_offset(), label->pos());
DCHECK_LT(pc_offset(), buffer_->size());
return pc_offset() - label->pos();
}
// Return the number of instructions generated from label to the
// current position.
uint64_t InstructionsGeneratedSince(const Label* label) {
return SizeOfCodeGeneratedSince(label) / kInstrSize;
}
static bool IsConstantPoolAt(Instruction* instr);
static int ConstantPoolSizeAt(Instruction* instr);
// See Assembler::CheckConstPool for more info.
void EmitPoolGuard();
// Prevent veneer pool emission until EndBlockVeneerPool is called.
// Call to this function can be nested but must be followed by an equal
// number of calls to EndBlockConstpool.
void StartBlockVeneerPool();
// Resume constant pool emission. Need to be called as many time as
// StartBlockVeneerPool to have an effect.
void EndBlockVeneerPool();
bool is_veneer_pool_blocked() const {
return veneer_pool_blocked_nesting_ > 0;
}
// Record a deoptimization reason that can be used by a log or cpu profiler.
// Use --trace-deopt to enable.
void RecordDeoptReason(DeoptimizeReason reason, SourcePosition position,
int id);
int buffer_space() const;
// Record the emission of a constant pool.
//
// The emission of constant and veneer pools depends on the size of the code
// generated and the number of RelocInfo recorded.
// The Debug mechanism needs to map code offsets between two versions of a
// function, compiled with and without debugger support (see for example
// Debug::PrepareForBreakPoints()).
// Compiling functions with debugger support generates additional code
// (DebugCodegen::GenerateSlot()). This may affect the emission of the pools
// and cause the version of the code with debugger support to have pools
// generated in different places.
// Recording the position and size of emitted pools allows to correctly
// compute the offset mappings between the different versions of a function in
// all situations.
//
// The parameter indicates the size of the pool (in bytes), including
// the marker and branch over the data.
void RecordConstPool(int size);
// Instruction set functions ------------------------------------------------
// Branch / Jump instructions.
// For branches offsets are scaled, i.e. in instructions not in bytes.
// Branch to register.
void br(const Register& xn);
// Branch-link to register.
void blr(const Register& xn);
// Branch to register with return hint.
void ret(const Register& xn = lr);
// Unconditional branch to label.
void b(Label* label);
// Conditional branch to label.
void b(Label* label, Condition cond);
// Unconditional branch to PC offset.
void b(int imm26);
// Conditional branch to PC offset.
void b(int imm19, Condition cond);
// Branch-link to label / pc offset.
void bl(Label* label);
void bl(int imm26);
// Compare and branch to label / pc offset if zero.
void cbz(const Register& rt, Label* label);
void cbz(const Register& rt, int imm19);
// Compare and branch to label / pc offset if not zero.
void cbnz(const Register& rt, Label* label);
void cbnz(const Register& rt, int imm19);
// Test bit and branch to label / pc offset if zero.
void tbz(const Register& rt, unsigned bit_pos, Label* label);
void tbz(const Register& rt, unsigned bit_pos, int imm14);
// Test bit and branch to label / pc offset if not zero.
void tbnz(const Register& rt, unsigned bit_pos, Label* label);
void tbnz(const Register& rt, unsigned bit_pos, int imm14);
// Address calculation instructions.
// Calculate a PC-relative address. Unlike for branches the offset in adr is
// unscaled (i.e. the result can be unaligned).
void adr(const Register& rd, Label* label);
void adr(const Register& rd, int imm21);
// Data Processing instructions.
// Add.
void add(const Register& rd, const Register& rn, const Operand& operand);
// Add and update status flags.
void adds(const Register& rd, const Register& rn, const Operand& operand);
// Compare negative.
void cmn(const Register& rn, const Operand& operand);
// Subtract.
void sub(const Register& rd, const Register& rn, const Operand& operand);
// Subtract and update status flags.
void subs(const Register& rd, const Register& rn, const Operand& operand);
// Compare.
void cmp(const Register& rn, const Operand& operand);
// Negate.
void neg(const Register& rd, const Operand& operand);
// Negate and update status flags.
void negs(const Register& rd, const Operand& operand);
// Add with carry bit.
void adc(const Register& rd, const Register& rn, const Operand& operand);
// Add with carry bit and update status flags.
void adcs(const Register& rd, const Register& rn, const Operand& operand);
// Subtract with carry bit.
void sbc(const Register& rd, const Register& rn, const Operand& operand);
// Subtract with carry bit and update status flags.
void sbcs(const Register& rd, const Register& rn, const Operand& operand);
// Negate with carry bit.
void ngc(const Register& rd, const Operand& operand);
// Negate with carry bit and update status flags.
void ngcs(const Register& rd, const Operand& operand);
// Logical instructions.
// Bitwise and (A & B).
void and_(const Register& rd, const Register& rn, const Operand& operand);
// Bitwise and (A & B) and update status flags.
void ands(const Register& rd, const Register& rn, const Operand& operand);
// Bit test, and set flags.
void tst(const Register& rn, const Operand& operand);
// Bit clear (A & ~B).
void bic(const Register& rd, const Register& rn, const Operand& operand);
// Bit clear (A & ~B) and update status flags.
void bics(const Register& rd, const Register& rn, const Operand& operand);
// Bitwise and.
void and_(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Bit clear immediate.
void bic(const VRegister& vd, const int imm8, const int left_shift = 0);
// Bit clear.
void bic(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Bitwise insert if false.
void bif(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Bitwise insert if true.
void bit(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Bitwise select.
void bsl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Polynomial multiply.
void pmul(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Vector move immediate.
void movi(const VRegister& vd, const uint64_t imm, Shift shift = LSL,
const int shift_amount = 0);
// Bitwise not.
void mvn(const VRegister& vd, const VRegister& vn);
// Vector move inverted immediate.
void mvni(const VRegister& vd, const int imm8, Shift shift = LSL,
const int shift_amount = 0);
// Signed saturating accumulate of unsigned value.
void suqadd(const VRegister& vd, const VRegister& vn);
// Unsigned saturating accumulate of signed value.
void usqadd(const VRegister& vd, const VRegister& vn);
// Absolute value.
void abs(const VRegister& vd, const VRegister& vn);
// Signed saturating absolute value.
void sqabs(const VRegister& vd, const VRegister& vn);
// Negate.
void neg(const VRegister& vd, const VRegister& vn);
// Signed saturating negate.
void sqneg(const VRegister& vd, const VRegister& vn);
// Bitwise not.
void not_(const VRegister& vd, const VRegister& vn);
// Extract narrow.
void xtn(const VRegister& vd, const VRegister& vn);
// Extract narrow (second part).
void xtn2(const VRegister& vd, const VRegister& vn);
// Signed saturating extract narrow.
void sqxtn(const VRegister& vd, const VRegister& vn);
// Signed saturating extract narrow (second part).
void sqxtn2(const VRegister& vd, const VRegister& vn);
// Unsigned saturating extract narrow.
void uqxtn(const VRegister& vd, const VRegister& vn);
// Unsigned saturating extract narrow (second part).
void uqxtn2(const VRegister& vd, const VRegister& vn);
// Signed saturating extract unsigned narrow.
void sqxtun(const VRegister& vd, const VRegister& vn);
// Signed saturating extract unsigned narrow (second part).
void sqxtun2(const VRegister& vd, const VRegister& vn);
// Move register to register.
void mov(const VRegister& vd, const VRegister& vn);
// Bitwise not or.
void orn(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Bitwise exclusive or.
void eor(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Bitwise or (A | B).
void orr(const Register& rd, const Register& rn, const Operand& operand);
// Bitwise or.
void orr(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Bitwise or immediate.
void orr(const VRegister& vd, const int imm8, const int left_shift = 0);
// Bitwise nor (A | ~B).
void orn(const Register& rd, const Register& rn, const Operand& operand);
// Bitwise eor/xor (A ^ B).
void eor(const Register& rd, const Register& rn, const Operand& operand);
// Bitwise enor/xnor (A ^ ~B).
void eon(const Register& rd, const Register& rn, const Operand& operand);
// Logical shift left variable.
void lslv(const Register& rd, const Register& rn, const Register& rm);
// Logical shift right variable.
void lsrv(const Register& rd, const Register& rn, const Register& rm);
// Arithmetic shift right variable.
void asrv(const Register& rd, const Register& rn, const Register& rm);
// Rotate right variable.
void rorv(const Register& rd, const Register& rn, const Register& rm);
// Bitfield instructions.
// Bitfield move.
void bfm(const Register& rd, const Register& rn, int immr, int imms);
// Signed bitfield move.
void sbfm(const Register& rd, const Register& rn, int immr, int imms);
// Unsigned bitfield move.
void ubfm(const Register& rd, const Register& rn, int immr, int imms);
// Bfm aliases.
// Bitfield insert.
void bfi(const Register& rd, const Register& rn, int lsb, int width) {
DCHECK_GE(width, 1);
DCHECK(lsb + width <= rn.SizeInBits());
bfm(rd, rn, (rd.SizeInBits() - lsb) & (rd.SizeInBits() - 1), width - 1);
}
// Bitfield extract and insert low.
void bfxil(const Register& rd, const Register& rn, int lsb, int width) {
DCHECK_GE(width, 1);
DCHECK(lsb + width <= rn.SizeInBits());
bfm(rd, rn, lsb, lsb + width - 1);
}
// Sbfm aliases.
// Arithmetic shift right.
void asr(const Register& rd, const Register& rn, int shift) {
DCHECK(shift < rd.SizeInBits());
sbfm(rd, rn, shift, rd.SizeInBits() - 1);
}
// Signed bitfield insert in zero.
void sbfiz(const Register& rd, const Register& rn, int lsb, int width) {
DCHECK_GE(width, 1);
DCHECK(lsb + width <= rn.SizeInBits());
sbfm(rd, rn, (rd.SizeInBits() - lsb) & (rd.SizeInBits() - 1), width - 1);
}
// Signed bitfield extract.
void sbfx(const Register& rd, const Register& rn, int lsb, int width) {
DCHECK_GE(width, 1);
DCHECK(lsb + width <= rn.SizeInBits());
sbfm(rd, rn, lsb, lsb + width - 1);
}
// Signed extend byte.
void sxtb(const Register& rd, const Register& rn) { sbfm(rd, rn, 0, 7); }
// Signed extend halfword.
void sxth(const Register& rd, const Register& rn) { sbfm(rd, rn, 0, 15); }
// Signed extend word.
void sxtw(const Register& rd, const Register& rn) { sbfm(rd, rn, 0, 31); }
// Ubfm aliases.
// Logical shift left.
void lsl(const Register& rd, const Register& rn, int shift) {
int reg_size = rd.SizeInBits();
DCHECK(shift < reg_size);
ubfm(rd, rn, (reg_size - shift) % reg_size, reg_size - shift - 1);
}
// Logical shift right.
void lsr(const Register& rd, const Register& rn, int shift) {
DCHECK(shift < rd.SizeInBits());
ubfm(rd, rn, shift, rd.SizeInBits() - 1);
}
// Unsigned bitfield insert in zero.
void ubfiz(const Register& rd, const Register& rn, int lsb, int width) {
DCHECK_GE(width, 1);
DCHECK(lsb + width <= rn.SizeInBits());
ubfm(rd, rn, (rd.SizeInBits() - lsb) & (rd.SizeInBits() - 1), width - 1);
}
// Unsigned bitfield extract.
void ubfx(const Register& rd, const Register& rn, int lsb, int width) {
DCHECK_GE(width, 1);
DCHECK(lsb + width <= rn.SizeInBits());
ubfm(rd, rn, lsb, lsb + width - 1);
}
// Unsigned extend byte.
void uxtb(const Register& rd, const Register& rn) { ubfm(rd, rn, 0, 7); }
// Unsigned extend halfword.
void uxth(const Register& rd, const Register& rn) { ubfm(rd, rn, 0, 15); }
// Unsigned extend word.
void uxtw(const Register& rd, const Register& rn) { ubfm(rd, rn, 0, 31); }
// Extract.
void extr(const Register& rd, const Register& rn, const Register& rm,
int lsb);
// Conditional select: rd = cond ? rn : rm.
void csel(const Register& rd, const Register& rn, const Register& rm,
Condition cond);
// Conditional select increment: rd = cond ? rn : rm + 1.
void csinc(const Register& rd, const Register& rn, const Register& rm,
Condition cond);
// Conditional select inversion: rd = cond ? rn : ~rm.
void csinv(const Register& rd, const Register& rn, const Register& rm,
Condition cond);
// Conditional select negation: rd = cond ? rn : -rm.
void csneg(const Register& rd, const Register& rn, const Register& rm,
Condition cond);
// Conditional set: rd = cond ? 1 : 0.
void cset(const Register& rd, Condition cond);
// Conditional set minus: rd = cond ? -1 : 0.
void csetm(const Register& rd, Condition cond);
// Conditional increment: rd = cond ? rn + 1 : rn.
void cinc(const Register& rd, const Register& rn, Condition cond);
// Conditional invert: rd = cond ? ~rn : rn.
void cinv(const Register& rd, const Register& rn, Condition cond);
// Conditional negate: rd = cond ? -rn : rn.
void cneg(const Register& rd, const Register& rn, Condition cond);
// Extr aliases.
void ror(const Register& rd, const Register& rs, unsigned shift) {
extr(rd, rs, rs, shift);
}
// Conditional comparison.
// Conditional compare negative.
void ccmn(const Register& rn, const Operand& operand, StatusFlags nzcv,
Condition cond);
// Conditional compare.
void ccmp(const Register& rn, const Operand& operand, StatusFlags nzcv,
Condition cond);
// Multiplication.
// 32 x 32 -> 32-bit and 64 x 64 -> 64-bit multiply.
void mul(const Register& rd, const Register& rn, const Register& rm);
// 32 + 32 x 32 -> 32-bit and 64 + 64 x 64 -> 64-bit multiply accumulate.
void madd(const Register& rd, const Register& rn, const Register& rm,
const Register& ra);
// -(32 x 32) -> 32-bit and -(64 x 64) -> 64-bit multiply.
void mneg(const Register& rd, const Register& rn, const Register& rm);
// 32 - 32 x 32 -> 32-bit and 64 - 64 x 64 -> 64-bit multiply subtract.
void msub(const Register& rd, const Register& rn, const Register& rm,
const Register& ra);
// 32 x 32 -> 64-bit multiply.
void smull(const Register& rd, const Register& rn, const Register& rm);
// Xd = bits<127:64> of Xn * Xm.
void smulh(const Register& rd, const Register& rn, const Register& rm);
// Signed 32 x 32 -> 64-bit multiply and accumulate.
void smaddl(const Register& rd, const Register& rn, const Register& rm,
const Register& ra);
// Unsigned 32 x 32 -> 64-bit multiply and accumulate.
void umaddl(const Register& rd, const Register& rn, const Register& rm,
const Register& ra);
// Signed 32 x 32 -> 64-bit multiply and subtract.
void smsubl(const Register& rd, const Register& rn, const Register& rm,
const Register& ra);
// Unsigned 32 x 32 -> 64-bit multiply and subtract.
void umsubl(const Register& rd, const Register& rn, const Register& rm,
const Register& ra);
// Signed integer divide.
void sdiv(const Register& rd, const Register& rn, const Register& rm);
// Unsigned integer divide.
void udiv(const Register& rd, const Register& rn, const Register& rm);
// Bit count, bit reverse and endian reverse.
void rbit(const Register& rd, const Register& rn);
void rev16(const Register& rd, const Register& rn);
void rev32(const Register& rd, const Register& rn);
void rev(const Register& rd, const Register& rn);
void clz(const Register& rd, const Register& rn);
void cls(const Register& rd, const Register& rn);
// Pointer Authentication Code for Instruction address, using key A, with
// address in x17 and modifier in x16 [Armv8.3].
void pacia1716();
// Pointer Authentication Code for Instruction address, using key A, with
// address in LR and modifier in SP [Armv8.3].
void paciasp();
// Authenticate Instruction address, using key A, with address in x17 and
// modifier in x16 [Armv8.3].
void autia1716();
// Authenticate Instruction address, using key A, with address in LR and
// modifier in SP [Armv8.3].
void autiasp();
// Memory instructions.
// Load integer or FP register.
void ldr(const CPURegister& rt, const MemOperand& src);
// Store integer or FP register.
void str(const CPURegister& rt, const MemOperand& dst);
// Load word with sign extension.
void ldrsw(const Register& rt, const MemOperand& src);
// Load byte.
void ldrb(const Register& rt, const MemOperand& src);
// Store byte.
void strb(const Register& rt, const MemOperand& dst);
// Load byte with sign extension.
void ldrsb(const Register& rt, const MemOperand& src);
// Load half-word.
void ldrh(const Register& rt, const MemOperand& src);
// Store half-word.
void strh(const Register& rt, const MemOperand& dst);
// Load half-word with sign extension.
void ldrsh(const Register& rt, const MemOperand& src);
// Load integer or FP register pair.
void ldp(const CPURegister& rt, const CPURegister& rt2,
const MemOperand& src);
// Store integer or FP register pair.
void stp(const CPURegister& rt, const CPURegister& rt2,
const MemOperand& dst);
// Load word pair with sign extension.
void ldpsw(const Register& rt, const Register& rt2, const MemOperand& src);
// Load literal to register from a pc relative address.
void ldr_pcrel(const CPURegister& rt, int imm19);
// Load literal to register.
void ldr(const CPURegister& rt, const Immediate& imm);
void ldr(const CPURegister& rt, const Operand& operand);
// Load-acquire word.
void ldar(const Register& rt, const Register& rn);
// Load-acquire exclusive word.
void ldaxr(const Register& rt, const Register& rn);
// Store-release word.
void stlr(const Register& rt, const Register& rn);
// Store-release exclusive word.
void stlxr(const Register& rs, const Register& rt, const Register& rn);
// Load-acquire byte.
void ldarb(const Register& rt, const Register& rn);
// Load-acquire exclusive byte.
void ldaxrb(const Register& rt, const Register& rn);
// Store-release byte.
void stlrb(const Register& rt, const Register& rn);
// Store-release exclusive byte.
void stlxrb(const Register& rs, const Register& rt, const Register& rn);
// Load-acquire half-word.
void ldarh(const Register& rt, const Register& rn);
// Load-acquire exclusive half-word.
void ldaxrh(const Register& rt, const Register& rn);
// Store-release half-word.
void stlrh(const Register& rt, const Register& rn);
// Store-release exclusive half-word.
void stlxrh(const Register& rs, const Register& rt, const Register& rn);
// Move instructions. The default shift of -1 indicates that the move
// instruction will calculate an appropriate 16-bit immediate and left shift
// that is equal to the 64-bit immediate argument. If an explicit left shift
// is specified (0, 16, 32 or 48), the immediate must be a 16-bit value.
//
// For movk, an explicit shift can be used to indicate which half word should
// be overwritten, eg. movk(x0, 0, 0) will overwrite the least-significant
// half word with zero, whereas movk(x0, 0, 48) will overwrite the
// most-significant.
// Move and keep.
void movk(const Register& rd, uint64_t imm, int shift = -1) {
MoveWide(rd, imm, shift, MOVK);
}
// Move with non-zero.
void movn(const Register& rd, uint64_t imm, int shift = -1) {
MoveWide(rd, imm, shift, MOVN);
}
// Move with zero.
void movz(const Register& rd, uint64_t imm, int shift = -1) {
MoveWide(rd, imm, shift, MOVZ);
}
// Misc instructions.
// Monitor debug-mode breakpoint.
void brk(int code);
// Halting debug-mode breakpoint.
void hlt(int code);
// Move register to register.
void mov(const Register& rd, const Register& rn);
// Move NOT(operand) to register.
void mvn(const Register& rd, const Operand& operand);
// System instructions.
// Move to register from system register.
void mrs(const Register& rt, SystemRegister sysreg);
// Move from register to system register.
void msr(SystemRegister sysreg, const Register& rt);
// System hint.
void hint(SystemHint code);
// Data memory barrier
void dmb(BarrierDomain domain, BarrierType type);
// Data synchronization barrier
void dsb(BarrierDomain domain, BarrierType type);
// Instruction synchronization barrier
void isb();
// Conditional speculation barrier.
void csdb();
// Alias for system instructions.
void nop() { hint(NOP); }
// Different nop operations are used by the code generator to detect certain
// states of the generated code.
enum NopMarkerTypes {
DEBUG_BREAK_NOP,
INTERRUPT_CODE_NOP,
ADR_FAR_NOP,
FIRST_NOP_MARKER = DEBUG_BREAK_NOP,
LAST_NOP_MARKER = ADR_FAR_NOP
};
void nop(NopMarkerTypes n);
// Add.
void add(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned halving add.
void uhadd(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Subtract.
void sub(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed halving add.
void shadd(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Multiply by scalar element.
void mul(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Multiply-add by scalar element.
void mla(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Multiply-subtract by scalar element.
void mls(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Signed long multiply-add by scalar element.
void smlal(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Signed long multiply-add by scalar element (second part).
void smlal2(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Unsigned long multiply-add by scalar element.
void umlal(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Unsigned long multiply-add by scalar element (second part).
void umlal2(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Signed long multiply-sub by scalar element.
void smlsl(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Signed long multiply-sub by scalar element (second part).
void smlsl2(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Unsigned long multiply-sub by scalar element.
void umlsl(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Unsigned long multiply-sub by scalar element (second part).
void umlsl2(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Signed long multiply by scalar element.
void smull(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Signed long multiply by scalar element (second part).
void smull2(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Unsigned long multiply by scalar element.
void umull(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Unsigned long multiply by scalar element (second part).
void umull2(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Add narrow returning high half.
void addhn(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Add narrow returning high half (second part).
void addhn2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed saturating double long multiply by element.
void sqdmull(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Signed saturating double long multiply by element (second part).
void sqdmull2(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Signed saturating doubling long multiply-add by element.
void sqdmlal(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Signed saturating doubling long multiply-add by element (second part).
void sqdmlal2(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Signed saturating doubling long multiply-sub by element.
void sqdmlsl(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Signed saturating doubling long multiply-sub by element (second part).
void sqdmlsl2(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Compare bitwise to zero.
void cmeq(const VRegister& vd, const VRegister& vn, int value);
// Compare signed greater than or equal to zero.
void cmge(const VRegister& vd, const VRegister& vn, int value);
// Compare signed greater than zero.
void cmgt(const VRegister& vd, const VRegister& vn, int value);
// Compare signed less than or equal to zero.
void cmle(const VRegister& vd, const VRegister& vn, int value);
// Compare signed less than zero.
void cmlt(const VRegister& vd, const VRegister& vn, int value);
// Unsigned rounding halving add.
void urhadd(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Compare equal.
void cmeq(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Compare signed greater than or equal.
void cmge(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Compare signed greater than.
void cmgt(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Compare unsigned higher.
void cmhi(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Compare unsigned higher or same.
void cmhs(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Compare bitwise test bits nonzero.
void cmtst(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed shift left by register.
void sshl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned shift left by register.
void ushl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed saturating doubling long multiply-subtract.
void sqdmlsl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed saturating doubling long multiply-subtract (second part).
void sqdmlsl2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed saturating doubling long multiply.
void sqdmull(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed saturating doubling long multiply (second part).
void sqdmull2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed saturating doubling multiply returning high half.
void sqdmulh(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed saturating rounding doubling multiply returning high half.
void sqrdmulh(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed saturating doubling multiply element returning high half.
void sqdmulh(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Signed saturating rounding doubling multiply element returning high half.
void sqrdmulh(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// Unsigned long multiply long.
void umull(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned long multiply (second part).
void umull2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Rounding add narrow returning high half.
void raddhn(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Subtract narrow returning high half.
void subhn(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Subtract narrow returning high half (second part).
void subhn2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Rounding add narrow returning high half (second part).
void raddhn2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Rounding subtract narrow returning high half.
void rsubhn(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Rounding subtract narrow returning high half (second part).
void rsubhn2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed saturating shift left by register.
void sqshl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned saturating shift left by register.
void uqshl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed rounding shift left by register.
void srshl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned rounding shift left by register.
void urshl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed saturating rounding shift left by register.
void sqrshl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned saturating rounding shift left by register.
void uqrshl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed absolute difference.
void sabd(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned absolute difference and accumulate.
void uaba(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Shift left by immediate and insert.
void sli(const VRegister& vd, const VRegister& vn, int shift);
// Shift right by immediate and insert.
void sri(const VRegister& vd, const VRegister& vn, int shift);
// Signed maximum.
void smax(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed pairwise maximum.
void smaxp(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Add across vector.
void addv(const VRegister& vd, const VRegister& vn);
// Signed add long across vector.
void saddlv(const VRegister& vd, const VRegister& vn);
// Unsigned add long across vector.
void uaddlv(const VRegister& vd, const VRegister& vn);
// FP maximum number across vector.
void fmaxnmv(const VRegister& vd, const VRegister& vn);
// FP maximum across vector.
void fmaxv(const VRegister& vd, const VRegister& vn);
// FP minimum number across vector.
void fminnmv(const VRegister& vd, const VRegister& vn);
// FP minimum across vector.
void fminv(const VRegister& vd, const VRegister& vn);
// Signed maximum across vector.
void smaxv(const VRegister& vd, const VRegister& vn);
// Signed minimum.
void smin(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed minimum pairwise.
void sminp(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed minimum across vector.
void sminv(const VRegister& vd, const VRegister& vn);
// One-element structure store from one register.
void st1(const VRegister& vt, const MemOperand& src);
// One-element structure store from two registers.
void st1(const VRegister& vt, const VRegister& vt2, const MemOperand& src);
// One-element structure store from three registers.
void st1(const VRegister& vt, const VRegister& vt2, const VRegister& vt3,
const MemOperand& src);
// One-element structure store from four registers.
void st1(const VRegister& vt, const VRegister& vt2, const VRegister& vt3,
const VRegister& vt4, const MemOperand& src);
// One-element single structure store from one lane.
void st1(const VRegister& vt, int lane, const MemOperand& src);
// Two-element structure store from two registers.
void st2(const VRegister& vt, const VRegister& vt2, const MemOperand& src);
// Two-element single structure store from two lanes.
void st2(const VRegister& vt, const VRegister& vt2, int lane,
const MemOperand& src);
// Three-element structure store from three registers.
void st3(const VRegister& vt, const VRegister& vt2, const VRegister& vt3,
const MemOperand& src);
// Three-element single structure store from three lanes.
void st3(const VRegister& vt, const VRegister& vt2, const VRegister& vt3,
int lane, const MemOperand& src);
// Four-element structure store from four registers.
void st4(const VRegister& vt, const VRegister& vt2, const VRegister& vt3,
const VRegister& vt4, const MemOperand& src);
// Four-element single structure store from four lanes.
void st4(const VRegister& vt, const VRegister& vt2, const VRegister& vt3,
const VRegister& vt4, int lane, const MemOperand& src);
// Unsigned add long.
void uaddl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned add long (second part).
void uaddl2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned add wide.
void uaddw(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned add wide (second part).
void uaddw2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed add long.
void saddl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed add long (second part).
void saddl2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed add wide.
void saddw(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed add wide (second part).
void saddw2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned subtract long.
void usubl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned subtract long (second part).
void usubl2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned subtract wide.
void usubw(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed subtract long.
void ssubl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed subtract long (second part).
void ssubl2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed integer subtract wide.
void ssubw(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed integer subtract wide (second part).
void ssubw2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned subtract wide (second part).
void usubw2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned maximum.
void umax(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned pairwise maximum.
void umaxp(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned maximum across vector.
void umaxv(const VRegister& vd, const VRegister& vn);
// Unsigned minimum.
void umin(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned pairwise minimum.
void uminp(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned minimum across vector.
void uminv(const VRegister& vd, const VRegister& vn);
// Transpose vectors (primary).
void trn1(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Transpose vectors (secondary).
void trn2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unzip vectors (primary).
void uzp1(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unzip vectors (secondary).
void uzp2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Zip vectors (primary).
void zip1(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Zip vectors (secondary).
void zip2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed shift right by immediate.
void sshr(const VRegister& vd, const VRegister& vn, int shift);
// Unsigned shift right by immediate.
void ushr(const VRegister& vd, const VRegister& vn, int shift);
// Signed rounding shift right by immediate.
void srshr(const VRegister& vd, const VRegister& vn, int shift);
// Unsigned rounding shift right by immediate.
void urshr(const VRegister& vd, const VRegister& vn, int shift);
// Signed shift right by immediate and accumulate.
void ssra(const VRegister& vd, const VRegister& vn, int shift);
// Unsigned shift right by immediate and accumulate.
void usra(const VRegister& vd, const VRegister& vn, int shift);
// Signed rounding shift right by immediate and accumulate.
void srsra(const VRegister& vd, const VRegister& vn, int shift);
// Unsigned rounding shift right by immediate and accumulate.
void ursra(const VRegister& vd, const VRegister& vn, int shift);
// Shift right narrow by immediate.
void shrn(const VRegister& vd, const VRegister& vn, int shift);
// Shift right narrow by immediate (second part).
void shrn2(const VRegister& vd, const VRegister& vn, int shift);
// Rounding shift right narrow by immediate.
void rshrn(const VRegister& vd, const VRegister& vn, int shift);
// Rounding shift right narrow by immediate (second part).
void rshrn2(const VRegister& vd, const VRegister& vn, int shift);
// Unsigned saturating shift right narrow by immediate.
void uqshrn(const VRegister& vd, const VRegister& vn, int shift);
// Unsigned saturating shift right narrow by immediate (second part).
void uqshrn2(const VRegister& vd, const VRegister& vn, int shift);
// Unsigned saturating rounding shift right narrow by immediate.
void uqrshrn(const VRegister& vd, const VRegister& vn, int shift);
// Unsigned saturating rounding shift right narrow by immediate (second part).
void uqrshrn2(const VRegister& vd, const VRegister& vn, int shift);
// Signed saturating shift right narrow by immediate.
void sqshrn(const VRegister& vd, const VRegister& vn, int shift);
// Signed saturating shift right narrow by immediate (second part).
void sqshrn2(const VRegister& vd, const VRegister& vn, int shift);
// Signed saturating rounded shift right narrow by immediate.
void sqrshrn(const VRegister& vd, const VRegister& vn, int shift);
// Signed saturating rounded shift right narrow by immediate (second part).
void sqrshrn2(const VRegister& vd, const VRegister& vn, int shift);
// Signed saturating shift right unsigned narrow by immediate.
void sqshrun(const VRegister& vd, const VRegister& vn, int shift);
// Signed saturating shift right unsigned narrow by immediate (second part).
void sqshrun2(const VRegister& vd, const VRegister& vn, int shift);
// Signed sat rounded shift right unsigned narrow by immediate.
void sqrshrun(const VRegister& vd, const VRegister& vn, int shift);
// Signed sat rounded shift right unsigned narrow by immediate (second part).
void sqrshrun2(const VRegister& vd, const VRegister& vn, int shift);
// FP reciprocal step.
void frecps(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP reciprocal estimate.
void frecpe(const VRegister& vd, const VRegister& vn);
// FP reciprocal square root estimate.
void frsqrte(const VRegister& vd, const VRegister& vn);
// FP reciprocal square root step.
void frsqrts(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed absolute difference and accumulate long.
void sabal(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed absolute difference and accumulate long (second part).
void sabal2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned absolute difference and accumulate long.
void uabal(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned absolute difference and accumulate long (second part).
void uabal2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed absolute difference long.
void sabdl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed absolute difference long (second part).
void sabdl2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned absolute difference long.
void uabdl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned absolute difference long (second part).
void uabdl2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Polynomial multiply long.
void pmull(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Polynomial multiply long (second part).
void pmull2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed long multiply-add.
void smlal(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed long multiply-add (second part).
void smlal2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned long multiply-add.
void umlal(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned long multiply-add (second part).
void umlal2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed long multiply-sub.
void smlsl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed long multiply-sub (second part).
void smlsl2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned long multiply-sub.
void umlsl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned long multiply-sub (second part).
void umlsl2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed long multiply.
void smull(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed long multiply (second part).
void smull2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed saturating doubling long multiply-add.
void sqdmlal(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed saturating doubling long multiply-add (second part).
void sqdmlal2(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned absolute difference.
void uabd(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed absolute difference and accumulate.
void saba(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP instructions.
// Move immediate to FP register.
void fmov(const VRegister& fd, double imm);
void fmov(const VRegister& fd, float imm);
// Move FP register to register.
void fmov(const Register& rd, const VRegister& fn);
// Move register to FP register.
void fmov(const VRegister& fd, const Register& rn);
// Move FP register to FP register.
void fmov(const VRegister& fd, const VRegister& fn);
// Move 64-bit register to top half of 128-bit FP register.
void fmov(const VRegister& vd, int index, const Register& rn);
// Move top half of 128-bit FP register to 64-bit register.
void fmov(const Register& rd, const VRegister& vn, int index);
// FP add.
void fadd(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP subtract.
void fsub(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP multiply.
void fmul(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP compare equal to zero.
void fcmeq(const VRegister& vd, const VRegister& vn, double imm);
// FP greater than zero.
void fcmgt(const VRegister& vd, const VRegister& vn, double imm);
// FP greater than or equal to zero.
void fcmge(const VRegister& vd, const VRegister& vn, double imm);
// FP less than or equal to zero.
void fcmle(const VRegister& vd, const VRegister& vn, double imm);
// FP less than to zero.
void fcmlt(const VRegister& vd, const VRegister& vn, double imm);
// FP absolute difference.
void fabd(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP pairwise add vector.
void faddp(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP pairwise add scalar.
void faddp(const VRegister& vd, const VRegister& vn);
// FP pairwise maximum scalar.
void fmaxp(const VRegister& vd, const VRegister& vn);
// FP pairwise maximum number scalar.
void fmaxnmp(const VRegister& vd, const VRegister& vn);
// FP pairwise minimum number scalar.
void fminnmp(const VRegister& vd, const VRegister& vn);
// FP vector multiply accumulate.
void fmla(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP vector multiply subtract.
void fmls(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP vector multiply extended.
void fmulx(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP absolute greater than or equal.
void facge(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP absolute greater than.
void facgt(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP multiply by element.
void fmul(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// FP fused multiply-add to accumulator by element.
void fmla(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// FP fused multiply-sub from accumulator by element.
void fmls(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// FP multiply extended by element.
void fmulx(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int vm_index);
// FP compare equal.
void fcmeq(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP greater than.
void fcmgt(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP greater than or equal.
void fcmge(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP pairwise maximum vector.
void fmaxp(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP pairwise minimum vector.
void fminp(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP pairwise minimum scalar.
void fminp(const VRegister& vd, const VRegister& vn);
// FP pairwise maximum number vector.
void fmaxnmp(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP pairwise minimum number vector.
void fminnmp(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP fused multiply-add.
void fmadd(const VRegister& vd, const VRegister& vn, const VRegister& vm,
const VRegister& va);
// FP fused multiply-subtract.
void fmsub(const VRegister& vd, const VRegister& vn, const VRegister& vm,
const VRegister& va);
// FP fused multiply-add and negate.
void fnmadd(const VRegister& vd, const VRegister& vn, const VRegister& vm,
const VRegister& va);
// FP fused multiply-subtract and negate.
void fnmsub(const VRegister& vd, const VRegister& vn, const VRegister& vm,
const VRegister& va);
// FP multiply-negate scalar.
void fnmul(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP reciprocal exponent scalar.
void frecpx(const VRegister& vd, const VRegister& vn);
// FP divide.
void fdiv(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP maximum.
void fmax(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP minimum.
void fmin(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP maximum.
void fmaxnm(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP minimum.
void fminnm(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// FP absolute.
void fabs(const VRegister& vd, const VRegister& vn);
// FP negate.
void fneg(const VRegister& vd, const VRegister& vn);
// FP square root.
void fsqrt(const VRegister& vd, const VRegister& vn);
// FP round to integer nearest with ties to away.
void frinta(const VRegister& vd, const VRegister& vn);
// FP round to integer, implicit rounding.
void frinti(const VRegister& vd, const VRegister& vn);
// FP round to integer toward minus infinity.
void frintm(const VRegister& vd, const VRegister& vn);
// FP round to integer nearest with ties to even.
void frintn(const VRegister& vd, const VRegister& vn);
// FP round to integer towards plus infinity.
void frintp(const VRegister& vd, const VRegister& vn);
// FP round to integer, exact, implicit rounding.
void frintx(const VRegister& vd, const VRegister& vn);
// FP round to integer towards zero.
void frintz(const VRegister& vd, const VRegister& vn);
// FP compare registers.
void fcmp(const VRegister& vn, const VRegister& vm);
// FP compare immediate.
void fcmp(const VRegister& vn, double value);
// FP conditional compare.
void fccmp(const VRegister& vn, const VRegister& vm, StatusFlags nzcv,
Condition cond);
// FP conditional select.
void fcsel(const VRegister& vd, const VRegister& vn, const VRegister& vm,
Condition cond);
// Common FP Convert functions.
void NEONFPConvertToInt(const Register& rd, const VRegister& vn, Instr op);
void NEONFPConvertToInt(const VRegister& vd, const VRegister& vn, Instr op);
// FP convert between precisions.
void fcvt(const VRegister& vd, const VRegister& vn);
// FP convert to higher precision.
void fcvtl(const VRegister& vd, const VRegister& vn);
// FP convert to higher precision (second part).
void fcvtl2(const VRegister& vd, const VRegister& vn);
// FP convert to lower precision.
void fcvtn(const VRegister& vd, const VRegister& vn);
// FP convert to lower prevision (second part).
void fcvtn2(const VRegister& vd, const VRegister& vn);
// FP convert to lower precision, rounding to odd.
void fcvtxn(const VRegister& vd, const VRegister& vn);
// FP convert to lower precision, rounding to odd (second part).
void fcvtxn2(const VRegister& vd, const VRegister& vn);
// FP convert to signed integer, nearest with ties to away.
void fcvtas(const Register& rd, const VRegister& vn);
// FP convert to unsigned integer, nearest with ties to away.
void fcvtau(const Register& rd, const VRegister& vn);
// FP convert to signed integer, nearest with ties to away.
void fcvtas(const VRegister& vd, const VRegister& vn);
// FP convert to unsigned integer, nearest with ties to away.
void fcvtau(const VRegister& vd, const VRegister& vn);
// FP convert to signed integer, round towards -infinity.
void fcvtms(const Register& rd, const VRegister& vn);
// FP convert to unsigned integer, round towards -infinity.
void fcvtmu(const Register& rd, const VRegister& vn);
// FP convert to signed integer, round towards -infinity.
void fcvtms(const VRegister& vd, const VRegister& vn);
// FP convert to unsigned integer, round towards -infinity.
void fcvtmu(const VRegister& vd, const VRegister& vn);
// FP convert to signed integer, nearest with ties to even.
void fcvtns(const Register& rd, const VRegister& vn);
// FP convert to unsigned integer, nearest with ties to even.
void fcvtnu(const Register& rd, const VRegister& vn);
// FP convert to signed integer, nearest with ties to even.
void fcvtns(const VRegister& rd, const VRegister& vn);
// FP convert to unsigned integer, nearest with ties to even.
void fcvtnu(const VRegister& rd, const VRegister& vn);
// FP convert to signed integer or fixed-point, round towards zero.
void fcvtzs(const Register& rd, const VRegister& vn, int fbits = 0);
// FP convert to unsigned integer or fixed-point, round towards zero.
void fcvtzu(const Register& rd, const VRegister& vn, int fbits = 0);
// FP convert to signed integer or fixed-point, round towards zero.
void fcvtzs(const VRegister& vd, const VRegister& vn, int fbits = 0);
// FP convert to unsigned integer or fixed-point, round towards zero.
void fcvtzu(const VRegister& vd, const VRegister& vn, int fbits = 0);
// FP convert to signed integer, round towards +infinity.
void fcvtps(const Register& rd, const VRegister& vn);
// FP convert to unsigned integer, round towards +infinity.
void fcvtpu(const Register& rd, const VRegister& vn);
// FP convert to signed integer, round towards +infinity.
void fcvtps(const VRegister& vd, const VRegister& vn);
// FP convert to unsigned integer, round towards +infinity.
void fcvtpu(const VRegister& vd, const VRegister& vn);
// Convert signed integer or fixed point to FP.
void scvtf(const VRegister& fd, const Register& rn, int fbits = 0);
// Convert unsigned integer or fixed point to FP.
void ucvtf(const VRegister& fd, const Register& rn, int fbits = 0);
// Convert signed integer or fixed-point to FP.
void scvtf(const VRegister& fd, const VRegister& vn, int fbits = 0);
// Convert unsigned integer or fixed-point to FP.
void ucvtf(const VRegister& fd, const VRegister& vn, int fbits = 0);
// Extract vector from pair of vectors.
void ext(const VRegister& vd, const VRegister& vn, const VRegister& vm,
int index);
// Duplicate vector element to vector or scalar.
void dup(const VRegister& vd, const VRegister& vn, int vn_index);
// Duplicate general-purpose register to vector.
void dup(const VRegister& vd, const Register& rn);
// Insert vector element from general-purpose register.
void ins(const VRegister& vd, int vd_index, const Register& rn);
// Move general-purpose register to a vector element.
void mov(const VRegister& vd, int vd_index, const Register& rn);
// Unsigned move vector element to general-purpose register.
void umov(const Register& rd, const VRegister& vn, int vn_index);
// Move vector element to general-purpose register.
void mov(const Register& rd, const VRegister& vn, int vn_index);
// Move vector element to scalar.
void mov(const VRegister& vd, const VRegister& vn, int vn_index);
// Insert vector element from another vector element.
void ins(const VRegister& vd, int vd_index, const VRegister& vn,
int vn_index);
// Move vector element to another vector element.
void mov(const VRegister& vd, int vd_index, const VRegister& vn,
int vn_index);
// Signed move vector element to general-purpose register.
void smov(const Register& rd, const VRegister& vn, int vn_index);
// One-element structure load to one register.
void ld1(const VRegister& vt, const MemOperand& src);
// One-element structure load to two registers.
void ld1(const VRegister& vt, const VRegister& vt2, const MemOperand& src);
// One-element structure load to three registers.
void ld1(const VRegister& vt, const VRegister& vt2, const VRegister& vt3,
const MemOperand& src);
// One-element structure load to four registers.
void ld1(const VRegister& vt, const VRegister& vt2, const VRegister& vt3,
const VRegister& vt4, const MemOperand& src);
// One-element single structure load to one lane.
void ld1(const VRegister& vt, int lane, const MemOperand& src);
// One-element single structure load to all lanes.
void ld1r(const VRegister& vt, const MemOperand& src);
// Two-element structure load.
void ld2(const VRegister& vt, const VRegister& vt2, const MemOperand& src);
// Two-element single structure load to one lane.
void ld2(const VRegister& vt, const VRegister& vt2, int lane,
const MemOperand& src);
// Two-element single structure load to all lanes.
void ld2r(const VRegister& vt, const VRegister& vt2, const MemOperand& src);
// Three-element structure load.
void ld3(const VRegister& vt, const VRegister& vt2, const VRegister& vt3,
const MemOperand& src);
// Three-element single structure load to one lane.
void ld3(const VRegister& vt, const VRegister& vt2, const VRegister& vt3,
int lane, const MemOperand& src);
// Three-element single structure load to all lanes.
void ld3r(const VRegister& vt, const VRegister& vt2, const VRegister& vt3,
const MemOperand& src);
// Four-element structure load.
void ld4(const VRegister& vt, const VRegister& vt2, const VRegister& vt3,
const VRegister& vt4, const MemOperand& src);
// Four-element single structure load to one lane.
void ld4(const VRegister& vt, const VRegister& vt2, const VRegister& vt3,
const VRegister& vt4, int lane, const MemOperand& src);
// Four-element single structure load to all lanes.
void ld4r(const VRegister& vt, const VRegister& vt2, const VRegister& vt3,
const VRegister& vt4, const MemOperand& src);
// Count leading sign bits.
void cls(const VRegister& vd, const VRegister& vn);
// Count leading zero bits (vector).
void clz(const VRegister& vd, const VRegister& vn);
// Population count per byte.
void cnt(const VRegister& vd, const VRegister& vn);
// Reverse bit order.
void rbit(const VRegister& vd, const VRegister& vn);
// Reverse elements in 16-bit halfwords.
void rev16(const VRegister& vd, const VRegister& vn);
// Reverse elements in 32-bit words.
void rev32(const VRegister& vd, const VRegister& vn);
// Reverse elements in 64-bit doublewords.
void rev64(const VRegister& vd, const VRegister& vn);
// Unsigned reciprocal square root estimate.
void ursqrte(const VRegister& vd, const VRegister& vn);
// Unsigned reciprocal estimate.
void urecpe(const VRegister& vd, const VRegister& vn);
// Signed pairwise long add and accumulate.
void sadalp(const VRegister& vd, const VRegister& vn);
// Signed pairwise long add.
void saddlp(const VRegister& vd, const VRegister& vn);
// Unsigned pairwise long add.
void uaddlp(const VRegister& vd, const VRegister& vn);
// Unsigned pairwise long add and accumulate.
void uadalp(const VRegister& vd, const VRegister& vn);
// Shift left by immediate.
void shl(const VRegister& vd, const VRegister& vn, int shift);
// Signed saturating shift left by immediate.
void sqshl(const VRegister& vd, const VRegister& vn, int shift);
// Signed saturating shift left unsigned by immediate.
void sqshlu(const VRegister& vd, const VRegister& vn, int shift);
// Unsigned saturating shift left by immediate.
void uqshl(const VRegister& vd, const VRegister& vn, int shift);
// Signed shift left long by immediate.
void sshll(const VRegister& vd, const VRegister& vn, int shift);
// Signed shift left long by immediate (second part).
void sshll2(const VRegister& vd, const VRegister& vn, int shift);
// Signed extend long.
void sxtl(const VRegister& vd, const VRegister& vn);
// Signed extend long (second part).
void sxtl2(const VRegister& vd, const VRegister& vn);
// Unsigned shift left long by immediate.
void ushll(const VRegister& vd, const VRegister& vn, int shift);
// Unsigned shift left long by immediate (second part).
void ushll2(const VRegister& vd, const VRegister& vn, int shift);
// Shift left long by element size.
void shll(const VRegister& vd, const VRegister& vn, int shift);
// Shift left long by element size (second part).
void shll2(const VRegister& vd, const VRegister& vn, int shift);
// Unsigned extend long.
void uxtl(const VRegister& vd, const VRegister& vn);
// Unsigned extend long (second part).
void uxtl2(const VRegister& vd, const VRegister& vn);
// Signed rounding halving add.
void srhadd(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned halving sub.
void uhsub(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed halving sub.
void shsub(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned saturating add.
void uqadd(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed saturating add.
void sqadd(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Unsigned saturating subtract.
void uqsub(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Signed saturating subtract.
void sqsub(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Add pairwise.
void addp(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Add pair of elements scalar.
void addp(const VRegister& vd, const VRegister& vn);
// Multiply-add to accumulator.
void mla(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Multiply-subtract to accumulator.
void mls(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Multiply.
void mul(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Table lookup from one register.
void tbl(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Table lookup from two registers.
void tbl(const VRegister& vd, const VRegister& vn, const VRegister& vn2,
const VRegister& vm);
// Table lookup from three registers.
void tbl(const VRegister& vd, const VRegister& vn, const VRegister& vn2,
const VRegister& vn3, const VRegister& vm);
// Table lookup from four registers.
void tbl(const VRegister& vd, const VRegister& vn, const VRegister& vn2,
const VRegister& vn3, const VRegister& vn4, const VRegister& vm);
// Table lookup extension from one register.
void tbx(const VRegister& vd, const VRegister& vn, const VRegister& vm);
// Table lookup extension from two registers.
void tbx(const VRegister& vd, const VRegister& vn, const VRegister& vn2,
const VRegister& vm);
// Table lookup extension from three registers.
void tbx(const VRegister& vd, const VRegister& vn, const VRegister& vn2,
const VRegister& vn3, const VRegister& vm);
// Table lookup extension from four registers.
void tbx(const VRegister& vd, const VRegister& vn, const VRegister& vn2,
const VRegister& vn3, const VRegister& vn4, const VRegister& vm);
// Instruction functions used only for test, debug, and patching.
// Emit raw instructions in the instruction stream.
void dci(Instr raw_inst) { Emit(raw_inst); }
// Emit 8 bits of data in the instruction stream.
void dc8(uint8_t data) { EmitData(&data, sizeof(data)); }
// Emit 32 bits of data in the instruction stream.
void dc32(uint32_t data) { EmitData(&data, sizeof(data)); }
// Emit 64 bits of data in the instruction stream.
void dc64(uint64_t data) { EmitData(&data, sizeof(data)); }
// Emit an address in the instruction stream.
void dcptr(Label* label);
// Copy a string into the instruction stream, including the terminating
// nullptr character. The instruction pointer (pc_) is then aligned correctly
// for subsequent instructions.
void EmitStringData(const char* string);
// Pseudo-instructions ------------------------------------------------------
// Parameters are described in arm64/instructions-arm64.h.
void debug(const char* message, uint32_t code, Instr params = BREAK);
// Required by V8.
void dd(uint32_t data) { dc32(data); }
void db(uint8_t data) { dc8(data); }
void dq(uint64_t data) { dc64(data); }
void dp(uintptr_t data) { dc64(data); }
// Code generation helpers --------------------------------------------------
Instruction* pc() const { return Instruction::Cast(pc_); }
Instruction* InstructionAt(ptrdiff_t offset) const {
return reinterpret_cast<Instruction*>(buffer_start_ + offset);
}
ptrdiff_t InstructionOffset(Instruction* instr) const {
return reinterpret_cast<byte*>(instr) - buffer_start_;
}
// Register encoding.
static Instr Rd(CPURegister rd) {
DCHECK_NE(rd.code(), kSPRegInternalCode);
return rd.code() << Rd_offset;
}
static Instr Rn(CPURegister rn) {
DCHECK_NE(rn.code(), kSPRegInternalCode);
return rn.code() << Rn_offset;
}
static Instr Rm(CPURegister rm) {
DCHECK_NE(rm.code(), kSPRegInternalCode);
return rm.code() << Rm_offset;
}
static Instr RmNot31(CPURegister rm) {
DCHECK_NE(rm.code(), kSPRegInternalCode);
DCHECK(!rm.IsZero());
return Rm(rm);
}
static Instr Ra(CPURegister ra) {
DCHECK_NE(ra.code(), kSPRegInternalCode);
return ra.code() << Ra_offset;
}
static Instr Rt(CPURegister rt) {
DCHECK_NE(rt.code(), kSPRegInternalCode);
return rt.code() << Rt_offset;
}
static Instr Rt2(CPURegister rt2) {
DCHECK_NE(rt2.code(), kSPRegInternalCode);
return rt2.code() << Rt2_offset;
}
static Instr Rs(CPURegister rs) {
DCHECK_NE(rs.code(), kSPRegInternalCode);
return rs.code() << Rs_offset;
}
// These encoding functions allow the stack pointer to be encoded, and
// disallow the zero register.
static Instr RdSP(Register rd) {
DCHECK(!rd.IsZero());
return (rd.code() & kRegCodeMask) << Rd_offset;
}
static Instr RnSP(Register rn) {
DCHECK(!rn.IsZero());
return (rn.code() & kRegCodeMask) << Rn_offset;
}
// Flags encoding.
inline static Instr Flags(FlagsUpdate S);
inline static Instr Cond(Condition cond);
// PC-relative address encoding.
inline static Instr ImmPCRelAddress(int imm21);
// Branch encoding.
inline static Instr ImmUncondBranch(int imm26);
inline static Instr ImmCondBranch(int imm19);
inline static Instr ImmCmpBranch(int imm19);
inline static Instr ImmTestBranch(int imm14);
inline static Instr ImmTestBranchBit(unsigned bit_pos);
// Data Processing encoding.
inline static Instr SF(Register rd);
inline static Instr ImmAddSub(int imm);
inline static Instr ImmS(unsigned imms, unsigned reg_size);
inline static Instr ImmR(unsigned immr, unsigned reg_size);
inline static Instr ImmSetBits(unsigned imms, unsigned reg_size);
inline static Instr ImmRotate(unsigned immr, unsigned reg_size);
inline static Instr ImmLLiteral(int imm19);
inline static Instr BitN(unsigned bitn, unsigned reg_size);
inline static Instr ShiftDP(Shift shift);
inline static Instr ImmDPShift(unsigned amount);
inline static Instr ExtendMode(Extend extend);
inline static Instr ImmExtendShift(unsigned left_shift);
inline static Instr ImmCondCmp(unsigned imm);
inline static Instr Nzcv(StatusFlags nzcv);
static bool IsImmAddSub(int64_t immediate);
static bool IsImmLogical(uint64_t value, unsigned width, unsigned* n,
unsigned* imm_s, unsigned* imm_r);
// MemOperand offset encoding.
inline static Instr ImmLSUnsigned(int imm12);
inline static Instr ImmLS(int imm9);
inline static Instr ImmLSPair(int imm7, unsigned size);
inline static Instr ImmShiftLS(unsigned shift_amount);
inline static Instr ImmException(int imm16);
inline static Instr ImmSystemRegister(int imm15);
inline static Instr ImmHint(int imm7);
inline static Instr ImmBarrierDomain(int imm2);
inline static Instr ImmBarrierType(int imm2);
inline static unsigned CalcLSDataSize(LoadStoreOp op);
// Instruction bits for vector format in data processing operations.
static Instr VFormat(VRegister vd) {
if (vd.Is64Bits()) {
switch (vd.LaneCount()) {
case 2:
return NEON_2S;
case 4:
return NEON_4H;
case 8:
return NEON_8B;
default:
UNREACHABLE();
}
} else {
DCHECK(vd.Is128Bits());
switch (vd.LaneCount()) {
case 2:
return NEON_2D;
case 4:
return NEON_4S;
case 8:
return NEON_8H;
case 16:
return NEON_16B;
default:
UNREACHABLE();
}
}
}
// Instruction bits for vector format in floating point data processing
// operations.
static Instr FPFormat(VRegister vd) {
if (vd.LaneCount() == 1) {
// Floating point scalar formats.
DCHECK(vd.Is32Bits() || vd.Is64Bits());
return vd.Is64Bits() ? FP64 : FP32;
}
// Two lane floating point vector formats.
if (vd.LaneCount() == 2) {
DCHECK(vd.Is64Bits() || vd.Is128Bits());
return vd.Is128Bits() ? NEON_FP_2D : NEON_FP_2S;
}
// Four lane floating point vector format.
DCHECK((vd.LaneCount() == 4) && vd.Is128Bits());
return NEON_FP_4S;
}
// Instruction bits for vector format in load and store operations.
static Instr LSVFormat(VRegister vd) {
if (vd.Is64Bits()) {
switch (vd.LaneCount()) {
case 1:
return LS_NEON_1D;
case 2:
return LS_NEON_2S;
case 4:
return LS_NEON_4H;
case 8:
return LS_NEON_8B;
default:
UNREACHABLE();
}
} else {
DCHECK(vd.Is128Bits());
switch (vd.LaneCount()) {
case 2:
return LS_NEON_2D;
case 4:
return LS_NEON_4S;
case 8:
return LS_NEON_8H;
case 16:
return LS_NEON_16B;
default:
UNREACHABLE();
}
}
}
// Instruction bits for scalar format in data processing operations.
static Instr SFormat(VRegister vd) {
DCHECK(vd.IsScalar());
switch (vd.SizeInBytes()) {
case 1:
return NEON_B;
case 2:
return NEON_H;
case 4:
return NEON_S;
case 8:
return NEON_D;
default:
UNREACHABLE();
}
}
static Instr ImmNEONHLM(int index, int num_bits) {
int h, l, m;
if (num_bits == 3) {
DCHECK(is_uint3(index));
h = (index >> 2) & 1;
l = (index >> 1) & 1;
m = (index >> 0) & 1;
} else if (num_bits == 2) {
DCHECK(is_uint2(index));
h = (index >> 1) & 1;
l = (index >> 0) & 1;
m = 0;
} else {
DCHECK(is_uint1(index) && (num_bits == 1));
h = (index >> 0) & 1;
l = 0;
m = 0;
}
return (h << NEONH_offset) | (l << NEONL_offset) | (m << NEONM_offset);
}
static Instr ImmNEONExt(int imm4) {
DCHECK(is_uint4(imm4));
return imm4 << ImmNEONExt_offset;
}
static Instr ImmNEON5(Instr format, int index) {
DCHECK(is_uint4(index));
int s = LaneSizeInBytesLog2FromFormat(static_cast<VectorFormat>(format));
int imm5 = (index << (s + 1)) | (1 << s);
return imm5 << ImmNEON5_offset;
}
static Instr ImmNEON4(Instr format, int index) {
DCHECK(is_uint4(index));
int s = LaneSizeInBytesLog2FromFormat(static_cast<VectorFormat>(format));
int imm4 = index << s;
return imm4 << ImmNEON4_offset;
}
static Instr ImmNEONabcdefgh(int imm8) {
DCHECK(is_uint8(imm8));
Instr instr;
instr = ((imm8 >> 5) & 7) << ImmNEONabc_offset;
instr |= (imm8 & 0x1f) << ImmNEONdefgh_offset;
return instr;
}
static Instr NEONCmode(int cmode) {
DCHECK(is_uint4(cmode));
return cmode << NEONCmode_offset;
}
static Instr NEONModImmOp(int op) {
DCHECK(is_uint1(op));
return op << NEONModImmOp_offset;
}
static bool IsImmLSUnscaled(int64_t offset);
static bool IsImmLSScaled(int64_t offset, unsigned size);
static bool IsImmLLiteral(int64_t offset);
// Move immediates encoding.
inline static Instr ImmMoveWide(int imm);
inline static Instr ShiftMoveWide(int shift);
// FP Immediates.
static Instr ImmFP(double imm);
static Instr ImmNEONFP(double imm);
inline static Instr FPScale(unsigned scale);
// FP register type.
inline static Instr FPType(VRegister fd);
// Unused on this architecture.
void MaybeEmitOutOfLineConstantPool() {}
void ForceConstantPoolEmissionWithoutJump() {
constpool_.Check(Emission::kForced, Jump::kOmitted);
}
void ForceConstantPoolEmissionWithJump() {
constpool_.Check(Emission::kForced, Jump::kRequired);
}
// Check if the const pool needs to be emitted while pretending that {margin}
// more bytes of instructions have already been emitted.
void EmitConstPoolWithJumpIfNeeded(size_t margin = 0) {
constpool_.Check(Emission::kIfNeeded, Jump::kRequired, margin);
}
// Returns true if we should emit a veneer as soon as possible for a branch
// which can at most reach to specified pc.
bool ShouldEmitVeneer(int max_reachable_pc,
size_t margin = kVeneerDistanceMargin);
bool ShouldEmitVeneers(size_t margin = kVeneerDistanceMargin) {
return ShouldEmitVeneer(unresolved_branches_first_limit(), margin);
}
// The maximum code size generated for a veneer. Currently one branch
// instruction. This is for code size checking purposes, and can be extended
// in the future for example if we decide to add nops between the veneers.
static constexpr int kMaxVeneerCodeSize = 1 * kInstrSize;
void RecordVeneerPool(int location_offset, int size);
// Emits veneers for branches that are approaching their maximum range.
// If need_protection is true, the veneers are protected by a branch jumping
// over the code.
void EmitVeneers(bool force_emit, bool need_protection,
size_t margin = kVeneerDistanceMargin);
void EmitVeneersGuard() { EmitPoolGuard(); }
// Checks whether veneers need to be emitted at this point.
// If force_emit is set, a veneer is generated for *all* unresolved branches.
void CheckVeneerPool(bool force_emit, bool require_jump,
size_t margin = kVeneerDistanceMargin);
using BlockConstPoolScope = ConstantPool::BlockScope;
class BlockPoolsScope {
public:
// Block veneer and constant pool. Emits pools if necessary to ensure that
// {margin} more bytes can be emitted without triggering pool emission.
explicit BlockPoolsScope(Assembler* assem, size_t margin = 0)
: assem_(assem), block_const_pool_(assem, margin) {
assem_->CheckVeneerPool(false, true, margin);
assem_->StartBlockVeneerPool();
}
BlockPoolsScope(Assembler* assem, PoolEmissionCheck check)
: assem_(assem), block_const_pool_(assem, check) {
assem_->StartBlockVeneerPool();
}
~BlockPoolsScope() { assem_->EndBlockVeneerPool(); }
private:
Assembler* assem_;
BlockConstPoolScope block_const_pool_;
DISALLOW_IMPLICIT_CONSTRUCTORS(BlockPoolsScope);
};
#if defined(V8_OS_WIN)
win64_unwindinfo::XdataEncoder* GetXdataEncoder() {
return xdata_encoder_.get();
}
win64_unwindinfo::BuiltinUnwindInfo GetUnwindInfo() const;
#endif
protected:
inline const Register& AppropriateZeroRegFor(const CPURegister& reg) const;
void LoadStore(const CPURegister& rt, const MemOperand& addr, LoadStoreOp op);
void LoadStorePair(const CPURegister& rt, const CPURegister& rt2,
const MemOperand& addr, LoadStorePairOp op);
void LoadStoreStruct(const VRegister& vt, const MemOperand& addr,
NEONLoadStoreMultiStructOp op);
void LoadStoreStruct1(const VRegister& vt, int reg_count,
const MemOperand& addr);
void LoadStoreStructSingle(const VRegister& vt, uint32_t lane,
const MemOperand& addr,
NEONLoadStoreSingleStructOp op);
void LoadStoreStructSingleAllLanes(const VRegister& vt,
const MemOperand& addr,
NEONLoadStoreSingleStructOp op);
void LoadStoreStructVerify(const VRegister& vt, const MemOperand& addr,
Instr op);
static bool IsImmLSPair(int64_t offset, unsigned size);
void Logical(const Register& rd, const Register& rn, const Operand& operand,
LogicalOp op);
void LogicalImmediate(const Register& rd, const Register& rn, unsigned n,
unsigned imm_s, unsigned imm_r, LogicalOp op);
void ConditionalCompare(const Register& rn, const Operand& operand,
StatusFlags nzcv, Condition cond,
ConditionalCompareOp op);
static bool IsImmConditionalCompare(int64_t immediate);
void AddSubWithCarry(const Register& rd, const Register& rn,
const Operand& operand, FlagsUpdate S,
AddSubWithCarryOp op);
// Functions for emulating operands not directly supported by the instruction
// set.
void EmitShift(const Register& rd, const Register& rn, Shift shift,
unsigned amount);
void EmitExtendShift(const Register& rd, const Register& rn, Extend extend,
unsigned left_shift);
void AddSub(const Register& rd, const Register& rn, const Operand& operand,
FlagsUpdate S, AddSubOp op);
static bool IsImmFP32(float imm);
static bool IsImmFP64(double imm);
// Find an appropriate LoadStoreOp or LoadStorePairOp for the specified
// registers. Only simple loads are supported; sign- and zero-extension (such
// as in LDPSW_x or LDRB_w) are not supported.
static inline LoadStoreOp LoadOpFor(const CPURegister& rt);
static inline LoadStorePairOp LoadPairOpFor(const CPURegister& rt,
const CPURegister& rt2);
static inline LoadStoreOp StoreOpFor(const CPURegister& rt);
static inline LoadStorePairOp StorePairOpFor(const CPURegister& rt,
const CPURegister& rt2);
static inline LoadLiteralOp LoadLiteralOpFor(const CPURegister& rt);
// Remove the specified branch from the unbound label link chain.
// If available, a veneer for this label can be used for other branches in the
// chain if the link chain cannot be fixed up without this branch.
void RemoveBranchFromLabelLinkChain(Instruction* branch, Label* label,
Instruction* label_veneer = nullptr);
private:
static uint32_t FPToImm8(double imm);
// Instruction helpers.
void MoveWide(const Register& rd, uint64_t imm, int shift,
MoveWideImmediateOp mov_op);
void DataProcShiftedRegister(const Register& rd, const Register& rn,
const Operand& operand, FlagsUpdate S, Instr op);
void DataProcExtendedRegister(const Register& rd, const Register& rn,
const Operand& operand, FlagsUpdate S,
Instr op);
void ConditionalSelect(const Register& rd, const Register& rn,
const Register& rm, Condition cond,
ConditionalSelectOp op);
void DataProcessing1Source(const Register& rd, const Register& rn,
DataProcessing1SourceOp op);
void DataProcessing3Source(const Register& rd, const Register& rn,
const Register& rm, const Register& ra,
DataProcessing3SourceOp op);
void FPDataProcessing1Source(const VRegister& fd, const VRegister& fn,
FPDataProcessing1SourceOp op);
void FPDataProcessing2Source(const VRegister& fd, const VRegister& fn,
const VRegister& fm,
FPDataProcessing2SourceOp op);
void FPDataProcessing3Source(const VRegister& fd, const VRegister& fn,
const VRegister& fm, const VRegister& fa,
FPDataProcessing3SourceOp op);
void NEONAcrossLanesL(const VRegister& vd, const VRegister& vn,
NEONAcrossLanesOp op);
void NEONAcrossLanes(const VRegister& vd, const VRegister& vn,
NEONAcrossLanesOp op);
void NEONModifiedImmShiftLsl(const VRegister& vd, const int imm8,
const int left_shift,
NEONModifiedImmediateOp op);
void NEONModifiedImmShiftMsl(const VRegister& vd, const int imm8,
const int shift_amount,
NEONModifiedImmediateOp op);
void NEON3Same(const VRegister& vd, const VRegister& vn, const VRegister& vm,
NEON3SameOp vop);
void NEONFP3Same(const VRegister& vd, const VRegister& vn,
const VRegister& vm, Instr op);
void NEON3DifferentL(const VRegister& vd, const VRegister& vn,
const VRegister& vm, NEON3DifferentOp vop);
void NEON3DifferentW(const VRegister& vd, const VRegister& vn,
const VRegister& vm, NEON3DifferentOp vop);
void NEON3DifferentHN(const VRegister& vd, const VRegister& vn,
const VRegister& vm, NEON3DifferentOp vop);
void NEONFP2RegMisc(const VRegister& vd, const VRegister& vn,
NEON2RegMiscOp vop, double value = 0.0);
void NEON2RegMisc(const VRegister& vd, const VRegister& vn,
NEON2RegMiscOp vop, int value = 0);
void NEONFP2RegMisc(const VRegister& vd, const VRegister& vn, Instr op);
void NEONAddlp(const VRegister& vd, const VRegister& vn, NEON2RegMiscOp op);
void NEONPerm(const VRegister& vd, const VRegister& vn, const VRegister& vm,
NEONPermOp op);
void NEONFPByElement(const VRegister& vd, const VRegister& vn,
const VRegister& vm, int vm_index,
NEONByIndexedElementOp op);
void NEONByElement(const VRegister& vd, const VRegister& vn,
const VRegister& vm, int vm_index,
NEONByIndexedElementOp op);
void NEONByElementL(const VRegister& vd, const VRegister& vn,
const VRegister& vm, int vm_index,
NEONByIndexedElementOp op);
void NEONShiftImmediate(const VRegister& vd, const VRegister& vn,
NEONShiftImmediateOp op, int immh_immb);
void NEONShiftLeftImmediate(const VRegister& vd, const VRegister& vn,
int shift, NEONShiftImmediateOp op);
void NEONShiftRightImmediate(const VRegister& vd, const VRegister& vn,
int shift, NEONShiftImmediateOp op);
void NEONShiftImmediateL(const VRegister& vd, const VRegister& vn, int shift,
NEONShiftImmediateOp op);
void NEONShiftImmediateN(const VRegister& vd, const VRegister& vn, int shift,
NEONShiftImmediateOp op);
void NEONXtn(const VRegister& vd, const VRegister& vn, NEON2RegMiscOp vop);
void NEONTable(const VRegister& vd, const VRegister& vn, const VRegister& vm,
NEONTableOp op);
Instr LoadStoreStructAddrModeField(const MemOperand& addr);
// Label helpers.
// Return an offset for a label-referencing instruction, typically a branch.
int LinkAndGetByteOffsetTo(Label* label);
// This is the same as LinkAndGetByteOffsetTo, but return an offset
// suitable for fields that take instruction offsets.
inline int LinkAndGetInstructionOffsetTo(Label* label);
static constexpr int kStartOfLabelLinkChain = 0;
// Verify that a label's link chain is intact.
void CheckLabelLinkChain(Label const* label);
// Emit the instruction at pc_.
void Emit(Instr instruction) {
STATIC_ASSERT(sizeof(*pc_) == 1);
STATIC_ASSERT(sizeof(instruction) == kInstrSize);
DCHECK_LE(pc_ + sizeof(instruction), buffer_start_ + buffer_->size());
memcpy(pc_, &instruction, sizeof(instruction));
pc_ += sizeof(instruction);
CheckBuffer();
}
// Emit data inline in the instruction stream.
void EmitData(void const* data, unsigned size) {
DCHECK_EQ(sizeof(*pc_), 1);
DCHECK_LE(pc_ + size, buffer_start_ + buffer_->size());
// TODO(all): Somehow register we have some data here. Then we can
// disassemble it correctly.
memcpy(pc_, data, size);
pc_ += size;
CheckBuffer();
}
void GrowBuffer();
void CheckBufferSpace();
void CheckBuffer();
// Emission of the veneer pools may be blocked in some code sequences.
int veneer_pool_blocked_nesting_; // Block emission if this is not zero.
// Relocation info generation
// Each relocation is encoded as a variable size value
static constexpr int kMaxRelocSize = RelocInfoWriter::kMaxSize;
RelocInfoWriter reloc_info_writer;
// Internal reference positions, required for (potential) patching in
// GrowBuffer(); contains only those internal references whose labels
// are already bound.
std::deque<int> internal_reference_positions_;
protected:
// Code generation
// The relocation writer's position is at least kGap bytes below the end of
// the generated instructions. This is so that multi-instruction sequences do
// not have to check for overflow. The same is true for writes of large
// relocation info entries, and debug strings encoded in the instruction
// stream.
static constexpr int kGap = 128;
public:
#ifdef DEBUG
// Functions used for testing.
size_t GetConstantPoolEntriesSizeForTesting() const {
// Do not include branch over the pool.
return constpool_.Entry32Count() * kInt32Size +
constpool_.Entry64Count() * kInt64Size;
}
static size_t GetCheckConstPoolIntervalForTesting() {
return ConstantPool::kCheckInterval;
}
static size_t GetApproxMaxDistToConstPoolForTesting() {
return ConstantPool::kApproxDistToPool64;
}
#endif
class FarBranchInfo {
public:
FarBranchInfo(int offset, Label* label)
: pc_offset_(offset), label_(label) {}
// Offset of the branch in the code generation buffer.
int pc_offset_;
// The label branched to.
Label* label_;
};
protected:
// Information about unresolved (forward) branches.
// The Assembler is only allowed to delete out-of-date information from here
// after a label is bound. The MacroAssembler uses this information to
// generate veneers.
//
// The second member gives information about the unresolved branch. The first
// member of the pair is the maximum offset that the branch can reach in the
// buffer. The map is sorted according to this reachable offset, allowing to
// easily check when veneers need to be emitted.
// Note that the maximum reachable offset (first member of the pairs) should
// always be positive but has the same type as the return value for
// pc_offset() for convenience.
std::multimap<int, FarBranchInfo> unresolved_branches_;
// We generate a veneer for a branch if we reach within this distance of the
// limit of the range.
static constexpr int kVeneerDistanceMargin = 1 * KB;
// The factor of 2 is a finger in the air guess. With a default margin of
// 1KB, that leaves us an addional 256 instructions to avoid generating a
// protective branch.
static constexpr int kVeneerNoProtectionFactor = 2;
static constexpr int kVeneerDistanceCheckMargin =
kVeneerNoProtectionFactor * kVeneerDistanceMargin;
int unresolved_branches_first_limit() const {
DCHECK(!unresolved_branches_.empty());
return unresolved_branches_.begin()->first;
}
// This PC-offset of the next veneer pool check helps reduce the overhead
// of checking for veneer pools.
// It is maintained to the closest unresolved branch limit minus the maximum
// veneer margin (or kMaxInt if there are no unresolved branches).
int next_veneer_pool_check_;
#if defined(V8_OS_WIN)
std::unique_ptr<win64_unwindinfo::XdataEncoder> xdata_encoder_;
#endif
private:
// Avoid overflows for displacements etc.
static const int kMaximalBufferSize = 512 * MB;
// If a veneer is emitted for a branch instruction, that instruction must be
// removed from the associated label's link chain so that the assembler does
// not later attempt (likely unsuccessfully) to patch it to branch directly to
// the label.
void DeleteUnresolvedBranchInfoForLabel(Label* label);
// This function deletes the information related to the label by traversing
// the label chain, and for each PC-relative instruction in the chain checking
// if pending unresolved information exists. Its complexity is proportional to
// the length of the label chain.
void DeleteUnresolvedBranchInfoForLabelTraverse(Label* label);
void AllocateAndInstallRequestedHeapObjects(Isolate* isolate);
int WriteCodeComments();
// The pending constant pool.
ConstantPool constpool_;
friend class EnsureSpace;
friend class ConstantPool;
};
class PatchingAssembler : public Assembler {
public:
// Create an Assembler with a buffer starting at 'start'.
// The buffer size is
// size of instructions to patch + kGap
// Where kGap is the distance from which the Assembler tries to grow the
// buffer.
// If more or fewer instructions than expected are generated or if some
// relocation information takes space in the buffer, the PatchingAssembler
// will crash trying to grow the buffer.
// Note that the instruction cache will not be flushed.
PatchingAssembler(const AssemblerOptions& options, byte* start,
unsigned count)
: Assembler(options,
ExternalAssemblerBuffer(start, count * kInstrSize + kGap)),
block_constant_pool_emission_scope(this) {}
~PatchingAssembler() {
// Verify we have generated the number of instruction we expected.
DCHECK_EQ(pc_offset() + kGap, buffer_->size());
}
// See definition of PatchAdrFar() for details.
static constexpr int kAdrFarPatchableNNops = 2;
static constexpr int kAdrFarPatchableNInstrs = kAdrFarPatchableNNops + 2;
void PatchAdrFar(int64_t target_offset);
void PatchSubSp(uint32_t immediate);
private:
BlockPoolsScope block_constant_pool_emission_scope;
};
class EnsureSpace {
public:
explicit EnsureSpace(Assembler* assembler) : block_pools_scope_(assembler) {
assembler->CheckBufferSpace();
}
private:
Assembler::BlockPoolsScope block_pools_scope_;
};
} // namespace internal
} // namespace v8
#endif // V8_CODEGEN_ARM64_ASSEMBLER_ARM64_H_
|
hamzahamidi/v8
|
src/objects/synthetic-module.h
|
<reponame>hamzahamidi/v8
// Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_OBJECTS_SYNTHETIC_MODULE_H_
#define V8_OBJECTS_SYNTHETIC_MODULE_H_
#include "src/objects/module.h"
// Has to be the last include (doesn't have include guards):
#include "src/objects/object-macros.h"
namespace v8 {
namespace internal {
// The runtime representation of a Synthetic Module Record, a module that can be
// instantiated by an embedder with embedder-defined exports and evaluation
// steps.
// https://heycam.github.io/webidl/#synthetic-module-records
class SyntheticModule
: public TorqueGeneratedSyntheticModule<SyntheticModule, Module> {
public:
NEVER_READ_ONLY_SPACE
DECL_VERIFIER(SyntheticModule)
DECL_PRINTER(SyntheticModule)
static void SetExport(Isolate* isolate, Handle<SyntheticModule> module,
Handle<String> export_name,
Handle<Object> export_value);
using BodyDescriptor = SubclassBodyDescriptor<
Module::BodyDescriptor,
FixedBodyDescriptor<kExportNamesOffset, kSize, kSize>>;
private:
friend class Module;
static V8_WARN_UNUSED_RESULT MaybeHandle<Cell> ResolveExport(
Isolate* isolate, Handle<SyntheticModule> module,
Handle<String> module_specifier, Handle<String> export_name,
MessageLocation loc, bool must_resolve);
static V8_WARN_UNUSED_RESULT bool PrepareInstantiate(
Isolate* isolate, Handle<SyntheticModule> module,
v8::Local<v8::Context> context, v8::Module::ResolveCallback callback);
static V8_WARN_UNUSED_RESULT bool FinishInstantiate(
Isolate* isolate, Handle<SyntheticModule> module);
static V8_WARN_UNUSED_RESULT MaybeHandle<Object> Evaluate(
Isolate* isolate, Handle<SyntheticModule> module);
TQ_OBJECT_CONSTRUCTORS(SyntheticModule)
};
} // namespace internal
} // namespace v8
#include "src/objects/object-macros-undef.h"
#endif // V8_OBJECTS_SYNTHETIC_MODULE_H_
|
hamzahamidi/v8
|
src/objects/js-number-format.h
|
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_INTL_SUPPORT
#error Internationalization is expected to be enabled.
#endif // V8_INTL_SUPPORT
#ifndef V8_OBJECTS_JS_NUMBER_FORMAT_H_
#define V8_OBJECTS_JS_NUMBER_FORMAT_H_
#include <set>
#include <string>
#include "src/execution/isolate.h"
#include "src/heap/factory.h"
#include "src/objects/intl-objects.h"
#include "src/objects/managed.h"
#include "src/objects/objects.h"
// Has to be the last include (doesn't have include guards):
#include "src/objects/object-macros.h"
namespace U_ICU_NAMESPACE {
class UnicodeString;
namespace number {
class LocalizedNumberFormatter;
} // namespace number
} // namespace U_ICU_NAMESPACE
namespace v8 {
namespace internal {
class JSNumberFormat : public JSObject {
public:
// ecma402/#sec-initializenumberformat
V8_WARN_UNUSED_RESULT static MaybeHandle<JSNumberFormat> New(
Isolate* isolate, Handle<Map> map, Handle<Object> locales,
Handle<Object> options, const char* service);
// ecma402/#sec-unwrapnumberformat
V8_WARN_UNUSED_RESULT static MaybeHandle<JSNumberFormat> UnwrapNumberFormat(
Isolate* isolate, Handle<JSReceiver> format_holder);
// ecma402/#sec-intl.numberformat.prototype.resolvedoptions
static Handle<JSObject> ResolvedOptions(Isolate* isolate,
Handle<JSNumberFormat> number_format);
V8_WARN_UNUSED_RESULT static MaybeHandle<JSArray> FormatToParts(
Isolate* isolate, Handle<JSNumberFormat> number_format,
Handle<Object> numeric_obj);
V8_WARN_UNUSED_RESULT static MaybeHandle<String> FormatNumeric(
Isolate* isolate,
const icu::number::LocalizedNumberFormatter& number_format,
Handle<Object> numeric_obj);
V8_EXPORT_PRIVATE static const std::set<std::string>& GetAvailableLocales();
// Helper functions shared with JSPluralRules.
static int32_t MinimumIntegerDigitsFromSkeleton(
const icu::UnicodeString& skeleton);
static bool FractionDigitsFromSkeleton(const icu::UnicodeString& skeleton,
int32_t* minimum, int32_t* maximum);
static bool SignificantDigitsFromSkeleton(const icu::UnicodeString& skeleton,
int32_t* minimum, int32_t* maximum);
static icu::number::LocalizedNumberFormatter SetDigitOptionsToFormatter(
const icu::number::LocalizedNumberFormatter& icu_number_formatter,
const Intl::NumberFormatDigitOptions& digit_options);
DECL_CAST(JSNumberFormat)
DECL_PRINTER(JSNumberFormat)
DECL_VERIFIER(JSNumberFormat)
// [[Style]] is one of the values "decimal", "percent", "currency",
// or "unit" identifying the style of the number format.
// Note: "unit" is added in proposal-unified-intl-numberformat
enum class Style { DECIMAL, PERCENT, CURRENCY, UNIT };
inline void set_style(Style style);
inline Style style() const;
// Layout description.
DEFINE_FIELD_OFFSET_CONSTANTS(JSObject::kHeaderSize,
TORQUE_GENERATED_JSNUMBER_FORMAT_FIELDS)
// Bit positions in |flags|.
#define FLAGS_BIT_FIELDS(V, _) \
V(StyleBits, Style, 2, _)
DEFINE_BIT_FIELDS(FLAGS_BIT_FIELDS)
#undef FLAGS_BIT_FIELDS
STATIC_ASSERT(Style::DECIMAL <= StyleBits::kMax);
STATIC_ASSERT(Style::PERCENT <= StyleBits::kMax);
STATIC_ASSERT(Style::CURRENCY <= StyleBits::kMax);
STATIC_ASSERT(Style::UNIT <= StyleBits::kMax);
DECL_ACCESSORS(locale, String)
DECL_ACCESSORS(icu_number_formatter,
Managed<icu::number::LocalizedNumberFormatter>)
DECL_ACCESSORS(bound_format, Object)
DECL_INT_ACCESSORS(flags)
OBJECT_CONSTRUCTORS(JSNumberFormat, JSObject);
};
struct NumberFormatSpan {
int32_t field_id;
int32_t begin_pos;
int32_t end_pos;
NumberFormatSpan() = default;
NumberFormatSpan(int32_t field_id, int32_t begin_pos, int32_t end_pos)
: field_id(field_id), begin_pos(begin_pos), end_pos(end_pos) {}
};
V8_EXPORT_PRIVATE std::vector<NumberFormatSpan> FlattenRegionsToParts(
std::vector<NumberFormatSpan>* regions);
} // namespace internal
} // namespace v8
#include "src/objects/object-macros-undef.h"
#endif // V8_OBJECTS_JS_NUMBER_FORMAT_H_
|
hamzahamidi/v8
|
src/heap/invalidated-slots-inl.h
|
<gh_stars>1-10
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_HEAP_INVALIDATED_SLOTS_INL_H_
#define V8_HEAP_INVALIDATED_SLOTS_INL_H_
#include <map>
#include "src/heap/invalidated-slots.h"
#include "src/heap/spaces.h"
#include "src/objects/objects-body-descriptors-inl.h"
#include "src/objects/objects-body-descriptors.h"
#include "src/objects/objects.h"
#include "src/utils/allocation.h"
namespace v8 {
namespace internal {
bool InvalidatedSlotsFilter::IsValid(Address slot) {
#ifdef DEBUG
DCHECK_LT(slot, sentinel_);
// Slots must come in non-decreasing order.
DCHECK_LE(last_slot_, slot);
last_slot_ = slot;
#endif
if (slot < invalidated_start_) {
return true;
}
while (slot >= next_invalidated_start_) {
NextInvalidatedObject();
}
HeapObject invalidated_object = HeapObject::FromAddress(invalidated_start_);
if (invalidated_size_ == 0) {
invalidated_size_ = invalidated_object.Size();
}
int offset = static_cast<int>(slot - invalidated_start_);
DCHECK_GT(offset, 0);
if (offset < invalidated_size_)
return invalidated_object.IsValidSlot(invalidated_object.map(), offset);
NextInvalidatedObject();
return true;
}
void InvalidatedSlotsFilter::NextInvalidatedObject() {
invalidated_start_ = next_invalidated_start_;
invalidated_size_ = 0;
if (iterator_ == iterator_end_) {
next_invalidated_start_ = sentinel_;
} else {
next_invalidated_start_ = iterator_->address();
iterator_++;
}
}
void InvalidatedSlotsCleanup::Free(Address free_start, Address free_end) {
#ifdef DEBUG
DCHECK_LT(free_start, free_end);
// Free regions should come in increasing order and do not overlap
DCHECK_LE(last_free_, free_start);
last_free_ = free_start;
#endif
if (iterator_ == iterator_end_) return;
// Ignore invalidated objects that start before free region
while (invalidated_start_ < free_start) {
++iterator_;
NextInvalidatedObject();
}
// Remove all invalidated objects that start within
// free region.
while (invalidated_start_ < free_end) {
iterator_ = invalidated_slots_->erase(iterator_);
NextInvalidatedObject();
}
}
void InvalidatedSlotsCleanup::NextInvalidatedObject() {
if (iterator_ != iterator_end_) {
invalidated_start_ = iterator_->address();
} else {
invalidated_start_ = sentinel_;
}
}
} // namespace internal
} // namespace v8
#endif // V8_HEAP_INVALIDATED_SLOTS_INL_H_
|
hamzahamidi/v8
|
src/objects/feedback-cell.h
|
<gh_stars>1000+
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_OBJECTS_FEEDBACK_CELL_H_
#define V8_OBJECTS_FEEDBACK_CELL_H_
#include "src/objects/struct.h"
// Has to be the last include (doesn't have include guards):
#include "src/objects/object-macros.h"
namespace v8 {
namespace internal {
// This is a special cell used to maintain both the link between a
// closure and its feedback vector, as well as a way to count the
// number of closures created for a certain function per native
// context. There's at most one FeedbackCell for each function in
// a native context.
class FeedbackCell : public Struct {
public:
static int GetInitialInterruptBudget() {
if (FLAG_lazy_feedback_allocation) {
return FLAG_budget_for_feedback_vector_allocation;
}
return FLAG_interrupt_budget;
}
// [value]: value of the cell.
DECL_ACCESSORS(value, HeapObject)
DECL_INT32_ACCESSORS(interrupt_budget)
DECL_CAST(FeedbackCell)
// Dispatched behavior.
DECL_PRINTER(FeedbackCell)
DECL_VERIFIER(FeedbackCell)
// Layout description.
DEFINE_FIELD_OFFSET_CONSTANTS(HeapObject::kHeaderSize,
TORQUE_GENERATED_FEEDBACK_CELL_FIELDS)
static const int kUnalignedSize = kSize;
static const int kAlignedSize = RoundUp<kObjectAlignment>(int{kSize});
inline void clear_padding();
inline void reset();
using BodyDescriptor =
FixedBodyDescriptor<kValueOffset, kInterruptBudgetOffset, kAlignedSize>;
OBJECT_CONSTRUCTORS(FeedbackCell, Struct);
};
} // namespace internal
} // namespace v8
#include "src/objects/object-macros-undef.h"
#endif // V8_OBJECTS_FEEDBACK_CELL_H_
|
hamzahamidi/v8
|
src/torque/earley-parser.h
|
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_TORQUE_EARLEY_PARSER_H_
#define V8_TORQUE_EARLEY_PARSER_H_
#include <map>
#include <memory>
#include <vector>
#include "src/base/optional.h"
#include "src/torque/contextual.h"
#include "src/torque/source-positions.h"
#include "src/torque/utils.h"
namespace v8 {
namespace internal {
namespace torque {
class Symbol;
class Item;
class ParseResultHolderBase {
public:
enum class TypeId;
virtual ~ParseResultHolderBase() = default;
template <class T>
T& Cast();
template <class T>
const T& Cast() const;
protected:
explicit ParseResultHolderBase(TypeId type_id) : type_id_(type_id) {
// MSVC wrongly complains about type_id_ being an unused private field.
USE(type_id_);
}
private:
const TypeId type_id_;
};
enum class ParseResultHolderBase::TypeId {
kStdString,
kBool,
kStdVectorOfString,
kExpressionPtr,
kIdentifierPtr,
kOptionalIdentifierPtr,
kStatementPtr,
kDeclarationPtr,
kTypeExpressionPtr,
kOptionalTypeExpressionPtr,
kLabelBlockPtr,
kOptionalLabelBlockPtr,
kNameAndTypeExpression,
kImplicitParameters,
kOptionalImplicitParameters,
kNameAndExpression,
kAnnotation,
kVectorOfAnnotation,
kClassFieldExpression,
kStructFieldExpression,
kStdVectorOfNameAndTypeExpression,
kStdVectorOfNameAndExpression,
kStdVectorOfClassFieldExpression,
kStdVectorOfStructFieldExpression,
kIncrementDecrementOperator,
kOptionalStdString,
kStdVectorOfStatementPtr,
kStdVectorOfDeclarationPtr,
kStdVectorOfStdVectorOfDeclarationPtr,
kStdVectorOfExpressionPtr,
kExpressionWithSource,
kParameterList,
kTypeList,
kOptionalTypeList,
kLabelAndTypes,
kStdVectorOfLabelAndTypes,
kStdVectorOfLabelBlockPtr,
kOptionalStatementPtr,
kOptionalExpressionPtr,
kTypeswitchCase,
kStdVectorOfTypeswitchCase,
kStdVectorOfIdentifierPtr,
kJsonValue,
kJsonMember,
kStdVectorOfJsonValue,
kStdVectorOfJsonMember,
};
using ParseResultTypeId = ParseResultHolderBase::TypeId;
template <class T>
class ParseResultHolder : public ParseResultHolderBase {
public:
explicit ParseResultHolder(T value)
: ParseResultHolderBase(id), value_(std::move(value)) {}
private:
V8_EXPORT_PRIVATE static const TypeId id;
friend class ParseResultHolderBase;
T value_;
};
template <class T>
T& ParseResultHolderBase::Cast() {
CHECK_EQ(ParseResultHolder<T>::id, type_id_);
return static_cast<ParseResultHolder<T>*>(this)->value_;
}
template <class T>
const T& ParseResultHolderBase::Cast() const {
CHECK_EQ(ParseResultHolder<T>::id, type_id_);
return static_cast<const ParseResultHolder<T>*>(this)->value_;
}
class ParseResult {
public:
template <class T>
explicit ParseResult(T x) : value_(new ParseResultHolder<T>(std::move(x))) {}
template <class T>
const T& Cast() const& {
return value_->Cast<T>();
}
template <class T>
T& Cast() & {
return value_->Cast<T>();
}
template <class T>
T&& Cast() && {
return std::move(value_->Cast<T>());
}
private:
std::unique_ptr<ParseResultHolderBase> value_;
};
using InputPosition = const char*;
struct MatchedInput {
MatchedInput(InputPosition begin, InputPosition end, SourcePosition pos)
: begin(begin), end(end), pos(pos) {}
InputPosition begin;
InputPosition end;
SourcePosition pos;
std::string ToString() const { return {begin, end}; }
};
class ParseResultIterator {
public:
explicit ParseResultIterator(std::vector<ParseResult> results,
MatchedInput matched_input)
: results_(std::move(results)), matched_input_(matched_input) {}
~ParseResultIterator() {
// Check that all parse results have been used.
CHECK_EQ(results_.size(), i_);
}
ParseResult Next() {
CHECK_LT(i_, results_.size());
return std::move(results_[i_++]);
}
template <class T>
T NextAs() {
return std::move(Next().Cast<T>());
}
bool HasNext() const { return i_ < results_.size(); }
const MatchedInput& matched_input() const { return matched_input_; }
private:
std::vector<ParseResult> results_;
size_t i_ = 0;
MatchedInput matched_input_;
DISALLOW_COPY_AND_ASSIGN(ParseResultIterator);
};
struct LexerResult {
std::vector<Symbol*> token_symbols;
std::vector<MatchedInput> token_contents;
};
using Action =
base::Optional<ParseResult> (*)(ParseResultIterator* child_results);
inline base::Optional<ParseResult> DefaultAction(
ParseResultIterator* child_results) {
if (!child_results->HasNext()) return base::nullopt;
return child_results->Next();
}
template <class T, Action action>
inline Action AsSingletonVector() {
return [](ParseResultIterator* child_results) -> base::Optional<ParseResult> {
auto result = action(child_results);
if (!result) return result;
return ParseResult{std::vector<T>{(*result).Cast<T>()}};
};
}
// A rule of the context-free grammar. Each rule can have an action attached to
// it, which is executed after the parsing is finished.
class Rule final {
public:
explicit Rule(std::vector<Symbol*> right_hand_side,
Action action = DefaultAction)
: right_hand_side_(std::move(right_hand_side)), action_(action) {}
Symbol* left() const {
DCHECK_NOT_NULL(left_hand_side_);
return left_hand_side_;
}
const std::vector<Symbol*>& right() const { return right_hand_side_; }
void SetLeftHandSide(Symbol* left_hand_side) {
DCHECK_NULL(left_hand_side_);
left_hand_side_ = left_hand_side;
}
V8_EXPORT_PRIVATE base::Optional<ParseResult> RunAction(
const Item* completed_item, const LexerResult& tokens) const;
private:
Symbol* left_hand_side_ = nullptr;
std::vector<Symbol*> right_hand_side_;
Action action_;
};
// A Symbol represents a terminal or a non-terminal of the grammar.
// It stores the list of rules, which have this symbol as the
// left-hand side.
// Terminals have an empty list of rules, they are created by the Lexer
// instead of from rules.
// Symbols need to reside at stable memory addresses, because the addresses are
// used in the parser.
class Symbol {
public:
Symbol() : Symbol({}) {}
Symbol(std::initializer_list<Rule> rules) { *this = rules; }
V8_EXPORT_PRIVATE Symbol& operator=(std::initializer_list<Rule> rules);
bool IsTerminal() const { return rules_.empty(); }
Rule* rule(size_t index) const { return rules_[index].get(); }
size_t rule_number() const { return rules_.size(); }
void AddRule(const Rule& rule) {
rules_.push_back(std::make_unique<Rule>(rule));
rules_.back()->SetLeftHandSide(this);
}
V8_EXPORT_PRIVATE base::Optional<ParseResult> RunAction(
const Item* item, const LexerResult& tokens);
private:
std::vector<std::unique_ptr<Rule>> rules_;
// Disallow copying and moving to ensure Symbol has a stable address.
DISALLOW_COPY_AND_ASSIGN(Symbol);
};
// Items are the core datastructure of Earley's algorithm.
// They consist of a (partially) matched rule, a marked position inside of the
// right-hand side of the rule (traditionally written as a dot) and an input
// range from {start} to {pos} that matches the symbols of the right-hand side
// that are left of the mark. In addition, they store a child and a left-sibling
// pointer to reconstruct the AST in the end.
class Item {
public:
Item(const Rule* rule, size_t mark, size_t start, size_t pos)
: rule_(rule), mark_(mark), start_(start), pos_(pos) {
DCHECK_LE(mark_, right().size());
}
// A complete item has the mark at the right end, which means the input range
// matches the complete rule.
bool IsComplete() const {
DCHECK_LE(mark_, right().size());
return mark_ == right().size();
}
// The symbol right after the mark is expected at {pos} for this item to
// advance.
Symbol* NextSymbol() const {
DCHECK(!IsComplete());
DCHECK_LT(mark_, right().size());
return right()[mark_];
}
// We successfully parsed NextSymbol() between {pos} and {new_pos}.
// If NextSymbol() was a non-terminal, then {child} is a pointer to a
// completed item for this parse.
// We create a new item, which moves the mark one forward.
Item Advance(size_t new_pos, const Item* child = nullptr) const {
if (child) {
DCHECK(child->IsComplete());
DCHECK_EQ(pos(), child->start());
DCHECK_EQ(new_pos, child->pos());
DCHECK_EQ(NextSymbol(), child->left());
}
Item result(rule_, mark_ + 1, start_, new_pos);
result.prev_ = this;
result.child_ = child;
return result;
}
// Collect the items representing the AST children of this completed item.
std::vector<const Item*> Children() const;
// The matched input separated according to the next branching AST level.
std::string SplitByChildren(const LexerResult& tokens) const;
// Check if {other} results in the same AST as this Item.
void CheckAmbiguity(const Item& other, const LexerResult& tokens) const;
MatchedInput GetMatchedInput(const LexerResult& tokens) const {
const MatchedInput& start = tokens.token_contents[start_];
const MatchedInput& end = start_ == pos_ ? tokens.token_contents[start_]
: tokens.token_contents[pos_ - 1];
CHECK_EQ(start.pos.source, end.pos.source);
SourcePosition combined{start.pos.source, start.pos.start, end.pos.end};
return {start.begin, end.end, combined};
}
// We exclude {prev_} and {child_} from equality and hash computations,
// because they are just globally unique data associated with an item.
bool operator==(const Item& other) const {
return rule_ == other.rule_ && mark_ == other.mark_ &&
start_ == other.start_ && pos_ == other.pos_;
}
friend size_t hash_value(const Item& i) {
return base::hash_combine(i.rule_, i.mark_, i.start_, i.pos_);
}
const Rule* rule() const { return rule_; }
Symbol* left() const { return rule_->left(); }
const std::vector<Symbol*>& right() const { return rule_->right(); }
size_t pos() const { return pos_; }
size_t start() const { return start_; }
private:
const Rule* rule_;
size_t mark_;
size_t start_;
size_t pos_;
const Item* prev_ = nullptr;
const Item* child_ = nullptr;
};
inline base::Optional<ParseResult> Symbol::RunAction(
const Item* item, const LexerResult& tokens) {
DCHECK(item->IsComplete());
DCHECK_EQ(item->left(), this);
return item->rule()->RunAction(item, tokens);
}
V8_EXPORT_PRIVATE const Item* RunEarleyAlgorithm(
Symbol* start, const LexerResult& tokens,
std::unordered_set<Item, base::hash<Item>>* processed);
inline base::Optional<ParseResult> ParseTokens(Symbol* start,
const LexerResult& tokens) {
std::unordered_set<Item, base::hash<Item>> table;
const Item* final_item = RunEarleyAlgorithm(start, tokens, &table);
return start->RunAction(final_item, tokens);
}
// The lexical syntax is dynamically defined while building the grammar by
// adding patterns and keywords to the Lexer.
// The term keyword here can stand for any fixed character sequence, including
// operators and parentheses.
// Each pattern or keyword automatically gets a terminal symbol associated with
// it. These symbols form the result of the lexing.
// Patterns and keywords are matched using the longest match principle. If the
// longest matching pattern coincides with a keyword, the keyword symbol is
// chosen instead of the pattern.
// In addition, there is a single whitespace pattern which is consumed but does
// not become part of the token list.
class Lexer {
public:
// Functions to define patterns. They try to match starting from {pos}. If
// successful, they return true and advance {pos}. Otherwise, {pos} stays
// unchanged.
using PatternFunction = bool (*)(InputPosition* pos);
void SetWhitespace(PatternFunction whitespace) {
match_whitespace_ = whitespace;
}
Symbol* Pattern(PatternFunction pattern) { return &patterns_[pattern]; }
Symbol* Token(const std::string& keyword) { return &keywords_[keyword]; }
V8_EXPORT_PRIVATE LexerResult RunLexer(const std::string& input);
private:
PatternFunction match_whitespace_ = [](InputPosition*) { return false; };
std::map<PatternFunction, Symbol> patterns_;
std::map<std::string, Symbol> keywords_;
Symbol* MatchToken(InputPosition* pos, InputPosition end);
};
// A grammar can have a result, which is the results of the start symbol.
// Grammar is intended to be subclassed, with Symbol members forming the
// mutually recursive rules of the grammar.
class Grammar {
public:
using PatternFunction = Lexer::PatternFunction;
explicit Grammar(Symbol* start) : start_(start) {}
base::Optional<ParseResult> Parse(const std::string& input) {
LexerResult tokens = lexer().RunLexer(input);
return ParseTokens(start_, tokens);
}
protected:
Symbol* Token(const std::string& s) { return lexer_.Token(s); }
Symbol* Pattern(PatternFunction pattern) { return lexer_.Pattern(pattern); }
void SetWhitespace(PatternFunction ws) { lexer_.SetWhitespace(ws); }
// NewSymbol() allocates a fresh symbol and stores it in the current grammar.
// This is necessary to define helpers that create new symbols.
Symbol* NewSymbol(std::initializer_list<Rule> rules = {}) {
Symbol* result = new Symbol(rules);
generated_symbols_.push_back(std::unique_ptr<Symbol>(result));
return result;
}
// Helper functions to define lexer patterns. If they match, they return true
// and advance {pos}. Otherwise, {pos} is unchanged.
V8_EXPORT_PRIVATE static bool MatchChar(int (*char_class)(int),
InputPosition* pos);
V8_EXPORT_PRIVATE static bool MatchChar(bool (*char_class)(char),
InputPosition* pos);
V8_EXPORT_PRIVATE static bool MatchAnyChar(InputPosition* pos);
V8_EXPORT_PRIVATE static bool MatchString(const char* s, InputPosition* pos);
// The action MatchInput() produces the input matched by the rule as
// result.
static base::Optional<ParseResult> YieldMatchedInput(
ParseResultIterator* child_results) {
return ParseResult{child_results->matched_input().ToString()};
}
// Create a new symbol to parse the given sequence of symbols.
// At most one of the symbols can return a result.
Symbol* Sequence(std::vector<Symbol*> symbols) {
return NewSymbol({Rule(std::move(symbols))});
}
template <class T, T value>
static base::Optional<ParseResult> YieldIntegralConstant(
ParseResultIterator* child_results) {
return ParseResult{value};
}
template <class T>
static base::Optional<ParseResult> YieldDefaultValue(
ParseResultIterator* child_results) {
return ParseResult{T{}};
}
template <class From, class To>
static base::Optional<ParseResult> CastParseResult(
ParseResultIterator* child_results) {
To result = std::move(child_results->NextAs<From>());
return ParseResult{std::move(result)};
}
// Try to parse {s} and return the result of type {Result} casted to {T}.
// Otherwise, the result is a default-constructed {T}.
template <class T, class Result = T>
Symbol* TryOrDefault(Symbol* s) {
return NewSymbol({Rule({s}, CastParseResult<Result, T>),
Rule({}, YieldDefaultValue<T>)});
}
template <class T>
static base::Optional<ParseResult> MakeSingletonVector(
ParseResultIterator* child_results) {
T x = child_results->NextAs<T>();
std::vector<T> result;
result.push_back(std::move(x));
return ParseResult{std::move(result)};
}
template <class T>
static base::Optional<ParseResult> MakeExtendedVector(
ParseResultIterator* child_results) {
std::vector<T> l = child_results->NextAs<std::vector<T>>();
T x = child_results->NextAs<T>();
l.push_back(std::move(x));
return ParseResult{std::move(l)};
}
// For example, NonemptyList(Token("A"), Token(",")) parses any of
// A or A,A or A,A,A and so on.
template <class T>
Symbol* NonemptyList(Symbol* element,
base::Optional<Symbol*> separator = {}) {
Symbol* list = NewSymbol();
*list = {Rule({element}, MakeSingletonVector<T>),
separator
? Rule({list, *separator, element}, MakeExtendedVector<T>)
: Rule({list, element}, MakeExtendedVector<T>)};
return list;
}
template <class T>
Symbol* List(Symbol* element, base::Optional<Symbol*> separator = {}) {
return TryOrDefault<std::vector<T>>(NonemptyList<T>(element, separator));
}
template <class T>
Symbol* Optional(Symbol* x) {
return TryOrDefault<base::Optional<T>, T>(x);
}
Symbol* CheckIf(Symbol* x) {
return NewSymbol({Rule({x}, YieldIntegralConstant<bool, true>),
Rule({}, YieldIntegralConstant<bool, false>)});
}
Lexer& lexer() { return lexer_; }
private:
Lexer lexer_;
std::vector<std::unique_ptr<Symbol>> generated_symbols_;
Symbol* start_;
};
} // namespace torque
} // namespace internal
} // namespace v8
#endif // V8_TORQUE_EARLEY_PARSER_H_
|
hamzahamidi/v8
|
src/common/ptr-compr.h
|
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_COMMON_PTR_COMPR_H_
#define V8_COMMON_PTR_COMPR_H_
#include "src/common/globals.h"
#if V8_TARGET_ARCH_64_BIT
namespace v8 {
namespace internal {
// See v8:7703 for details about how pointer compression works.
constexpr size_t kPtrComprHeapReservationSize = size_t{4} * GB;
constexpr size_t kPtrComprIsolateRootBias = kPtrComprHeapReservationSize / 2;
constexpr size_t kPtrComprIsolateRootAlignment = size_t{4} * GB;
} // namespace internal
} // namespace v8
#endif // V8_TARGET_ARCH_64_BIT
#endif // V8_COMMON_PTR_COMPR_H_
|
hamzahamidi/v8
|
src/torque/ast.h
|
<reponame>hamzahamidi/v8<gh_stars>1000+
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_TORQUE_AST_H_
#define V8_TORQUE_AST_H_
#include <iostream>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "src/base/optional.h"
#include "src/torque/constants.h"
#include "src/torque/source-positions.h"
#include "src/torque/utils.h"
namespace v8 {
namespace internal {
namespace torque {
#define AST_EXPRESSION_NODE_KIND_LIST(V) \
V(CallExpression) \
V(CallMethodExpression) \
V(IntrinsicCallExpression) \
V(StructExpression) \
V(LogicalOrExpression) \
V(LogicalAndExpression) \
V(SpreadExpression) \
V(ConditionalExpression) \
V(IdentifierExpression) \
V(StringLiteralExpression) \
V(NumberLiteralExpression) \
V(FieldAccessExpression) \
V(ElementAccessExpression) \
V(DereferenceExpression) \
V(AssignmentExpression) \
V(IncrementDecrementExpression) \
V(NewExpression) \
V(AssumeTypeImpossibleExpression) \
V(StatementExpression) \
V(TryLabelExpression)
#define AST_TYPE_EXPRESSION_NODE_KIND_LIST(V) \
V(BasicTypeExpression) \
V(FunctionTypeExpression) \
V(UnionTypeExpression)
#define AST_STATEMENT_NODE_KIND_LIST(V) \
V(BlockStatement) \
V(ExpressionStatement) \
V(IfStatement) \
V(WhileStatement) \
V(ForLoopStatement) \
V(BreakStatement) \
V(ContinueStatement) \
V(ReturnStatement) \
V(DebugStatement) \
V(AssertStatement) \
V(TailCallStatement) \
V(VarDeclarationStatement) \
V(GotoStatement)
#define AST_TYPE_DECLARATION_NODE_KIND_LIST(V) \
V(AbstractTypeDeclaration) \
V(TypeAliasDeclaration) \
V(ClassDeclaration) \
V(StructDeclaration)
#define AST_DECLARATION_NODE_KIND_LIST(V) \
AST_TYPE_DECLARATION_NODE_KIND_LIST(V) \
V(GenericDeclaration) \
V(SpecializationDeclaration) \
V(ExternConstDeclaration) \
V(NamespaceDeclaration) \
V(ConstDeclaration) \
V(CppIncludeDeclaration) \
V(TorqueMacroDeclaration) \
V(TorqueBuiltinDeclaration) \
V(ExternalMacroDeclaration) \
V(ExternalBuiltinDeclaration) \
V(ExternalRuntimeDeclaration) \
V(IntrinsicDeclaration)
#define AST_NODE_KIND_LIST(V) \
AST_EXPRESSION_NODE_KIND_LIST(V) \
AST_TYPE_EXPRESSION_NODE_KIND_LIST(V) \
AST_STATEMENT_NODE_KIND_LIST(V) \
AST_DECLARATION_NODE_KIND_LIST(V) \
V(Identifier) \
V(LabelBlock)
struct AstNode {
public:
enum class Kind {
#define ENUM_ITEM(name) k##name,
AST_NODE_KIND_LIST(ENUM_ITEM)
#undef ENUM_ITEM
};
AstNode(Kind kind, SourcePosition pos) : kind(kind), pos(pos) {}
virtual ~AstNode() = default;
const Kind kind;
SourcePosition pos;
};
struct AstNodeClassCheck {
template <class T>
static bool IsInstanceOf(AstNode* node);
};
// Boilerplate for most derived classes.
#define DEFINE_AST_NODE_LEAF_BOILERPLATE(T) \
static const Kind kKind = Kind::k##T; \
static T* cast(AstNode* node) { \
DCHECK_EQ(node->kind, kKind); \
return static_cast<T*>(node); \
} \
static T* DynamicCast(AstNode* node) { \
if (!node) return nullptr; \
if (node->kind != kKind) return nullptr; \
return static_cast<T*>(node); \
}
// Boilerplate for classes with subclasses.
#define DEFINE_AST_NODE_INNER_BOILERPLATE(T) \
static T* cast(AstNode* node) { \
DCHECK(AstNodeClassCheck::IsInstanceOf<T>(node)); \
return static_cast<T*>(node); \
} \
static T* DynamicCast(AstNode* node) { \
if (!node) return nullptr; \
if (!AstNodeClassCheck::IsInstanceOf<T>(node)) return nullptr; \
return static_cast<T*>(node); \
}
struct Expression : AstNode {
Expression(Kind kind, SourcePosition pos) : AstNode(kind, pos) {}
DEFINE_AST_NODE_INNER_BOILERPLATE(Expression)
using VisitCallback = std::function<void(Expression*)>;
virtual void VisitAllSubExpressions(VisitCallback callback) {
// TODO(szuend): Hoist this up to AstNode and make it a
// general Ast visitor.
}
};
struct LocationExpression : Expression {
LocationExpression(Kind kind, SourcePosition pos) : Expression(kind, pos) {}
DEFINE_AST_NODE_INNER_BOILERPLATE(LocationExpression)
};
struct TypeExpression : AstNode {
TypeExpression(Kind kind, SourcePosition pos) : AstNode(kind, pos) {}
DEFINE_AST_NODE_INNER_BOILERPLATE(TypeExpression)
};
struct Declaration : AstNode {
Declaration(Kind kind, SourcePosition pos) : AstNode(kind, pos) {}
DEFINE_AST_NODE_INNER_BOILERPLATE(Declaration)
};
struct Statement : AstNode {
Statement(Kind kind, SourcePosition pos) : AstNode(kind, pos) {}
DEFINE_AST_NODE_INNER_BOILERPLATE(Statement)
};
class Namespace;
struct NamespaceDeclaration : Declaration {
DEFINE_AST_NODE_LEAF_BOILERPLATE(NamespaceDeclaration)
NamespaceDeclaration(SourcePosition pos, std::string name,
std::vector<Declaration*> declarations)
: Declaration(kKind, pos),
declarations(std::move(declarations)),
name(name) {}
std::vector<Declaration*> declarations;
std::string name;
};
class Ast {
public:
Ast() {}
std::vector<Declaration*>& declarations() { return declarations_; }
const std::vector<Declaration*>& declarations() const {
return declarations_;
}
template <class T>
T* AddNode(std::unique_ptr<T> node) {
T* result = node.get();
nodes_.push_back(std::move(node));
return result;
}
void DeclareImportForCurrentFile(SourceId import_id) {
declared_imports_[CurrentSourcePosition::Get().source].insert(import_id);
}
private:
std::vector<Declaration*> declarations_;
std::vector<std::unique_ptr<AstNode>> nodes_;
std::map<SourceId, std::set<SourceId>> declared_imports_;
};
static const char* const kThisParameterName = "this";
// A Identifier is a string with a SourcePosition attached.
struct Identifier : AstNode {
DEFINE_AST_NODE_LEAF_BOILERPLATE(Identifier)
Identifier(SourcePosition pos, std::string identifier)
: AstNode(kKind, pos), value(std::move(identifier)) {}
std::string value;
};
inline std::ostream& operator<<(std::ostream& os, Identifier* id) {
return os << id->value;
}
struct IdentifierPtrValueEq {
bool operator()(const Identifier* a, const Identifier* b) {
return a->value < b->value;
}
};
struct IdentifierExpression : LocationExpression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(IdentifierExpression)
IdentifierExpression(SourcePosition pos,
std::vector<std::string> namespace_qualification,
Identifier* name, std::vector<TypeExpression*> args = {})
: LocationExpression(kKind, pos),
namespace_qualification(std::move(namespace_qualification)),
name(name),
generic_arguments(std::move(args)) {}
IdentifierExpression(SourcePosition pos, Identifier* name,
std::vector<TypeExpression*> args = {})
: IdentifierExpression(pos, {}, name, std::move(args)) {}
bool IsThis() const { return name->value == kThisParameterName; }
void VisitAllSubExpressions(VisitCallback callback) override {
callback(this);
}
std::vector<std::string> namespace_qualification;
Identifier* name;
std::vector<TypeExpression*> generic_arguments;
};
struct IntrinsicCallExpression : Expression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(IntrinsicCallExpression)
IntrinsicCallExpression(SourcePosition pos, Identifier* name,
std::vector<TypeExpression*> generic_arguments,
std::vector<Expression*> arguments)
: Expression(kKind, pos),
name(name),
generic_arguments(std::move(generic_arguments)),
arguments(std::move(arguments)) {}
void VisitAllSubExpressions(VisitCallback callback) override {
for (auto argument : arguments) {
argument->VisitAllSubExpressions(callback);
}
callback(this);
}
Identifier* name;
std::vector<TypeExpression*> generic_arguments;
std::vector<Expression*> arguments;
};
struct CallMethodExpression : Expression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(CallMethodExpression)
CallMethodExpression(SourcePosition pos, Expression* target,
IdentifierExpression* method,
std::vector<Expression*> arguments,
std::vector<Identifier*> labels)
: Expression(kKind, pos),
target(target),
method(method),
arguments(std::move(arguments)),
labels(std::move(labels)) {}
void VisitAllSubExpressions(VisitCallback callback) override {
target->VisitAllSubExpressions(callback);
method->VisitAllSubExpressions(callback);
for (auto argument : arguments) {
argument->VisitAllSubExpressions(callback);
}
callback(this);
}
Expression* target;
IdentifierExpression* method;
std::vector<Expression*> arguments;
std::vector<Identifier*> labels;
};
struct CallExpression : Expression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(CallExpression)
CallExpression(SourcePosition pos, IdentifierExpression* callee,
std::vector<Expression*> arguments,
std::vector<Identifier*> labels)
: Expression(kKind, pos),
callee(callee),
arguments(std::move(arguments)),
labels(std::move(labels)) {}
void VisitAllSubExpressions(VisitCallback callback) override {
callee->VisitAllSubExpressions(callback);
for (auto argument : arguments) {
argument->VisitAllSubExpressions(callback);
}
callback(this);
}
IdentifierExpression* callee;
std::vector<Expression*> arguments;
std::vector<Identifier*> labels;
};
struct NameAndExpression {
Identifier* name;
Expression* expression;
};
struct StructExpression : Expression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(StructExpression)
StructExpression(SourcePosition pos, TypeExpression* type,
std::vector<NameAndExpression> initializers)
: Expression(kKind, pos),
type(type),
initializers(std::move(initializers)) {}
void VisitAllSubExpressions(VisitCallback callback) override {
for (auto& initializer : initializers) {
initializer.expression->VisitAllSubExpressions(callback);
}
callback(this);
}
TypeExpression* type;
std::vector<NameAndExpression> initializers;
};
struct LogicalOrExpression : Expression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(LogicalOrExpression)
LogicalOrExpression(SourcePosition pos, Expression* left, Expression* right)
: Expression(kKind, pos), left(left), right(right) {}
void VisitAllSubExpressions(VisitCallback callback) override {
left->VisitAllSubExpressions(callback);
right->VisitAllSubExpressions(callback);
callback(this);
}
Expression* left;
Expression* right;
};
struct LogicalAndExpression : Expression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(LogicalAndExpression)
LogicalAndExpression(SourcePosition pos, Expression* left, Expression* right)
: Expression(kKind, pos), left(left), right(right) {}
void VisitAllSubExpressions(VisitCallback callback) override {
left->VisitAllSubExpressions(callback);
right->VisitAllSubExpressions(callback);
callback(this);
}
Expression* left;
Expression* right;
};
struct SpreadExpression : Expression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(SpreadExpression)
SpreadExpression(SourcePosition pos, Expression* spreadee)
: Expression(kKind, pos), spreadee(spreadee) {}
void VisitAllSubExpressions(VisitCallback callback) override {
spreadee->VisitAllSubExpressions(callback);
callback(this);
}
Expression* spreadee;
};
struct ConditionalExpression : Expression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(ConditionalExpression)
ConditionalExpression(SourcePosition pos, Expression* condition,
Expression* if_true, Expression* if_false)
: Expression(kKind, pos),
condition(condition),
if_true(if_true),
if_false(if_false) {}
void VisitAllSubExpressions(VisitCallback callback) override {
condition->VisitAllSubExpressions(callback);
if_true->VisitAllSubExpressions(callback);
if_false->VisitAllSubExpressions(callback);
callback(this);
}
Expression* condition;
Expression* if_true;
Expression* if_false;
};
struct StringLiteralExpression : Expression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(StringLiteralExpression)
StringLiteralExpression(SourcePosition pos, std::string literal)
: Expression(kKind, pos), literal(std::move(literal)) {}
void VisitAllSubExpressions(VisitCallback callback) override {
callback(this);
}
std::string literal;
};
struct NumberLiteralExpression : Expression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(NumberLiteralExpression)
NumberLiteralExpression(SourcePosition pos, std::string name)
: Expression(kKind, pos), number(std::move(name)) {}
void VisitAllSubExpressions(VisitCallback callback) override {
callback(this);
}
std::string number;
};
struct ElementAccessExpression : LocationExpression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(ElementAccessExpression)
ElementAccessExpression(SourcePosition pos, Expression* array,
Expression* index)
: LocationExpression(kKind, pos), array(array), index(index) {}
void VisitAllSubExpressions(VisitCallback callback) override {
array->VisitAllSubExpressions(callback);
index->VisitAllSubExpressions(callback);
callback(this);
}
Expression* array;
Expression* index;
};
struct FieldAccessExpression : LocationExpression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(FieldAccessExpression)
FieldAccessExpression(SourcePosition pos, Expression* object,
Identifier* field)
: LocationExpression(kKind, pos), object(object), field(field) {}
void VisitAllSubExpressions(VisitCallback callback) override {
object->VisitAllSubExpressions(callback);
callback(this);
}
Expression* object;
Identifier* field;
};
struct DereferenceExpression : LocationExpression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(DereferenceExpression)
DereferenceExpression(SourcePosition pos, Expression* reference)
: LocationExpression(kKind, pos), reference(reference) {}
void VisitAllSubExpressions(VisitCallback callback) override {
reference->VisitAllSubExpressions(callback);
callback(this);
}
Expression* reference;
};
struct AssignmentExpression : Expression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(AssignmentExpression)
AssignmentExpression(SourcePosition pos, Expression* location,
Expression* value)
: AssignmentExpression(pos, location, base::nullopt, value) {}
AssignmentExpression(SourcePosition pos, Expression* location,
base::Optional<std::string> op, Expression* value)
: Expression(kKind, pos),
location(location),
op(std::move(op)),
value(value) {}
void VisitAllSubExpressions(VisitCallback callback) override {
location->VisitAllSubExpressions(callback);
value->VisitAllSubExpressions(callback);
callback(this);
}
Expression* location;
base::Optional<std::string> op;
Expression* value;
};
enum class IncrementDecrementOperator { kIncrement, kDecrement };
struct IncrementDecrementExpression : Expression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(IncrementDecrementExpression)
IncrementDecrementExpression(SourcePosition pos, Expression* location,
IncrementDecrementOperator op, bool postfix)
: Expression(kKind, pos), location(location), op(op), postfix(postfix) {}
void VisitAllSubExpressions(VisitCallback callback) override {
location->VisitAllSubExpressions(callback);
callback(this);
}
Expression* location;
IncrementDecrementOperator op;
bool postfix;
};
// This expression is only used in the desugaring of typeswitch, and it allows
// to bake in the static information that certain types are impossible at a
// certain position in the control flow.
// The result type is the type of {expression} minus the provided type.
struct AssumeTypeImpossibleExpression : Expression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(AssumeTypeImpossibleExpression)
AssumeTypeImpossibleExpression(SourcePosition pos,
TypeExpression* excluded_type,
Expression* expression)
: Expression(kKind, pos),
excluded_type(excluded_type),
expression(expression) {}
void VisitAllSubExpressions(VisitCallback callback) override {
expression->VisitAllSubExpressions(callback);
callback(this);
}
TypeExpression* excluded_type;
Expression* expression;
};
struct NewExpression : Expression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(NewExpression)
NewExpression(SourcePosition pos, TypeExpression* type,
std::vector<NameAndExpression> initializers)
: Expression(kKind, pos),
type(type),
initializers(std::move(initializers)) {}
void VisitAllSubExpressions(VisitCallback callback) override {
for (auto& initializer : initializers) {
initializer.expression->VisitAllSubExpressions(callback);
}
callback(this);
}
TypeExpression* type;
std::vector<NameAndExpression> initializers;
};
enum class ImplicitKind { kNoImplicit, kJSImplicit, kImplicit };
struct ParameterList {
std::vector<Identifier*> names;
std::vector<TypeExpression*> types;
ImplicitKind implicit_kind = ImplicitKind::kNoImplicit;
SourcePosition implicit_kind_pos = SourcePosition::Invalid();
size_t implicit_count = 0;
bool has_varargs = false;
std::string arguments_variable = "";
static ParameterList Empty() { return {}; }
std::vector<TypeExpression*> GetImplicitTypes() {
return std::vector<TypeExpression*>(types.begin(),
types.begin() + implicit_count);
}
std::vector<TypeExpression*> GetExplicitTypes() {
return std::vector<TypeExpression*>(types.begin() + implicit_count,
types.end());
}
};
struct BasicTypeExpression : TypeExpression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(BasicTypeExpression)
BasicTypeExpression(SourcePosition pos,
std::vector<std::string> namespace_qualification,
std::string name,
std::vector<TypeExpression*> generic_arguments)
: TypeExpression(kKind, pos),
namespace_qualification(std::move(namespace_qualification)),
is_constexpr(IsConstexprName(name)),
name(std::move(name)),
generic_arguments(std::move(generic_arguments)) {}
std::vector<std::string> namespace_qualification;
bool is_constexpr;
std::string name;
std::vector<TypeExpression*> generic_arguments;
};
struct FunctionTypeExpression : TypeExpression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(FunctionTypeExpression)
FunctionTypeExpression(SourcePosition pos,
std::vector<TypeExpression*> parameters,
TypeExpression* return_type)
: TypeExpression(kKind, pos),
parameters(std::move(parameters)),
return_type(return_type) {}
std::vector<TypeExpression*> parameters;
TypeExpression* return_type;
};
struct UnionTypeExpression : TypeExpression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(UnionTypeExpression)
UnionTypeExpression(SourcePosition pos, TypeExpression* a, TypeExpression* b)
: TypeExpression(kKind, pos), a(a), b(b) {}
TypeExpression* a;
TypeExpression* b;
};
struct ExpressionStatement : Statement {
DEFINE_AST_NODE_LEAF_BOILERPLATE(ExpressionStatement)
ExpressionStatement(SourcePosition pos, Expression* expression)
: Statement(kKind, pos), expression(expression) {}
Expression* expression;
};
struct IfStatement : Statement {
DEFINE_AST_NODE_LEAF_BOILERPLATE(IfStatement)
IfStatement(SourcePosition pos, bool is_constexpr, Expression* condition,
Statement* if_true, base::Optional<Statement*> if_false)
: Statement(kKind, pos),
condition(condition),
is_constexpr(is_constexpr),
if_true(if_true),
if_false(if_false) {}
Expression* condition;
bool is_constexpr;
Statement* if_true;
base::Optional<Statement*> if_false;
};
struct WhileStatement : Statement {
DEFINE_AST_NODE_LEAF_BOILERPLATE(WhileStatement)
WhileStatement(SourcePosition pos, Expression* condition, Statement* body)
: Statement(kKind, pos), condition(condition), body(body) {}
Expression* condition;
Statement* body;
};
struct ReturnStatement : Statement {
DEFINE_AST_NODE_LEAF_BOILERPLATE(ReturnStatement)
ReturnStatement(SourcePosition pos, base::Optional<Expression*> value)
: Statement(kKind, pos), value(value) {}
base::Optional<Expression*> value;
};
struct DebugStatement : Statement {
DEFINE_AST_NODE_LEAF_BOILERPLATE(DebugStatement)
DebugStatement(SourcePosition pos, const std::string& reason,
bool never_continues)
: Statement(kKind, pos),
reason(reason),
never_continues(never_continues) {}
std::string reason;
bool never_continues;
};
struct AssertStatement : Statement {
DEFINE_AST_NODE_LEAF_BOILERPLATE(AssertStatement)
AssertStatement(SourcePosition pos, bool debug_only, Expression* expression,
std::string source)
: Statement(kKind, pos),
debug_only(debug_only),
expression(expression),
source(std::move(source)) {}
bool debug_only;
Expression* expression;
std::string source;
};
struct TailCallStatement : Statement {
DEFINE_AST_NODE_LEAF_BOILERPLATE(TailCallStatement)
TailCallStatement(SourcePosition pos, CallExpression* call)
: Statement(kKind, pos), call(call) {}
CallExpression* call;
};
struct VarDeclarationStatement : Statement {
DEFINE_AST_NODE_LEAF_BOILERPLATE(VarDeclarationStatement)
VarDeclarationStatement(
SourcePosition pos, bool const_qualified, Identifier* name,
base::Optional<TypeExpression*> type,
base::Optional<Expression*> initializer = base::nullopt)
: Statement(kKind, pos),
const_qualified(const_qualified),
name(name),
type(type),
initializer(initializer) {}
bool const_qualified;
Identifier* name;
base::Optional<TypeExpression*> type;
base::Optional<Expression*> initializer;
};
struct BreakStatement : Statement {
DEFINE_AST_NODE_LEAF_BOILERPLATE(BreakStatement)
explicit BreakStatement(SourcePosition pos) : Statement(kKind, pos) {}
};
struct ContinueStatement : Statement {
DEFINE_AST_NODE_LEAF_BOILERPLATE(ContinueStatement)
explicit ContinueStatement(SourcePosition pos) : Statement(kKind, pos) {}
};
struct GotoStatement : Statement {
DEFINE_AST_NODE_LEAF_BOILERPLATE(GotoStatement)
GotoStatement(SourcePosition pos, Identifier* label,
const std::vector<Expression*>& arguments)
: Statement(kKind, pos), label(label), arguments(std::move(arguments)) {}
Identifier* label;
std::vector<Expression*> arguments;
};
struct ForLoopStatement : Statement {
DEFINE_AST_NODE_LEAF_BOILERPLATE(ForLoopStatement)
ForLoopStatement(SourcePosition pos, base::Optional<Statement*> declaration,
base::Optional<Expression*> test,
base::Optional<Statement*> action, Statement* body)
: Statement(kKind, pos),
var_declaration(),
test(std::move(test)),
action(std::move(action)),
body(std::move(body)) {
if (declaration)
var_declaration = VarDeclarationStatement::cast(*declaration);
}
base::Optional<VarDeclarationStatement*> var_declaration;
base::Optional<Expression*> test;
base::Optional<Statement*> action;
Statement* body;
};
struct LabelBlock : AstNode {
DEFINE_AST_NODE_LEAF_BOILERPLATE(LabelBlock)
LabelBlock(SourcePosition pos, Identifier* label,
const ParameterList& parameters, Statement* body)
: AstNode(kKind, pos),
label(label),
parameters(parameters),
body(std::move(body)) {}
Identifier* label;
ParameterList parameters;
Statement* body;
};
struct StatementExpression : Expression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(StatementExpression)
StatementExpression(SourcePosition pos, Statement* statement)
: Expression(kKind, pos), statement(statement) {}
Statement* statement;
};
struct TryLabelExpression : Expression {
DEFINE_AST_NODE_LEAF_BOILERPLATE(TryLabelExpression)
TryLabelExpression(SourcePosition pos, bool catch_exceptions,
Expression* try_expression, LabelBlock* label_block)
: Expression(kKind, pos),
catch_exceptions(catch_exceptions),
try_expression(try_expression),
label_block(label_block) {}
bool catch_exceptions;
Expression* try_expression;
LabelBlock* label_block;
};
struct BlockStatement : Statement {
DEFINE_AST_NODE_LEAF_BOILERPLATE(BlockStatement)
explicit BlockStatement(SourcePosition pos, bool deferred = false,
std::vector<Statement*> statements = {})
: Statement(kKind, pos),
deferred(deferred),
statements(std::move(statements)) {}
bool deferred;
std::vector<Statement*> statements;
};
struct TypeDeclaration : Declaration {
DEFINE_AST_NODE_INNER_BOILERPLATE(TypeDeclaration)
TypeDeclaration(Kind kKind, SourcePosition pos, Identifier* name)
: Declaration(kKind, pos), name(name) {}
Identifier* name;
};
struct AbstractTypeDeclaration : TypeDeclaration {
DEFINE_AST_NODE_LEAF_BOILERPLATE(AbstractTypeDeclaration)
AbstractTypeDeclaration(SourcePosition pos, Identifier* name, bool transient,
base::Optional<Identifier*> extends,
base::Optional<std::string> generates)
: TypeDeclaration(kKind, pos, name),
is_constexpr(IsConstexprName(name->value)),
transient(transient),
extends(extends),
generates(std::move(generates)) {}
bool is_constexpr;
bool transient;
base::Optional<Identifier*> extends;
base::Optional<std::string> generates;
};
struct TypeAliasDeclaration : TypeDeclaration {
DEFINE_AST_NODE_LEAF_BOILERPLATE(TypeAliasDeclaration)
TypeAliasDeclaration(SourcePosition pos, Identifier* name,
TypeExpression* type)
: TypeDeclaration(kKind, pos, name), type(type) {}
TypeExpression* type;
};
struct NameAndTypeExpression {
Identifier* name;
TypeExpression* type;
};
struct ImplicitParameters {
Identifier* kind;
std::vector<NameAndTypeExpression> parameters;
};
struct StructFieldExpression {
NameAndTypeExpression name_and_type;
bool const_qualified;
};
enum class ConditionalAnnotationType {
kPositive,
kNegative,
};
struct ConditionalAnnotation {
std::string condition;
ConditionalAnnotationType type;
};
struct Annotation {
Identifier* name;
base::Optional<std::string> param;
};
struct ClassFieldExpression {
NameAndTypeExpression name_and_type;
base::Optional<std::string> index;
std::vector<ConditionalAnnotation> conditions;
bool weak;
bool const_qualified;
bool generate_verify;
};
struct LabelAndTypes {
Identifier* name;
std::vector<TypeExpression*> types;
};
using LabelAndTypesVector = std::vector<LabelAndTypes>;
struct CallableDeclaration : Declaration {
CallableDeclaration(AstNode::Kind kind, SourcePosition pos,
bool transitioning, Identifier* name,
ParameterList parameters, TypeExpression* return_type,
LabelAndTypesVector labels)
: Declaration(kind, pos),
transitioning(transitioning),
name(name),
parameters(std::move(parameters)),
return_type(return_type),
labels(std::move(labels)) {}
DEFINE_AST_NODE_INNER_BOILERPLATE(CallableDeclaration)
bool transitioning;
Identifier* name;
ParameterList parameters;
TypeExpression* return_type;
LabelAndTypesVector labels;
};
struct MacroDeclaration : CallableDeclaration {
DEFINE_AST_NODE_INNER_BOILERPLATE(MacroDeclaration)
MacroDeclaration(AstNode::Kind kind, SourcePosition pos, bool transitioning,
Identifier* name, base::Optional<std::string> op,
ParameterList parameters, TypeExpression* return_type,
const LabelAndTypesVector& labels)
: CallableDeclaration(kind, pos, transitioning, name,
std::move(parameters), return_type, labels),
op(std::move(op)) {
if (parameters.implicit_kind == ImplicitKind::kJSImplicit) {
Error("Cannot use \"js-implicit\" with macros, use \"implicit\" instead.")
.Position(parameters.implicit_kind_pos);
}
}
base::Optional<std::string> op;
};
struct ExternalMacroDeclaration : MacroDeclaration {
DEFINE_AST_NODE_LEAF_BOILERPLATE(ExternalMacroDeclaration)
ExternalMacroDeclaration(SourcePosition pos, bool transitioning,
std::string external_assembler_name,
Identifier* name, base::Optional<std::string> op,
ParameterList parameters,
TypeExpression* return_type,
const LabelAndTypesVector& labels)
: MacroDeclaration(kKind, pos, transitioning, name, std::move(op),
std::move(parameters), return_type, labels),
external_assembler_name(std::move(external_assembler_name)) {}
std::string external_assembler_name;
};
struct IntrinsicDeclaration : CallableDeclaration {
DEFINE_AST_NODE_LEAF_BOILERPLATE(IntrinsicDeclaration)
IntrinsicDeclaration(SourcePosition pos, Identifier* name,
ParameterList parameters, TypeExpression* return_type)
: CallableDeclaration(kKind, pos, false, name, std::move(parameters),
return_type, {}) {
if (parameters.implicit_kind != ImplicitKind::kNoImplicit) {
Error("Intinsics cannot have implicit parameters.");
}
}
};
struct TorqueMacroDeclaration : MacroDeclaration {
DEFINE_AST_NODE_LEAF_BOILERPLATE(TorqueMacroDeclaration)
TorqueMacroDeclaration(SourcePosition pos, bool transitioning,
Identifier* name, base::Optional<std::string> op,
ParameterList parameters, TypeExpression* return_type,
const LabelAndTypesVector& labels, bool export_to_csa,
base::Optional<Statement*> body)
: MacroDeclaration(kKind, pos, transitioning, name, std::move(op),
std::move(parameters), return_type, labels),
export_to_csa(export_to_csa),
body(body) {}
bool export_to_csa;
base::Optional<Statement*> body;
};
struct BuiltinDeclaration : CallableDeclaration {
DEFINE_AST_NODE_INNER_BOILERPLATE(BuiltinDeclaration)
BuiltinDeclaration(AstNode::Kind kind, SourcePosition pos,
bool javascript_linkage, bool transitioning,
Identifier* name, ParameterList parameters,
TypeExpression* return_type)
: CallableDeclaration(kind, pos, transitioning, name,
std::move(parameters), return_type, {}),
javascript_linkage(javascript_linkage) {
if (parameters.implicit_kind == ImplicitKind::kJSImplicit &&
!javascript_linkage) {
Error(
"\"js-implicit\" is for implicit parameters passed according to the "
"JavaScript calling convention. Use \"implicit\" instead.");
}
if (parameters.implicit_kind == ImplicitKind::kImplicit &&
javascript_linkage) {
Error(
"The JavaScript calling convention implicitly passes a fixed set of "
"values. Use \"js-implicit\" to refer to those.")
.Position(parameters.implicit_kind_pos);
}
}
bool javascript_linkage;
};
struct ExternalBuiltinDeclaration : BuiltinDeclaration {
DEFINE_AST_NODE_LEAF_BOILERPLATE(ExternalBuiltinDeclaration)
ExternalBuiltinDeclaration(SourcePosition pos, bool transitioning,
bool javascript_linkage, Identifier* name,
ParameterList parameters,
TypeExpression* return_type)
: BuiltinDeclaration(kKind, pos, javascript_linkage, transitioning, name,
std::move(parameters), return_type) {}
};
struct TorqueBuiltinDeclaration : BuiltinDeclaration {
DEFINE_AST_NODE_LEAF_BOILERPLATE(TorqueBuiltinDeclaration)
TorqueBuiltinDeclaration(SourcePosition pos, bool transitioning,
bool javascript_linkage, Identifier* name,
ParameterList parameters,
TypeExpression* return_type,
base::Optional<Statement*> body)
: BuiltinDeclaration(kKind, pos, javascript_linkage, transitioning, name,
std::move(parameters), return_type),
body(body) {}
base::Optional<Statement*> body;
};
struct ExternalRuntimeDeclaration : CallableDeclaration {
DEFINE_AST_NODE_LEAF_BOILERPLATE(ExternalRuntimeDeclaration)
ExternalRuntimeDeclaration(SourcePosition pos, bool transitioning,
Identifier* name, ParameterList parameters,
TypeExpression* return_type)
: CallableDeclaration(kKind, pos, transitioning, name, parameters,
return_type, {}) {}
};
struct ConstDeclaration : Declaration {
DEFINE_AST_NODE_LEAF_BOILERPLATE(ConstDeclaration)
ConstDeclaration(SourcePosition pos, Identifier* name, TypeExpression* type,
Expression* expression)
: Declaration(kKind, pos),
name(name),
type(type),
expression(expression) {}
Identifier* name;
TypeExpression* type;
Expression* expression;
};
struct GenericDeclaration : Declaration {
DEFINE_AST_NODE_LEAF_BOILERPLATE(GenericDeclaration)
GenericDeclaration(SourcePosition pos,
std::vector<Identifier*> generic_parameters,
CallableDeclaration* declaration)
: Declaration(kKind, pos),
generic_parameters(std::move(generic_parameters)),
declaration(declaration) {}
std::vector<Identifier*> generic_parameters;
CallableDeclaration* declaration;
};
struct SpecializationDeclaration : CallableDeclaration {
DEFINE_AST_NODE_LEAF_BOILERPLATE(SpecializationDeclaration)
SpecializationDeclaration(SourcePosition pos, bool transitioning,
Identifier* name,
std::vector<TypeExpression*> generic_parameters,
ParameterList parameters,
TypeExpression* return_type,
LabelAndTypesVector labels, Statement* body)
: CallableDeclaration(kKind, pos, transitioning, name,
std::move(parameters), return_type,
std::move(labels)),
generic_parameters(std::move(generic_parameters)),
body(body) {}
std::vector<TypeExpression*> generic_parameters;
Statement* body;
};
struct ExternConstDeclaration : Declaration {
DEFINE_AST_NODE_LEAF_BOILERPLATE(ExternConstDeclaration)
ExternConstDeclaration(SourcePosition pos, Identifier* name,
TypeExpression* type, std::string literal)
: Declaration(kKind, pos),
name(name),
type(type),
literal(std::move(literal)) {}
Identifier* name;
TypeExpression* type;
std::string literal;
};
struct StructDeclaration : TypeDeclaration {
DEFINE_AST_NODE_LEAF_BOILERPLATE(StructDeclaration)
StructDeclaration(SourcePosition pos, Identifier* name,
std::vector<Declaration*> methods,
std::vector<StructFieldExpression> fields,
std::vector<Identifier*> generic_parameters)
: TypeDeclaration(kKind, pos, name),
methods(std::move(methods)),
fields(std::move(fields)),
generic_parameters(std::move(generic_parameters)) {}
std::vector<Declaration*> methods;
std::vector<StructFieldExpression> fields;
std::vector<Identifier*> generic_parameters;
bool IsGeneric() const { return !generic_parameters.empty(); }
};
struct ClassDeclaration : TypeDeclaration {
DEFINE_AST_NODE_LEAF_BOILERPLATE(ClassDeclaration)
ClassDeclaration(SourcePosition pos, Identifier* name, ClassFlags flags,
base::Optional<TypeExpression*> super,
base::Optional<std::string> generates,
std::vector<Declaration*> methods,
std::vector<ClassFieldExpression> fields)
: TypeDeclaration(kKind, pos, name),
flags(flags),
super(super),
generates(std::move(generates)),
methods(std::move(methods)),
fields(std::move(fields)) {}
ClassFlags flags;
base::Optional<TypeExpression*> super;
base::Optional<std::string> generates;
std::vector<Declaration*> methods;
std::vector<ClassFieldExpression> fields;
};
struct CppIncludeDeclaration : Declaration {
DEFINE_AST_NODE_LEAF_BOILERPLATE(CppIncludeDeclaration)
CppIncludeDeclaration(SourcePosition pos, std::string include_path)
: Declaration(kKind, pos), include_path(std::move(include_path)) {}
std::string include_path;
};
#define ENUM_ITEM(name) \
case AstNode::Kind::k##name: \
return std::is_base_of<T, name>::value; \
break;
template <class T>
bool AstNodeClassCheck::IsInstanceOf(AstNode* node) {
switch (node->kind) {
AST_NODE_KIND_LIST(ENUM_ITEM)
default:
UNIMPLEMENTED();
}
return true;
}
#undef ENUM_ITEM
inline bool IsDeferred(Statement* stmt) {
if (auto* block = BlockStatement::DynamicCast(stmt)) {
return block->deferred;
}
return false;
}
DECLARE_CONTEXTUAL_VARIABLE(CurrentAst, Ast);
template <class T, class... Args>
T* MakeNode(Args... args) {
return CurrentAst::Get().AddNode(std::unique_ptr<T>(
new T(CurrentSourcePosition::Get(), std::move(args)...)));
}
} // namespace torque
} // namespace internal
} // namespace v8
#endif // V8_TORQUE_AST_H_
|
hamzahamidi/v8
|
src/strings/string-hasher-inl.h
|
<reponame>hamzahamidi/v8
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_STRINGS_STRING_HASHER_INL_H_
#define V8_STRINGS_STRING_HASHER_INL_H_
#include "src/strings/string-hasher.h"
#include "src/objects/objects.h"
#include "src/objects/string-inl.h"
#include "src/strings/char-predicates-inl.h"
#include "src/utils/utils-inl.h"
namespace v8 {
namespace internal {
uint32_t StringHasher::AddCharacterCore(uint32_t running_hash, uint16_t c) {
running_hash += c;
running_hash += (running_hash << 10);
running_hash ^= (running_hash >> 6);
return running_hash;
}
uint32_t StringHasher::GetHashCore(uint32_t running_hash) {
running_hash += (running_hash << 3);
running_hash ^= (running_hash >> 11);
running_hash += (running_hash << 15);
int32_t hash = static_cast<int32_t>(running_hash & String::kHashBitMask);
int32_t mask = (hash - 1) >> 31;
return running_hash | (kZeroHash & mask);
}
uint32_t StringHasher::GetTrivialHash(int length) {
DCHECK_GT(length, String::kMaxHashCalcLength);
// String hash of a large string is simply the length.
return (length << String::kHashShift) | String::kIsNotArrayIndexMask;
}
template <typename schar>
uint32_t StringHasher::HashSequentialString(const schar* chars, int length,
uint64_t seed) {
// Check whether the string is a valid array index. In that case, compute the
// array index hash. It'll fall through to compute a regular string hash from
// the start if it turns out that the string isn't a valid array index.
if (IsInRange(length, 1, String::kMaxArrayIndexSize)) {
if (IsDecimalDigit(chars[0]) && (length == 1 || chars[0] != '0')) {
uint32_t index = chars[0] - '0';
int i = 1;
do {
if (i == length) {
return MakeArrayIndexHash(index, length);
}
} while (TryAddIndexChar(&index, chars[i++]));
}
} else if (length > String::kMaxHashCalcLength) {
return GetTrivialHash(length);
}
// Non-array-index hash.
DCHECK_LE(0, length);
DCHECK_IMPLIES(0 < length, chars != nullptr);
uint32_t running_hash = static_cast<uint32_t>(seed);
const schar* end = &chars[length];
while (chars != end) {
running_hash = AddCharacterCore(running_hash, *chars++);
}
return (GetHashCore(running_hash) << String::kHashShift) |
String::kIsNotArrayIndexMask;
}
std::size_t SeededStringHasher::operator()(const char* name) const {
return StringHasher::HashSequentialString(
name, static_cast<int>(strlen(name)), hashseed_);
}
} // namespace internal
} // namespace v8
#endif // V8_STRINGS_STRING_HASHER_INL_H_
|
chuffa/ITensor
|
itensor/mps/sites/fermion.h
|
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#pragma once
#include "itensor/mps/siteset.h"
#include "itensor/util/str.h"
namespace itensor {
class FermionSite;
using Fermion = BasicSiteSet<FermionSite>;
class FermionSite
{
Index s;
public:
FermionSite(Index I) : s(I) { }
FermionSite(Args const& args = Args::global())
{
auto ts = TagSet("Site,Fermion");
auto n = 1;
if(args.defined("SiteNumber"))
{
n = args.getInt("SiteNumber");
ts.addTags("n="+str(n));
}
auto conserveQNs = args.getBool("ConserveQNs",true);
auto conserve_Nf = args.getBool("ConserveNf",conserveQNs);
auto oddevenupdown = args.getBool("OddEvenUpDown",false);
if(not conserveQNs)
{
s = Index(2,ts);
}
else if(not oddevenupdown) //usual case
{
if(conserve_Nf) //usual case
{
s = Index(QN({"Nf",0,-1}),1,
QN({"Nf",1,-1}),1,Out,ts);
}
else
{
s = Index(QN({"Pf",0,-2}),1,
QN({"Pf",1,-2}),1,Out,ts);
}
}
else
{
auto q_emp = QN({"Sz",0},{"Nf",0,-1});
QN q_occ;
if(n%2==1) q_occ = QN({"Sz",+1},{"Nf",1,-1});
else q_occ = QN({"Sz",-1},{"Nf",1,-1});
s = Index(q_emp,1,
q_occ,1,Out,ts);
}
}
Index
index() const { return s; }
IndexVal
state(std::string const& state)
{
if(state == "Emp" || state == "0")
{
return s(1);
}
else
if(state == "Occ" || state == "1")
{
return s(2);
}
else
{
throw ITError("State " + state + " not recognized");
}
return IndexVal{};
}
ITensor
op(std::string const& opname,
Args const& args) const
{
auto sP = prime(s);
auto Emp = s(1);
auto EmpP = sP(1);
auto Occ = s(2);
auto OccP = sP(2);
auto Op = ITensor(dag(s),sP);
if(opname == "N" || opname == "n")
{
Op.set(Occ,OccP,1);
}
else
if(opname == "C")
{
Op.set(Occ,EmpP,1);
}
else
if(opname == "Cdag")
{
Op.set(Emp,OccP,1);
}
else
if(opname == "A")
{
Op.set(Occ,EmpP,1);
}
else
if(opname == "Adag")
{
Op.set(Emp,OccP,1);
}
else
if(opname == "F" || opname == "FermiPhase")
{
Op.set(Emp,EmpP,1);
Op.set(Occ,OccP,-1);
}
else
if(opname == "projEmp")
{
Op.set(Emp,EmpP,1);
}
else
if(opname == "projOcc")
{
Op.set(Occ,OccP,1);
}
else
{
throw ITError("Operator \"" + opname + "\" name not recognized");
}
return Op;
}
//
// Deprecated, for backwards compatibility
//
FermionSite(int n, Args const& args = Args::global())
{
*this = FermionSite({args,"SiteNumber=",n});
}
};
//
// Deprecated, for backwards compatability
//
using SpinlessSite = FermionSite;
using Spinless = BasicSiteSet<SpinlessSite>;
} //namespace itensor
|
chuffa/ITensor
|
itensor/util/cplx_literal.h
|
<filename>itensor/util/cplx_literal.h
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_CPLX_LITERAL_H
#define __ITENSOR_CPLX_LITERAL_H
#include <complex>
namespace itensor {
template<typename T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
std::complex<double> inline
operator*(T i, std::complex<double> const& z) { return double(i)*z; }
template<typename T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
std::complex<double>
operator*(std::complex<double> const& z, T i) { return z*double(i); }
template<typename T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
std::complex<double> inline
operator/(T i, std::complex<double> const& z) { return double(i)/z; }
template<typename T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
std::complex<double>
operator/(std::complex<double> const& z, T i) { return z/double(i); }
template<typename T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
std::complex<double>
operator+(T i, std::complex<double> const& z) { return double(i)+z; }
template<typename T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
std::complex<double>
operator+(std::complex<double> const& z, T i) { return z+double(i); }
template<typename T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
std::complex<double>
operator-(T i, std::complex<double> const& z) { return double(i)-z; }
template<typename T, typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
std::complex<double>
operator-(std::complex<double> const& z, T i) { return z-double(i); }
std::complex<double> constexpr inline
operator"" _i(unsigned long long int i)
{
return std::complex<double>(0.,i);
}
std::complex<double> constexpr inline
operator"" _i(long double x)
{
return std::complex<double>(0.,x);
}
} //namespace itensor
#endif
|
chuffa/ITensor
|
itensor/mps/TEvolObserver.h
|
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_TEVOLOBSERVER_H
#define __ITENSOR_TEVOLOBSERVER_H
#include "itensor/util/readwrite.h"
#include "itensor/mps/observer.h"
namespace itensor {
//
// Class for monitoring time evolution calculations.
// The measure and checkDone methods are virtual
// so that behavior can be customized in a
// derived class.
//
class TEvolObserver : public Observer
{
public:
TEvolObserver(Args const& args = Args::global());
virtual ~TEvolObserver() { }
void virtual
measure(Args const& args = Args::global());
bool virtual
checkDone(Args const& args = Args::global());
private:
/////////////
//
// Data Members
bool done_,
show_percent_;
//
/////////////
}; // class TEvolObserver
inline TEvolObserver::
TEvolObserver(const Args& args)
:
done_(false),
show_percent_(args.getBool("ShowPercent",true))
{
}
void inline TEvolObserver::
measure(const Args& args)
{
const Real t = args.getReal("Time");
if(show_percent_)
{
const Real ttotal = args.getReal("TotalTime");
Real percentdone = (100.*t)/ttotal;
if(percentdone < 99.5 || (std::fabs(t-ttotal) < 1E-10))
{
printf("\b\b\b%2.f%%",percentdone);
std::cout.flush();
}
}
}
bool inline TEvolObserver::
checkDone(const Args& args)
{
const Real t = args.getReal("Time");
if(fileExists("STOP_TEVOL"))
{
println("File STOP_TEVOL found: stopping this time evolution run at time ",t);
std::remove("STOP_TEVOL");
return true;
}
//Set done_ flag to true so any outer callers using this Observer will also terminate.
if(fileExists("STOP_TEVOL_ALL"))
{
println("File STOP_TEVOL_ALL found: stopping this time evolution at time ",t);
std::remove("STOP_TEVOL_ALL");
done_ = true;
return done_;
}
return done_;
}
} //namespace itensor
#endif // __ITENSOR_TEVOLOBSERVER_H
|
chuffa/ITensor
|
itensor/util/vector_no_init.h
|
<gh_stars>100-1000
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_VECTOR_NO_INIT_H
#define __ITENSOR_VECTOR_NO_INIT_H
#include <vector>
namespace itensor {
template <class T>
class uninitialized_allocator
{
public:
typedef T value_type;
uninitialized_allocator() noexcept { }
template <class U>
uninitialized_allocator(uninitialized_allocator<U> const&) noexcept { }
T*
allocate(std::size_t n)
{
return static_cast<T*>(::operator new(n * sizeof(T)));
}
void
deallocate(T* p, std::size_t) noexcept
{
::operator delete(static_cast<void*>(p));
}
template <class U>
void construct(U*) noexcept
{
//TODO: do we want this trait check? It fails for std::complex<double>
//static_assert(std::is_trivially_default_constructible<U>::value,
//"This allocator can only be used with trivally default constructible types");
}
template <class U, class A0, class... Args>
void
construct(U* up, A0&& a0, Args&&... args) noexcept
{
::new(up) U(std::forward<A0>(a0), std::forward<Args>(args)...);
}
bool
operator==(uninitialized_allocator<T> const&) { return true; }
bool
operator!=(uninitialized_allocator<T> const&) { return false; }
};
template<typename T>
using vector_no_init = std::vector<T,uninitialized_allocator<T>>;
} //namespace itensor
#endif
|
chuffa/ITensor
|
sample/src/hubbard.h
|
#include <itensor/all.h>
using namespace itensor;
AutoMPO
hubbard_2d_ky(SiteSet const& sites, Args const& args)
{
auto Nx = args.getInt("Nx");
auto Ny = args.getInt("Ny");
auto U = args.getReal("U", 0.0);
auto t = args.getReal("t", 1.0);
auto ampo = AutoMPO(sites);
for(auto x : range(Nx))
for(auto ky : range(Ny))
{
int s = x * Ny + ky + 1;
double disp = -2 * t * cos((2 * M_PI / Ny) * ky);
if(std::abs(disp) > 1e-12)
{
ampo += disp, "Nup", s;
ampo += disp, "Ndn", s;
}
}
for(auto x : range(Nx-1))
for(auto ky : range(Ny))
{
int s1 = x * Ny + ky + 1;
int s2 = (x + 1) * Ny + ky + 1;
ampo += -t, "Cdagup", s1, "Cup", s2;
ampo += -t, "Cdagup", s2, "Cup", s1;
ampo += -t, "Cdagdn", s1, "Cdn", s2;
ampo += -t, "Cdagdn", s2, "Cdn", s1;
}
if(U != 0)
{
for(auto x : range(Nx))
for(auto ky : range(Ny))
for(auto py : range(Ny))
for(auto qy : range(Ny))
{
int s1 = x * Ny + (ky + qy + Ny) % Ny + 1;
int s2 = x * Ny + (py - qy + Ny) % Ny + 1;
int s3 = x * Ny + py + 1;
int s4 = x * Ny + ky + 1;
ampo += (U / Ny), "Cdagdn", s1, "Cdagup", s2, "Cup", s3, "Cdn", s4;
}
}
return ampo;
}
|
chuffa/ITensor
|
itensor/util/infarray.h
|
<filename>itensor/util/infarray.h
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_INFARRAY_H
#define __ITENSOR_INFARRAY_H
#include <array>
#include <vector>
#include <iterator>
#include "itensor/util/error.h"
#include "itensor/util/safe_ptr.h"
#ifdef DEBUG
#define CHECK_IND(X) check_ind(X);
#else
#define CHECK_IND(X)
#endif
#ifdef DEBUG
#define CHECK_EMPTY check_empty();
#else
#define CHECK_EMPTY
#endif
namespace itensor {
template<typename T, size_t ArrSize>
class InfArray
{
public:
using array_type = std::array<T,ArrSize>;
using value_type = typename array_type::value_type;
using size_type = typename array_type::size_type;
using difference_type = typename array_type::difference_type;
using reference = typename array_type::reference;
using const_reference = typename array_type::const_reference;
using pointer = value_type*;
using const_pointer = const value_type*;
using iterator = pointer;
using const_iterator = const_pointer;
private:
pointer data_ = nullptr;
size_t size_ = 0;
array_type arr_;
std::vector<T> vec_;
public:
InfArray()
: size_(0)
{
data_ = &(arr_[0]);
#ifdef DEBUG
if(size_ <= ArrSize) assert(data_==&(arr_[0]));
#endif
}
InfArray(size_t size)
{
if(size <= ArrSize)
{
data_ = &(arr_[0]);
size_ = size;
}
else
{
//println("Resizing vec_ in InfArray");
vec_.resize(size);
data_ = vec_.data();
size_ = vec_.size();
}
#ifdef DEBUG
if(size_ <= ArrSize) assert(data_==&(arr_[0]));
#endif
}
InfArray(size_t size,
const_reference value)
: InfArray(size)
{
std::fill(data_,data_+size_,value);
#ifdef DEBUG
if(size_ <= ArrSize) assert(data_==&(arr_[0]));
#endif
}
InfArray(std::initializer_list<T> init)
: InfArray(init.size())
{
auto p = data_;
for(auto& el : init)
{
*p = el;
++p;
}
}
InfArray(const InfArray& o)
: size_(o.size_),
arr_(o.arr_),
vec_(o.vec_)
{
setDataPtr();
}
InfArray&
operator=(const InfArray& o)
{
size_ = o.size_;
arr_ = o.arr_;
vec_ = o.vec_;
setDataPtr();
return *this;
}
InfArray(InfArray&& o)
: size_(o.size_),
arr_(std::move(o.arr_)),
vec_(std::move(o.vec_))
{
o.size_ = 0;
o.data_ = nullptr;
setDataPtr();
}
InfArray&
operator=(InfArray&& o)
{
size_ = o.size_;
arr_ = std::move(o.arr_);
vec_ = std::move(o.vec_);
o.size_ = 0;
o.data_ = nullptr;
setDataPtr();
return *this;
}
void
resize(size_t new_size)
{
if(new_size > ArrSize)
{
//println("Resizing vec_ in InfArray");
vec_.resize(new_size);
if(size_ <= ArrSize)
{
//auto pv = MAKE_SAFE_PTR(vec_.data(),vec_.size());
//std::copy(arr_.begin(),arr_.begin()+size_,pv);
auto pv = vec_.data();
std::copy(arr_.begin(),arr_.begin()+size_,pv);
}
data_ = vec_.data();
}
else //new_size <= ArrSize and not zero
{
if(size_ > ArrSize)
{
//auto pa = MAKE_SAFE_PTR(&(arr_[0]),ArrSize);
//std::copy(vec_.begin(),vec_.begin()+new_size,pa);
auto pa = &(arr_[0]);
std::copy(vec_.begin(),vec_.begin()+new_size,pa);
}
vec_.clear();
data_ = &(arr_[0]);
}
size_ = new_size;
#ifdef DEBUG
if(size_ <= ArrSize) assert(data_==&(arr_[0]));
else assert(data_==vec_.data());
#endif
}
void
assign(size_t new_size,
const_reference val)
{
resize(new_size);
std::fill(begin(),end(),val);
}
void
fill(const_reference val)
{
std::fill(begin(),end(),val);
}
size_t
size() const { return size_; }
size_t constexpr static
arr_size() { return ArrSize; }
size_t
vec_size() const { return vec_.size(); }
void
clear()
{
data_ = &(arr_[0]);
size_ = 0;
vec_.clear();
}
void
swap(InfArray& other)
{
arr_.swap(other.arr_);
vec_.swap(other.vec_);
std::swap(size_,other.size_);
setDataPtr();
}
explicit operator bool() const { return size_!=0; }
reference
operator[](size_t i)
{
CHECK_IND(i)
#ifdef DEBUG
if(size_ <= ArrSize) assert(data_==&(arr_[0]));
else assert(data_==vec_.data());
#endif
return data_[i];
}
const_reference
operator[](size_t i) const
{
CHECK_IND(i)
#ifdef DEBUG
if(size_ <= ArrSize) assert(data_==&(arr_[0]));
else assert(data_==vec_.data());
#endif
return data_[i];
}
void
push_back(const_reference val)
{
if(size_ < ArrSize)
{
arr_[size_] = val;
++size_;
}
else if(size_ == ArrSize)
{
resize(size_+1);
back() = val;
}
else
{
vec_.push_back(val);
data_ = vec_.data();
++size_;
}
#ifdef DEBUG
if(size_ <= ArrSize) assert(data_==&(arr_[0]));
else assert(data_==vec_.data());
#endif
}
void
push_back(value_type&& val)
{
if(size_ < ArrSize)
{
arr_[size_] = std::move(val);
++size_;
}
else if(size_ == ArrSize)
{
resize(size_+1);
back() = std::move(val);
}
else
{
vec_.emplace_back(std::move(val));
data_ = vec_.data();
++size_;
}
#ifdef DEBUG
if(size_ <= ArrSize) assert(data_==&(arr_[0]));
else assert(data_==vec_.data());
#endif
}
void
erase(const_iterator it)
{
if(size_ <= ArrSize)
{
auto* e = &(arr_[size_]);
iterator p = &(arr_[0]);
for(; p != e; ++p)
if(p == it) break;
if(p == e) throw std::runtime_error("erase: element not found");
for(; (p+1) != e; ++p)
{
*p = *(p+1);
}
}
else
{
//TODO: if new size <= ArrSize move data?
auto vit = vec_.begin();
for(; vit != vec_.end(); ++vit)
if(&(*vit) == it) break;
if(vit == vec_.end()) throw std::runtime_error("erase: element not found");
vec_.erase(vit);
data_ = vec_.data();
}
--size_;
#ifdef DEBUG
if(size_ <= ArrSize) assert(data_==&(arr_[0]));
else assert(data_==vec_.data());
#endif
}
reference
at(size_t i) { check_ind(i); return data_[i]; }
const_reference
at(size_t i) const { check_ind(i); return data_[i]; }
pointer
data() { return data_; }
const_pointer
data() const { return data_; }
reference
front() { CHECK_EMPTY return *data_; }
const_reference
front() const { CHECK_EMPTY return *data_; }
reference
back() { CHECK_EMPTY return *(data_+(size_-1)); }
const_reference
back() const { CHECK_EMPTY return *(data_+(size_-1)); }
bool
empty() const { return size_==0; }
iterator
begin() { return data_; }
iterator
end() { return data_+size_; }
const_iterator
begin() const { return data_; }
const_iterator
end() const { return data_+size_; }
const_iterator
cbegin() const { return data_; }
const_iterator
cend() const { return data_+size_; }
std::reverse_iterator<iterator>
rbegin() { return std::reverse_iterator<iterator>(end()); }
std::reverse_iterator<iterator>
rend() { return std::reverse_iterator<iterator>(begin()); }
std::reverse_iterator<const_iterator>
rbegin() const { return std::reverse_iterator<const_iterator>(end()); }
std::reverse_iterator<const_iterator>
rend() const { return std::reverse_iterator<const_iterator>(begin()); }
template<typename T2, size_t ArrSize2>
bool
operator==(InfArray<T2,ArrSize2> const& v2) const
{
if(size() != v2.size()) return false;
for(int i = 0; i < size(); ++i)
if(operator[](i) != v2[i]) return false;
return true;
}
private:
void
setDataPtr()
{
if(size_ <= ArrSize) data_ = &(arr_[0]);
else data_ = vec_.data();
}
void
check_ind(size_t i) const
{
//if(i >= size_) Error("index out of range in InfArray");
if(i >= size_) throw std::runtime_error("index out of range in InfArray");
}
void
check_empty() const
{
if(size_==0) Error("InfArray is empty");
}
};
//template<typename T, size_t ArrSize>
//class InfArray
// {
// //InfArray(std::initializer_list<T> init)
// // {
// // resize(init.size());
// // auto p = data_;
// // for(auto& el : init)
// // {
// // *p = el;
// // ++p;
// // }
// // }
//
// size_t
// size() const { return size_; }
//
// size_t constexpr
// arr_size() const { return ArrSize; }
//
// size_t
// vec_size() const { return vec_.size(); }
//
// //void
// //resize(size_t new_size)
// // {
// // if(new_size > ArrSize)
// // {
// // vec_.resize(new_size);
// // if(size_ <= ArrSize)
// // {
// // auto pv = MAKE_SAFE_PTR(vec_.data(),vec_.size());
// // std::copy(arr_.begin(),arr_.begin()+size_,pv);
// // }
// // data_ = vec_.data();
// // }
// // else //new_size <= ArrSize and not zero
// // {
// // if(size_ > ArrSize)
// // {
// // auto pa = MAKE_SAFE_PTR(&(arr_[0]),ArrSize);
// // std::copy(vec_.begin(),vec_.begin()+new_size,pa);
// // }
// // vec_.clear();
// // data_ = &(arr_[0]);
// // }
// // size_ = new_size;
// // }
//
// void
// clear()
// {
// data_ = &(arr_[0]);
// size_ = 0;
// vec_.clear();
// }
//
// //void
// //push_back(const_reference val)
// // {
// // if(size_ < ArrSize)
// // {
// // arr_[size_] = val;
// // ++size_;
// // }
// // else if(size_ == ArrSize)
// // {
// // resize(size_+1);
// // back() = val;
// // }
// // else
// // {
// // vec_.push_back(val);
// // data_ = vec_.data();
// // ++size_;
// // }
// // }
//
// //void
// //push_back(value_type&& val)
// // {
// // if(size_ < ArrSize)
// // {
// // arr_[size_] = std::move(val);
// // ++size_;
// // }
// // else if(size_ == ArrSize)
// // {
// // resize(size_+1);
// // back() = std::move(val);
// // }
// // else
// // {
// // vec_.emplace_back(std::move(val));
// // data_ = vec_.data();
// // ++size_;
// // }
// // }
//
// //void
// //assign(size_t count,
// // const_reference val)
// // {
// // resize(count);
// // fill(val);
// // }
//
// explicit operator bool() const { return size_!=0; }
//
// //reference
// //operator[](size_t i) { CHECK_IND(i) return *(data_+i); }
//
// //const_reference
// //operator[](size_t i) const { CHECK_IND(i) return *(data_+i); }
//
// //TODO DEBUG
// reference
// operator[](size_t i)
// {
// CHECK_IND(i)
// //return arr_[i];
// //data_ = &(arr_[0]);
//#ifdef DEBUG
// if(size_ <= ArrSize) assert(data_==&(arr_[0]));
//#endif
// return data_[i];
// }
//
// //TODO DEBUG
// const_reference
// operator[](size_t i) const
// {
// CHECK_IND(i)
// //return arr_[i];
// //auto cdata_ = &(arr_[0]);
//#ifdef DEBUG
// if(size_ <= ArrSize) assert(data_==&(arr_[0]));
//#endif
// return data_[i];
// }
//
// reference
// at(size_t i) { check_ind(i); return data_[i]; }
//
// const_reference
// at(size_t i) const { check_ind(i); return data_[i]; }
//
// reference
// front() { CHECK_EMPTY return *data_; }
//
// const_reference
// front() const { CHECK_EMPTY return *data_; }
//
// //reference
// //back() { CHECK_EMPTY return data_[size_-1]; }
//
// //const_reference
// //back() const { CHECK_EMPTY return data_[size_-1]; }
//
// pointer
// data() { return data_; }
//
// const_pointer
// data() const { return data_; }
//
// bool
// empty() const { return size_==0; }
//
// void
// fill(const_reference val)
// {
// if(size_==0) return;
// std::fill(data_,data_+size_,val);
// }
//
// void
// swap(InfArray& other)
// {
// std::swap(data_,other.data_);
// std::swap(size_,other.size_);
// arr_.swap(other.arr_);
// vec_.swap(other.vec_);
//#ifdef DEBUG
// if(size_ <= ArrSize) assert(data_==&(arr_[0]));
//#endif
// }
//
// iterator
// begin() { return data_; }
//
// iterator
// end() { return data_+size_; }
//
// const_iterator
// begin() const { return data_; }
//
// const_iterator
// end() const { return data_+size_; }
//
// const_iterator
// cbegin() const { return data_; }
//
// const_iterator
// cend() const { return data_+size_; }
//
// private:
// void
// check_ind(size_t i) const
// {
// if(i >= size_) Error("index out of range in InfArray");
// }
// void
// check_empty() const
// {
// if(size_==0) Error("InfArray is empty");
// }
// };
} //namespace itensor
#undef CHECK_EMPTY
#undef CHECK_IND
#endif
|
chuffa/ITensor
|
itensor/mps/tevol.h
|
<reponame>chuffa/ITensor<filename>itensor/mps/tevol.h
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_TEVOL_H
#define __ITENSOR_TEVOL_H
#include "itensor/mps/mpo.h"
#include "itensor/mps/bondgate.h"
#include "itensor/mps/TEvolObserver.h"
namespace itensor {
//
// Evolves an MPS in real or imaginary time by an amount ttotal in steps
// of tstep using the list of bond gates provided.
//
// Arguments recognized:
// "Verbose": if true, print useful information to stdout
//
template <class Iterable>
Real
gateTEvol(Iterable const& gatelist,
Real ttotal,
Real tstep,
MPS & psi,
Args const& args = Args::global());
template <class Iterable>
Real
gateTEvol(Iterable const& gatelist,
Real ttotal,
Real tstep,
MPS & psi,
Observer& obs,
Args args = Args::global());
//
//
// Implementations
//
template <class Iterable>
Real
gateTEvol(Iterable const& gatelist,
Real ttotal,
Real tstep,
MPS & psi,
Observer& obs,
Args args)
{
const bool verbose = args.getBool("Verbose",false);
const bool do_normalize = args.getBool("Normalize",true);
const int nt = int(ttotal/tstep+(1e-9*(ttotal/tstep)));
if(fabs(nt*tstep-ttotal) > 1E-9)
{
Error("Timestep not commensurate with total time");
}
if(verbose)
{
printfln("Taking %d steps of timestep %.5f, total time %.5f",nt,tstep,ttotal);
}
psi.position(gatelist.front().i1());
Real tot_norm = norm(psi);
Real tsofar = 0;
for(auto tt : range1(nt))
{
auto g = gatelist.begin();
while(g != gatelist.end())
{
auto i1 = g->i1();
auto i2 = g->i2();
auto AA = psi(i1)*psi(i2)*g->gate();
AA.replaceTags("Site,1","Site,0");
++g;
if(g != gatelist.end())
{
//Look ahead to next gate position
auto ni1 = g->i1();
auto ni2 = g->i2();
//SVD AA to restore MPS form
//before applying current gate
if(ni1 >= i2)
{
psi.svdBond(i1,AA,Fromleft,args);
psi.position(ni1); //does no work if position already ni1
}
else
{
psi.svdBond(i1,AA,Fromright,args);
psi.position(ni2); //does no work if position already ni2
}
}
else
{
//No next gate to analyze, just restore MPS form
psi.svdBond(i1,AA,Fromright,args);
}
}
if(do_normalize)
{
tot_norm *= psi.normalize();
}
tsofar += tstep;
args.add("TimeStepNum",tt);
args.add("Time",tsofar);
args.add("TotalTime",ttotal);
obs.measure(args);
}
if(verbose)
{
printfln("\nTotal time evolved = %.5f\n",tsofar);
}
return tot_norm;
} // gateTEvol
template <class Iterable>
Real
gateTEvol(Iterable const& gatelist,
Real ttotal,
Real tstep,
MPS & psi,
Args const& args)
{
TEvolObserver obs(args);
return gateTEvol(gatelist,ttotal,tstep,psi,obs,args);
}
} //namespace itensor
#endif
|
chuffa/ITensor
|
itensor/itdata/qcombiner.h
|
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_QCOMBINER_H
#define __ITENSOR_QCOMBINER_H
#include "itensor/itdata/qdense.h"
#include <tuple>
namespace itensor {
class QN;
class QCombiner
{
struct BlockRange
{
size_t block = 0,
start = 0,
extent = 0;
void
write(std::ostream& s) const
{
s.write((char*)&block, sizeof(size_t));
s.write((char*)&start, sizeof(size_t));
s.write((char*)&extent, sizeof(size_t));
}
void
read(std::istream& s)
{
s.read((char*)&block, sizeof(size_t));
s.read((char*)&start, sizeof(size_t));
s.read((char*)&extent, sizeof(size_t));
}
std::ostream&
print(std::ostream & s) const
{
s << "Block: " << block << ", Start: " << start << ", Extent: " << extent << "\n";
return s;
}
};
public:
using storage_type = std::vector<BlockRange>;
using size_type = storage_type::size_type;
//private:
Range R_;
storage_type store_;
public:
QCombiner() { }
template<typename Inds>
explicit
QCombiner(Inds const& cinds)
{
//set up range to sum over all possible
//blocks that can be formed out of combined inds
auto RB = RangeBuilder(cinds.size());
for(auto j : itensor::range(cinds))
RB.nextIndex(cinds[j].nblock());
R_ = RB.build();
store_.resize(dim(R_));
}
explicit
QCombiner(Range && range, storage_type && store)
: R_(std::move(range)),
store_(std::move(store))
{ }
Range const&
range() const { return R_; }
storage_type const&
store() const { return store_; }
void
setBlockRange(Range::iterator const& bit,
size_type block,
size_type start,
size_type extent)
{
auto& bs = store_.at(bit.offset());
bs.block = block;
bs.start = start;
bs.extent = extent;
}
template<typename BlockInd>
std::tuple<size_type,size_type,size_type>
getBlockRange(BlockInd const& bind) const
{
auto& bs = store_.at(offset(R_,bind));
return std::make_tuple(bs.block,bs.start,bs.start+bs.extent);
}
};
const char*
typeNameOf(QCombiner const& d);
void
read(std::istream& s, QCombiner & dat);
void
write(std::ostream& s, QCombiner const& dat);
std::ostream&
operator<<(std::ostream& s, QCombiner const& dat);
Cplx
doTask(GetElt const& g, QCombiner const& c);
Real inline
doTask(NormNoScale, QCombiner const& d) { return 0; }
void inline
doTask(Conj,QCombiner const& d) { }
template<typename T>
void
doTask(Contract & C,
QDense<T> const& d,
QCombiner const& cmb,
ManageStore & m);
template<typename T>
void
doTask(Contract & C,
QCombiner const& cmb,
QDense<T> const& d,
ManageStore & m);
void inline
doTask(PrintIT & P,
QCombiner const& d) { P.s << "QCombiner "; }
auto inline
doTask(StorageType const& S, QCombiner const& d) ->StorageType::Type { return StorageType::QCombiner; }
QN inline
doTask(CalcDiv const& C, QCombiner const& d) { return QN{}; }
bool inline
doTask(CheckComplex, QCombiner const& d) { return false; }
} //namespace itensor
#endif
|
chuffa/ITensor
|
itensor/tensor/contract_impl.h
|
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_CONTRACT_IMPL_H__
#define __ITENSOR_CONTRACT_IMPL_H__
namespace itensor {
namespace detail {
//Helper class for ncprod.
//Holds an container of pointers to value_type,
//PtrInter interface pretends this is an actual
//container of values (not pointers) instead
template<typename value_type_, size_t ArrSize>
class PtrInd
{
public:
using value_type = value_type_;
using pointer_type = value_type const*;
using storage_type = InfArray<pointer_type,ArrSize>;
using size_type = typename storage_type::size_type;
private:
storage_type ptrs_;
public:
PtrInd(size_type size)
: ptrs_(size,nullptr)
{ }
size_type
size() const { return ptrs_.size(); }
void
set(size_type n, pointer_type p)
{
ptrs_[n] = p;
}
value_type const&
operator[](size_type n) const
{
return *(ptrs_[n]);
}
};
} //namespace detail
//Non-contracting product
template<typename R, typename VA, typename VB>
void
ncprod_impl(TenRefc<R,VA> A, Labels const& ai,
TenRefc<R,VB> B, Labels const& bi,
TenRef<R,common_type<VA,VB>> C, Labels const& ci)
{
auto rA = order(A),
rB = order(B),
rC = order(C);
auto cb = rangeBegin(C.range());
auto ce = rangeEnd(C.range());
using value_type = stdx::remove_reference_t<decltype(cb[0])>;
using PtrIndType = detail::PtrInd<value_type,Labels::arr_size()>;
auto aind = PtrIndType(rA);
auto bind = PtrIndType(rB);
for(auto nc : range(rC))
{
for(auto na : range(rA))
{
if(ci[nc] == ai[na])
{
aind.set(na,&cb[nc]);
break;
}
}
for(auto nb : range(rB))
{
if(ci[nc] == bi[nb])
{
bind.set(nb,&cb[nc]);
break;
}
}
}
auto pa = MAKE_SAFE_PTR(A.data(),A.size());
auto pb = MAKE_SAFE_PTR(B.data(),B.size());
auto pc = MAKE_SAFE_PTR(C.data(),C.size());
for(; cb != ce; ++cb)
{
pc[cb.offset()] = pa[offset(A,aind)] * pb[offset(B,bind)];
}
}
template<class TA, class TB, class TC>
void
ncprod(TA && A, Labels const& ai,
TB && B, Labels const& bi,
TC && C, Labels const& ci)
{
ncprod_impl(makeRef(A),ai,makeRef(B),bi,makeRef(C),ci);
}
} // namespace itensor
#endif
|
chuffa/ITensor
|
itensor/tagset.h
|
//
// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef __ITENSOR_TAGSET_H
#define __ITENSOR_TAGSET_H
#include "itensor/smallstring.h"
#include "itensor/global.h"
#include "itensor/util/h5/wrap_h5.hpp"
namespace itensor {
using Tag = SmallString;
class TagSet;
//
// TagSet
//
class TagSet
{
public:
using tags_type = std::array<Tag,MAX_TAGS>;
using prime_type = int;
private:
tags_type tags_;
prime_type primelevel_ = -1;
size_t size_ = 0;
public:
TagSet() {}
//
// Convert a character array to a TagSet.
// Parses the array for ',' and splits up into tags, for example:
// "a,b,c" -> Tag("a"),Tag("b"),Tag("c")
TagSet(const char* s);
TagSet(std::string const& s) : TagSet(s.c_str()) {}
// 0-indexed access
Tag const&
operator[](int i) const { return tags_[i]; }
Tag &
operator[](int i) { return tags_[i]; }
int
primeLevel() const { return primelevel_;}
void
setPrime(int plev) { primelevel_ = plev;}
void
prime(int plinc = 1) { primelevel_ += plinc;}
size_t
size() const {return size_;}
operator std::string () const
{
std::string str = "";
for(auto i : range(size_))
{
str += std::string(tags_[i]);
if( i < size_-1 ) str += ",";
}
if( primelevel_ >= 0 ) str += "," + std::to_string(primelevel_);
return str;
}
bool
hasTags(TagSet const& ts) const;
int
tagPosition(Tag const& t) const;
void
addTag(Tag const& t);
void
addTags(TagSet const& ts);
void
removeTag(Tag const& t);
void
removeTags(TagSet const& ts);
void
setTags(TagSet const& ts);
void
noTags();
void
replaceTags(TagSet const& tsremove, TagSet const& tsadd);
};
// Get the number of tags in the TagSet
size_t
size(TagSet const& ts);
int
primeLevel(TagSet const& ts);
TagSet
setPrime(TagSet ts, int plev);
bool
operator==(TagSet const& t1, TagSet const& t2);
bool
operator!=(TagSet const& t1, TagSet const& t2);
bool
hasTags(TagSet const& T, TagSet const& ts);
TagSet
addTags(TagSet T, TagSet const& ts);
TagSet
removeTags(TagSet T, TagSet const& ts);
std::ostream&
operator<<(std::ostream & s, TagSet const& ts);
void
write(std::ostream& s, TagSet const& ts);
void
read(std::istream& s, TagSet & ts);
#ifdef ITENSOR_USE_HDF5
void
h5_write(h5::group parent, std::string const& name, TagSet const& ts);
void
h5_read(h5::group parent, std::string const& name, TagSet & ts);
#endif
} //namespace itensor
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.