SlideShare a Scribd company logo
1 of 25
Download to read offline
Compiler Lecture Note, Intermediate Language Page 1
제 9 장
중 간 언어
컴파일러 입문
Compiler Lecture Note, Intermediate Language Page 2
Contents
• Introduction
• Polish Notation
• Three Address Code
• Tree Structured Code
• Abstract Machine Code
• Concluding Remarks
Compiler Lecture Note, Intermediate Language Page 3
• Compiler Model
Source
Program
Lexical Analyzer
Syntax Analyzer
Semantic Analyzer
Intermediate
Code Generator
tokens
AST
Front-End
Code Optimizer
Target Code Generator
IC
Back-End
IL
Object
Program
Front-End- language dependant part
Back-End - machine dependant part
Introduction
Compiler Lecture Note, Intermediate Language Page 4
• IL 사용의 장점
– Compiler를 기능적으로 독립적인 Modul들로 구성
– Compiler 자체의 portability 증가
– Easy Translation
• 고급 소스 언어와 저급 목적 코드간의 semantic gap를 이어주는 교량 역할
– 중간코드를 이용하여 optimization를 수행
• 기계와 독립적인 최적화 가능
• 기계어로 바뀐 상태에서 행하는 것보다 훨씬 효율적으로 최적화 수행
– Interpretive compiling 시스템에서 interpreter를 이용하여 실행
• IL사용의 결점
– 목적 코드로 직접 번역하는 것 보다 컴파일 시간이 더 많이 소요
– 비효율적인 코드 생산
• 중간 코드로부터 목적 코드로의 번역 과정 필요
• 중간언어 단계에서 간단한 최적화를 통해 극복
Compiler Lecture Note, Intermediate Language Page 5
• Two level Code Generation
• ILS
– 소스로부터 자동화에 의해 얻을 수 있는 형태
– 소스 언어에 의존적이며 high level이다.
• ILT
– 후단부의 자동화에 의해 목적기계로의 번역이 매우 쉬운 형태
– 목적기계에 의존적이며 low level이다.
• ILS to ILT
– ILS에서 ILT로의 번역이 주된 작업임.
Source Front-End ILS ILS-ILT ILT Back-End Target
• IL의 종류
– Polish Notation  Prefix notation, IR
– Three Address Code  Triple, Quadruple, Indirect Triple
– Tree Structured Code  AST, TCOL, Diana
– Abstract Machine Code  P-code, EM-code, U-code, Bytecode
Compiler Lecture Note, Intermediate Language Page 6
Compiler Lecture Note, Intermediate Language Page 7
☞ Polish mathematician Lucasiewiez invented the parenthesis-free notation.
• Postfix(Suffix) Polish Notation
• earliest IL
• popular for interpreted language - SNOBOL, BASIC
– general form :
e1 e2 ... ek OP (k ≥ 1)
where, OP : k_ary operator
ei : any postfix expression (1 ≤ i ≤ k)
Polish Notation
Compiler Lecture Note, Intermediate Language Page 8
– example :
if a then if c-d then a+c else a*c else a+b
〓〉a L1 BZ c d - L2 BZ a c + L3 BR
L2: a c * L3 BR L1: a b + L3:
– note
1) high level: source to IL - fast & easy translation
IL to target - difficulty
2) easy evaluation - operand stack
3) optimization 부적당 - 다른 IL로의 translation 필요
4) parentheses free notation - arithmetic expression
– interpretive language에 적합
Source Translator Postfix Evaluator Result
Compiler Lecture Note, Intermediate Language Page 9
• most popular IL, optimizing compiler
• General form:
A := B op C
where, A : result address
B, C : operand addresses
op : operator
(1) Quadruple - 4-tuple notation
<operator>,<operand1>,<operand2>,<result>
(2) Triple - 3-tuple notation
<operator>,<operand1>,<operand2>
(3) Indirect triple - execution order table & triples
Three Address Code
Compiler Lecture Note, Intermediate Language Page 10
– example
• A ← B + C * D / E
• F ← C * D
Quadruple Triple
Indirect Triple
Operations Triple
* C D T1 (1) * C D 1.(1) (1) * C D
/ T1 E T2 (2) / (1) E 2.(2) (2) / (1) E
+ B T2 T3 (3) + B (2) 3.(3) (3) + B (2)
 T3 A (4)  A (3) 4.(4) (4)  A (3)
* C D T4 (5) * C D 5.(1) (5)  F (1)
 T4 F (6)  F (5) 6.(5)
