Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[NPM] Add hooks for llvm passes in llvmlite #1091

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
88 changes: 88 additions & 0 deletions examples/printer-passes-npm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
try:
import faulthandler; faulthandler.enable()
except ImportError:
pass

import llvmlite.ir as ll
import llvmlite.binding as llvm


llvm.initialize()
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()

strmod = """
define i32 @foo3(i32* noalias nocapture readonly %src) {
entry:
br label %loop.header

loop.header:
%iv = phi i64 [ 0, %entry ], [ %inc, %loop.latch ]
%r1 = phi i32 [ 0, %entry ], [ %r3, %loop.latch ]
%arrayidx = getelementptr inbounds i32, i32* %src, i64 %iv
%src_element = load i32, i32* %arrayidx, align 4
%cmp = icmp eq i32 0, %src_element
br i1 %cmp, label %loop.if, label %loop.latch

loop.if:
%r2 = add i32 %r1, 1
br label %loop.latch
loop.latch:
%r3 = phi i32 [%r1, %loop.header], [%r2, %loop.if]
%inc = add nuw nsw i64 %iv, 1
%exitcond = icmp eq i64 %inc, 9
br i1 %exitcond, label %loop.end, label %loop.header
loop.end:
%r.lcssa = phi i32 [ %r3, %loop.latch ]
ret i32 %r.lcssa
}
"""

dbgmodstr = """
define void @f() !dbg !4 {
ret void, !dbg !15
}

!llvm.dbg.cu = !{!0, !8}
!llvm.module.flags = !{!13, !16}

!0 = distinct !DICompileUnit(language: DW_LANG_C99, producer: "clang version 3.4 (192092)", isOptimized: false, emissionKind: FullDebug, file: !1, enums: !2, retainedTypes: !2, globals: !2, imports: !2)
!1 = !DIFile(filename: "test1.c", directory: "/tmp")
!2 = !{}
!4 = distinct !DISubprogram(name: "f", line: 1, isLocal: false, isDefinition: true, virtualIndex: 6, isOptimized: false, unit: !0, scopeLine: 1, file: !1, scope: !5, type: !6, retainedNodes: !2)
!5 = !DIFile(filename: "test1.c", directory: "/tmp")
!6 = !DISubroutineType(types: !7)
!7 = !{null}
!8 = distinct !DICompileUnit(language: DW_LANG_C99, producer: "clang version 3.4 (192092)", isOptimized: false, emissionKind: FullDebug, file: !9, enums: !2, retainedTypes: !2, globals: !2, imports: !2)
!9 = !DIFile(filename: "test2.c", directory: "/tmp")
!11 = distinct !DISubprogram(name: "g", line: 1, isLocal: false, isDefinition: true, virtualIndex: 6, isOptimized: false, unit: !8, scopeLine: 1, file: !9, scope: !12, type: !6, retainedNodes: !2)
!12 = !DIFile(filename: "test2.c", directory: "/tmp")
!13 = !{i32 2, !"Dwarf Version", i32 4}
!14 = !DILocation(line: 1, scope: !4)
!15 = !DILocation(line: 1, scope: !11, inlinedAt: !14)
!16 = !{i32 1, !"Debug Info Version", i32 3}
"""


llmod = llvm.parse_assembly(strmod)
dbgmod = llvm.parse_assembly(dbgmodstr)

target_machine = llvm.Target.from_default_triple().create_target_machine()
pto = llvm.create_pipeline_tuning_options(speed_level=0)
pb = llvm.create_pass_builder(target_machine, pto)
pm = llvm.create_new_module_pass_manager()

pm.add_module_debug_info_pass()
pm.add_cfg_printer_pass()
pm.add_cfg_only_printer_pass()
pm.add_dom_printer_pass()
pm.add_dom_only_printer_pass()
pm.add_post_dom_printer_pass()
pm.add_post_dom_only_printer_pass()
pm.add_dom_only_printer_pass()
# pm.add_post_dom_viewer_pass()
# pm.add_dom_viewer_pass()
# pm.add_post_dom_only_viewer_pass()

