I want to simply pass a variable from assembly over to C and C over to assembly.
The problem is i don't want to use fixed memory addressing (IE. putting the value in a specific location and then using a pointer to access that specific location).
I was initially thinking that i could use registers, but there are only 16 in total! I may have more than 16 values which i want to pass over.
So the next thing i can think of is pushing the values onto the stack. But does this mean i have to use inline assembly to access it in C? something like this:
asm ( assembler template
: output operands /* optional */
: input operands /* optional */
: list of clobbered registers /* optional */
);
Is there any other way to go about this? Can anyone give me a REALLY simple example of putting something on the stack, and then accessing it in C code?
Assembly Noob!
Can you declare a regular C function, call it from C, and allow the compiler to handle the arguments automatically (according to whatever your local convention is)?
If so, you just implement that function using asm, and refer to the named C argument list variables directly.
Eg, using the 68881's fsinx instruction:
float my_fsinx(float angle)
{
float result;
asm ("fsinx %1,%0" : "=f" (result) : "f" (angle));
return result;
}
This example is based on the GCC Extended Asm docs, where you should be able to find some more examples.
Now extended, as per the comment, to handle variable numbers of arguments via a simple pointer & count ...
float my_fsinx_sum(float *angles, int num_angles)
{
float result, sum;
int i;
for (i=0, sum=0; i < num_angles; ++i)
{
asm ("fsinx %1,%0" : "=f" (result) : "f" (angles[i]));
sum += result;
}
return sum;
}
No, I'm not sure why you'd want to sum the sines of a bunch of angles either, but hopefully you get the idea. I haven't tried this, so it's possible the angles[i] value needs to be copied out into a local float variable before the asm - try it and see.
You could also use a variable argument-list function, but that's a little more complicated. Without more detail on what you're trying to accomplish and what you've already tried, I can't guess which is better.
Edit --
OK, now I've seen your comment above, you definitely don't want a variable argument-list function: those still have a number of arguments hardcoded at the call site.
Related
Say I have a tight loop in C, within which I use the value of a global variable to do some arithmetics, e.g.
double c;
// ... initialize c somehow ...
double f(double*a, int n) {
double sum = 0.0;
int i;
for (i = 0; i < n; i++) {
sum += a[i]*c;
}
return sum;
}
with c the global variable. Is c "read anew from global scope" in each loop iteration? After all, it could've been changed by some other thread executing some other function, right? Hence would the code be faster by taking a local (function stack) copy of c prior to the loop and only use this copy?
double f(double*a, int n) {
double sum = 0.0;
int i;
double c_cp = c;
for (i = 0; i < n; i++) {
sum += a[i]*c_cp;
}
return sum;
}
Though I haven't specified how c is initialized, let's assume it's done in some way such that the value is unknown at compile time. Also, c is really a constant throughout runtime, i.e. I as the programmer knows that its value won't change. Can I let the compiler in on this information, e.g. using static double c in the global scope? Does this change the a[i]*c vs. a[i]*c_cp question?
My own research
Reading e.g. the "Global variables" section of this, it seems clear that taking a local copy of the global variable is the way to go. However, they want to update the value of the global variable, whereas I only ever want to read its value.
Using godbolt I fail to notice any real difference in the assembly for both c vs. c_cp and double c vs. static double c.
Any decently smart compiler will optimize your code so it will behave as your second code snippet. Using static won't change much, but if you want to ensure read on each iteration then use volatile.
Great point there about changes from a different thread. Compiler will maintain integrity of your code as far as single-threaded execution goes. That means that it can reorder your code, skip something, add something -- as long as the end result is still the same.
With multiple threads it is your job to ensure that things still happen in a specific order, not just that the end result is right. The way to ensure that are memory barriers. It's a fun topic to read, but one that is best avoided unless you're an expert.
Once everything translated to machine code, you will get no difference whatsoever. If c is global, any access to c will reference the address of c or most probably, in a tight loop c will be kept in a register, or in the worst case the L1 cache.
On a Linux machine you can easily generate the assembly and examine the resultant code.
You can also run benchmarks.
int main()
{
int B = 1;
int x = rand()%10+1;
int x1 = rand()%10+1;
int A = 1;
while((B <= 5))
{
B++;
A++;
if(B == x)
{
return 0;
}
}
task(A) //The variable A passes in the range of values before the task function
A = -2;
return 0;
}
/*How can I use frama-c to get the range of A at task code if I want to get the range of A at task statement position instead of the range of A at the end of the program execution*/
How can I use frama-c to get the range of A at task code if I want to get the range of A at task statement position instead of the range of A at the end of the program execution
If I understand your question well, you would like to know the interval of variation of A at a specific statement. I assume that you're are relying on the Eva plug-in, as it is the kind of information that is typically given by Eva (at least if I interpret well "instead of the range of A at the end of the program execution").
There are two possibilities. The first one is to use the programmatic API of Eva, namely the Db.Value module. This requires knowledge of OCaml and reading the Frama-C developer manual, but is the most flexible and stable way to access the information. Briefly speaking, Db.Value.get_state will, as its name suggests, return the abstract state computed after a run of the Eva analyzer, for the statement given as argument, while Db.Value.eval_expr, will, given an abstract state and an expression, compute the abstract value of the expression in the corresponding state.
The second possibility is to use the Frama_C_show_each_* family of built-in functions: whenever Eva encounters a function whose name starts with Frama_C_show_each_, it will print on the standard output the abstract value of the arguments given to the function in the current abstract state. Hence, adding Frama_C_show_each_A(A); before the call to task(A) will give you, with frama-c -eva test.i, among other things
[eva] test.i:19: Frama_C_show_each_A: [1..2147483647]
Note that I've modified your code in order to let it run properly with Frama-C:
added prototype extern int rand(void); and extern void task(int);
added a ';' after task(A)
Please ensure that you provide a minimal, complete and verifiable example with your questions, this makes them much, much, easier to answer
I have one question:
int swapnum( int x, int y )
{
int tempnum ;
tempnum = x ;
x = y ;
y = tempnum ;
return tempnum;
}
int swapnum(int, int);
int main( )
{
int x = 35, y = 45 ;
printf("Before swapping: %d, %d", x, y);
swapnum(x, y);
printf("\nAfter swapping: %d, %d", x, y);
return 0;
}
I have found this example in internet which demonstrates how call by value works. I understand everything except one thing. For what do we need call by value if we do not get changed result in main? I understood idea of call by reference; we will receive changed result but for what do we need call by value if result is changed only locally (in upper part of this code) and main stays unchanged (printf("\nAfter swapping: %d, %d", x, y);)? And if you write your example too to demonstrate it would be great.
There are even functions which do not return anything.
They have a prototype like
void useTwoNums(int, int);
They illustrate even better than your example that it is not necessary to return anything, even less something which somehow uses the two input parameters and/or depends on them.
The concept which you seem to be missing is the difference between "functions" in mathematical context and "functions" in programming. In programming a function might well do something without returning something. One example is a function which just nicely prints the input values, compare printf(),
http://en.cppreference.com/w/c/io/fprintf
Its return value can be handled inside the return-value-free function to illustrate.
The extreme case would be a function with neither parameters nor return value:
void DoSomethingInFreespace(void);. Functions like that can achieve the data to process e.g. via other input channels. Or they are simply refactored pieces of code, e.g. for reuse, which have a sufficiently rich context, e.g. global or file local variables.
To make the answer more complete, I will integrate some points from comments (including the one by OP, which focuses on return values):
With call-by-value functions are more close to mathematical functions, and are then much more easily composed. (Jean-Baptiste Yunès).
and
it allows you to send values without worrying that some function will change them. It's very convenient. (njzk2)
Both (and other, too) stress that a mathematical function does not alter the parameters; this is something of a "promise" which programmers appreciate.
Turning it around:
when using call by value if you want that [a value in the context outside of the function, e.g.] main be changed we must return the result (OP)
Different angle:
when using call by reference, we don't need to return; it [the parameter] itself changes [outside of the context of the called function and can be used as a] result (OP)
I have found this example in internet which demonstrates how works call by value. I understand everything except one thing: for what do we need call by value?
You don't need call-by-value. But call-by-value is how C works, and most programming languages actually, so you would do well to learn it.
I understood idea of call by reference, we will receive changed result but for what do we need call by value if result is changed only locally
Call-by-value is used in most programming languages because it makes it easier to think about the code. When you see doStuff(x, y); you know that x and y won't change. They can only change if you write doStuff(&x, &y); or x = doStuff(y); or something like that. You don't need go and look up the DoStuff Manual to find out whether doStuff is supposed to change them.
and if you write your example too to demonstrate it would be great.
There's really nothing to demonstrate; the point of call-by-value is that nothing happens. Do you want a demonstration of nothing happening?
The return value is useful when you have formulas.
If you want to calculate the hypotenus from the cathetus and you pass the value of the latters, you do not want theit value modified.
I have some C function which, among other things, does a modulo operation. So it looks something like
const int M = 641;
void func( ...parameters..) {
int x;
... some operations ...
x %= M;
... some more operations ...
}
Now, what is crucial for me is that the number M here is a constant. If I would not tell the compiler that M is a constant, then I would get much slower performance.
Currently, I am very happy with my function func( .. ) , and I want would like to extend it, so it can work on different moduli. But again, it is crucial here that these moduli are fixed. So I would like to be able to do something like
const int arrayM[] = {641, 31, 75, 81, 123};
and then have for each index in the array of constants array_M[i] a version of the function func, say func_i, which is a copy of the function func, but where array_M[i] replaces the role of M.
In practice, my array of constants arrayM[] will consist of around 600 explicit prime numbers, which I will choose in a particular way so that x % array_M[i] compiles to a very fast modulus function (for instance Mersenne primes).
My question is: How do I do this in C without making 600 copies of my function func, and changing the variable M in the code each time ?
Finally, I would like to ask the same question again for CUDA code. So if I would have a cuda-kernel, where at some point in the code a modulus M operation is carried out, and I want to have different copies of the same kernel (one for each index of array_M).
You may use a define like:
#define F(i,n) void func_##i() { printf("%d\n",n); }
#include <stdio.h>
F(1,641)
F(2,31)
...
int main() {
func_1();
func_2();
}
It is possible to obtain the same effect from a list of constant but it is much much more tricky. See recursive macro.
Most compilers will do constant propagation. You need to turn up the optimisation level high. The only way to be sure however is to examine the assembly code, or to explicitly write the code out with the constants folded in, which is ugly and hard to maintain. C++ allows you to specify a scalar as a template.
Greetings and salutations,
I am looking for information regrading design patterns for working with a large number of functions in C99.
Background:
I am working on a complete G-Code interpreter for my pet project, a desktop CNC mill. Currently, commands are sent over a serial interface to an AVR microcontroller. These commands are then parsed and executed to make the milling head move. a typical example of a line might look like
N01 F5.0 G90 M48 G1 X1 Y2 Z3
where G90, M48, and G1 are "action" codes and F5.0, X1, Y2, Z3 are parameters (N01 is the optional line number and is ignored). Currently the parsing is coming along swimmingly, but now it is time to make the machine actually move.
For each of the G and M codes, a specific action needs to be taken. This ranges from controlled motion to coolant activation/deactivation, to performing canned cycles. To this end, my current design features a function that uses a switch to select the proper function and return a pointer to that function which can then be used to call the individual code's function at the proper time.
Questions:
1) Is there a better way to resolve an arbitrary code to its respective function than a switch statement? Note that this is being implemented on a microcontroller and memory is EXTREMELY tight (2K total). I have considered a lookup table but, unfortunately, the code distribution is sparse leading to a lot of wasted space. There are ~100 distinct codes and sub-codes.
2) How does one go about function pointers in C when the names (and possibly signatures) may change? If the function signatures are different, is this even possible?
3) Assuming the functions have the same signature (which is where I am leaning), is there a way to typedef a generic type of that signature to be passed around and called from?
My apologies for the scattered questioning. Thank you in advance for your assistance.
1) Perfect hashing may be used to map the keywords to token numbers (opcodes) , which can be used to index a table of function pointers. The number of required arguments can also be put in this table.
2) You don's want overloaded / heterogeneous functions. Optional arguments might be possible.
3) your only choice is to use varargs, IMHO
I'm not an expert on embedded systems, but I have experience with VLSI. So sorry if I'm stating the obvious.
The function-pointer approach is probably the best way. But you'll need to either:
Arrange all your action codes to be consecutive in address.
Implement an action code decoder similar to an opcode decoder in a normal processor.
The first option is probably the better way (simple and small memory footprint). But if you can't control your action codes, you'll need to implement a decoder via another lookup table.
I'm not entirely sure on what you mean by "function signature". Function pointers should just be a number - which the compiler resolves.
EDIT:
Either way, I think two lookup tables (1 for function pointers, and one for decoder) is still going to be much smaller than a large switch statement. For varying parameters, use "dummy" parameters to make them all consistent. I'm not sure what the consequences of force casting everything to void-pointers to structs will be on an embedded processor.
EDIT 2:
Actually, a decoder can't be implementated with just a lookup table if the opcode space is too large. My mistake there. So 1 is really the only viable option.
Is there a better way ... than a switch statement?
Make a list of all valid action codes (a constant in program memory, so it doesn't use any of your scarce RAM), and sequentially compare each one with the received code. Perhaps reserve index "0" to mean "unknown action code".
For example:
// Warning: untested code.
typedef int (*ActionFunctionPointer)( int, int, char * );
struct parse_item{
const char action_letter;
const int action_number; // you might be able to get away with a single byte here, if none of your actions are above 255.
// alas, http://reprap.org/wiki/G-code mentions a "M501" code.
const ActionFunctionPointer action_function_pointer;
};
int m0_handler( int speed, int extrude_rate, char * message ){ // M0: Stop
speed_x = 0; speed_y = 0; speed_z = 0; speed_e = 0;
}
int g4_handler ( int dwell_time, int extrude_rate, char * message ){ // G4: Dwell
delay(dwell_time);
}
const struct parse_item parse_table[] = {
{ '\0', 0, unrecognized_action } // special error-handler
{ 'M', 0, m0_handler }, // M0: Stop
// ...
{ 'G', 4, g4_handler }, // G4: Dwell
{ '\0', 0, unrecognized_action } // special error-handler
}
ActionFunctionPointer get_action_function_pointer( char * buffer ){
char letter = get_letter( buffer );
int action_number = get_number( buffer );
int index = 0;
ActionFunctionPointer f = 0;
do{
index++;
if( (letter == parse_table[index].action_letter ) and
(action_number == parse_table[index].action_number) ){
f = parse_table[index].action_function_pointer;
};
if('\0' == parse_table[index].action_letter ){
index = 0;
f = unrecognized_action;
};
}while(0 == f);
return f;
}
How does one go about function pointers in C when the names (and
possibly signatures) may change? If the function signatures are
different, is this even possible?
It's possible to create a function pointer in C that (at different times) points to functions with more or less parameters (different signatures) using varargs.
Alternatively, you can force all the functions that might possibly be pointed to by that function pointer to all have exactly the same parameters and return value (the same signature) by adding "dummy" parameters to the functions that require fewer parameters than the others.
In my experience, the "dummy parameters" approach seems to be easier to understand and use less memory than the varargs approach.
Is there a way to typedef a generic type of that signature
to be passed around and called from?
Yes.
Pretty much all the code I've ever seen that uses function pointers
also creates a typedef to refer to that particular type of function.
(Except, of course, for Obfuscated contest entries).
See the above example and Wikibooks: C programming: pointers to functions for details.
p.s.:
Is there some reason you are re-inventing the wheel?
Could maybe perhaps one of the following pre-existing G-code interpreters for the AVR work for you, perhaps with a little tweaking?
FiveD,
Sprinter,
Marlin,
Teacup Firmware,
sjfw,
Makerbot,
or
Grbl?
(See http://reprap.org/wiki/Comparison_of_RepRap_Firmwares ).