Compiler Lecture Note, Intermediate Language Page 11
• Note
• Quadruple vs. Triple
– quadruple - optimization 용이
– triple - removal of temporary addresses
⇒ Indirect Triple
• extensive code optimization 용이
– IL rearrange 가능 (triple 제외)
• easy translation - source to IL
• difficult to generate good code
– quadruple to two-address machine
– triple to three-address machine
Compiler Lecture Note, Intermediate Language Page 12
• Abstract Syntax Tree
– parse tree에서 redundant한 information 제거.
• ┌ leaf node --- variable name, constant
└ internal node --- operator
– 예 : a * b + c / d a[i] = exp;
Tree Structured Code
add
divmul
b ca d
assign
expindex
ia
Compiler Lecture Note, Intermediate Language Page 13
• Tree Structured Common Language(TCOL)
– Variants of AST - containing the result of semantic analysis.
Example) int a; float b;
...
b = a + 1;
AST TCOL
add
1a
assign
b float
assign
b
addi
1
a
Compiler Lecture Note, Intermediate Language Page 14
Abstract Machine Code
• Abstract Machine을 이용한 portable compiler의 모델
• Abstract Machine의 설계
– source language의 기본 연산과 모드에 근거
• 기본 연산은 source program을 구성하는 가장 간단하고 대부분 직
접적인 연산에 대응
• 기본적인 자료 모드는 source language의 가장 간단한 형
• 기본적인 모드와 연산들이 Abstract Machine의 명령어를 결정
– 실제 컴퓨터에 효율적으로 설치 가능 여부도 고려
front-end back-end
target
machine
abstract machine
interpreter
source
program interface target code
abstract
machine
code
Compiler Lecture Note, Intermediate Language Page 15
• Motivation
• ┌ rapid development of machine architectures
└ proliferation of programming languages
– portable & adaptable compiler design --- P_CODE
• porting --- rewriting only back-end
– compiler building system --- EM_CODE
M front-ends
N back-ends
+ M compilers for N target machines
Compiler Lecture Note, Intermediate Language Page 16
• Pascal-P Code
– Pascal compiler를 제작하는데 사용된 intermediate language
• Pascal-P compiler
– P-코드에서 실제 기계로의 번역기 또는 P-code interpreter를 사용함
으로써 쉽게 이식이 가능
– 소스 언어로부터 P-code로의 translation과 interpretation이 비교적 쉽
게 설계
– P-code에 대한 가상 기계가 P-기계이며, P-기계도 모든 연산이
스택에서 행해지는 가상적인 스택 기계(hypothetical stack
machine)
Pascal P CompilerPascal Program P-code
Compiler Lecture Note, Intermediate Language Page 17
• EM-code
– ACK 중간 언어
• ACK(Amsterdam Compiler Kit)
– Algol 형태의 소스 언어와 바이트 기계 형태의 목적 기계에 적합한
EM-기계라는 가상 기계를 설정하고 언어에 대한 전단부와 목적 기
계에 대한 후단부를 제공함으로써 사용자가 필요한 컴파일러를 쉽
게 제작하도록 도와주는 기구
– 가상적인 스택의 개념을 둔 기계 구조
– 소스 언어로부터 EM-코드로의 번역과 EM-코드의 인터프리테
이션이 비교적 쉽게 설계
– EM-코드를 이용하여 제작한 컴파일러는 EM-코드에서 목적
기계로의 번역기 또는 EM-코드 인터프리터만을 교환함으로
써 쉽게 이식 가능
• U-code
– Portable Pascal compiler에서 사용한 중간 형태
– 가상적인 스택 기계에 근거
• 모든 명령어들은 가상 스택을 기준으로 정의
• 스택에서 모든 연산 수행
– 스택 기계는 모든 연산을 스택에서 실행하므로 변수들의 주소
는 스택에 대한 주소 부여 방법 이용
• 모든 변수에 대한 주소는 두 개의 항목(B, O)의 형태로 구성
– B : 블록의 번호
– O : 블록의 시작으로부터의 offset
– 예
– 블록 번호는 프로그램 main이 1, procedure P가 2, procedure Q가 3
– procedure Q에 선언된 변수 i와 j의 주소는 각각 (3, 1)과 (3, 2)로 표현
Compiler Lecture Note, Intermediate Language Page 18
program main
procedure P
procedure Q
var i : integer;
j : boolean;
• U-code 명령어들의 형태와 기능에 따른 분류
1. 단일 명령어 ⇒ notop, neg
2. 이진 명령어 ⇒ add, sub, mult, divop, nodop, swp
andop, orop, gt, lt, ge, le, eq, ne
3. 스택 운영 명령어 ⇒ lod, str, ldc, ldr
4. 제어 흐름 명령어 ⇒ ujp, tjp, fjp
5. 범위 검사 명령어 ⇒ chkh, chkl
6. 간접 주소 명령어 ⇒ ixa, sta
7. procedure 명령어 ⇒ cal, ret, ldp, proc, endop
8. 기타 명령어 ⇒ bgn, sym
Compiler Lecture Note, Intermediate Language Page 19
• U-code로 작성된 프로그램의 전체 구조
– 먼저 global variable의 속성이 나오며, 그 다음에 procedure의 code가
나올 수 있으며, 마지막에 주 프로그램에 대한 code가 나옴
– 하나의 procedure는 local variable의 속성과 code로 구성
– 맨 처음, bgn(begin)으로 제어가 넘어와 실행이 시작
Compiler Lecture Note, Intermediate Language Page 20
sym(s) global variable(s)
<name> proc
sym(s) for procedure
codes for procedure
···
endop
bgn
codes for main program
···
endop
• Bytecode
– Java 프로그래밍 환경에서 지원하는 IL로서 이기종간의 실행 환경
에 적합하도록 설계된 스택 기반의 가상 기계 코드
– Java compiler
• Java 프로그램을 입력 받아 JVM(Java Virtual Machine)의 명령어 집합인
byetcode 생성
• Intermediate code 형태인 bytecode는 이기종간의 실행 환경에 적합하도
록 설계되어 portability과 유연성이 높다.
• interpreter 방식과 JIT(Just-In-Time) compiler 방식에 의해서 실행
Compiler Lecture Note, Intermediate Language Page 21
Java CompilerJava Program Bytecode JVM 실행 결과
– Bytecode는 일반적인 Abstract Machine Code의 특징을 모두 포함
– Bytecode 만의 특징
• 네트워크 상에서 전송 효율을 위해 code를 가능한 작고 간결하게 설계
• Java language의 기능을 반영하는 명령어가 존재
– 배열, 클래스, 예외, 스레드 등을 직접 다룰 수 있는 명령어 포함
• 자료형에 따라서 명령어가 각기 따로 존재
– ex) iadd 는 int 덧셈, fadd는 float 덧셈
• 복합기능을 갖는 명령어를 제공
– ex) pop2는 stack에서 연속해서 두 번을 pop하는 기능
Compiler Lecture Note, Intermediate Language Page 22
• IL의 4가지 분류
– Polish Notation  Postfix notation, IR
– Three Address Code  Triple, Quadruple, Indirect Triple
– Tree Structured Code  AST, TCOL, Diana
– Abstract Machine Code  P-code, EM-code, U-code, Bytecode
• IL이 갖추어야 할 요건
1. 중간 레벨성(Intermediate level)
• 소스 언어와 비교해서는 low-level이고 목적 기계와 비교해서는 high-
level의 성격을 유지해야 하는 속성을 의미
• IL이 너무 한쪽으로 치우쳐 있으면 IL과 다른 한쪽과의 의미적 차이가
커져 번역이 어려워지며 또한 이식성 결여
– Postfix polish notation과 syntax tree는 high-level
– Triple, quadruple는 비교적 high-level
– Abstract Machine Code 는 비교적 low-level
– TCOL만이 비교적 intermediate level이 좋은 언어
Compiler Lecture Note, Intermediate Language Page 23
2. 효율적인 처리의 적합성(Efficient processing)
• 소스 언어에서 중간 언어로 번역, 중간언어에서 목적 언어로 번역
– High-level에 치우친 중간 코드는 소스 언어에서 IL로 번역이 쉬운 반면 IL에서
목적 언어로 번역이 어려움
– Low-level 에 가까운 것은 반대 현상이 나타남
• 인터프리테이션(Interpretation)
– Abstract machine code가 가장 우수
– Postfix 표현도 operand stack을 이용하여 쉽게 interpretation을 할 수 있는 형태
– Tree 구조 코드는 tree 구조상 interpretation에 가장 많은 결함을 보임
• 최적화(Optimization)
– 쉽게 코드를 이동할 수 있는 quadruple이 효과적이며 tree 구조도 고급 언어의
제어 구조를 내포할 수 있으며 tree의 재구성이 쉽기 때문에 optimization에 적
합한 형태
– Postfix 표현이나 triple 표현은 연산의 결과가 위치에 영향을 미치지 때문에
optimization에 부적합
3. 외부 표현성 (External representation)
• Tree 구조 code만이 선형 구조가 아닌 관계로 단점을 나타냄
4. 확장성(Extensibility)
• 비교적 모든 중간 언어들이 좋은 편
• Abstract Machine Code만 약간의 결함
Compiler Lecture Note, Intermediate Language Page 24
5. 이식성(Portability)
• 크게 영향을 주는 기계 종속성과 언어 종속성의 분명한 구분성에서는
TCOL과 가상 기계 코드가 가장 우수
• 소스 언어에 가까운 고급 표현인 postfix 표현과 AST는 부적당
• Intermediate Language의 비교
Compiler Lecture Note, Intermediate Language Page 25
IL
Criteria
Polish
Notation
Three Address
Code
Tree
Structured
Abstract
Machine
CodePost IR Quadra Triple AST TCOL
Intermediate level C B B B C A B
efficient
processing
source to IL
translation
A C B B A B C
IL to target
translation
C A B B C A A
interpretation A B B B C C A
optimization C B A C A A B
external representation B B A B C B A
extensibility A A A A A A B
clean separation C B B B C A A
A : 좋다
B : 보통이다
C : 나쁘다

