Не компилится программа с ассемблерной вставкой
Происходит ошибка при компиляции программы на g++ 7.5.0
6asm.cpp: In function ‘int findElement(std::vector<int>&, int)’:
6asm.cpp:32:6: error: ‘asm’ operand has impossible constraints
);
^
#include <iostream>
#include <vector>
using namespace std;
int findElement(vector<int>& arr, int target) {
int index = -1;
asm volatile(
"xor %%eax, %%eax\n"
"mov %[arr], %%esi\n"
"mov %[target], %%ecx\n"
"mov $-1, %[index]\n"
"mov $0, %%ebx\n"
"search_loop:"
"cmp %%ecx, (%%esi, %%ebx, 4)\n"
"je found\n"
"inc %%ebx\n"
"cmp %%ebx, %[arrSize]\n"
"jl search_loop\n"
"jmp search_end\n"
"found:"
"mov %%ebx, %[index]\n"
"search_end:"
: [index] "+r" (index)
: [arr] "r" (arr.data()), [target] "r" (target), [arrSize] "r" (arr.size())
: "eax", "ebx", "ecx", "esi"
);
return index;
}
int main() {
vector<int> array = {10, 20, 30, 40, 50};
int target = 30;
int foundIndex = findElement(array, target);
if (foundIndex != -1) {
cout << "Element " << target << " found at index " << foundIndex << endl;
} else {
cout << "Element " << target << " not found in the array" << endl;
}
return 0;
}
UPD:
Получилось скомпилить, но решает не правильно. Всегда попадает на ветку else.
#include <iostream>
#include <vector>
using namespace std;
int findElement(vector<int>& arr, int target) {
int index = -1;
asm volatile(
"xor %%eax, %%eax\n"
"movl %[arr], %%esi\n"
"movl %[target], %%ecx\n"
"movl $-1, %[index]\n"
"movl $0, %%ebx\n"
"search_loop: \n"
"cmpl %%ecx, (%%esi, %%ebx, 4)\n"
"je found\n"
"incl %%ebx\n"
"cmpl %%ebx, %[arrSize]\n"
"jl search_loop\n"
"jmp search_end\n"
"found: \n"
"movl %%ebx, %[index]\n"
"search_end: \n"
: [index] "+g" (index)
: [arr] "r" (arr.data()), [target] "g" (target), [arrSize] "g" (arr.size())
: "eax", "ebx", "ecx", "esi"
);
return index;
}
int main() {
vector<int> array = {10, 20, 30, 40, 50};
int target = 30;
int foundIndex = findElement(array, target);
if (foundIndex != -1) {
cout << "Element " << target << " found at index " << foundIndex << endl;
} else {
cout << "Element " << target << " not found in the array" << endl;
}
return 0;
}