Pregunta

I write a simple program about 3x + 1 problem, intend to tell the diffrences between jump instructions and conditional transfer instruction.

The code works well when compiled with the flag -O0. However, when I compile it with -O1 or -O2 flag, the code seems to be caught in an "infinite loop".

Do you have any ideas to correct my code to make it work? thx

g++ version

$ g++ --version
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3

compile command

g++ -std=c++0x -O1 -Wall -g -o "foo" "foo.cc"

Here is my code.

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <ctime>

using namespace std;

#define print(x) cout << x << endl
#define input(x) cin >> x
#define ENTER "\n\t"

#if defined(__i386__)
static __inline__ unsigned long long rdtsc(void)
{
    unsigned long long int x;
    __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
    return x;
}
#elif defined(__x86_64__)
static __inline__ unsigned long long rdtsc(void)
{
    unsigned hi, lo;
    __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
    return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32 );
}
#endif

const int SIZE = 100000;

int nums[SIZE];

void down_to_one(int v)
{
    if (v == 1) {
        return;
    } else if (v % 2 == 0) {
        down_to_one(v >> 1);
    } else {
        down_to_one(3 * v + 1);
    }
}

void down_to_one_asm(int v)
{
    if (v == 1) {
        return;
    }
    __asm__ __volatile__(
        "movl %0, %%eax" ENTER
        "sarl %%eax"     ENTER
        "leal 1(%0, %0, 2), %%ebx" ENTER
        "testl $1, %0" ENTER
        "cmovel  %%eax, %0" ENTER
        "cmovnel %%ebx, %0" ENTER
        :"=c"(v)
        :"c"(v)
    );
    down_to_one_asm(v);
}

int main()
{
    unsigned long long start, end;

    start = rdtsc();
    for (int i = 1; i <= SIZE; i++) {
        down_to_one(i);
    }
    end = rdtsc();
    print(end - start);

    ////
    __asm__ ("":::"memory");
    ////

    start = rdtsc();
    for (int i = 1; i <= SIZE; i++) {
        down_to_one_asm(i);
    }
    end = rdtsc();
    print(end - start);

    return 0;
}
¿Fue útil?

Solución

You haven't specified where the infinite loop is occurring. One potential source of problems is the down_to_one_asm function. You also need to specify the registers you have clobbered, e.g.

: "=c" (v) : "c" (v) : "%eax", "%ebx"

You might be getting away with "-O0", but higher levels are probably optimizing the call-stack/frame setup - and "-O2" is (IIRC) implementing tail-call optimization.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top