More Related Content

Similar to Ch09

Chaper24 languages high_and_low
Chaper24 languages high_and_lowChaper24 languages high_and_low
Chaper24 languages high_and_lowKyungryul KIM
 
[KGC2014] 두 마리 토끼를 잡기 위한 C++ - C# 혼합 멀티플랫폼 게임 아키텍처 설계
[KGC2014] 두 마리 토끼를 잡기 위한 C++ - C#  혼합 멀티플랫폼 게임 아키텍처 설계[KGC2014] 두 마리 토끼를 잡기 위한 C++ - C#  혼합 멀티플랫폼 게임 아키텍처 설계
[KGC2014] 두 마리 토끼를 잡기 위한 C++ - C# 혼합 멀티플랫폼 게임 아키텍처 설계Sungkyun Kim
 
리눅스 데스크톱의 한국어 입력 개요
리눅스 데스크톱의 한국어 입력 개요리눅스 데스크톱의 한국어 입력 개요
리눅스 데스크톱의 한국어 입력 개요Changwoo Ryu
 
The Deep Learning Compiler
The Deep Learning CompilerThe Deep Learning Compiler
The Deep Learning CompilerTae Young Lee
 
어플리케이션 성능 최적화 기법
어플리케이션 성능 최적화 기법어플리케이션 성능 최적화 기법
어플리케이션 성능 최적화 기법Daniel Kim
 
Korean input overview in the linux desktop
Korean input overview in the linux desktopKorean input overview in the linux desktop
Korean input overview in the linux desktopgnomekr
 
(게임개발을위한) printf("Hello World!"); 그 이상의 콘솔 프로그래밍
(게임개발을위한) printf("Hello World!"); 그 이상의 콘솔 프로그래밍(게임개발을위한) printf("Hello World!"); 그 이상의 콘솔 프로그래밍
(게임개발을위한) printf("Hello World!"); 그 이상의 콘솔 프로그래밍NDOORS
 
05_컴파일러최적화전략(1)
05_컴파일러최적화전략(1)05_컴파일러최적화전략(1)
05_컴파일러최적화전략(1)noerror
 
Assembly 스터디 1
Assembly 스터디 1Assembly 스터디 1
Assembly 스터디 1Jinkyoung Kim
 
6. code level reversing
6. code level reversing6. code level reversing
6. code level reversingYoungjun Chang
 
