introduction to llvm - inf.ed.ac.uk · lld.bc .bc .o a.out libraries/objects c/c++, fortran,...
TRANSCRIPT
IntroductiontoLLVMUG3CompilingTechniques
Autumn 2017
ContactInformation
• Instructor:AaronSmith• Email:[email protected]• Office:IF1.29• OfficeHours:Anytimebyappointment(i.e.sendanemail)
Schedule• Week1
• Nov14:IntroductiontoLLVM• Nov17:HowtoWriteanLLVMPass• LAB:YourFirstLLVMPass
• Week2• Nov21:LLVMInternalsPartI• Nov24:LLVMInternalsPartII• LAB:DeadCodeElimination
• Week3• Nov28:DataflowAnalysis• Dec1:CompilerTrivia!!• LAB:WorkonFinalProject
ProjectOverview
• LLVMiswritteninC++• ButnotemplatesortrickyC++code• IfyouknowCorJavayouwillbeOKAY
• LLVMsourcesarehostedinbothSVNandGit• YoucanuseeitherbutwewillonlydiscussGit inthecourse• YouneedtosubmitthefinalprojecttoBitbucket
• ProjectwillbegradedonLinux• LLVMworksonOSXandWindowsbutwewillonlygradeonLinux• IfyouworkonotherplatformsmakesureitalsoworksonLinux!
• FinalprojectisduebyMonday,January15,2018at10am
GettingStarted
• ReadtheoriginalLLVMpaper(optional)• LLVM:ACompilationFrameworkforLifelongProgramAnalysis&Transformation,ChrisLattner andVikram Adve,CGO2004• http://dl.acm.org/citation.cfm?id=977673
• ReadtheDr DobbsarticleonLLVM(optional)• TheDesignofLLVM,ChrisLattner,2012• http://www.drdobbs.com/architecture-and-design/the-design-of-llvm/240001128
• LookatLLVM.org
WhatisLLVM?
• Anopensourceframeworkforbuildingtools• ToolsarecreatedbylinkingtogethervariouslibrariesprovidedbytheLLVMprojectandyourown
• Anextensible,stronglytypedintermediaterepresentation,i.e.LLVMIR• https://llvm.org/docs/LangRef.html
• AnindustrialstrengthC/C++optimizingcompiler• Whichyoumightknowasclang/clang++butthesearereallyjustdriversthatinvokedifferentparts(libraries)ofLLVM
HistoryofLLVM
• StartedbyChrisLattner atUIUC~2000• FirstcommercialusewasasanOpenGLJitteronOSXatApple
• EvolvedovermanyyearsintoacompleteC/C++compilerwhichuntilrecentlyrequiredpartsofGCC• llvm-gcc
• ManyusesofLLVMintheworldtoday• OSX(XCode)platformcompiler• FreeBSDplatformcompiler• GoogleAndroidNDKcompiler• ARMreferencecompiler• MicrosoftDirectXshader compiler• NVIDIACUDAcompiler
TypicalOptimizingCompiler
Frontend BackendOptimizer Linker.o
a.out
libraries/objects
LLVMOptimizingCompiler
clang llcopt
LLVMBitcode
lld.o.bc.bc
a.out
libraries/objects
C/C++,FORTRAN,Python,Ruby,JavascriptObjective-C,Haskell,Lua,…
ARM,x86,PowerPC,MIPS,SystemZ,Hexagon,WebAssembly,…
Loopunrolling,Deadcodeelimination,Commonsubexpressionelimination,…
WhatToolsDoesLLVMProvide?• Lots!clang,opt,llc,lld arejustfourofmany
WhatOptimizationsDoesLLVMSupport?• Lots!Let’sseebyrunning‘opt--help'
HowtoGettheLLVMSources
• LLVMissplitintomultipleGit repositories• Forthisclassyouwillneedtheclang andllvm git repos
• Chooseadirectorytoclonethereposinto• TheLLVMrepoisalwaysclonedfirst• OtherreposareclonedinsidetheLLVMdirectory
cddirectory-to-clone-intogit clonehttps://github.com/llvm-mirror/llvmcdllvm/toolsgit clonehttps://github.com/llvm-mirror/clang
HowtoBuildLLVM• LLVMrequiresCmake version3.4.2+togeneratethebuildfiles
• ThelatestversionofCmake isalreadyinstalledonDICE
• BydefaultCmake generatesadebugversionofthebuildfilesthatcompileLLVM
atthelowestoptimizationlevelandwithassertionsenabledanddebugsymbols
• Easiesttodebugbutslowtocompilelargeprogramsandtakesupthemostdiskspace
• Cmake supportsseveralbuildsystems
• make,XCode,VisualStudio,Ninjaandmore
• IfyouareworkingonDICEyouwillgenerateMakefiles formake
• CreateanewdirectoryoutsidetheLLVMsourcedirectoryforyourbuild
cddirectory-for-build
cmake path-to-llvm-sources
cmake --build.
Let’sTryCompilingaProgramwithLLVM
HowtoGenerateLLVMIRfromSource
• TogenerateLLVMIRuseclangwith‘-emit-llvm’option• ‘–S’generatesatextfileand‘–c’generatesabinary• clangfoo.c –emit-llvm –S• clangfoo.c –emit-llvm –c
• Toconvertabinaryfile(.bc)toatextfile(.ll)usethellvm disassembler• llvm-disfoo.bc
• Toconvertatextfile(.ll)toabinaryfile(.bc)usethellvm assembler• llvm-asfoo.ll
Let’sLookCloseratLLVMIR
• SomecharacteristicsofLLVMIR• RISC-likeinstructionset• Stronglytyped• Explicitcontrolflow• Usesavirtualregistersetwithinfinitetemporaries(%)• InStaticSingleAssignmentform• Abstractsmachinedetailssuchascallingconventionsandstackreferences
• LLVMIRreferenceisonline• https://llvm.org/docs/LangRef.html
@x = global i32 10, align 4
define i32 @main() #0 {%1 = alloca i32, align 4%2 = alloca i32, align 4store i32 0, i32* %1, align 4store i32 0, i32* %2, align 4%3 = load i32, i32* @x, align 4%4 = icmp ne i32 %3, 0br i1 %4, label %5, label %8
;<label>:5:%6 = load i32, i32* %2, align 4%7 = add nsw i32 %6, 1store i32 %7, i32* %2, align 4br label %8
;<label>:8:%9 = load i32, i32* %2, align 4ret i32 %9
}
int x = 7;int main() {
int n = 0;if (x != 0)
n++;return n;
}
Wherearethevirtualregisters?Whatarethetypes?Whereisthecontrolflow?Whatdoes‘@x’mean?Howabout‘alloca’?
Doyourememberhowtothegeneratebitcode?
OptimizingLLVMIR• PreviousLLVMIRwasnotoptimal• Weknowtheprogramreturns1bylookingatit• Let’soptimizethebitcode with‘opt’• Bydefault‘opt’doesnothing,youmustspecifyanoptimizationsuchas‘–O2’
int x = 7;int main() {
int n = 0;if (x != 0)
n++;return n;
}
definei32@main()local_unnamed_addr #0{%1=loadi32,i32*@x,align4%2=icmp nei32%1,0%.=zext i1%2toi32reti32%.}
opt–O2foo.ll –ofoo-new.bc
GeneratingMachineCodefromLLVMIR
• Use‘llc’
NextTime• HowtowriteyourownLLVMpass