SlideShare a Scribd company logo
1 of 21
INLINE ASSEMBLY
LANGUAGE PROGRAMS IN
        C/C++
         1



              SUBMITTED BY,




                        9/3/2012
Introduction
                               2

First of all, what does term "inline" mean?
 Generally the inline term is used to instruct the compiler
  to insert the code of a function into the code of its caller
  at the point where the actual call is made. Such
  functions are called "inline functions". The benefit of
  inlining is that it reduces function-call overhead.
 Now, it's easier to guess about inline assembly. It is just
  a set of assembly instructions written as inline
  functions.
                                                          9/3/2012
Introduction
                            3


 Assembly language serves many purposes, such as
 improving program speed, reducing memory needs,
 and controlling hardware.
 We can use the inline assembler to embed assembly-
 language instructions directly in your C and C++ source
 programs without extra assembly and link steps.
 We can mix the assembly statements within C/C++
 programs using keyword asm

                                                    9/3/2012
Inline Assembler Overview
                             4



 The inline assembler lets us embed assembly-language
  instructions in our C and C++ source programs without
  extra assembly and link steps.
 Inline assembly code can use any C or C++ variable or
  function name that is in scope.
 The asm keyword invokes the inline assembler and can
  appear wherever a C or C++ statement is legal. It cannot
  appear by itself.
 It must be followed by an assembly instruction, a group of
  instructions enclosed in braces, or, at the very least, an
  empty pair of braces.

                                                       9/3/2012
Advantages of Inline Assembly
                              5


 The inline assembler doesn't require separate assembly
 and link steps, it is more convenient than a separate
 assembler.
 Inline assembly code can use any C variable or function
 name that is in scope, so it is easy to integrate it with
 our program's C code.
 Because the assembly code can be mixed inline with C
 or C++ statements, it can do tasks that are
 cumbersome or impossible in C or C++.
                                                        9/3/2012
Advantages of Inline Assembly
                           6

The uses of inline assembly include:

 Writing functions in assembly language.
 Spot-optimizing speed-critical sections of code.
 Making direct hardware access for device drivers.
 Writing prolog and epilog code for "naked" calls.




                                                      9/3/2012
asm
                                      7

 The asm keyword invokes the inline assembler and can appear
  wherever a C or C++ statement is legal. It cannot appear by itself.
 It must be followed by an assembly instruction, a group of instructions
  enclosed in braces, or, at the very least, an empty pair of braces.

 Grammar
        asm-statement:
               asm assembly-instruction ;opt
               asm { assembly-instruction-list } ;opt
        assembly-instruction-list:
               assembly-instruction ;opt
               assembly-instruction ; assembly-instruction-list ;opt


                                                                       9/3/2012
asm
                          8

 The following code fragment is a simple asm block
 enclosed in braces:

     asm {
             mov al, 2
             mov dx, 0xD007
             out dx, al
             }


                                                9/3/2012
asm
                            9

 Alternatively, you can put asm in front of each
  assembly instruction:
            asm mov al, 2
            asm mov dx, 0xD007
            asm out dx, al
 Because the asm keyword is a statement separator,
  you can also put assembly instructions on the same
  line:
  asm mov al, 2 asm mov dx, 0xD007 asm out dx, al

                                                    9/3/2012
asm
                                 10


 All three examples generate the same code, but the first style

  (enclosing the asm block in braces) has some advantages.

 The braces clearly separate assembly code from C or C++ code

  and avoid needless repetition of the asm keyword.

 Braces can also prevent ambiguities. If you want to put a C or

  C++ statement on the same line as an asm block, you must
  enclose the block in braces. Without the braces, the compiler
  cannot tell where assembly code stops and C or C++ statements
  begin.
                                                             9/3/2012