Windows Registered I/O (RIO) vs IOCP
Windows Registered I/O (RIO) vs IOCPWindows Registered I/O (RIO) vs IOCP
Windows Registered I/O (RIO) vs IOCPSeungmo Koo
 
강좌 04 펌웨어 구조 설계
강좌 04 펌웨어 구조 설계강좌 04 펌웨어 구조 설계
강좌 04 펌웨어 구조 설계chcbaram
 
이기종 멀티코어 프로세서를 위한 프로그래밍 언어 및 영상처리 오픈소스
이기종 멀티코어 프로세서를 위한 프로그래밍 언어 및 영상처리 오픈소스이기종 멀티코어 프로세서를 위한 프로그래밍 언어 및 영상처리 오픈소스
이기종 멀티코어 프로세서를 위한 프로그래밍 언어 및 영상처리 오픈소스Seunghwa Song
 
The Future of C# and .NET Framework
The Future of C# and .NET FrameworkThe Future of C# and .NET Framework
The Future of C# and .NET Framework명신 김
 
kics2013-winter-biomp-slide-20130127-1340
kics2013-winter-biomp-slide-20130127-1340kics2013-winter-biomp-slide-20130127-1340
kics2013-winter-biomp-slide-20130127-1340Samsung Electronics
 
프로그래밍 언어의 기본 개념과 주요 프로그래밍 언어
프로그래밍 언어의 기본 개념과 주요 프로그래밍 언어프로그래밍 언어의 기본 개념과 주요 프로그래밍 언어
프로그래밍 언어의 기본 개념과 주요 프로그래밍 언어Bizmerce Corp
 
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍인프콘 2022 - Rust 크로스 플랫폼 프로그래밍
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍Chris Ohk
 
Assembly 스터디 2
Assembly 스터디 2Assembly 스터디 2
Assembly 스터디 2Jinkyoung Kim
 
[170403 2주차]C언어 A반
[170403 2주차]C언어 A반[170403 2주차]C언어 A반
[170403 2주차]C언어 A반arundine
 

Similar to Ch09 (20)

Chaper24 languages high_and_low
Chaper24 languages high_and_lowChaper24 languages high_and_low
Chaper24 languages high_and_low
 
[KGC2014] 두 마리 토끼를 잡기 위한 C++ - C# 혼합 멀티플랫폼 게임 아키텍처 설계
[KGC2014] 두 마리 토끼를 잡기 위한 C++ - C#  혼합 멀티플랫폼 게임 아키텍처 설계[KGC2014] 두 마리 토끼를 잡기 위한 C++ - C#  혼합 멀티플랫폼 게임 아키텍처 설계
[KGC2014] 두 마리 토끼를 잡기 위한 C++ - C# 혼합 멀티플랫폼 게임 아키텍처 설계
 
llvm 소개
llvm 소개llvm 소개
llvm 소개
 
리눅스 데스크톱의 한국어 입력 개요
리눅스 데스크톱의 한국어 입력 개요리눅스 데스크톱의 한국어 입력 개요
리눅스 데스크톱의 한국어 입력 개요
 
The Deep Learning Compiler
The Deep Learning CompilerThe Deep Learning Compiler
The Deep Learning Compiler
 
어플리케이션 성능 최적화 기법
어플리케이션 성능 최적화 기법어플리케이션 성능 최적화 기법
어플리케이션 성능 최적화 기법
 
Korean input overview in the linux desktop
Korean input overview in the linux desktopKorean input overview in the linux desktop
Korean input overview in the linux desktop
 
(게임개발을위한) printf("Hello World!"); 그 이상의 콘솔 프로그래밍
(게임개발을위한) printf("Hello World!"); 그 이상의 콘솔 프로그래밍(게임개발을위한) printf("Hello World!"); 그 이상의 콘솔 프로그래밍
(게임개발을위한) printf("Hello World!"); 그 이상의 콘솔 프로그래밍
 
05_컴파일러최적화전략(1)
05_컴파일러최적화전략(1)05_컴파일러최적화전략(1)
05_컴파일러최적화전략(1)
 
Assembly 스터디 1
Assembly 스터디 1Assembly 스터디 1
Assembly 스터디 1
 
6. code level reversing
6. code level reversing6. code level reversing
6. code level reversing
 
Windows Registered I/O (RIO) vs IOCP
Windows Registered I/O (RIO) vs IOCPWindows Registered I/O (RIO) vs IOCP
Windows Registered I/O (RIO) vs IOCP
 
강좌 04 펌웨어 구조 설계
강좌 04 펌웨어 구조 설계강좌 04 펌웨어 구조 설계
강좌 04 펌웨어 구조 설계
 
이기종 멀티코어 프로세서를 위한 프로그래밍 언어 및 영상처리 오픈소스
이기종 멀티코어 프로세서를 위한 프로그래밍 언어 및 영상처리 오픈소스이기종 멀티코어 프로세서를 위한 프로그래밍 언어 및 영상처리 오픈소스
이기종 멀티코어 프로세서를 위한 프로그래밍 언어 및 영상처리 오픈소스
 
The Future of C# and .NET Framework
The Future of C# and .NET FrameworkThe Future of C# and .NET Framework
The Future of C# and .NET Framework
 
kics2013-winter-biomp-slide-20130127-1340
kics2013-winter-biomp-slide-20130127-1340kics2013-winter-biomp-slide-20130127-1340
kics2013-winter-biomp-slide-20130127-1340
 
프로그래밍 언어의 기본 개념과 주요 프로그래밍 언어
프로그래밍 언어의 기본 개념과 주요 프로그래밍 언어프로그래밍 언어의 기본 개념과 주요 프로그래밍 언어
프로그래밍 언어의 기본 개념과 주요 프로그래밍 언어
 
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍인프콘 2022 - Rust 크로스 플랫폼 프로그래밍
인프콘 2022 - Rust 크로스 플랫폼 프로그래밍
 
