Run-time Stack of C code - stack

I don't know if the title of my question is right, but I'm studying run-time stacks and I have the following C code:
int main() {
int a, b, c , x;
a = 4;
b = 5
c = 6
x = func(a, b, c);
return;
}
int func(int x, int y, int z) {
int p, q, r;
p = x*x;
q = y/z;
r = p + q;
return r;
}
This is compiled and loaded in location x3000.
I'm dealing with simulated computer called lc3. I need to find out how the run-time stack would look when this code is executed. My understanding of the topic is too limited in order to actually solve this, but here is how I think it should look:
x0000
(I don't know how the return should look either)
(Assignments that I don't know how to interpret)
r
q
p
main's frame pointer
Return address to main
Return value to main
x a
y b
z c
(I don't know the assignments should look in the run-time stack)
x
c
b
a
xEFFF
I hope someone can offer me some clarity in this subject. Thank you in advance.

Ok, this all depends on the ABI you are using. If it is anything similar to SystemV x86 Abi (the one in 32-bit linuxes). It should look like what you have described. (I have modified my answer to match what the wikipedia describes for LC-3)
first of all, you reach main(), and have 4 local variables, each of one is an int. (Assuming each int is 4 bytes, and stack aligned to 4 bytes), they will be stored in:
0xEFFC: a
0xEFF8: b
0xEFF4: c
0xEFF0: x
Then you call a function, namely func(). The LC-3 abi says that the parameters must be passed on the stack, from rigth to left:
0xEFEC: z --> c
0xEFE8: y --> b
0xEFE4: x --> a
Then you should save space for the return value, put the return address, and save your R5:
0xEFE0: Return value
0xEFDC: Return address to main
0xEFD8: Space for R5
Local variables again:
0xEFD4: p
0xEFD0: q
0xEFCC: r
On modern systems, the return value can be passed in registers (like EAX). It depends on your ABI where to pass it. Probably it can be returned on the stack too.
Another thing is that each function can create an stack frame, pushing into the stack the parent's Base Stack Address, and assuming their stack starts from that address.
You should probably have a document in where all these things are defined.

Related

need help understanding metamethod of table being set to that table

I'm not sure what the point of setting the metamethod of Stack to Stack is.
I've looked around but none of the explanations made too much sense. I get that sometimes instances may need to fall back on Stack for any missing methods but was hoping for a clearer explanation.
Stack = {}
Stack.__index = Stack
Let's say you have a "2d vector" "class" which has a .x and a .y. You write a dotproduct function for them:
function dotproduct(a, b)
return a.x * b.x + a.y * b.y
end
The simplest way to let you write foo:dot(bar) would be to put a .dot property on every new instance:
-- Make a "V2" namespace
local V2 = {}
function V2.new(x, y)
return {
x = x,
y = y,
-- Attach any methods to the object, also
dot = dotproduct,
}
end
However, as the number of methods grows, this gets worse for two reasons. One is that your objects get larger -- even though you only need to hold two numbers on each vector, most of the hashtable is functions which are always the same! Another is that multiple constructors get difficult because you need to duplicate the work in each constructor.
A solution to this is the __index metatable. Instead of copying each method onto each new object, you can just point to where to find "missing" methods as they needed:
V2.dot = dotproduct
function V2.new(x, y)
return setmetatable({x = x, y = y}, {__index = V2})
end
This design has a small drawback. First, you're allocating a new metatable in addition to every table, which is a waste of memory (all of the metatables are the same). Second, you don't have an opportunity to override other methods without growing this new metatable (the same annoyance from before).
So, we just make V2 be the single metatable:
V2.__index = V2
function V2.new(x, y)
return setmetatable({x = x, y = y}, V2)
end

Implementing post / pre increment / decrement when translating to Lua

I'm writing a LSL to Lua translator, and I'm having all sorts of trouble implementing incrementing and decrementing operators. LSL has such things using the usual C like syntax (x++, x--, ++x, --x), but Lua does not. Just to avoid massive amounts of typing, I refer to these sorts of operators as "crements". In the below code, I'll use "..." to represent other parts of the expression.
... x += 1 ...
Wont work, coz Lua only has simple assignment.
... x = x + 1 ...
Wont work coz that's a statement, and Lua can't use statements in expressions. LSL can use crements in expressions.
function preIncrement(x) x = x + 1; return x; end
... preIncrement(x) ...
While it does provide the correct value in the expression, Lua is pass by value for numbers, so the original variable is not changed. If I could get this to actually change the variable, then all is good. Messing with the environment might not be such a good idea, dunno what scope x is. I think I'll investigate that next. The translator could output scope details.
Assuming the above function exists -
... x = preIncrement(x) ...
Wont work for the "it's a statement" reason.
Other solutions start to get really messy.
x = preIncrement(x)
... x ...
Works fine, except when the original LSL code is something like this -
while (doOneThing(x++))
{
doOtherThing(x);
}
Which becomes a whole can of worms. Using tables in the function -
function preIncrement(x) x[1] = x[1] + 1; return x[1]; end
temp = {x}
... preincrement(temp) ...
x = temp[1]
Is even messier, and has the same problems.
Starting to look like I might have to actually analyse the surrounding code instead of just doing simple translations to sort out what the correct way to implement any given crement will be. Anybody got any simple ideas?
I think to really do this properly you're going to have to do some more detailed analysis, and splitting of some expressions into multiple statements, although many can probably be translated pretty straight-forwardly.
Note that at least in C, you can delay post-increments/decrements to the next "sequence point", and put pre-increments/decrements before the previous sequence point; sequence points are only located in a few places: between statements, at "short-circuit operators" (&& and ||), etc. (more info here)
So it's fine to replace x = *y++ + z * f (); with { x = *y + z * f(); y = y + 1; }—the user isn't allowed to assume that y will be incremented before anything else in the statement, only that the value used in *y will be y before it's incremented. Similarly, x = *--y + z * f(); can be replaced with { y = y - 1; x = *y + z * f (); }
Lua is designed to be pretty much impervious to implementations of this sort of thing. It may be done as kind of a compiler/interpreter issue, since the interpreter can know that variables only change when a statement is executed.
There's no way to implement this kind of thing in Lua. Not in the general case. You could do it for global variables by passing a string to the increment function. But obviously it wouldn't work for locals, or for variables that are in a table that is itself global.
Lua doesn't want you to do it; it's best to find a way to work within the restriction. And that means code analysis.
Your proposed solution only will work when your Lua variables are all global. Unless this is something LSL also does, you will get trouble translating LSL programs that use variables called the same way in different places.
Lua is only able of modifying one lvalue per statement - tables being passed to functions are the only exception to this rule. You could use a local table to store all locals, and that would help you out with the pre-...-crements; they can be evaluated before the expression they are contained in is evauated. But the post-...-crements have to be evaluated later on, which is simply not possible in lua - at least not without some ugly code involving anonymous functions.
So you have one options: you must accept that some LSL statements will get translated to several Lua statements.
Say you have a LSL statement with increments like this:
f(integer x) {
integer y = x + x++;
return (y + ++y)
}
You can translate this to a Lua statement like this:
function f(x) {
local post_incremented_x = x + 1 -- extra statement 1 for post increment
local y = x + post_incremented_x
x = post_incremented_x -- extra statement 2 for post increment
local pre_incremented_y = y + 1
return y + pre_incremented_y
y = pre_incremented_y -- this line will never be executed
}
So you basically will have to add two statements per ..-crement used in your statements. For complex structures, that will mean calculating the order in which the expressions are evaluated.
For what is worth, I like with having post decrements and predecrements as individual statements in languages. But I consider it a flaw of the language when they can also be used as expressions. The syntactic sugar quickly becomes semantic diabetes.
After some research and thinking I've come up with an idea that might work.
For globals -
function preIncrement(x)
_G[x] = _G[x] + 1
return _G[x]
end
... preIncrement("x") ...
For locals and function parameters (which are locals to) I know at the time I'm parsing the crement that it is local, I can store four flags to tell me which of the four crements is being used in the variables AST structure. Then when it comes time to output the variables definition, I can output something like this -
local x;
function preIncrement_x() x = x + 1; return x; end
function postDecrement_x() local y = x; x = x - 1; return y; end
... preIncrement_x() ...
In most of your assessment of configurability to the code. You are trying to hard pass data types from one into another. And call it a 'translator'. And in all of this you miss regex and other pattern match capacities. Which are far more present in LUA than LSL. And since the LSL code is being passed into LUA. Try using them, along with other functions. Which would define the work more as a translator, than a hard pass.
Yes I know this was asked a while ago. Though, for other viewers of this topic. Never forget the environments you are working in. EVER. Use what they give you to the best ability you can.

Determine upper/lower bound for variables in an arbitrary propositional formula [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
Given an arbitrary propositional formula PHI (linear constraints on some variables), what is the best way to determine the (approximate) upper and lower bound for each variable?
Some variables may be unbounded. In this case, an algorithm should conclude that there's no upper/lower bound for those variables.
e.g., PHI = (x=3 AND y>=1). The upper and lower bound for x are both 3. The lower bound for y is 1, and y does not have an upper bound.
This is a very simple example, but is there a solution in general (perhaps using SMT solver)?
This assumes the SAT/UNSAT domain of each variable is continuous.
Use an SMT solver to check for a solution to the formula. If there's no solution then that means no upper/lower bounds, so stop.
For each variable in the formula, conduct two binary searches over the domain of the variable, one searching for the lower bound, the other for the upper bound. The starting value in the search for each variable is the value for the variable in the solution found in step 1. Use the SMT solver to probe each search value for satisfiability and methodically bracket the bounds for each variable.
Pseudo code for the search functions, assuming integer domain variables:
lower_bound(variable, start, formula)
{
lo = -inf;
hi = start;
last_sat = start;
incr = 1;
do {
variable = (lo + hi) / 2;
if (SMT(formula) == UNSAT) {
lo = variable + incr;
} else {
last_sat = variable;
hi = variable - incr;
}
} while (lo <= hi);
return last_sat;
}
and
upper_bound(variable, start, formula)
{
lo = start;
hi = +inf;
last_sat = start;
do {
variable = (lo + hi) / 2;
if (SMT(formula) == SAT) {
last_sat = variable;
lo = variable + incr;
} else {
hi = variable - incr;
}
} while (lo <= hi);
return last_sat;
}
-inf/+inf are the smallest/largest values representable in the domain of each variable. If lower_bound returns -inf then the variable has no lower bound. If upper_bound returns +inf then the variable has no upper bound.
In practice most of such optimization problems require some sort of iterate-until-maximum/minimum kind of external driver on top of the SMT solver. Quantified approaches are also possible that can leverage the particular capabilities of the SMT solvers, but in practice such constraints end up being too hard for the underlying solver. See this discussion in particular: How to optimize a piece of code in Z3? (PI_NON_NESTED_ARITH_WEIGHT related)
Having said that, most high-level language bindings include the necessary machinery to simplify your life. For instance, if you use the Haskell SBV library to script z3, you can have:
Prelude> import Data.SBV
Prelude Data.SBV> maximize Quantified head 2 (\[x, y] -> x.==3 &&& y.>=1)
Just [3,1]
Prelude Data.SBV> maximize Quantified (head . tail) 2 (\[x, y] -> x.==3 &&& y.>=1)
Nothing
Prelude Data.SBV> minimize Quantified head 2 (\[x, y] -> x.==3 &&& y.>=1)
Just [3,1]
Prelude Data.SBV> minimize Quantified (head . tail) 2 (\[x, y] -> x.==3 &&& y.>=1)
Just [3,1]
The first result states x=3, y=1 maximizes x with respect to the predicate x==3 && y>=1.
The second result says there is no value that maximizes y with respect to the same predicate.
Third call says x=3,y=1 minimizes the predicate with respect to x.
Fourth call says x=3,y=1 minimizes the predicate with respect to y.
(See http://hackage.haskell.org/packages/archive/sbv/0.9.24/doc/html/Data-SBV.html#g:34 for details.)
You can also use the option "Iterative" (instead of Quantified) to have the library do the optimization iteratively instead of using quantifiers. These two techniques are not equivalent as the latter can get stuck in a local minima/maxima, but iterative approaches might solve problems where the quantified version is way too much to handle for the SMT solver.

Erlang Code Snippet that shows off its benefits?

I'm giving a small presentation to a group of C/C++ programmers who have very little experience with functional languages. Part of the presentation mentions Erlang, and I would like to give a specific small code example.
There is a ton of awesome information on StackOverflow about how/where Erlang is used and its advantages. One of the most common advantages I see is how it can do a lot with just a little terse code, especially compared to C/C++.
I am looking for a good code snippet of Erlang that simply illustrates these types of benefits. Especially something thats easily done in Erlang with few lines, that would be much more complicated in C/C++.
Anyone have any interesting suggestions?
Check out example 4 for an excellent example of Erlang's bit syntax. I'm sure there are a number of c/c++ developers that will appreciate the brevity of the syntax!
I would use an example which shows how easy it is to do concurrency.
So basically write map-reduce (but never ever use that word to describe it to a C programmer).
You could start with showing a program that plays Fizz Buzz, and then proceed to make it concurrent. Should easily fit a whiteboard, or two pages of powerpoint.
A Co-worker suggested using Merge-Sort as an example:
http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort#Erlang
mergeSort(L) when length(L) == 1 -> L;
mergeSort(L) when length(L) > 1 ->
{L1, L2} = lists:split(length(L) div 2, L),
lists:merge(mergeSort(L1), mergeSort(L2)).
Multi-process version:
pMergeSort(L) when length(L) == 1 -> L;
pMergeSort(L) when length(L) > 1 ->
{L1, L2} = lists:split(length(L) div 2, L),
spawn(mergesort, pMergeSort2, [L1, self()]),
spawn(mergesort, pMergeSort2, [L2, self()]),
mergeResults([]).
pMergeSort2(L, Parent) when length(L) == 1 -> Parent ! L;
pMergeSort2(L, Parent) when length(L) > 1 ->
{L1, L2} = lists:split(length(L) div 2, L),
spawn(mergesort, pMergeSort2, [L1, self()]),
spawn(mergesort, pMergeSort2, [L2, self()]),
Parent ! mergeResults([]).
Pythagorean Triples. Get all number combinations below 30 whereby the 3 numbers make a right angled triangle as it is according to Pythagoras.
[{X,Y,Z} || X <- lists:seq(1,30),
Y <- lists:seq(1,30),
Z <- lists:seq(1,30), ((X * X) + (Y * Y)) == (Z * Z)].
Try doing that in C/C++ , or Java and see if you will avoid a for loop if not more than one depending on your skill level :)
the factorial code snippet is the best i have always used to show how short erlang programs can be
-module(factorial).
-export([calculate/1]).
calculate(0) -> 1;
calculate(N) -> N * calculate(N -1).
As simple as that. That short program illustrates not only how short Erlang programs can be, But also: Pattern Matching, Function Clauses and Last Call Optimization. I always had a C++ version of the same, below:
#include<iostream.h>
#include<conio.h>
long factorial(unsigned int a);
void main() {
unsigned int a;
long fac;
.....
.....
return factorial(a);
}
long factorial(unsigned int x) {
long fac=1;
if(x == 0) {return 1;}
else {
while(x > 0) {
fac *= x;
x -= 1 ;
}
return fac; }
}
Well, this may not be the shortest C++ version, but i know you get the idea.

Lua base converter

I need a base converter function for Lua. I need to convert from base 10 to base 2,3,4,5,6,7,8,9,10,11...36 how can i to this?
In the string to number direction, the function tonumber() takes an optional second argument that specifies the base to use, which may range from 2 to 36 with the obvious meaning for digits in bases greater than 10.
In the number to string direction, this can be done slightly more efficiently than Nikolaus's answer by something like this:
local floor,insert = math.floor, table.insert
function basen(n,b)
n = floor(n)
if not b or b == 10 then return tostring(n) end
local digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
local t = {}
local sign = ""
if n < 0 then
sign = "-"
n = -n
end
repeat
local d = (n % b) + 1
n = floor(n / b)
insert(t, 1, digits:sub(d,d))
until n == 0
return sign .. table.concat(t,"")
end
This creates fewer garbage strings to collect by using table.concat() instead of repeated calls to the string concatenation operator ... Although it makes little practical difference for strings this small, this idiom should be learned because otherwise building a buffer in a loop with the concatenation operator will actually tend to O(n2) performance while table.concat() has been designed to do substantially better.
There is an unanswered question as to whether it is more efficient to push the digits on a stack in the table t with calls to table.insert(t,1,digit), or to append them to the end with t[#t+1]=digit, followed by a call to string.reverse() to put the digits in the right order. I'll leave the benchmarking to the student. Note that although the code I pasted here does run and appears to get correct answers, there may other opportunities to tune it further.
For example, the common case of base 10 is culled off and handled with the built in tostring() function. But similar culls can be done for bases 8 and 16 which have conversion specifiers for string.format() ("%o" and "%x", respectively).
Also, neither Nikolaus's solution nor mine handle non-integers particularly well. I emphasize that here by forcing the value n to an integer with math.floor() at the beginning.
Correctly converting a general floating point value to any base (even base 10) is fraught with subtleties, which I leave as an exercise to the reader.
you can use a loop to convert an integer into a string containting the required base. for bases below 10 use the following code, if you need a base larger than that you need to add a line that mapps the result of x % base to a character (usign an array for example)
x = 1234
r = ""
base = 8
while x > 0 do
r = "" .. (x % base ) .. r
x = math.floor(x / base)
end
print( r );

Resources