Using C or C++ in asm Blocks
                                         11

         Because inline assembly instructions can be mixed with C or C++
  statements, they can refer to C or C++ variables by name and use many other
  elements of those languages.
                  An asm block can use the following language elements:
 Symbols, including labels and variable and function names

 Constants, including symbolic constants and enum members

 Macros and preprocessor directives

 Comments (both /* */ and // )

 Type names (wherever a MASM type would be legal)

 typedef names, generally used with operators such as PTR and TYPE or to
  specify structure or union members


                                                                           9/3/2012
Jumping to Labels in Inline Assembly
                                    12

 Like an ordinary C or C++ label, a label in an asm block has scope
  throughout the function in which it is defined (not only in the block).
  Both assembly instructions and goto statements can jump to
  labels inside or outside the asm block.
 Labels defined in asm blocks are not case sensitive; both goto
  statements and assembly instructions can refer to those labels
  without regard to case. C and C++ labels are case sensitive only
  when used by goto statements. Assembly instructions can jump to a
  C or C++ label without regard to case.


                                                                    9/3/2012
Jumping to Labels in Inline Assembly
                               13
 Example:
             Void func( void )
                    {
                            goto C_Dest;
                            goto A_Dest;
                    asm {
                            jmp C_Dest ;
                            jmp A_Dest ;
                            a_dest: ;    asm label
                          }
                            C_Dest:      /* C label */
                            return;
                     }
                    int main()
                     {}
                                                         9/3/2012
Example
                                14
#include<stdio.h>                    JNC next
#include<conio.h>                    lea dx,a
void main()                          mov ah,09h
{                                    int 21h
      char a[5]="ODD$";              jmp er
      char b[5]="EVEN$";             }
net:                                 next:
               asm{                           asm
               mov cl,al             {
               mov bl,13                      lea dx,b
               mov ah,0x01                    mov ah,09h
               int 0x21                       int 21h
               cmp bl,al                      jmp er
               jnz net               }
               mov al,cl             er:
               sub al,0x30                    getch();
               shr al,1              }                     9/3/2012
Calling C Functions in Inline Assembly
                                          15

 An __asm block can call C functions, including C library routines. The following
  example calls the printf library routine:
  Example:        char format[]=" %s %sn";
                  char hello[]="hello";
                  char world[]="world";
                  void main()
                             {
                                       asm{
                                       mov ax,offset world
                                       push ax
                                       mov ax,offset hello
                                       push ax
                                       mov ax,offset format
                                       push ax
                                       call printf
                                       pop bx
                                       pop bx
                                       pop bx
                             }
                                                                               9/3/2012
Calling C Functions in Inline Assembly
                              16


 Because function arguments are passed on the stack,
 you simply push the needed arguments — string
 pointers, in the previous example — before calling the
 function. The arguments are pushed in reverse order, so
 they come off the stack in the desired order. To emulate
 the C statement
              printf( format, hello, world );
 the example pushes pointers to world, hello, and format,
 in that order, and then calls printf.
                                                      9/3/2012
Calling C++ Functions in Inline Assembly
                                17


 An asm block can call only global C++ functions that are not
  overloaded.
 If we call an overloaded global C++ function or a C++ member
  function, the compiler issues an error.
 We can also call any functions declared with extern "C"
  linkage.
 This allows an asm block within a C++ program to call the C
  library functions, because all the standard header files declare
  the library functions to have extern "C" linkage.
                                                            9/3/2012
Defining asm Blocks as C Macros
                                 18


 C macros offer a convenient way to insert assembly code

 into your source code, but they demand extra care
 because a macro expands into a single logical line. To
 create trouble-free macros, follow these rules:
    Enclose the asm block in braces.

    Put the asm keyword in front of each assembly instruction.

    Use old-style C comments ( /* comment */) instead of assembly-
     style comments ( ; comment) or single-line C comments ( //
     comment).
                                                              9/3/2012
Defining asm Blocks as C Macros
                           19

 To illustrate, the following example defines a simple
 macro:
    #define PORTIO asm
               {
               asm mov al, 2
               asm mov dx, 0xD007
               asm out dx, al
                }


                                                   9/3/2012
Optimizing Inline Assembly
                                   20


 The presence of an asm block in a function affects
 optimization in several ways.
    First, the compiler doesn't try to optimize the asm block itself.
     What you write in assembly language is exactly what you get.
    Second, the presence of an asm block affects register variable
     storage. The compiler avoids enregistering variables across an
     asm block if the register's contents would be changed by the
     asm block.
    Finally, some other function-wide optimizations will be affected
     by the inclusion of assembly language in a function.
                                                                  9/3/2012
21




     9/3/2012

More Related Content

What's hot

Interrupts for PIC18
Interrupts for PIC18Interrupts for PIC18
Interrupts for PIC18raosandy11
 
Mastering Microcontroller : TIMERS, PWM, CAN, RTC,LOW POWER
Mastering Microcontroller : TIMERS, PWM, CAN, RTC,LOW POWERMastering Microcontroller : TIMERS, PWM, CAN, RTC,LOW POWER
Mastering Microcontroller : TIMERS, PWM, CAN, RTC,LOW POWERFastBit Embedded Brain Academy
 
JVM JIT compilation overview by Vladimir Ivanov
JVM JIT compilation overview by Vladimir IvanovJVM JIT compilation overview by Vladimir Ivanov
JVM JIT compilation overview by Vladimir IvanovZeroTurnaround
 
Introduction to Embedded Architecture
Introduction to Embedded Architecture Introduction to Embedded Architecture
Introduction to Embedded Architecture amrutachintawar239
 
Myths of Big Partitions (Robert Stupp, DataStax) | Cassandra Summit 2016
Myths of Big Partitions (Robert Stupp, DataStax) | Cassandra Summit 2016Myths of Big Partitions (Robert Stupp, DataStax) | Cassandra Summit 2016
Myths of Big Partitions (Robert Stupp, DataStax) | Cassandra Summit 2016DataStax
 
A whirlwind tour of the LLVM optimizer
A whirlwind tour of the LLVM optimizerA whirlwind tour of the LLVM optimizer
A whirlwind tour of the LLVM optimizerNikita Popov
 
Velocity 2015 linux perf tools
Velocity 2015 linux perf toolsVelocity 2015 linux perf tools
Velocity 2015 linux perf toolsBrendan Gregg
 
Intel 8086 internal architecture & pin diagram
Intel 8086 internal architecture & pin diagramIntel 8086 internal architecture & pin diagram
Intel 8086 internal architecture & pin diagramkrunal47
 
Understanding eBPF in a Hurry!
Understanding eBPF in a Hurry!Understanding eBPF in a Hurry!
Understanding eBPF in a Hurry!Ray Jenkins
 
Unit 1 Introduction to Embedded computing and ARM processor
Unit 1 Introduction to Embedded computing and ARM processorUnit 1 Introduction to Embedded computing and ARM processor
Unit 1 Introduction to Embedded computing and ARM processorVenkat Ramanan C
 
Vmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is bootedVmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is bootedAdrian Huang
 
Microchip's 16-bit and 32-bit PIC MCUs
Microchip's 16-bit and 32-bit PIC MCUsMicrochip's 16-bit and 32-bit PIC MCUs
Microchip's 16-bit and 32-bit PIC MCUsPremier Farnell
 
The e820 trap of Linux kernel hibernation
The e820 trap of Linux kernel hibernationThe e820 trap of Linux kernel hibernation
The e820 trap of Linux kernel hibernationjoeylikernel
 
RISC-V Introduction
RISC-V IntroductionRISC-V Introduction
RISC-V IntroductionYi-Hsiu Hsu
 

What's hot (20)

Interrupts for PIC18
Interrupts for PIC18Interrupts for PIC18
Interrupts for PIC18
 
Microprocessor 8086
Microprocessor 8086Microprocessor 8086
Microprocessor 8086
 
Mastering Microcontroller : TIMERS, PWM, CAN, RTC,LOW POWER
Mastering Microcontroller : TIMERS, PWM, CAN, RTC,LOW POWERMastering Microcontroller : TIMERS, PWM, CAN, RTC,LOW POWER
Mastering Microcontroller : TIMERS, PWM, CAN, RTC,LOW POWER
 
STM32 Microcontroller Clocks and RCC block
STM32 Microcontroller Clocks and RCC blockSTM32 Microcontroller Clocks and RCC block
STM32 Microcontroller Clocks and RCC block
 
JVM JIT compilation overview by Vladimir Ivanov
JVM JIT compilation overview by Vladimir IvanovJVM JIT compilation overview by Vladimir Ivanov
JVM JIT compilation overview by Vladimir Ivanov
 
Kernel crashdump
Kernel crashdumpKernel crashdump
Kernel crashdump
 
8085 instruction set
8085 instruction set8085 instruction set
8085 instruction set
 
Introduction to Embedded Architecture
Introduction to Embedded Architecture Introduction to Embedded Architecture
Introduction to Embedded Architecture
 
Myths of Big Partitions (Robert Stupp, DataStax) | Cassandra Summit 2016
Myths of Big Partitions (Robert Stupp, DataStax) | Cassandra Summit 2016Myths of Big Partitions (Robert Stupp, DataStax) | Cassandra Summit 2016
Myths of Big Partitions (Robert Stupp, DataStax) | Cassandra Summit 2016
 
A whirlwind tour of the LLVM optimizer
A whirlwind tour of the LLVM optimizerA whirlwind tour of the LLVM optimizer
A whirlwind tour of the LLVM optimizer
 
Zynq architecture
Zynq architectureZynq architecture
Zynq architecture
 
Velocity 2015 linux perf tools
Velocity 2015 linux perf toolsVelocity 2015 linux perf tools
Velocity 2015 linux perf tools
 
Intel 8086 internal architecture & pin diagram
Intel 8086 internal architecture & pin diagramIntel 8086 internal architecture & pin diagram
Intel 8086 internal architecture & pin diagram
 
Understanding eBPF in a Hurry!
Understanding eBPF in a Hurry!Understanding eBPF in a Hurry!
Understanding eBPF in a Hurry!
 
Unit 1 Introduction to Embedded computing and ARM processor
Unit 1 Introduction to Embedded computing and ARM processorUnit 1 Introduction to Embedded computing and ARM processor
Unit 1 Introduction to Embedded computing and ARM processor
 
Vmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is bootedVmlinux: anatomy of bzimage and how x86 64 processor is booted
Vmlinux: anatomy of bzimage and how x86 64 processor is booted
 
Microchip's 16-bit and 32-bit PIC MCUs
Microchip's 16-bit and 32-bit PIC MCUsMicrochip's 16-bit and 32-bit PIC MCUs
Microchip's 16-bit and 32-bit PIC MCUs
 
The e820 trap of Linux kernel hibernation
The e820 trap of Linux kernel hibernationThe e820 trap of Linux kernel hibernation
The e820 trap of Linux kernel hibernation
 
RISC-V Introduction
RISC-V IntroductionRISC-V Introduction
RISC-V Introduction
 
ARM CORTEX M3 PPT
ARM CORTEX M3 PPTARM CORTEX M3 PPT
ARM CORTEX M3 PPT
 

Viewers also liked

Inline asm in c gọi hàm ngat
Inline asm in c gọi hàm ngatInline asm in c gọi hàm ngat
Inline asm in c gọi hàm ngatMy Đá
 
Programming The Arm Microprocessor For Embedded Systems
Programming The Arm Microprocessor For Embedded SystemsProgramming The Arm Microprocessor For Embedded Systems
Programming The Arm Microprocessor For Embedded Systemsjoshparrish13
 
Linux Kernel Booting Process (2) - For NLKB
Linux Kernel Booting Process (2) - For NLKBLinux Kernel Booting Process (2) - For NLKB
Linux Kernel Booting Process (2) - For NLKBshimosawa
 
Design of embedded systems
Design of embedded systemsDesign of embedded systems
Design of embedded systemsPradeep Kumar TS
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
Unit 1 embedded systems and applications
Unit 1 embedded systems and applicationsUnit 1 embedded systems and applications
Unit 1 embedded systems and applicationsDr.YNM
 

Viewers also liked (8)

Inline asm in c gọi hàm ngat
Inline asm in c gọi hàm ngatInline asm in c gọi hàm ngat
Inline asm in c gọi hàm ngat
 
Programming The Arm Microprocessor For Embedded Systems
Programming The Arm Microprocessor For Embedded SystemsProgramming The Arm Microprocessor For Embedded Systems
Programming The Arm Microprocessor For Embedded Systems
 
optimization c code on blackfin
optimization c code on blackfinoptimization c code on blackfin
optimization c code on blackfin
 
Linux Kernel Booting Process (2) - For NLKB
Linux Kernel Booting Process (2) - For NLKBLinux Kernel Booting Process (2) - For NLKB
Linux Kernel Booting Process (2) - For NLKB
 
Design of embedded systems
Design of embedded systemsDesign of embedded systems
Design of embedded systems
 
Inline function
Inline functionInline function
Inline function
 
Embedded System Presentation
Embedded System PresentationEmbedded System Presentation
Embedded System Presentation
 
Unit 1 embedded systems and applications
Unit 1 embedded systems and applicationsUnit 1 embedded systems and applications
Unit 1 embedded systems and applications
 

Similar to Inline assembly language programs in c

Similar to Inline assembly language programs in c (20)

1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx1 CMPS 12M Introduction to Data Structures Lab La.docx
1 CMPS 12M Introduction to Data Structures Lab La.docx
 
Csharp_Chap06
Csharp_Chap06Csharp_Chap06
Csharp_Chap06
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
 
Complete C programming Language Course
Complete C programming Language CourseComplete C programming Language Course
Complete C programming Language Course
 
7986-lect 7.pdf
7986-lect 7.pdf7986-lect 7.pdf
7986-lect 7.pdf
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 
Alp 05
Alp 05Alp 05
Alp 05
 
Alp 05
Alp 05Alp 05
Alp 05
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 
88 c programs 15184
88 c programs 1518488 c programs 15184
88 c programs 15184
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
 
Objective c beginner's guide
Objective c beginner's guideObjective c beginner's guide
Objective c beginner's guide
 
Go1
Go1Go1
Go1
 
Traduccion a ensamblador
Traduccion a ensambladorTraduccion a ensamblador
Traduccion a ensamblador
 
C Programming
C ProgrammingC Programming
C Programming
 
cppt-170218053903 (1).pptx
cppt-170218053903 (1).pptxcppt-170218053903 (1).pptx
cppt-170218053903 (1).pptx
 
Cordovilla
CordovillaCordovilla
Cordovilla
 
C basics
C basicsC basics
C basics
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
Chap03[1]
Chap03[1]Chap03[1]
Chap03[1]
 

More from Tech_MX

Virtual base class
Virtual base classVirtual base class
Virtual base classTech_MX
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimationTech_MX
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
String & its application
String & its applicationString & its application
String & its applicationTech_MX
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2Tech_MX
 
Stack data structure
Stack data structureStack data structure
Stack data structureTech_MX
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application Tech_MX
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applicationsTech_MX
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2Tech_MX
 
Set data structure
Set data structure Set data structure
Set data structure Tech_MX
 
Real time Operating System
Real time Operating SystemReal time Operating System
Real time Operating SystemTech_MX
 
Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Tech_MX
 
Motherboard of a pc
Motherboard of a pcMotherboard of a pc
Motherboard of a pcTech_MX
 
More on Lex
More on LexMore on Lex
More on LexTech_MX
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbmsTech_MX
 
Merging files (Data Structure)
Merging files (Data Structure)Merging files (Data Structure)
Merging files (Data Structure)Tech_MX
 
Memory dbms
Memory dbmsMemory dbms
Memory dbmsTech_MX
 

More from Tech_MX (20)

Virtual base class
Virtual base classVirtual base class
Virtual base class
 
Uid
UidUid
Uid
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimation
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
String & its application
String & its applicationString & its application
String & its application
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application
 
Spss
SpssSpss
Spss
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applications
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2
 
Set data structure
Set data structure Set data structure
Set data structure
 
Real time Operating System
Real time Operating SystemReal time Operating System
Real time Operating System
 
Parsing
ParsingParsing
Parsing
 
Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)
 
Motherboard of a pc
Motherboard of a pcMotherboard of a pc
Motherboard of a pc
 
More on Lex
More on LexMore on Lex
More on Lex
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbms
 
Merging files (Data Structure)
Merging files (Data Structure)Merging files (Data Structure)
Merging files (Data Structure)
 
Memory dbms
Memory dbmsMemory dbms
Memory dbms
 

Recently uploaded

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 

Recently uploaded (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 

Inline assembly language programs in c

  • 1. INLINE ASSEMBLY LANGUAGE PROGRAMS IN C/C++ 1 SUBMITTED BY, 9/3/2012
  • 2. Introduction 2 First of all, what does term "inline" mean?  Generally the inline term is used to instruct the compiler to insert the code of a function into the code of its caller at the point where the actual call is made. Such functions are called "inline functions". The benefit of inlining is that it reduces function-call overhead.  Now, it's easier to guess about inline assembly. It is just a set of assembly instructions written as inline functions. 9/3/2012
  • 3. Introduction 3  Assembly language serves many purposes, such as improving program speed, reducing memory needs, and controlling hardware.  We can use the inline assembler to embed assembly- language instructions directly in your C and C++ source programs without extra assembly and link steps.  We can mix the assembly statements within C/C++ programs using keyword asm 9/3/2012
  • 4. Inline Assembler Overview 4  The inline assembler lets us embed assembly-language instructions in our C and C++ source programs without extra assembly and link steps.  Inline assembly code can use any C or C++ variable or function name that is in scope.  The asm keyword invokes the inline assembler and can appear wherever a C or C++ statement is legal. It cannot appear by itself.  It must be followed by an assembly instruction, a group of instructions enclosed in braces, or, at the very least, an empty pair of braces. 9/3/2012
  • 5. Advantages of Inline Assembly 5  The inline assembler doesn't require separate assembly and link steps, it is more convenient than a separate assembler.  Inline assembly code can use any C variable or function name that is in scope, so it is easy to integrate it with our program's C code.  Because the assembly code can be mixed inline with C or C++ statements, it can do tasks that are cumbersome or impossible in C or C++. 9/3/2012
  • 6. Advantages of Inline Assembly 6 The uses of inline assembly include:  Writing functions in assembly language.  Spot-optimizing speed-critical sections of code.  Making direct hardware access for device drivers.  Writing prolog and epilog code for "naked" calls. 9/3/2012
  • 7. asm 7  The asm keyword invokes the inline assembler and can appear wherever a C or C++ statement is legal. It cannot appear by itself.  It must be followed by an assembly instruction, a group of instructions enclosed in braces, or, at the very least, an empty pair of braces.  Grammar asm-statement: asm assembly-instruction ;opt asm { assembly-instruction-list } ;opt assembly-instruction-list: assembly-instruction ;opt assembly-instruction ; assembly-instruction-list ;opt 9/3/2012
  • 8. asm 8  The following code fragment is a simple asm block enclosed in braces: asm { mov al, 2 mov dx, 0xD007 out dx, al } 9/3/2012
  • 9. asm 9  Alternatively, you can put asm in front of each assembly instruction: asm mov al, 2 asm mov dx, 0xD007 asm out dx, al  Because the asm keyword is a statement separator, you can also put assembly instructions on the same line: asm mov al, 2 asm mov dx, 0xD007 asm out dx, al 9/3/2012
  • 10. asm 10  All three examples generate the same code, but the first style (enclosing the asm block in braces) has some advantages.  The braces clearly separate assembly code from C or C++ code and avoid needless repetition of the asm keyword.  Braces can also prevent ambiguities. If you want to put a C or C++ statement on the same line as an asm block, you must enclose the block in braces. Without the braces, the compiler cannot tell where assembly code stops and C or C++ statements begin. 9/3/2012
  • 11. Using C or C++ in asm Blocks 11 Because inline assembly instructions can be mixed with C or C++ statements, they can refer to C or C++ variables by name and use many other elements of those languages. An asm block can use the following language elements:  Symbols, including labels and variable and function names  Constants, including symbolic constants and enum members  Macros and preprocessor directives  Comments (both /* */ and // )  Type names (wherever a MASM type would be legal)  typedef names, generally used with operators such as PTR and TYPE or to specify structure or union members 9/3/2012
  • 12. Jumping to Labels in Inline Assembly 12  Like an ordinary C or C++ label, a label in an asm block has scope throughout the function in which it is defined (not only in the block). Both assembly instructions and goto statements can jump to labels inside or outside the asm block.  Labels defined in asm blocks are not case sensitive; both goto statements and assembly instructions can refer to those labels without regard to case. C and C++ labels are case sensitive only when used by goto statements. Assembly instructions can jump to a C or C++ label without regard to case. 9/3/2012
  • 13. Jumping to Labels in Inline Assembly 13  Example: Void func( void ) { goto C_Dest; goto A_Dest; asm { jmp C_Dest ; jmp A_Dest ; a_dest: ; asm label } C_Dest: /* C label */ return; } int main() {} 9/3/2012
  • 14. Example 14 #include<stdio.h> JNC next #include<conio.h> lea dx,a void main() mov ah,09h { int 21h char a[5]="ODD$"; jmp er char b[5]="EVEN$"; } net: next: asm{ asm mov cl,al { mov bl,13 lea dx,b mov ah,0x01 mov ah,09h int 0x21 int 21h cmp bl,al jmp er jnz net } mov al,cl er: sub al,0x30 getch(); shr al,1 } 9/3/2012
  • 15. Calling C Functions in Inline Assembly 15  An __asm block can call C functions, including C library routines. The following example calls the printf library routine: Example: char format[]=" %s %sn"; char hello[]="hello"; char world[]="world"; void main() { asm{ mov ax,offset world push ax mov ax,offset hello push ax mov ax,offset format push ax call printf pop bx pop bx pop bx } 9/3/2012
  • 16. Calling C Functions in Inline Assembly 16  Because function arguments are passed on the stack, you simply push the needed arguments — string pointers, in the previous example — before calling the function. The arguments are pushed in reverse order, so they come off the stack in the desired order. To emulate the C statement printf( format, hello, world );  the example pushes pointers to world, hello, and format, in that order, and then calls printf. 9/3/2012
  • 17. Calling C++ Functions in Inline Assembly 17  An asm block can call only global C++ functions that are not overloaded.  If we call an overloaded global C++ function or a C++ member function, the compiler issues an error.  We can also call any functions declared with extern "C" linkage.  This allows an asm block within a C++ program to call the C library functions, because all the standard header files declare the library functions to have extern "C" linkage. 9/3/2012
  • 18. Defining asm Blocks as C Macros 18  C macros offer a convenient way to insert assembly code into your source code, but they demand extra care because a macro expands into a single logical line. To create trouble-free macros, follow these rules:  Enclose the asm block in braces.  Put the asm keyword in front of each assembly instruction.  Use old-style C comments ( /* comment */) instead of assembly- style comments ( ; comment) or single-line C comments ( // comment). 9/3/2012
  • 19. Defining asm Blocks as C Macros 19  To illustrate, the following example defines a simple macro: #define PORTIO asm { asm mov al, 2 asm mov dx, 0xD007 asm out dx, al } 9/3/2012
  • 20. Optimizing Inline Assembly 20  The presence of an asm block in a function affects optimization in several ways.  First, the compiler doesn't try to optimize the asm block itself. What you write in assembly language is exactly what you get.  Second, the presence of an asm block affects register variable storage. The compiler avoids enregistering variables across an asm block if the register's contents would be changed by the asm block.  Finally, some other function-wide optimizations will be affected by the inclusion of assembly language in a function. 9/3/2012
  • 21. 21 9/3/2012