Assembly 스터디 2
Assembly 스터디 2Assembly 스터디 2
Assembly 스터디 2
 
[170403 2주차]C언어 A반
[170403 2주차]C언어 A반[170403 2주차]C언어 A반
[170403 2주차]C언어 A반
 

More from Hankyo

01.실행환경 실습교재(공통기반)
01.실행환경 실습교재(공통기반)01.실행환경 실습교재(공통기반)
01.실행환경 실습교재(공통기반)Hankyo
 
01.모바일 프레임워크 이론
01.모바일 프레임워크 이론01.모바일 프레임워크 이론
01.모바일 프레임워크 이론Hankyo
 
01.공통컴포넌트 교육교재
01.공통컴포넌트 교육교재01.공통컴포넌트 교육교재
01.공통컴포넌트 교육교재Hankyo
 
01.개발환경 교육교재
01.개발환경 교육교재01.개발환경 교육교재
01.개발환경 교육교재Hankyo
 
07.실행환경 교육교재(표준프레임워크 세부 적용기준)
07.실행환경 교육교재(표준프레임워크 세부 적용기준)07.실행환경 교육교재(표준프레임워크 세부 적용기준)
07.실행환경 교육교재(표준프레임워크 세부 적용기준)Hankyo
 
06.실행환경 실습교재(easy company,해답)
06.실행환경 실습교재(easy company,해답)06.실행환경 실습교재(easy company,해답)
06.실행환경 실습교재(easy company,해답)Hankyo
 
06.실행환경 실습교재(easy company,문제)
06.실행환경 실습교재(easy company,문제)06.실행환경 실습교재(easy company,문제)
06.실행환경 실습교재(easy company,문제)Hankyo
 
05.실행환경 교육교재(업무처리,연계통합)
05.실행환경 교육교재(업무처리,연계통합)05.실행환경 교육교재(업무처리,연계통합)
05.실행환경 교육교재(업무처리,연계통합)Hankyo
 
04.실행환경 실습교재(화면처리)
04.실행환경 실습교재(화면처리)04.실행환경 실습교재(화면처리)
04.실행환경 실습교재(화면처리)Hankyo
 
04.실행환경 교육교재(화면처리)
04.실행환경 교육교재(화면처리)04.실행환경 교육교재(화면처리)
04.실행환경 교육교재(화면처리)Hankyo
 
04.모바일 device api_실습교재
04.모바일 device api_실습교재04.모바일 device api_실습교재
04.모바일 device api_실습교재Hankyo
 
04.[참고]개발환경 실습교재
04.[참고]개발환경 실습교재04.[참고]개발환경 실습교재
04.[참고]개발환경 실습교재Hankyo
 
03.실행환경 실습교재(배치처리)
03.실행환경 실습교재(배치처리)03.실행환경 실습교재(배치처리)
03.실행환경 실습교재(배치처리)Hankyo
 
03.실행환경 교육교재(배치처리)
03.실행환경 교육교재(배치처리)03.실행환경 교육교재(배치처리)
03.실행환경 교육교재(배치처리)Hankyo
 
03.모바일 실습교재(모바일 공통컴포넌트 실습)
03.모바일 실습교재(모바일 공통컴포넌트 실습)03.모바일 실습교재(모바일 공통컴포넌트 실습)
03.모바일 실습교재(모바일 공통컴포넌트 실습)Hankyo
 
03.[참고]표준프레임워크기반 개발방법
03.[참고]표준프레임워크기반 개발방법03.[참고]표준프레임워크기반 개발방법
03.[참고]표준프레임워크기반 개발방법Hankyo
 
03.[참고]개발환경 교육교재
03.[참고]개발환경 교육교재03.[참고]개발환경 교육교재
03.[참고]개발환경 교육교재Hankyo
 
02.실행환경 실습교재(데이터처리)
02.실행환경 실습교재(데이터처리)02.실행환경 실습교재(데이터처리)
02.실행환경 실습교재(데이터처리)Hankyo
 
02.실행환경 교육교재(데이터처리)
02.실행환경 교육교재(데이터처리)02.실행환경 교육교재(데이터처리)
02.실행환경 교육교재(데이터처리)Hankyo
 
02.모바일 실습교재(ux component)
02.모바일 실습교재(ux component)02.모바일 실습교재(ux component)
02.모바일 실습교재(ux component)Hankyo
 

More from Hankyo (20)

01.실행환경 실습교재(공통기반)
01.실행환경 실습교재(공통기반)01.실행환경 실습교재(공통기반)
01.실행환경 실습교재(공통기반)
 
01.모바일 프레임워크 이론
01.모바일 프레임워크 이론01.모바일 프레임워크 이론
01.모바일 프레임워크 이론
 
01.공통컴포넌트 교육교재
01.공통컴포넌트 교육교재01.공통컴포넌트 교육교재
01.공통컴포넌트 교육교재
 
01.개발환경 교육교재
01.개발환경 교육교재01.개발환경 교육교재
01.개발환경 교육교재
 
07.실행환경 교육교재(표준프레임워크 세부 적용기준)
07.실행환경 교육교재(표준프레임워크 세부 적용기준)07.실행환경 교육교재(표준프레임워크 세부 적용기준)
07.실행환경 교육교재(표준프레임워크 세부 적용기준)
 
06.실행환경 실습교재(easy company,해답)
06.실행환경 실습교재(easy company,해답)06.실행환경 실습교재(easy company,해답)
06.실행환경 실습교재(easy company,해답)
 