pm.run(llmod, pb)
pm.run(dbgmod, pb)
286 changes: 286 additions & 0 deletions ffi/PASSREGISTRY.def
Original file line number Diff line number Diff line change
@@ -0,0 +1,286 @@
// Use this file to register/de-register llvm optimization passes in llvmlite

#ifndef MODULE_PASS
#define MODULE_PASS(NAME)
#endif
MODULE_PASS(VerifierPass)
MODULE_PASS(ConstantMergePass)
MODULE_PASS(DeadArgumentEliminationPass)
MODULE_PASS(CallGraphDOTPrinterPass)
MODULE_PASS(AlwaysInlinerPass)
MODULE_PASS(ReversePostOrderFunctionAttrsPass)
MODULE_PASS(GlobalDCEPass)
MODULE_PASS(GlobalOptPass)
MODULE_PASS(IPSCCPPass)
MODULE_PASS(InternalizePass)
MODULE_PASS(MergeFunctionsPass)
MODULE_PASS(PartialInlinerPass)
MODULE_PASS(StripSymbolsPass)
MODULE_PASS(StripDeadDebugInfoPass)
MODULE_PASS(StripDeadPrototypesPass)
MODULE_PASS(StripDebugDeclarePass)
MODULE_PASS(StripNonDebugSymbolsPass)
#undef MODULE_PASS

#ifndef FUNCTION_PASS
#define FUNCTION_PASS(NAME)
#endif
FUNCTION_PASS(AAEvaluator)
FUNCTION_PASS(SimplifyCFGPass)
FUNCTION_PASS(LoopUnrollPass)
FUNCTION_PASS(InstCombinePass)
FUNCTION_PASS(JumpThreadingPass)
FUNCTION_PASS(CFGPrinterPass)
FUNCTION_PASS(CFGOnlyPrinterPass)
FUNCTION_PASS(DomPrinter)
FUNCTION_PASS(DomOnlyPrinter)
FUNCTION_PASS(PostDomPrinter)
FUNCTION_PASS(PostDomOnlyPrinter)
FUNCTION_PASS(DomViewer)
FUNCTION_PASS(DomOnlyViewer)
FUNCTION_PASS(PostDomViewer)
FUNCTION_PASS(PostDomOnlyViewer)
FUNCTION_PASS(LintPass)
FUNCTION_PASS(ADCEPass)
FUNCTION_PASS(BreakCriticalEdgesPass)
FUNCTION_PASS(DSEPass)
FUNCTION_PASS(DCEPass)
FUNCTION_PASS(AggressiveInstCombinePass)
FUNCTION_PASS(LCSSAPass)
FUNCTION_PASS(NewGVNPass)
FUNCTION_PASS(LoopSimplifyPass)
FUNCTION_PASS(SCCPPass)
FUNCTION_PASS(LowerAtomicPass)
FUNCTION_PASS(LowerInvokePass)
FUNCTION_PASS(LowerSwitchPass)
FUNCTION_PASS(MemCpyOptPass)
FUNCTION_PASS(UnifyFunctionExitNodesPass)
FUNCTION_PASS(ReassociatePass)
FUNCTION_PASS(RegToMemPass)
// FIXME: FUNCTION_PASS(SROAPass)
FUNCTION_PASS(SinkingPass)
FUNCTION_PASS(TailCallElimPass)
FUNCTION_PASS(InstructionNamerPass)
#undef FUNCTION_PASS

// TODO: Add them if needed
// FUNCTION_PASS_WITH_PARAMS(SimplifyCFGPass)
// FUNCTION_PASS_WITH_PARAMS(LoopUnrollPass)

#ifndef LOOP_PASS
#define LOOP_PASS(NAME)
#endif
LOOP_PASS(LoopRotatePass)
LOOP_PASS(LoopDeletionPass)
LOOP_PASS(LoopStrengthReducePass)
#undef LOOP_PASS

#ifndef CGSCC_PASS
#define CGSCC_PASS(NAME)
#endif
CGSCC_PASS(ArgumentPromotionPass)
CGSCC_PASS(PostOrderFunctionAttrsPass)
#undef CGSCC_PASS

