資源簡介
學生在學習《編譯原理》課程設計中,結合各章節的構造編譯程序的基本理論,總共用一周的時間完成課程設計。要求用C或C++語言描述及上機調試,實現五個題目中任意一個,是學生將理論與實際應用結合其,起來,受到軟件設計等開發過程的全面訓練,從而提高學生軟件開發的能力。
能完成指定寄存器個數的情況下降一中間代碼程序段翻譯成會變語言目標代碼(匯編指令應包括加、減、乘、除),要求指令條數最少的情況下,盡量使用寄存器,盡量少訪問內存,這樣才能做到運行效率高。
代碼片段和文件信息
#include
#include
#include
char?temp=‘a‘-1;//用于標志不同的寄存器?
stack?NumberStack;//堆棧
int?stackPointer;
typedef?struct{
int?operationName;//操作碼?
char?registerName;//使用的寄存器?
char?numberValue;//操作數?
}OperationStruct;
?
OperationStruct?operations[40];
int?operationNowIndex=0;//表示當前是第幾個操作?
int?registerFlag;//寄存器標志:0表示為空,非0,被占用?
char?inputString[40];
//判斷是否為操作符,并將基轉換成對應的數字表示?
int?isOperator(char?ch){
switch(ch){
case?‘+‘:
return?3;
case?‘-‘:
return?4;
case?‘*‘:
return?5;
case?‘/‘:
return?6;
default:
return?0;
}
}
//判斷是否為數字?
int?isNumber(char?ch){
if(ch>=‘0‘&&ch<=‘9‘)
return?1;
return?0;
}
//根據運算符和當前寄存器的狀態,轉換成對應的操作?
void?GenerateOperations(char?ch){ //如果是操作符就從棧中彈出兩個操作數?
char?x1x2;
x2=NumberStack.top();
NumberStack.pop();
x1=NumberStack.top();
NumberStack.pop();
if(registerFlag==0){ //?如果寄存器沒被占用,直接生成運算指令:X1裝載到R,X2與之進行對應的運算?
operations[operationNowIndex].operationName=1; //裝載NumberStack[S-1]即x1?到寄存器R
operations[operationNowIndex].registerName=‘R‘;
operations[operationNowIndex].numberValue=x1;
operationNowIndex++;
operations[operationNowIndex].operationName=isOperator(ch); //將操作符變成數字代碼?
operations[operationNowIndex].registerName=‘R‘;
operations[operationNowIndex].numberValue=x2;
operationNowIndex++;
}else?if(x1!=‘R‘&&x2!=‘R‘&®isterFlag!=0){//x1和x2都不是寄存器的值,且寄存器被占用
temp++; //用一個新的變量來保存數據,比如ab……?
operations[operationNowIndex].operationName=2; //******? *******
operations[operationNowIndex].registerName=‘R‘; //****** 將寄存器中數據保存到臨時變量 *******
operations[operationNowIndex].numberValue=temp; //****** *******
NumberStack.pop();
NumberStack.push(temp); //將臨時變量壓入堆棧?
operationNowIndex++;
//以上已經將寄存器清空了,可以按上一個條件中的方法進行操作了?
operations[operationNowIndex].operationName=1; //和上面一個條件中的方法一樣?
operations[operationNowIndex].registerName=‘R‘;
operations[operationNowIndex].numberValue=x1;
operationNowIndex++;
operations[operationNowIndex].operationName=isOperator(ch);
operations[operationNowIndex].registerName=‘R‘;
operations[operationNowIndex].numberValue=x2;
operationNowIndex++;
}else?if(x1==‘R‘&&x2!=‘R‘&®isterFlag==(stackPointer-1)){//x1是寄存器,x2是操作數,?直接進行操作,因為已經有一個操作數了?
operations[operationNowIndex].operationName=isOperator(ch);
operations[operationNowIndex].registerName=‘R‘;
operations[operationNowIndex].numberValue=x2;
評論
共有 條評論