06.실행환경 실습교재(easy company,문제)
06.실행환경 실습교재(easy company,문제)06.실행환경 실습교재(easy company,문제)
06.실행환경 실습교재(easy company,문제)
 
05.실행환경 교육교재(업무처리,연계통합)
05.실행환경 교육교재(업무처리,연계통합)05.실행환경 교육교재(업무처리,연계통합)
05.실행환경 교육교재(업무처리,연계통합)
 
04.실행환경 실습교재(화면처리)
04.실행환경 실습교재(화면처리)04.실행환경 실습교재(화면처리)
04.실행환경 실습교재(화면처리)
 
04.실행환경 교육교재(화면처리)
04.실행환경 교육교재(화면처리)04.실행환경 교육교재(화면처리)
04.실행환경 교육교재(화면처리)
 
04.모바일 device api_실습교재
04.모바일 device api_실습교재04.모바일 device api_실습교재
04.모바일 device api_실습교재
 
04.[참고]개발환경 실습교재
04.[참고]개발환경 실습교재04.[참고]개발환경 실습교재
04.[참고]개발환경 실습교재
 
03.실행환경 실습교재(배치처리)
03.실행환경 실습교재(배치처리)03.실행환경 실습교재(배치처리)
03.실행환경 실습교재(배치처리)
 
03.실행환경 교육교재(배치처리)
03.실행환경 교육교재(배치처리)03.실행환경 교육교재(배치처리)
03.실행환경 교육교재(배치처리)
 
03.모바일 실습교재(모바일 공통컴포넌트 실습)
03.모바일 실습교재(모바일 공통컴포넌트 실습)03.모바일 실습교재(모바일 공통컴포넌트 실습)
03.모바일 실습교재(모바일 공통컴포넌트 실습)
 
03.[참고]표준프레임워크기반 개발방법
03.[참고]표준프레임워크기반 개발방법03.[참고]표준프레임워크기반 개발방법
03.[참고]표준프레임워크기반 개발방법
 
03.[참고]개발환경 교육교재
03.[참고]개발환경 교육교재03.[참고]개발환경 교육교재
03.[참고]개발환경 교육교재
 
02.실행환경 실습교재(데이터처리)
02.실행환경 실습교재(데이터처리)02.실행환경 실습교재(데이터처리)
02.실행환경 실습교재(데이터처리)
 
02.실행환경 교육교재(데이터처리)
02.실행환경 교육교재(데이터처리)02.실행환경 교육교재(데이터처리)
02.실행환경 교육교재(데이터처리)
 
02.모바일 실습교재(ux component)
02.모바일 실습교재(ux component)02.모바일 실습교재(ux component)
02.모바일 실습교재(ux component)
 