// TODO: Add them if needed
/**
MODULE_PASS("attributor", AttributorPass())
MODULE_PASS("annotation2metadata", Annotation2MetadataPass())
MODULE_PASS("openmp-opt", OpenMPOptPass())
MODULE_PASS("called-value-propagation", CalledValuePropagationPass())
MODULE_PASS("canonicalize-aliases", CanonicalizeAliasesPass())
MODULE_PASS("cg-profile", CGProfilePass())
MODULE_PASS("check-debugify", NewPMCheckDebugifyPass())
MODULE_PASS("coro-early", CoroEarlyPass())
MODULE_PASS("coro-cleanup", CoroCleanupPass())
MODULE_PASS("cross-dso-cfi", CrossDSOCFIPass())
MODULE_PASS("debugify", NewPMDebugifyPass())
MODULE_PASS("dot-callgraph", CallGraphDOTPrinterPass())
MODULE_PASS("elim-avail-extern", EliminateAvailableExternallyPass())
MODULE_PASS("extract-blocks", BlockExtractorPass())
MODULE_PASS("forceattrs", ForceFunctionAttrsPass())
MODULE_PASS("function-import", FunctionImportPass())
MODULE_PASS("function-specialization", FunctionSpecializationPass())
MODULE_PASS("globalsplit", GlobalSplitPass())
MODULE_PASS("hotcoldsplit", HotColdSplittingPass())
MODULE_PASS("inferattrs", InferFunctionAttrsPass())
MODULE_PASS("inliner-wrapper", ModuleInlinerWrapperPass())
MODULE_PASS("inliner-ml-advisor-release", ModuleInlinerWrapperPass(getInlineParams(), true, {}, InliningAdvisorMode::Release, 0))
MODULE_PASS("print<inline-advisor>", InlineAdvisorAnalysisPrinterPass(dbgs()))
MODULE_PASS("inliner-wrapper-no-mandatory-first", ModuleInlinerWrapperPass(getInlineParams(),false))
MODULE_PASS("insert-gcov-profiling", GCOVProfilerPass())
MODULE_PASS("instrorderfile", InstrOrderFilePass())
MODULE_PASS("instrprof", InstrProfiling())
MODULE_PASS("invalidate<all>", InvalidateAllAnalysesPass())
MODULE_PASS("iroutliner", IROutlinerPass())
MODULE_PASS("print-ir-similarity", IRSimilarityAnalysisPrinterPass(dbgs()))
MODULE_PASS("lower-global-dtors", LowerGlobalDtorsPass())
MODULE_PASS("lowertypetests", LowerTypeTestsPass())
MODULE_PASS("metarenamer", MetaRenamerPass())
MODULE_PASS("name-anon-globals", NameAnonGlobalPass())
MODULE_PASS("no-op-module", NoOpModulePass())
MODULE_PASS("objc-arc-apelim", ObjCARCAPElimPass())
MODULE_PASS("pgo-icall-prom", PGOIndirectCallPromotion())
MODULE_PASS("pgo-instr-gen", PGOInstrumentationGen())
MODULE_PASS("pgo-instr-use", PGOInstrumentationUse())
MODULE_PASS("print-profile-summary", ProfileSummaryPrinterPass(dbgs()))
MODULE_PASS("print-callgraph", CallGraphPrinterPass(dbgs()))
MODULE_PASS("print", PrintModulePass(dbgs()))
MODULE_PASS("print-lcg", LazyCallGraphPrinterPass(dbgs()))
MODULE_PASS("print-lcg-dot", LazyCallGraphDOTPrinterPass(dbgs()))
MODULE_PASS("print-must-be-executed-contexts", MustBeExecutedContextPrinterPass(dbgs()))
MODULE_PASS("print-stack-safety", StackSafetyGlobalPrinterPass(dbgs()))
MODULE_PASS("print<module-debuginfo>", ModuleDebugInfoPrinterPass(dbgs()))
MODULE_PASS("recompute-globalsaa", RecomputeGlobalsAAPass())
MODULE_PASS("rel-lookup-table-converter", RelLookupTableConverterPass())
MODULE_PASS("rewrite-statepoints-for-gc", RewriteStatepointsForGC())
MODULE_PASS("rewrite-symbols", RewriteSymbolPass())
MODULE_PASS("sample-profile", SampleProfileLoaderPass())
MODULE_PASS("scc-oz-module-inliner",buildInlinerPipeline(OptimizationLevel::Oz, ThinOrFullLTOPhase::None))
MODULE_PASS("pseudo-probe", SampleProfileProbePass(TM))
MODULE_PASS("strip-nonlinetable-debuginfo", StripNonLineTableDebugInfoPass())
MODULE_PASS("synthetic-counts-propagation", SyntheticCountsPropagation())
MODULE_PASS("trigger-crash", TriggerCrashPass())
MODULE_PASS("verify", VerifierPass())
MODULE_PASS("view-callgraph", CallGraphViewerPass())
MODULE_PASS("wholeprogramdevirt", WholeProgramDevirtPass())
MODULE_PASS("dfsan", DataFlowSanitizerPass())
MODULE_PASS("msan-module", ModuleMemorySanitizerPass({}))
MODULE_PASS("module-inline", ModuleInlinerPass())
MODULE_PASS("tsan-module", ModuleThreadSanitizerPass())
MODULE_PASS("sancov-module", ModuleSanitizerCoveragePass())
MODULE_PASS("memprof-module", ModuleMemProfilerPass())
MODULE_PASS("poison-checking", PoisonCheckingPass())
MODULE_PASS("pseudo-probe-update", PseudoProbeUpdatePass())

CGSCC_PASS("argpromotion", ArgumentPromotionPass())
CGSCC_PASS("invalidate<all>", InvalidateAllAnalysesPass())
CGSCC_PASS("attributor-cgscc", AttributorCGSCCPass())
CGSCC_PASS("openmp-opt-cgscc", OpenMPOptCGSCCPass())
CGSCC_PASS("no-op-cgscc", NoOpCGSCCPass())

FUNCTION_PASS("add-discriminators", AddDiscriminatorsPass())
FUNCTION_PASS("assume-builder", AssumeBuilderPass())
FUNCTION_PASS("assume-simplify", AssumeSimplifyPass())
FUNCTION_PASS("alignment-from-assumptions", AlignmentFromAssumptionsPass())
FUNCTION_PASS("annotation-remarks", AnnotationRemarksPass())
FUNCTION_PASS("bdce", BDCEPass())
FUNCTION_PASS("bounds-checking", BoundsCheckingPass())
FUNCTION_PASS("callsite-splitting", CallSiteSplittingPass())
FUNCTION_PASS("consthoist", ConstantHoistingPass())
FUNCTION_PASS("constraint-elimination", ConstraintEliminationPass())
FUNCTION_PASS("chr", ControlHeightReductionPass())
FUNCTION_PASS("coro-elide", CoroElidePass())
FUNCTION_PASS("correlated-propagation", CorrelatedValuePropagationPass())
FUNCTION_PASS("dfa-jump-threading", DFAJumpThreadingPass())
FUNCTION_PASS("div-rem-pairs", DivRemPairsPass())
FUNCTION_PASS("fix-irreducible", FixIrreduciblePass())
FUNCTION_PASS("flattencfg", FlattenCFGPass())
FUNCTION_PASS("make-guards-explicit", MakeGuardsExplicitPass())
FUNCTION_PASS("gvn-hoist", GVNHoistPass())
FUNCTION_PASS("gvn-sink", GVNSinkPass())
FUNCTION_PASS("helloworld", HelloWorldPass())
FUNCTION_PASS("infer-address-spaces", InferAddressSpacesPass())
FUNCTION_PASS("instcombine", InstCombinePass())
FUNCTION_PASS("instcount", InstCountPass())
FUNCTION_PASS("instsimplify", InstSimplifyPass())
FUNCTION_PASS("invalidate<all>", InvalidateAllAnalysesPass())
FUNCTION_PASS("irce", IRCEPass())
FUNCTION_PASS("float2int", Float2IntPass())
FUNCTION_PASS("no-op-function", NoOpFunctionPass())
FUNCTION_PASS("libcalls-shrinkwrap", LibCallsShrinkWrapPass())
FUNCTION_PASS("inject-tli-mappings", InjectTLIMappings())
FUNCTION_PASS("lower-expect", LowerExpectIntrinsicPass())
FUNCTION_PASS("lower-guard-intrinsic", LowerGuardIntrinsicPass())
FUNCTION_PASS("lower-constant-intrinsics", LowerConstantIntrinsicsPass())
FUNCTION_PASS("lower-widenable-condition", LowerWidenableConditionPass())
FUNCTION_PASS("guard-widening", GuardWideningPass())
FUNCTION_PASS("load-store-vectorizer", LoadStoreVectorizerPass())
FUNCTION_PASS("loop-sink", LoopSinkPass())
FUNCTION_PASS("mem2reg", PromotePass())
FUNCTION_PASS("mergeicmps", MergeICmpsPass())
FUNCTION_PASS("nary-reassociate", NaryReassociatePass())
FUNCTION_PASS("jump-threading", JumpThreadingPass())
FUNCTION_PASS("partially-inline-libcalls", PartiallyInlineLibCallsPass())
FUNCTION_PASS("loop-data-prefetch", LoopDataPrefetchPass())
FUNCTION_PASS("loop-load-elim", LoopLoadEliminationPass())
FUNCTION_PASS("loop-fusion", LoopFusePass())
FUNCTION_PASS("loop-distribute", LoopDistributePass())
FUNCTION_PASS("loop-versioning", LoopVersioningPass())
FUNCTION_PASS("objc-arc", ObjCARCOptPass())
FUNCTION_PASS("objc-arc-contract", ObjCARCContractPass())
FUNCTION_PASS("objc-arc-expand", ObjCARCExpandPass())
FUNCTION_PASS("pgo-memop-opt", PGOMemOPSizeOpt())
FUNCTION_PASS("print", PrintFunctionPass(dbgs()))
FUNCTION_PASS("print<assumptions>", AssumptionPrinterPass(dbgs()))
FUNCTION_PASS("print<block-freq>", BlockFrequencyPrinterPass(dbgs()))
FUNCTION_PASS("print<branch-prob>", BranchProbabilityPrinterPass(dbgs()))
FUNCTION_PASS("print<cost-model>", CostModelPrinterPass(dbgs()))
FUNCTION_PASS("print<cycles>", CycleInfoPrinterPass(dbgs()))
FUNCTION_PASS("print<da>", DependenceAnalysisPrinterPass(dbgs()))
FUNCTION_PASS("print<divergence>", DivergenceAnalysisPrinterPass(dbgs()))
FUNCTION_PASS("print<domtree>", DominatorTreePrinterPass(dbgs()))
FUNCTION_PASS("print<postdomtree>", PostDominatorTreePrinterPass(dbgs()))
FUNCTION_PASS("print<delinearization>", DelinearizationPrinterPass(dbgs()))
FUNCTION_PASS("print<demanded-bits>", DemandedBitsPrinterPass(dbgs()))
FUNCTION_PASS("print<domfrontier>", DominanceFrontierPrinterPass(dbgs()))
FUNCTION_PASS("print<func-properties>", FunctionPropertiesPrinterPass(dbgs()))
FUNCTION_PASS("print<inline-cost>", InlineCostAnnotationPrinterPass(dbgs()))
FUNCTION_PASS("print<inliner-size-estimator>",InlineSizeEstimatorAnalysisPrinterPass(dbgs()))
FUNCTION_PASS("print<loops>", LoopPrinterPass(dbgs()))
FUNCTION_PASS("print<memoryssa>", MemorySSAPrinterPass(dbgs()))
FUNCTION_PASS("print<memoryssa-walker>", MemorySSAWalkerPrinterPass(dbgs()))
FUNCTION_PASS("print<phi-values>", PhiValuesPrinterPass(dbgs()))
FUNCTION_PASS("print<regions>", RegionInfoPrinterPass(dbgs()))
FUNCTION_PASS("print<scalar-evolution>", ScalarEvolutionPrinterPass(dbgs()))
FUNCTION_PASS("print<stack-safety-local>", StackSafetyPrinterPass(dbgs()))
FUNCTION_PASS("print-alias-sets", AliasSetsPrinterPass(dbgs()))
FUNCTION_PASS("print-predicateinfo", PredicateInfoPrinterPass(dbgs()))
FUNCTION_PASS("print-mustexecute", MustExecutePrinterPass(dbgs()))
FUNCTION_PASS("print-memderefs", MemDerefPrinterPass(dbgs()))
FUNCTION_PASS("redundant-dbg-inst-elim", RedundantDbgInstEliminationPass())
FUNCTION_PASS("scalarize-masked-mem-intrin", ScalarizeMaskedMemIntrinPass())
FUNCTION_PASS("scalarizer", ScalarizerPass())
FUNCTION_PASS("separate-const-offset-from-gep", SeparateConstOffsetFromGEPPass())
FUNCTION_PASS("slp-vectorizer", SLPVectorizerPass())
FUNCTION_PASS("slsr", StraightLineStrengthReducePass())
FUNCTION_PASS("speculative-execution", SpeculativeExecutionPass())
FUNCTION_PASS("strip-gc-relocates", StripGCRelocates())
FUNCTION_PASS("structurizecfg", StructurizeCFGPass())
FUNCTION_PASS("unify-loop-exits", UnifyLoopExitsPass())
FUNCTION_PASS("vector-combine", VectorCombinePass())
FUNCTION_PASS("verify", VerifierPass())
FUNCTION_PASS("verify<domtree>", DominatorTreeVerifierPass())
FUNCTION_PASS("verify<loops>", LoopVerifierPass())
FUNCTION_PASS("verify<memoryssa>", MemorySSAVerifierPass())
FUNCTION_PASS("verify<regions>", RegionInfoVerifierPass())
FUNCTION_PASS("verify<safepoint-ir>", SafepointIRVerifierPass())
FUNCTION_PASS("verify<scalar-evolution>", ScalarEvolutionVerifierPass())
FUNCTION_PASS("view-cfg", CFGViewerPass())
FUNCTION_PASS("view-cfg-only", CFGOnlyViewerPass())
FUNCTION_PASS("tlshoist", TLSVariableHoistPass())
FUNCTION_PASS("transform-warning", WarnMissedTransformationsPass())
FUNCTION_PASS("tsan", ThreadSanitizerPass())
FUNCTION_PASS("memprof", MemProfilerPass())

LOOP_PASS("canon-freeze", CanonicalizeFreezeInLoopsPass())
LOOP_PASS("dot-ddg", DDGDotPrinterPass())
LOOP_PASS("invalidate<all>", InvalidateAllAnalysesPass())
LOOP_PASS("loop-idiom", LoopIdiomRecognizePass())
LOOP_PASS("loop-instsimplify", LoopInstSimplifyPass())
LOOP_PASS("no-op-loop", NoOpLoopPass())
LOOP_PASS("print", PrintLoopPass(dbgs()))
LOOP_PASS("loop-simplifycfg", LoopSimplifyCFGPass())
LOOP_PASS("indvars", IndVarSimplifyPass())
LOOP_PASS("loop-unroll-full", LoopFullUnrollPass())
LOOP_PASS("print-access-info", LoopAccessInfoPrinterPass(dbgs()))
LOOP_PASS("print<ddg>", DDGAnalysisPrinterPass(dbgs()))
LOOP_PASS("print<iv-users>", IVUsersPrinterPass(dbgs()))
LOOP_PASS("print<loopnest>", LoopNestPrinterPass(dbgs()))
LOOP_PASS("print<loop-cache-cost>", LoopCachePrinterPass(dbgs()))
LOOP_PASS("loop-predication", LoopPredicationPass())
LOOP_PASS("guard-widening", GuardWideningPass())
LOOP_PASS("loop-bound-split", LoopBoundSplitPass())
LOOP_PASS("loop-reroll", LoopRerollPass())
LOOP_PASS("loop-versioning-licm", LoopVersioningLICMPass())
**/
Loading