clang及参数和生成中间代码

Clang是一个C语言、C++、Objective-C、Objective-C++语言的轻量级编译器。源代码发布于BSD协议下。Clang将支持其普通lambda表达式、返回类型的简化处理以及更好的处理constexpr关键字。 Clang是一个C++编写、基于LLVM、发布于LLVM BSD许可证下的C/C++/Objective-C/Objective-C++编译器。它与GNU C语言规范几乎完全兼容(当然,也有部分不兼容的内容,包括编译命令选项也会有点差异),并在此基础上增加了额外的语法特性,比如C函数重载(通过__attribute__((overloadable))来修饰函数),其目标(之一)就是超越GCC。

Clang 的开发背景
由于 GNU 编译器套装 (GCC) 系统庞大,而且 Apple 大量使用的 Objective-C 在 GCC 中优先级较低,同时 GCC 作为一个纯粹的编译系统,与 IDE 配合并不优秀,Apple 决定从零开始写 C family 的前端,也就是基于 LLVM 的 Clang 了。Clang 由 Apple 公司开发,源代码授权使用 BSD 的开源授权。
相比于 GCC,Clang 具有如下优点:
编译速度快:在某些平台上,Clang 的编译速度显著的快过 GCC。
占用内存小:Clang 生成的 AST 所占用的内存是 GCC 的五分之一左右。
模块化设计:Clang 采用基于库的模块化设计,易于 IDE 集成及其他用途的重用。
诊断信息可读性强:在编译过程中,Clang 创建并保留了大量详细的元数据 (metadata),有利于调试和错误报告。
设计清晰简单,容易理解,易于扩展增强。与代码基础古老的 GCC 相比,学习曲线平缓。
当前 Clang 还处在不断完善过程中,相比于 GCC, Clang 在以下方面还需要加强:
支持更多语言:GCC 除了支持 C/C++/Objective-C, 还支持 Fortran/Pascal/Java/Ada/Go 和其他语言。Clang 目前支持的语言有 C/C++/Objective-C/Objective-C++。
加强对 C++ 的支持:Clang 对 C++ 的支持依然落后于 GCC,Clang 还需要加强对 C++ 提供全方位支持。
支持更多平台:GCC 流行的时间比较长,已经被广泛使用,对各种平台的支持也很完备。Clang 目前支持的平台有 Linux/Windows/Mac OS。
命令行
zzx:clang zzx$ clang -help OVERVIEW: clang LLVM compilerUSAGE: clang [options] OPTIONS: -###Print (but do not run) the commands to run for this compilation --analyzer-output Static analyzer report output format (html|plist|plist-multi-file|plist-html|text). --analyzeRun the static analyzer -arcmt-migrate-emit-errors Emit ARC errors even if the migrator can fix them -arcmt-migrate-report-output Output path for the plist report -cl-denorms-are-zeroOpenCL only. Allow denormals to be flushed to zero. -cl-fast-relaxed-mathOpenCL only. Sets -cl-finite-math-only and -cl-unsafe-math-optimizations, and defines __FAST_RELAXED_MATH__. -cl-finite-math-onlyOpenCL only. Allow floating-point optimizations that assume arguments and results are not NaNs or +-Inf. -cl-fp32-correctly-rounded-divide-sqrt OpenCL only. Specify that single precision floating-point divide and sqrt used in the program source are correctly rounded. -cl-kernel-arg-infoOpenCL only. Generate kernel argument metadata. -cl-mad-enableOpenCL only. Allow use of less precise MAD computations in the generated binary. -cl-no-signed-zerosOpenCL only. Allow use of less precise no signed zeros computations in the generated binary. -cl-opt-disableOpenCL only. This option disables all optimizations. By default optimizations are enabled. -cl-single-precision-constant OpenCL only. Treat double precision floating-point constant as single precision constant. -cl-std=OpenCL language standard to compile for. -cl-strict-aliasingOpenCL only. This option is added for compatibility with OpenCL 1.0. -cl-unsafe-math-optimizations OpenCL only. Allow unsafe floating-point optimizations.Also implies -cl-no-signed-zeros and -cl-mad-enable. --cuda-compile-host-device Compile CUDA code for both host and device (default).Has no effect on non-CUDA compilations. --cuda-device-onlyCompile CUDA code for device only --cuda-gpu-arch= CUDA GPU architecture (e.g. sm_35).May be specified more than once. --cuda-host-onlyCompile CUDA code for host only.Has no effect on non-CUDA compilations. --cuda-noopt-device-debug Enable device-side debug info generation. Disables ptxas optimizations. --cuda-path=CUDA installation path -cxx-isystem Add directory to the C++ SYSTEM include search path -cOnly run preprocess, compile, and assemble steps -dDPrint macro definitions in -E mode in addition to normal output -dependency-dot Filename to write DOT-formatted header dependencies to -dependency-file Filename (or -) to write dependency output to -dMPrint macro definitions in -E mode instead of normal output -emit-astEmit Clang AST files for source inputs -emit-llvmUse the LLVM representation for assembler and object files -EOnly run the preprocessor -faltivecEnable AltiVec vector initializer syntax -fansi-escape-codesUse ANSI escape codes for diagnostics -fapinotes-cache-path= Specify the API notes cache path -fapinotes-modulesEnable module-based external API notes support -fapinotes-swift-version= Specify the Swift version to use when filtering API notes -fapinotesEnable external API notes support -fapple-kextUse Apple's kernel extensions ABI -fapple-pragma-packEnable Apple gcc-compatible #pragma pack handling -fapplication-extension Restrict code to those available for App Extensions -fblocksEnable the 'blocks' language feature -fborland-extensionsAccept non-standard constructs supported by the Borland compiler -fbuild-session-file= Use the last modification time of as the build session timestamp -fbuild-session-timestamp=Set the -iwithprefix/-iwithprefixbefore prefix -iquote Add directory to QUOTE include search path -isysroot Set the system root directory (usually /) -isystem-after Add directory to end of the SYSTEM include search path -isystem Add directory to SYSTEM include search path -ivfsoverlay Overlay the virtual filesystem described by file over the real file system -iwithprefixbefore Set directory to include search path with prefix -iwithprefix Set directory to SYSTEM include search path with prefix -iwithsysroot Add directory to SYSTEM include search path, absolute paths are relative to -isysroot -I Add directory to include search path -mabicallsEnable SVR4-style position-independent code (Mips only) -malign-doubleAlign doubles to two words in structs (x86 only) -mbackchainLink stack frames through backchain on System Z -mcrcAllow use of CRC instructions (ARM only) -MDWrite a depfile containing user and system headers -meabi Set EABI type, e.g. 4, 5 or gnu (default depends on triple) -mfix-cortex-a53-835769 Workaround Cortex-A53 erratum 835769 (AArch64 only) -mfp32Use 32-bit floating point registers (MIPS only) -mfp64Use 64-bit floating point registers (MIPS only) -MF Write depfile output from -MMD, -MD, -MM, or -M to -mgeneral-regs-onlyGenerate code which only uses the general purpose registers (AArch64 only) -mglobal-mergeEnable merging of globals -MGAdd missing headers to depfile -mhvx-doubleEnable Hexagon Double Vector eXtensions -mhvxEnable Hexagon Vector eXtensions -miamcuUse Intel MCU ABI --migrateRun the migrator -mincremental-linker-compatible (integrated-as) Emit an object file which can be used with an incremental linker -mios-version-min= Set iOS deployment target -mllvm Additional arguments to forward to LLVM's option processing -mlong-callsGenerate an indirect jump to enable jumps further than 64M -mmacosx-version-min= Set Mac OS X deployment target -MMDWrite a depfile containing user headers -mms-bitfieldsSet the default structure layout to be compatible with the Microsoft compiler standard -mmsaEnable MSA ASE (MIPS only) -MMLike -MMD, but also implies -E and writes to stdout by default -mno-abicallsDisable SVR4-style position-independent code (Mips only) -mno-fix-cortex-a53-835769 Don't workaround Cortex-A53 erratum 835769 (AArch64 only) -mno-global-mergeDisable merging of globals -mno-hvx-doubleDisable Hexagon Double Vector eXtensions -mno-hvxDisable Hexagon Vector eXtensions -mno-implicit-floatDon't generate implicit floating point instructions -mno-incremental-linker-compatible (integrated-as) Emit an object file which cannot be used with an incremental linker -mno-long-callsRestore the default behaviour of not generating long calls -mno-movtDisallow use of movt/movw pairs (ARM only) -mno-ms-bitfieldsDo not set the default structure layout to be compatible with the Microsoft compiler standard -mno-msaDisable MSA ASE (MIPS only) -mno-restrict-itAllow generation of deprecated IT blocks for ARMv8. It is off by default for ARMv8 Thumb mode -mno-unaligned-accessForce all memory accesses to be aligned (AArch32/AArch64 only) -mnocrcDisallow use of CRC instructions (ARM only) -module-dependency-dir Directory to dump module dependencies to -momit-leaf-frame-pointer Omit frame pointer setup for leaf functions -MPCreate phony target for each dependency (other than main file) -mqdsp6-compatEnable hexagon-qdsp6 backward compatibility -MQ Specify name of main file output to quote in depfile -mrelax-all(integrated-as) Relax all machine instructions -mrestrict-itDisallow generation of deprecated IT blocks for ARMv8. It is on by default for ARMv8 Thumb mode. -mrtdMake StdCall calling convention the default -msoft-floatUse software floating point -mstack-alignment= Set the stack alignment -mstack-probe-size= Set the stack probe size -mstackrealignForce realign the stack at entry to every function -mthread-model The thread model to use, e.g. posix, single (posix by default) -MT Specify name of main file output in depfile -munaligned-accessAllow memory accesses to be unaligned (AArch32/AArch64 only) -MVUse NMake/Jom format for the depfile -MLike -MD, but also implies -E and writes to stdout by default --no-cuda-version-check Don't error out if the detected version of the CUDA install is too low for the requested CUDA gpu architecture. --no-system-header-prefix=
Treat all #include paths starting with
as not including a system header. -nobuiltinincDisable builtin #include directories -nostdinc++Disable standard #include directories for the C++ standard library -ObjC++Treat source input files as Objective-C++ inputs -objcmt-atomic-property Make migration to 'atomic' properties -objcmt-migrate-allEnable migration to modern ObjC -objcmt-migrate-annotation Enable migration to property and method annotations -objcmt-migrate-designated-init Enable migration to infer NS_DESIGNATED_INITIALIZER for initializer methods -objcmt-migrate-instancetype Enable migration to infer instancetype for method result type -objcmt-migrate-literals Enable migration to modern ObjC literals -objcmt-migrate-ns-macros Enable migration to NS_ENUM/NS_OPTIONS macros -objcmt-migrate-property-dot-syntax Enable migration of setter/getter messages to property-dot syntax -objcmt-migrate-property Enable migration to modern ObjC property -objcmt-migrate-protocol-conformance Enable migration to add protocol conformance on classes -objcmt-migrate-readonly-property Enable migration to modern ObjC readonly property -objcmt-migrate-readwrite-property Enable migration to modern ObjC readwrite property -objcmt-migrate-subscripting Enable migration to modern ObjC subscripting -objcmt-ns-nonatomic-iosonly Enable migration to use NS_NONATOMIC_IOSONLY macro for setting property's 'atomic' attribute -objcmt-returns-innerpointer-property Enable migration to annotate property with NS_RETURNS_INNER_POINTER -objcmt-whitelist-dir-path= Only modify files with a filename contained in the provided directory path -ObjCTreat source input files as Objective-C inputs -o Write output to -pgEnable mcount instrumentation -pipeUse pipes between commands, when possible -print-file-name= Print the full library path of -print-ivar-layoutEnable Objective-C Ivar layout bitmap print trace -print-libgcc-file-name Print the library path for "libgcc.a" -print-prog-name= Print the full program path of -print-search-dirsPrint the paths used for finding libraries and programs -pthreadSupport POSIX threads in generated code -PDisable linemarker output in -E mode -Qunused-argumentsDon't emit warning for unused driver arguments -relocatable-pchWhether to build a relocatable precompiled header -rewrite-legacy-objcRewrite Legacy Objective-C source to C++ -rewrite-objcRewrite Objective-C source to C++ -Rpass-analysis= Report transformation analysis from optimization passes whose name matches the given POSIX regular expression -Rpass-missed=Report missed transformations by optimization passes whose name matches the given POSIX regular expression -Rpass=Report transformations performed by optimization passes whose name matches the given POSIX regular expression -REnable the specified remark -save-stats=Save llvm statistics. -save-statsSave llvm statistics. -save-temps=Save intermediate compilation results. -save-tempsSave intermediate compilation results -serialize-diagnostics Serialize compiler diagnostics to a file -std=Language standard to compile for -stdlib=C++ standard library to use --system-header-prefix=
Treat all #include paths starting with
as including a system header. -SOnly run preprocess and compilation steps --target=Generate code for the given target -timeTime individual commands -traditional-cppEnable some traditional CPP emulation -trigraphsProcess trigraph sequences -undefundef all system defines --verify-debug-infoVerify the binary representation of debug output -verify-pchLoad and verify that a pre-compiled header file is not stale -vShow commands to run and use verbose output -Wa,Pass the comma separated arguments into the assembler -Wl,Pass the comma separated arguments into the linker -working-directory Resolve file paths relative to the specified directory -Wp,Pass the comma separated arguments into the preprocessor -WEnable the specified warning -wSuppress all warnings -XanalyzerPassto the static analyzer -XassemblerPassto the assembler -XclangPassto the clang compiler -Xcuda-fatbinaryPassto fatbinary invocation -Xcuda-ptxasPassto the ptxas assembler -XlinkerPassto the linker -XpreprocessorPassto the preprocessor -x Treat subsequent input files as having type -zPass -zto the linker

生成中间代码
2.c代码
#include int main(){ int i=1024; void (^blk)(void) = ^{ printf("i=%d", i); }; blk(); return 0; }

【clang及参数和生成中间代码】生成中间代码
clang-emit-llvm 2.c -S -o 2.o

    推荐阅读