Ch09

  • 1. Compiler Lecture Note, Intermediate Language Page 1 제 9 장 중 간 언어 컴파일러 입문
  • 2. Compiler Lecture Note, Intermediate Language Page 2 Contents • Introduction • Polish Notation • Three Address Code • Tree Structured Code • Abstract Machine Code • Concluding Remarks
  • 3. Compiler Lecture Note, Intermediate Language Page 3 • Compiler Model Source Program Lexical Analyzer Syntax Analyzer Semantic Analyzer Intermediate Code Generator tokens AST Front-End Code Optimizer Target Code Generator IC Back-End IL Object Program Front-End- language dependant part Back-End - machine dependant part Introduction
  • 4. Compiler Lecture Note, Intermediate Language Page 4 • IL 사용의 장점 – Compiler를 기능적으로 독립적인 Modul들로 구성 – Compiler 자체의 portability 증가 – Easy Translation • 고급 소스 언어와 저급 목적 코드간의 semantic gap를 이어주는 교량 역할 – 중간코드를 이용하여 optimization를 수행 • 기계와 독립적인 최적화 가능 • 기계어로 바뀐 상태에서 행하는 것보다 훨씬 효율적으로 최적화 수행 – Interpretive compiling 시스템에서 interpreter를 이용하여 실행 • IL사용의 결점 – 목적 코드로 직접 번역하는 것 보다 컴파일 시간이 더 많이 소요 – 비효율적인 코드 생산 • 중간 코드로부터 목적 코드로의 번역 과정 필요 • 중간언어 단계에서 간단한 최적화를 통해 극복
  • 5. Compiler Lecture Note, Intermediate Language Page 5 • Two level Code Generation • ILS – 소스로부터 자동화에 의해 얻을 수 있는 형태 – 소스 언어에 의존적이며 high level이다. • ILT – 후단부의 자동화에 의해 목적기계로의 번역이 매우 쉬운 형태 – 목적기계에 의존적이며 low level이다. • ILS to ILT – ILS에서 ILT로의 번역이 주된 작업임. Source Front-End ILS ILS-ILT ILT Back-End Target
  • 6. • IL의 종류 – Polish Notation  Prefix notation, IR – Three Address Code  Triple, Quadruple, Indirect Triple – Tree Structured Code  AST, TCOL, Diana – Abstract Machine Code  P-code, EM-code, U-code, Bytecode Compiler Lecture Note, Intermediate Language Page 6
  • 7. Compiler Lecture Note, Intermediate Language Page 7 ☞ Polish mathematician Lucasiewiez invented the parenthesis-free notation. • Postfix(Suffix) Polish Notation • earliest IL • popular for interpreted language - SNOBOL, BASIC – general form : e1 e2 ... ek OP (k ≥ 1) where, OP : k_ary operator ei : any postfix expression (1 ≤ i ≤ k) Polish Notation
  • 8. Compiler Lecture Note, Intermediate Language Page 8 – example : if a then if c-d then a+c else a*c else a+b 〓〉a L1 BZ c d - L2 BZ a c + L3 BR L2: a c * L3 BR L1: a b + L3: – note 1) high level: source to IL - fast & easy translation IL to target - difficulty 2) easy evaluation - operand stack 3) optimization 부적당 - 다른 IL로의 translation 필요 4) parentheses free notation - arithmetic expression – interpretive language에 적합 Source Translator Postfix Evaluator Result
  • 9. Compiler Lecture Note, Intermediate Language Page 9 • most popular IL, optimizing compiler • General form: A := B op C where, A : result address B, C : operand addresses op : operator (1) Quadruple - 4-tuple notation <operator>,<operand1>,<operand2>,<result> (2) Triple - 3-tuple notation <operator>,<operand1>,<operand2> (3) Indirect triple - execution order table & triples Three Address Code
  • 10. Compiler Lecture Note, Intermediate Language Page 10 – example • A ← B + C * D / E • F ← C * D Quadruple Triple Indirect Triple Operations Triple * C D T1 (1) * C D 1.(1) (1) * C D / T1 E T2 (2) / (1) E 2.(2) (2) / (1) E + B T2 T3 (3) + B (2) 3.(3) (3) + B (2)  T3 A (4)  A (3) 4.(4) (4)  A (3) * C D T4 (5) * C D 5.(1) (5)  F (1)  T4 F (6)  F (5) 6.(5)
  • 11. Compiler Lecture Note, Intermediate Language Page 11 • Note • Quadruple vs. Triple – quadruple - optimization 용이 – triple - removal of temporary addresses ⇒ Indirect Triple • extensive code optimization 용이 – IL rearrange 가능 (triple 제외) • easy translation - source to IL • difficult to generate good code – quadruple to two-address machine – triple to three-address machine
  • 12. Compiler Lecture Note, Intermediate Language Page 12 • Abstract Syntax Tree – parse tree에서 redundant한 information 제거. • ┌ leaf node --- variable name, constant └ internal node --- operator – 예 : a * b + c / d a[i] = exp; Tree Structured Code add divmul b ca d assign expindex ia
  • 13. Compiler Lecture Note, Intermediate Language Page 13 • Tree Structured Common Language(TCOL) – Variants of AST - containing the result of semantic analysis. Example) int a; float b; ... b = a + 1; AST TCOL add 1a assign b float assign b addi 1 a
  • 14. Compiler Lecture Note, Intermediate Language Page 14 Abstract Machine Code • Abstract Machine을 이용한 portable compiler의 모델 • Abstract Machine의 설계 – source language의 기본 연산과 모드에 근거 • 기본 연산은 source program을 구성하는 가장 간단하고 대부분 직 접적인 연산에 대응 • 기본적인 자료 모드는 source language의 가장 간단한 형 • 기본적인 모드와 연산들이 Abstract Machine의 명령어를 결정 – 실제 컴퓨터에 효율적으로 설치 가능 여부도 고려 front-end back-end target machine abstract machine interpreter source program interface target code abstract machine code
  • 15. Compiler Lecture Note, Intermediate Language Page 15 • Motivation • ┌ rapid development of machine architectures └ proliferation of programming languages – portable & adaptable compiler design --- P_CODE • porting --- rewriting only back-end – compiler building system --- EM_CODE M front-ends N back-ends + M compilers for N target machines
  • 16. Compiler Lecture Note, Intermediate Language Page 16 • Pascal-P Code – Pascal compiler를 제작하는데 사용된 intermediate language • Pascal-P compiler – P-코드에서 실제 기계로의 번역기 또는 P-code interpreter를 사용함 으로써 쉽게 이식이 가능 – 소스 언어로부터 P-code로의 translation과 interpretation이 비교적 쉽 게 설계 – P-code에 대한 가상 기계가 P-기계이며, P-기계도 모든 연산이 스택에서 행해지는 가상적인 스택 기계(hypothetical stack machine) Pascal P CompilerPascal Program P-code
  • 17. Compiler Lecture Note, Intermediate Language Page 17 • EM-code – ACK 중간 언어 • ACK(Amsterdam Compiler Kit) – Algol 형태의 소스 언어와 바이트 기계 형태의 목적 기계에 적합한 EM-기계라는 가상 기계를 설정하고 언어에 대한 전단부와 목적 기 계에 대한 후단부를 제공함으로써 사용자가 필요한 컴파일러를 쉽 게 제작하도록 도와주는 기구 – 가상적인 스택의 개념을 둔 기계 구조 – 소스 언어로부터 EM-코드로의 번역과 EM-코드의 인터프리테 이션이 비교적 쉽게 설계 – EM-코드를 이용하여 제작한 컴파일러는 EM-코드에서 목적 기계로의 번역기 또는 EM-코드 인터프리터만을 교환함으로 써 쉽게 이식 가능
  • 18. • U-code – Portable Pascal compiler에서 사용한 중간 형태 – 가상적인 스택 기계에 근거 • 모든 명령어들은 가상 스택을 기준으로 정의 • 스택에서 모든 연산 수행 – 스택 기계는 모든 연산을 스택에서 실행하므로 변수들의 주소 는 스택에 대한 주소 부여 방법 이용 • 모든 변수에 대한 주소는 두 개의 항목(B, O)의 형태로 구성 – B : 블록의 번호 – O : 블록의 시작으로부터의 offset – 예 – 블록 번호는 프로그램 main이 1, procedure P가 2, procedure Q가 3 – procedure Q에 선언된 변수 i와 j의 주소는 각각 (3, 1)과 (3, 2)로 표현 Compiler Lecture Note, Intermediate Language Page 18 program main procedure P procedure Q var i : integer; j : boolean;
  • 19. • U-code 명령어들의 형태와 기능에 따른 분류 1. 단일 명령어 ⇒ notop, neg 2. 이진 명령어 ⇒ add, sub, mult, divop, nodop, swp andop, orop, gt, lt, ge, le, eq, ne 3. 스택 운영 명령어 ⇒ lod, str, ldc, ldr 4. 제어 흐름 명령어 ⇒ ujp, tjp, fjp 5. 범위 검사 명령어 ⇒ chkh, chkl 6. 간접 주소 명령어 ⇒ ixa, sta 7. procedure 명령어 ⇒ cal, ret, ldp, proc, endop 8. 기타 명령어 ⇒ bgn, sym Compiler Lecture Note, Intermediate Language Page 19
  • 20. • U-code로 작성된 프로그램의 전체 구조 – 먼저 global variable의 속성이 나오며, 그 다음에 procedure의 code가 나올 수 있으며, 마지막에 주 프로그램에 대한 code가 나옴 – 하나의 procedure는 local variable의 속성과 code로 구성 – 맨 처음, bgn(begin)으로 제어가 넘어와 실행이 시작 Compiler Lecture Note, Intermediate Language Page 20 sym(s) global variable(s) <name> proc sym(s) for procedure codes for procedure ··· endop bgn codes for main program ··· endop
  • 21. • Bytecode – Java 프로그래밍 환경에서 지원하는 IL로서 이기종간의 실행 환경 에 적합하도록 설계된 스택 기반의 가상 기계 코드 – Java compiler • Java 프로그램을 입력 받아 JVM(Java Virtual Machine)의 명령어 집합인 byetcode 생성 • Intermediate code 형태인 bytecode는 이기종간의 실행 환경에 적합하도 록 설계되어 portability과 유연성이 높다. • interpreter 방식과 JIT(Just-In-Time) compiler 방식에 의해서 실행 Compiler Lecture Note, Intermediate Language Page 21 Java CompilerJava Program Bytecode JVM 실행 결과
  • 22. – Bytecode는 일반적인 Abstract Machine Code의 특징을 모두 포함 – Bytecode 만의 특징 • 네트워크 상에서 전송 효율을 위해 code를 가능한 작고 간결하게 설계 • Java language의 기능을 반영하는 명령어가 존재 – 배열, 클래스, 예외, 스레드 등을 직접 다룰 수 있는 명령어 포함 • 자료형에 따라서 명령어가 각기 따로 존재 – ex) iadd 는 int 덧셈, fadd는 float 덧셈 • 복합기능을 갖는 명령어를 제공 – ex) pop2는 stack에서 연속해서 두 번을 pop하는 기능 Compiler Lecture Note, Intermediate Language Page 22
  • 23. • IL의 4가지 분류 – Polish Notation  Postfix notation, IR – Three Address Code  Triple, Quadruple, Indirect Triple – Tree Structured Code  AST, TCOL, Diana – Abstract Machine Code  P-code, EM-code, U-code, Bytecode • IL이 갖추어야 할 요건 1. 중간 레벨성(Intermediate level) • 소스 언어와 비교해서는 low-level이고 목적 기계와 비교해서는 high- level의 성격을 유지해야 하는 속성을 의미 • IL이 너무 한쪽으로 치우쳐 있으면 IL과 다른 한쪽과의 의미적 차이가 커져 번역이 어려워지며 또한 이식성 결여 – Postfix polish notation과 syntax tree는 high-level – Triple, quadruple는 비교적 high-level – Abstract Machine Code 는 비교적 low-level – TCOL만이 비교적 intermediate level이 좋은 언어 Compiler Lecture Note, Intermediate Language Page 23
  • 24. 2. 효율적인 처리의 적합성(Efficient processing) • 소스 언어에서 중간 언어로 번역, 중간언어에서 목적 언어로 번역 – High-level에 치우친 중간 코드는 소스 언어에서 IL로 번역이 쉬운 반면 IL에서 목적 언어로 번역이 어려움 – Low-level 에 가까운 것은 반대 현상이 나타남 • 인터프리테이션(Interpretation) – Abstract machine code가 가장 우수 – Postfix 표현도 operand stack을 이용하여 쉽게 interpretation을 할 수 있는 형태 – Tree 구조 코드는 tree 구조상 interpretation에 가장 많은 결함을 보임 • 최적화(Optimization) – 쉽게 코드를 이동할 수 있는 quadruple이 효과적이며 tree 구조도 고급 언어의 제어 구조를 내포할 수 있으며 tree의 재구성이 쉽기 때문에 optimization에 적 합한 형태 – Postfix 표현이나 triple 표현은 연산의 결과가 위치에 영향을 미치지 때문에 optimization에 부적합 3. 외부 표현성 (External representation) • Tree 구조 code만이 선형 구조가 아닌 관계로 단점을 나타냄 4. 확장성(Extensibility) • 비교적 모든 중간 언어들이 좋은 편 • Abstract Machine Code만 약간의 결함 Compiler Lecture Note, Intermediate Language Page 24
  • 25. 5. 이식성(Portability) • 크게 영향을 주는 기계 종속성과 언어 종속성의 분명한 구분성에서는 TCOL과 가상 기계 코드가 가장 우수 • 소스 언어에 가까운 고급 표현인 postfix 표현과 AST는 부적당 • Intermediate Language의 비교 Compiler Lecture Note, Intermediate Language Page 25 IL Criteria Polish Notation Three Address Code Tree Structured Abstract Machine CodePost IR Quadra Triple AST TCOL Intermediate level C B B B C A B efficient processing source to IL translation A C B B A B C IL to target translation C A B B C A A interpretation A B B B C C A optimization C B A C A A B external representation B B A B C B A extensibility A A A A A A B clean separation C B B B C A A A : 좋다 B : 보통이다 C : 나쁘다