Esempio n. 1
0
        public Generator(OptimizationMode optimized)
        {
            _optimized = optimized;

            switch (optimized)
            {
                case OptimizationMode.NoOptimization:
                    _beginEndStructName = "ByteArrayPart";
                    break;
                case OptimizationMode.SingleStatic:
                    _beginEndStructName = "BeginEnd";
                    break;
                case OptimizationMode.IndexedArray:
                    _beginEndStructName = "BeginEndIndex";
                    break;
            }
        }
Esempio n. 2
0
        private ArgumentSyntax ParseCommandLine(string[] args)
        {
            IReadOnlyList <string> inputFiles     = Array.Empty <string>();
            IReadOnlyList <string> referenceFiles = Array.Empty <string>();

            bool optimize = false;

            bool           waitForDebugger = false;
            AssemblyName   name            = typeof(Program).GetTypeInfo().Assembly.GetName();
            ArgumentSyntax argSyntax       = ArgumentSyntax.Parse(args, syntax =>
            {
                syntax.ApplicationName = name.Name.ToString();

                // HandleHelp writes to error, fails fast with crash dialog and lacks custom formatting.
                syntax.HandleHelp   = false;
                syntax.HandleErrors = true;

                syntax.DefineOption("h|help", ref _help, "Help message for ILC");
                syntax.DefineOptionList("r|reference", ref referenceFiles, "Reference file(s) for compilation");
                syntax.DefineOption("o|out", ref _outputFilePath, "Output file path");
                syntax.DefineOption("O", ref optimize, "Enable optimizations");
                syntax.DefineOption("g", ref _enableDebugInfo, "Emit debugging information");
                syntax.DefineOption("cpp", ref _isCppCodegen, "Compile for C++ code-generation");
                syntax.DefineOption("wasm", ref _isWasmCodegen, "Compile for WebAssembly code-generation");
                syntax.DefineOption("dgmllog", ref _dgmlLogFileName, "Save result of dependency analysis as DGML");
                syntax.DefineOption("fulllog", ref _generateFullDgmlLog, "Save detailed log of dependency analysis");
                syntax.DefineOption("scandgmllog", ref _scanDgmlLogFileName, "Save result of scanner dependency analysis as DGML");
                syntax.DefineOption("scanfulllog", ref _generateFullScanDgmlLog, "Save detailed log of scanner dependency analysis");
                syntax.DefineOption("verbose", ref _isVerbose, "Enable verbose logging");
                syntax.DefineOption("systemmodule", ref _systemModuleName, "System module name (default: System.Private.CoreLib)");
                syntax.DefineOption("multifile", ref _multiFile, "Compile only input files (do not compile referenced assemblies)");
                syntax.DefineOption("waitfordebugger", ref waitForDebugger, "Pause to give opportunity to attach debugger");
                syntax.DefineOption("usesharedgenerics", ref _useSharedGenerics, "Enable shared generics");
                syntax.DefineOptionList("codegenopt", ref _codegenOptions, "Define a codegen option");
                syntax.DefineOptionList("rdxml", ref _rdXmlFilePaths, "RD.XML file(s) for compilation");
                syntax.DefineOption("map", ref _mapFileName, "Generate a map file");
                syntax.DefineOption("metadatalog", ref _metadataLogFileName, "Generate a metadata log file");
                syntax.DefineOption("scan", ref _useScanner, "Use IL scanner to generate optimized code (implied by -O)");
                syntax.DefineOption("noscan", ref _noScanner, "Do not use IL scanner to generate optimized code");
                syntax.DefineOption("ildump", ref _ilDump, "Dump IL assembly listing for compiler-generated IL");

                syntax.DefineOption("targetarch", ref _targetArchitectureStr, "Target architecture for cross compilation");
                syntax.DefineOption("targetos", ref _targetOSStr, "Target OS for cross compilation");

                syntax.DefineOption("singlemethodtypename", ref _singleMethodTypeName, "Single method compilation: name of the owning type");
                syntax.DefineOption("singlemethodname", ref _singleMethodName, "Single method compilation: name of the method");
                syntax.DefineOptionList("singlemethodgenericarg", ref _singleMethodGenericArgs, "Single method compilation: generic arguments to the method");

                syntax.DefineParameterList("in", ref inputFiles, "Input file(s) to compile");
            });

            if (waitForDebugger)
            {
                Console.WriteLine("Waiting for debugger to attach. Press ENTER to continue");
                Console.ReadLine();
            }

            _optimizationMode = optimize ? OptimizationMode.Blended : OptimizationMode.None;

            foreach (var input in inputFiles)
            {
                Helpers.AppendExpandedPaths(_inputFilePaths, input, true);
            }

            foreach (var reference in referenceFiles)
            {
                Helpers.AppendExpandedPaths(_referenceFilePaths, reference, false);
            }

            return(argSyntax);
        }
 public CompilationBuilder UseOptimizationMode(OptimizationMode mode)
 {
     _optimizationMode = mode;
     return(this);
 }
Esempio n. 4
0
        private void ProcessCommandLine(string[] args)
        {
            PerfEventSource.StartStopEvents.CommandLineProcessingStart();
            _commandLineOptions = new CommandLineOptions(args);
            PerfEventSource.StartStopEvents.CommandLineProcessingStop();

            if (_commandLineOptions.Help)
            {
                return;
            }

            if (_commandLineOptions.WaitForDebugger)
            {
                Console.WriteLine(SR.WaitingForDebuggerAttach);
                Console.ReadLine();
            }

            if (_commandLineOptions.CompileBubbleGenerics)
            {
                if (!_commandLineOptions.CompositeOrInputBubble)
                {
                    Console.WriteLine(SR.WarningIgnoringBubbleGenerics);
                    _commandLineOptions.CompileBubbleGenerics = false;
                }
            }

            _optimizationMode = OptimizationMode.None;
            if (_commandLineOptions.OptimizeDisabled)
            {
                if (_commandLineOptions.Optimize || _commandLineOptions.OptimizeSpace || _commandLineOptions.OptimizeTime)
                {
                    Console.WriteLine(SR.WarningOverridingOptimize);
                }
            }
            else if (_commandLineOptions.OptimizeSpace)
            {
                if (_commandLineOptions.OptimizeTime)
                {
                    Console.WriteLine(SR.WarningOverridingOptimizeSpace);
                }
                _optimizationMode = OptimizationMode.PreferSize;
            }
            else if (_commandLineOptions.OptimizeTime)
            {
                _optimizationMode = OptimizationMode.PreferSpeed;
            }
            else if (_commandLineOptions.Optimize)
            {
                _optimizationMode = OptimizationMode.Blended;
            }

            foreach (var input in _commandLineOptions.InputFilePaths)
            {
                Helpers.AppendExpandedPaths(_inputFilePaths, input, true);
            }

            foreach (var input in _commandLineOptions.UnrootedInputFilePaths)
            {
                Helpers.AppendExpandedPaths(_unrootedInputFilePaths, input, true);
            }

            foreach (var reference in _commandLineOptions.ReferenceFilePaths)
            {
                Helpers.AppendExpandedPaths(_referenceFilePaths, reference, false);
            }


            int alignment = _commandLineOptions.CustomPESectionAlignment;

            if (alignment != 0)
            {
                // Must be a power of two and >= 4096
                if (alignment < 4096 || (alignment & (alignment - 1)) != 0)
                {
                    throw new CommandLineException(SR.InvalidCustomPESectionAlignment);
                }
            }

            if (_commandLineOptions.MethodLayout != null)
            {
                _methodLayout = _commandLineOptions.MethodLayout.ToLowerInvariant() switch
                {
                    "defaultsort" => ReadyToRunMethodLayoutAlgorithm.DefaultSort,
                    "exclusiveweight" => ReadyToRunMethodLayoutAlgorithm.ExclusiveWeight,
                    "hotcold" => ReadyToRunMethodLayoutAlgorithm.HotCold,
                    "hotwarmcold" => ReadyToRunMethodLayoutAlgorithm.HotWarmCold,
                    "callfrequency" => ReadyToRunMethodLayoutAlgorithm.CallFrequency,
                    _ => throw new CommandLineException(SR.InvalidMethodLayout)
                };
            }

            if (_commandLineOptions.FileLayout != null)
            {
                _fileLayout = _commandLineOptions.FileLayout.ToLowerInvariant() switch
                {
                    "defaultsort" => ReadyToRunFileLayoutAlgorithm.DefaultSort,
                    "methodorder" => ReadyToRunFileLayoutAlgorithm.MethodOrder,
                    _ => throw new CommandLineException(SR.InvalidFileLayout)
                };
            }
        }
Esempio n. 5
0
        private void RunSingleCompilation(Dictionary <string, string> inFilePaths, InstructionSetSupport instructionSetSupport, string compositeRootPath, Dictionary <string, string> unrootedInputFilePaths, HashSet <ModuleDesc> versionBubbleModulesHash, CompilerTypeSystemContext typeSystemContext)
        {
            //
            // Initialize output filename
            //
            var outFile = _commandLineOptions.OutNearInput ? inFilePaths.First().Value.Replace(".dll", ".ni.dll") : _commandLineOptions.OutputFilePath;

            using (PerfEventSource.StartStopEvents.CompilationEvents())
            {
                ICompilation compilation;
                using (PerfEventSource.StartStopEvents.LoadingEvents())
                {
                    List <EcmaModule> inputModules   = new List <EcmaModule>();
                    List <EcmaModule> rootingModules = new List <EcmaModule>();
                    Guid?inputModuleMvid             = null;

                    foreach (var inputFile in inFilePaths)
                    {
                        EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value);
                        inputModules.Add(module);
                        rootingModules.Add(module);
                        versionBubbleModulesHash.Add(module);

                        if (!_commandLineOptions.Composite && !inputModuleMvid.HasValue)
                        {
                            inputModuleMvid = module.MetadataReader.GetGuid(module.MetadataReader.GetModuleDefinition().Mvid);
                        }

                        if (!_commandLineOptions.CompositeOrInputBubble)
                        {
                            break;
                        }
                    }

                    foreach (var unrootedInputFile in unrootedInputFilePaths)
                    {
                        EcmaModule module = typeSystemContext.GetModuleFromPath(unrootedInputFile.Value);
                        inputModules.Add(module);
                        versionBubbleModulesHash.Add(module);
                    }

                    //
                    // Initialize compilation group and compilation roots
                    //

                    // Single method mode?
                    MethodDesc singleMethod = CheckAndParseSingleMethodModeArguments(typeSystemContext);

                    var logger = new Logger(Console.Out, _commandLineOptions.Verbose);

                    List <string> mibcFiles = new List <string>();
                    foreach (var file in _commandLineOptions.MibcFilePaths)
                    {
                        mibcFiles.Add(file);
                    }

                    List <ModuleDesc> versionBubbleModules = new List <ModuleDesc>(versionBubbleModulesHash);

                    if (!_commandLineOptions.Composite && inputModules.Count != 1)
                    {
                        throw new Exception(string.Format(SR.ErrorMultipleInputFilesCompositeModeOnly, string.Join("; ", inputModules)));
                    }

                    ReadyToRunCompilationModuleGroupBase compilationGroup;
                    List <ICompilationRootProvider>      compilationRoots = new List <ICompilationRootProvider>();
                    if (singleMethod != null)
                    {
                        // Compiling just a single method
                        compilationGroup = new SingleMethodCompilationModuleGroup(
                            typeSystemContext,
                            _commandLineOptions.Composite,
                            _commandLineOptions.InputBubble,
                            inputModules,
                            versionBubbleModules,
                            _commandLineOptions.CompileBubbleGenerics,
                            singleMethod);
                        compilationRoots.Add(new SingleMethodRootProvider(singleMethod));
                    }
                    else if (_commandLineOptions.CompileNoMethods)
                    {
                        compilationGroup = new NoMethodsCompilationModuleGroup(
                            typeSystemContext,
                            _commandLineOptions.Composite,
                            _commandLineOptions.InputBubble,
                            inputModules,
                            versionBubbleModules,
                            _commandLineOptions.CompileBubbleGenerics);
                    }
                    else
                    {
                        // Single assembly compilation.
                        compilationGroup = new ReadyToRunSingleAssemblyCompilationModuleGroup(
                            typeSystemContext,
                            _commandLineOptions.Composite,
                            _commandLineOptions.InputBubble,
                            inputModules,
                            versionBubbleModules,
                            _commandLineOptions.CompileBubbleGenerics);
                    }

                    // Load any profiles generated by method call chain analyis
                    CallChainProfile jsonProfile = null;

                    if (!string.IsNullOrEmpty(_commandLineOptions.CallChainProfileFile))
                    {
                        jsonProfile = new CallChainProfile(_commandLineOptions.CallChainProfileFile, typeSystemContext, _referenceableModules);
                    }

                    // Examine profile guided information as appropriate
                    ProfileDataManager profileDataManager =
                        new ProfileDataManager(logger,
                                               _referenceableModules,
                                               inputModules,
                                               versionBubbleModules,
                                               _commandLineOptions.CompileBubbleGenerics ? inputModules[0] : null,
                                               mibcFiles,
                                               jsonProfile,
                                               typeSystemContext,
                                               compilationGroup,
                                               _commandLineOptions.EmbedPgoData);

                    if (_commandLineOptions.Partial)
                    {
                        compilationGroup.ApplyProfilerGuidedCompilationRestriction(profileDataManager);
                    }
                    else
                    {
                        compilationGroup.ApplyProfilerGuidedCompilationRestriction(null);
                    }

                    if ((singleMethod == null) && !_commandLineOptions.CompileNoMethods)
                    {
                        // For normal compilations add compilation roots.
                        foreach (var module in rootingModules)
                        {
                            compilationRoots.Add(new ReadyToRunRootProvider(
                                                     module,
                                                     profileDataManager,
                                                     profileDrivenPartialNGen: _commandLineOptions.Partial));

                            if (!_commandLineOptions.CompositeOrInputBubble)
                            {
                                break;
                            }
                        }
                    }
                    // In single-file compilation mode, use the assembly's DebuggableAttribute to determine whether to optimize
                    // or produce debuggable code if an explicit optimization level was not specified on the command line
                    OptimizationMode optimizationMode = _optimizationMode;
                    if (optimizationMode == OptimizationMode.None && !_commandLineOptions.OptimizeDisabled && !_commandLineOptions.Composite)
                    {
                        System.Diagnostics.Debug.Assert(inputModules.Count == 1);
                        optimizationMode = ((EcmaAssembly)inputModules[0].Assembly).HasOptimizationsDisabled() ? OptimizationMode.None : OptimizationMode.Blended;
                    }

                    //
                    // Compile
                    //

                    ReadyToRunCodegenCompilationBuilder builder = new ReadyToRunCodegenCompilationBuilder(
                        typeSystemContext, compilationGroup, _allInputFilePaths.Values, compositeRootPath);
                    string compilationUnitPrefix = "";
                    builder.UseCompilationUnitPrefix(compilationUnitPrefix);

                    ILProvider ilProvider = new ReadyToRunILProvider();

                    DependencyTrackingLevel trackingLevel = _commandLineOptions.DgmlLogFileName == null ?
                                                            DependencyTrackingLevel.None : (_commandLineOptions.GenerateFullDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First);

                    builder
                    .UseIbcTuning(_commandLineOptions.Tuning)
                    .UseResilience(_commandLineOptions.Resilient)
                    .UseMapFile(_commandLineOptions.Map)
                    .UseMapCsvFile(_commandLineOptions.MapCsv)
                    .UsePdbFile(_commandLineOptions.Pdb, _commandLineOptions.PdbPath)
                    .UsePerfMapFile(_commandLineOptions.PerfMap, _commandLineOptions.PerfMapPath, inputModuleMvid)
                    .UseProfileFile(jsonProfile != null)
                    .UseParallelism(_commandLineOptions.Parallelism)
                    .UseProfileData(profileDataManager)
                    .FileLayoutAlgorithms(_methodLayout, _fileLayout)
                    .UseJitPath(_commandLineOptions.JitPath)
                    .UseInstructionSetSupport(instructionSetSupport)
                    .UseCustomPESectionAlignment(_commandLineOptions.CustomPESectionAlignment)
                    .UseVerifyTypeAndFieldLayout(_commandLineOptions.VerifyTypeAndFieldLayout)
                    .GenerateOutputFile(outFile)
                    .UseILProvider(ilProvider)
                    .UseBackendOptions(_commandLineOptions.CodegenOptions)
                    .UseLogger(logger)
                    .UseDependencyTracking(trackingLevel)
                    .UseCompilationRoots(compilationRoots)
                    .UseOptimizationMode(optimizationMode);

                    if (_commandLineOptions.PrintReproInstructions)
                    {
                        builder.UsePrintReproInstructions(CreateReproArgumentString);
                    }

                    compilation = builder.ToCompilation();
                }
                compilation.Compile(outFile);

                if (_commandLineOptions.DgmlLogFileName != null)
                {
                    compilation.WriteDependencyLog(_commandLineOptions.DgmlLogFileName);
                }

                compilation.Dispose();
            }
        }
Esempio n. 6
0
        private int Run(string[] args)
        {
            using (PerfEventSource.StartStopEvents.CompilationEvents())
            {
                ICompilation compilation;
                using (PerfEventSource.StartStopEvents.LoadingEvents())
                {
                    InitializeDefaultOptions();

                    ProcessCommandLine(args);

                    if (_commandLineOptions.Help)
                    {
                        Console.WriteLine(_commandLineOptions.HelpText);
                        return(1);
                    }

                    if (_commandLineOptions.OutputFilePath == null)
                    {
                        throw new CommandLineException(SR.MissingOutputFile);
                    }

                    ConfigureTarget();
                    InstructionSetSupport instructionSetSupport = ConfigureInstructionSetSupport();

                    //
                    // Initialize type system context
                    //

                    SharedGenericsMode genericsMode = SharedGenericsMode.CanonicalReferenceTypes;

                    var targetDetails = new TargetDetails(_targetArchitecture, _targetOS, TargetAbi.CoreRT, instructionSetSupport.GetVectorTSimdVector());

                    bool versionBubbleIncludesCoreLib = false;
                    if (_commandLineOptions.InputBubble)
                    {
                        versionBubbleIncludesCoreLib = true;
                    }
                    else
                    {
                        foreach (var inputFile in _inputFilePaths)
                        {
                            if (String.Compare(inputFile.Key, "System.Private.CoreLib", StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                versionBubbleIncludesCoreLib = true;
                                break;
                            }
                        }
                        if (!versionBubbleIncludesCoreLib)
                        {
                            foreach (var inputFile in _unrootedInputFilePaths)
                            {
                                if (String.Compare(inputFile.Key, "System.Private.CoreLib", StringComparison.OrdinalIgnoreCase) == 0)
                                {
                                    versionBubbleIncludesCoreLib = true;
                                    break;
                                }
                            }
                        }
                    }

                    _typeSystemContext = new ReadyToRunCompilerContext(targetDetails, genericsMode, versionBubbleIncludesCoreLib);

                    string compositeRootPath = _commandLineOptions.CompositeRootPath;

                    //
                    // TODO: To support our pre-compiled test tree, allow input files that aren't managed assemblies since
                    // some tests contain a mixture of both managed and native binaries.
                    //
                    // See: https://github.com/dotnet/corert/issues/2785
                    //
                    // When we undo this this hack, replace this foreach with
                    //  typeSystemContext.InputFilePaths = _inputFilePaths;
                    //
                    Dictionary <string, string> allInputFilePaths    = new Dictionary <string, string>();
                    Dictionary <string, string> inputFilePaths       = new Dictionary <string, string>();
                    List <ModuleDesc>           referenceableModules = new List <ModuleDesc>();
                    foreach (var inputFile in _inputFilePaths)
                    {
                        try
                        {
                            var module = _typeSystemContext.GetModuleFromPath(inputFile.Value);
                            allInputFilePaths.Add(inputFile.Key, inputFile.Value);
                            inputFilePaths.Add(inputFile.Key, inputFile.Value);
                            referenceableModules.Add(module);
                            if (compositeRootPath == null)
                            {
                                compositeRootPath = Path.GetDirectoryName(inputFile.Value);
                            }
                        }
                        catch (TypeSystemException.BadImageFormatException)
                        {
                            // Keep calm and carry on.
                        }
                    }

                    Dictionary <string, string> unrootedInputFilePaths = new Dictionary <string, string>();
                    foreach (var unrootedInputFile in _unrootedInputFilePaths)
                    {
                        try
                        {
                            var module = _typeSystemContext.GetModuleFromPath(unrootedInputFile.Value);
                            if (!allInputFilePaths.ContainsKey(unrootedInputFile.Key))
                            {
                                allInputFilePaths.Add(unrootedInputFile.Key, unrootedInputFile.Value);
                                unrootedInputFilePaths.Add(unrootedInputFile.Key, unrootedInputFile.Value);
                                referenceableModules.Add(module);
                                if (compositeRootPath == null)
                                {
                                    compositeRootPath = Path.GetDirectoryName(unrootedInputFile.Value);
                                }
                            }
                        }
                        catch (TypeSystemException.BadImageFormatException)
                        {
                            // Keep calm and carry on.
                        }
                    }

                    CheckManagedCppInputFiles(allInputFilePaths.Values);

                    _typeSystemContext.InputFilePaths     = allInputFilePaths;
                    _typeSystemContext.ReferenceFilePaths = _referenceFilePaths;

                    List <EcmaModule>    inputModules             = new List <EcmaModule>();
                    List <EcmaModule>    rootingModules           = new List <EcmaModule>();
                    HashSet <ModuleDesc> versionBubbleModulesHash = new HashSet <ModuleDesc>();

                    foreach (var inputFile in inputFilePaths)
                    {
                        EcmaModule module = _typeSystemContext.GetModuleFromPath(inputFile.Value);
                        inputModules.Add(module);
                        rootingModules.Add(module);
                        versionBubbleModulesHash.Add(module);

                        if (!_commandLineOptions.CompositeOrInputBubble)
                        {
                            break;
                        }
                    }

                    foreach (var unrootedInputFile in unrootedInputFilePaths)
                    {
                        EcmaModule module = _typeSystemContext.GetModuleFromPath(unrootedInputFile.Value);
                        inputModules.Add(module);
                        versionBubbleModulesHash.Add(module);
                    }

                    string systemModuleName = _commandLineOptions.SystemModule ?? DefaultSystemModule;
                    _typeSystemContext.SetSystemModule((EcmaModule)_typeSystemContext.GetModuleForSimpleName(systemModuleName));

                    if (_typeSystemContext.InputFilePaths.Count == 0)
                    {
                        if (_commandLineOptions.InputFilePaths.Count > 0)
                        {
                            Console.WriteLine(SR.InputWasNotLoadable);
                            return(2);
                        }
                        throw new CommandLineException(SR.NoInputFiles);
                    }

                    //
                    // Initialize compilation group and compilation roots
                    //

                    // Single method mode?
                    MethodDesc singleMethod = CheckAndParseSingleMethodModeArguments(_typeSystemContext);

                    var logger = new Logger(Console.Out, _commandLineOptions.Verbose);

                    List <string> mibcFiles = new List <string>();
                    foreach (var file in _commandLineOptions.MibcFilePaths)
                    {
                        mibcFiles.Add(file);
                    }

                    foreach (var referenceFile in _referenceFilePaths.Values)
                    {
                        try
                        {
                            EcmaModule module = _typeSystemContext.GetModuleFromPath(referenceFile);
                            if (versionBubbleModulesHash.Contains(module))
                            {
                                // Ignore reference assemblies that have also been passed as inputs
                                continue;
                            }
                            referenceableModules.Add(module);
                            if (_commandLineOptions.InputBubble)
                            {
                                // In large version bubble mode add reference paths to the compilation group
                                versionBubbleModulesHash.Add(module);
                            }
                        }
                        catch { } // Ignore non-managed pe files
                    }

                    List <ModuleDesc> versionBubbleModules = new List <ModuleDesc>(versionBubbleModulesHash);

                    if (!_commandLineOptions.Composite && inputModules.Count != 1)
                    {
                        throw new Exception(string.Format(SR.ErrorMultipleInputFilesCompositeModeOnly, string.Join("; ", inputModules)));
                    }

                    ReadyToRunCompilationModuleGroupBase compilationGroup;
                    List <ICompilationRootProvider>      compilationRoots = new List <ICompilationRootProvider>();
                    if (singleMethod != null)
                    {
                        // Compiling just a single method
                        compilationGroup = new SingleMethodCompilationModuleGroup(
                            _typeSystemContext,
                            _commandLineOptions.Composite,
                            _commandLineOptions.InputBubble,
                            inputModules,
                            versionBubbleModules,
                            _commandLineOptions.CompileBubbleGenerics,
                            singleMethod);
                        compilationRoots.Add(new SingleMethodRootProvider(singleMethod));
                    }
                    else if (_commandLineOptions.CompileNoMethods)
                    {
                        compilationGroup = new NoMethodsCompilationModuleGroup(
                            _typeSystemContext,
                            _commandLineOptions.Composite,
                            _commandLineOptions.InputBubble,
                            inputModules,
                            versionBubbleModules,
                            _commandLineOptions.CompileBubbleGenerics);
                    }
                    else
                    {
                        // Single assembly compilation.
                        compilationGroup = new ReadyToRunSingleAssemblyCompilationModuleGroup(
                            _typeSystemContext,
                            _commandLineOptions.Composite,
                            _commandLineOptions.InputBubble,
                            inputModules,
                            versionBubbleModules,
                            _commandLineOptions.CompileBubbleGenerics);
                    }

                    // Examine profile guided information as appropriate
                    ProfileDataManager profileDataManager =
                        new ProfileDataManager(logger,
                                               referenceableModules,
                                               inputModules,
                                               versionBubbleModules,
                                               _commandLineOptions.CompileBubbleGenerics ? inputModules[0] : null,
                                               mibcFiles,
                                               _typeSystemContext,
                                               compilationGroup);

                    if (_commandLineOptions.Partial)
                    {
                        compilationGroup.ApplyProfilerGuidedCompilationRestriction(profileDataManager);
                    }
                    else
                    {
                        compilationGroup.ApplyProfilerGuidedCompilationRestriction(null);
                    }

                    if ((singleMethod == null) && !_commandLineOptions.CompileNoMethods)
                    {
                        // For normal compilations add compilation roots.
                        foreach (var module in rootingModules)
                        {
                            compilationRoots.Add(new ReadyToRunRootProvider(
                                                     module,
                                                     profileDataManager,
                                                     profileDrivenPartialNGen: _commandLineOptions.Partial));

                            if (!_commandLineOptions.CompositeOrInputBubble)
                            {
                                break;
                            }
                        }
                    }
                    // In single-file compilation mode, use the assembly's DebuggableAttribute to determine whether to optimize
                    // or produce debuggable code if an explicit optimization level was not specified on the command line
                    if (_optimizationMode == OptimizationMode.None && !_commandLineOptions.OptimizeDisabled && !_commandLineOptions.Composite)
                    {
                        System.Diagnostics.Debug.Assert(inputModules.Count == 1);
                        _optimizationMode = ((EcmaAssembly)inputModules[0].Assembly).HasOptimizationsDisabled() ? OptimizationMode.None : OptimizationMode.Blended;
                    }

                    //
                    // Compile
                    //

                    ReadyToRunCodegenCompilationBuilder builder = new ReadyToRunCodegenCompilationBuilder(
                        _typeSystemContext, compilationGroup, allInputFilePaths.Values, compositeRootPath);
                    string compilationUnitPrefix = "";
                    builder.UseCompilationUnitPrefix(compilationUnitPrefix);

                    ILProvider ilProvider = new ReadyToRunILProvider();

                    DependencyTrackingLevel trackingLevel = _commandLineOptions.DgmlLogFileName == null ?
                                                            DependencyTrackingLevel.None : (_commandLineOptions.GenerateFullDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First);

                    builder
                    .UseIbcTuning(_commandLineOptions.Tuning)
                    .UseResilience(_commandLineOptions.Resilient)
                    .UseMapFile(_commandLineOptions.Map)
                    .UseMapCsvFile(_commandLineOptions.MapCsv)
                    .UseParallelism(_commandLineOptions.Parallelism)
                    .UseProfileData(profileDataManager)
                    .FileLayoutAlgorithms(_methodLayout, _fileLayout)
                    .UseJitPath(_commandLineOptions.JitPath)
                    .UseInstructionSetSupport(instructionSetSupport)
                    .UseCustomPESectionAlignment(_commandLineOptions.CustomPESectionAlignment)
                    .UseVerifyTypeAndFieldLayout(_commandLineOptions.VerifyTypeAndFieldLayout)
                    .GenerateOutputFile(_commandLineOptions.OutputFilePath)
                    .UseILProvider(ilProvider)
                    .UseBackendOptions(_commandLineOptions.CodegenOptions)
                    .UseLogger(logger)
                    .UseDependencyTracking(trackingLevel)
                    .UseCompilationRoots(compilationRoots)
                    .UseOptimizationMode(_optimizationMode);

                    compilation = builder.ToCompilation();
                }
                compilation.Compile(_commandLineOptions.OutputFilePath);

                if (_commandLineOptions.DgmlLogFileName != null)
                {
                    compilation.WriteDependencyLog(_commandLineOptions.DgmlLogFileName);
                }
            }

            return(0);
        }
Esempio n. 7
0
        private ArgumentSyntax ParseCommandLine(string[] args)
        {
            IReadOnlyList <string> inputFiles     = Array.Empty <string>();
            IReadOnlyList <string> referenceFiles = Array.Empty <string>();

            bool optimize      = false;
            bool optimizeSpace = false;
            bool optimizeTime  = false;

            bool           waitForDebugger = false;
            AssemblyName   name            = typeof(Program).GetTypeInfo().Assembly.GetName();
            ArgumentSyntax argSyntax       = ArgumentSyntax.Parse(args, syntax =>
            {
                syntax.ApplicationName = name.Name.ToString();

                // HandleHelp writes to error, fails fast with crash dialog and lacks custom formatting.
                syntax.HandleHelp   = false;
                syntax.HandleErrors = true;

                syntax.DefineOption("h|help", ref _help, "Help message for ILC");
                syntax.DefineOptionList("r|reference", ref referenceFiles, "Reference file(s) for compilation");
                syntax.DefineOption("o|out", ref _outputFilePath, "Output file path");
                syntax.DefineOption("O", ref optimize, "Enable optimizations");
                syntax.DefineOption("Os", ref optimizeSpace, "Enable optimizations, favor code space");
                syntax.DefineOption("Ot", ref optimizeTime, "Enable optimizations, favor code speed");
                syntax.DefineOption("g", ref _enableDebugInfo, "Emit debugging information");
                syntax.DefineOption("cpp", ref _isCppCodegen, "Compile for C++ code-generation");
                syntax.DefineOption("wasm", ref _isWasmCodegen, "Compile for WebAssembly code-generation");
                syntax.DefineOption("nativelib", ref _nativeLib, "Compile as static or shared library");
                syntax.DefineOption("exportsfile", ref _exportsFile, "File to write exported method definitions");
                syntax.DefineOption("dgmllog", ref _dgmlLogFileName, "Save result of dependency analysis as DGML");
                syntax.DefineOption("fulllog", ref _generateFullDgmlLog, "Save detailed log of dependency analysis");
                syntax.DefineOption("scandgmllog", ref _scanDgmlLogFileName, "Save result of scanner dependency analysis as DGML");
                syntax.DefineOption("scanfulllog", ref _generateFullScanDgmlLog, "Save detailed log of scanner dependency analysis");
                syntax.DefineOption("verbose", ref _isVerbose, "Enable verbose logging");
                syntax.DefineOption("systemmodule", ref _systemModuleName, "System module name (default: System.Private.CoreLib)");
                syntax.DefineOption("multifile", ref _multiFile, "Compile only input files (do not compile referenced assemblies)");
                syntax.DefineOption("waitfordebugger", ref waitForDebugger, "Pause to give opportunity to attach debugger");
                syntax.DefineOption("usesharedgenerics", ref _useSharedGenerics, "Enable shared generics");
                syntax.DefineOptionList("codegenopt", ref _codegenOptions, "Define a codegen option");
                syntax.DefineOptionList("rdxml", ref _rdXmlFilePaths, "RD.XML file(s) for compilation");
                syntax.DefineOption("rootallapplicationassemblies", ref _rootAllApplicationAssemblies, "Consider all non-framework assemblies dynamically used");
                syntax.DefineOption("map", ref _mapFileName, "Generate a map file");
                syntax.DefineOption("metadatalog", ref _metadataLogFileName, "Generate a metadata log file");
                syntax.DefineOption("nometadatablocking", ref _noMetadataBlocking, "Ignore metadata blocking for internal implementation details");
                syntax.DefineOption("disablereflection", ref _disableReflection, "Disable generation of reflection metadata");
                syntax.DefineOption("completetypemetadata", ref _completeTypesMetadata, "Generate complete metadata for types");
                syntax.DefineOption("scanreflection", ref _scanReflection, "Scan IL for reflection patterns");
                syntax.DefineOption("scan", ref _useScanner, "Use IL scanner to generate optimized code (implied by -O)");
                syntax.DefineOption("noscan", ref _noScanner, "Do not use IL scanner to generate optimized code");
                syntax.DefineOption("ildump", ref _ilDump, "Dump IL assembly listing for compiler-generated IL");
                syntax.DefineOption("stacktracedata", ref _emitStackTraceData, "Emit data to support generating stack trace strings at runtime");
                syntax.DefineOption("methodbodyfolding", ref _methodBodyFolding, "Fold identical method bodies");
                syntax.DefineOptionList("initassembly", ref _initAssemblies, "Assembly(ies) with a library initializer");
                syntax.DefineOptionList("appcontextswitch", ref _appContextSwitches, "System.AppContext switches to set");
                syntax.DefineOptionList("runtimeopt", ref _runtimeOptions, "Runtime options to set");
                syntax.DefineOptionList("removefeature", ref _removedFeatures, "Framework features to remove");

                syntax.DefineOption("targetarch", ref _targetArchitectureStr, "Target architecture for cross compilation");
                syntax.DefineOption("targetos", ref _targetOSStr, "Target OS for cross compilation");

                syntax.DefineOption("singlemethodtypename", ref _singleMethodTypeName, "Single method compilation: name of the owning type");
                syntax.DefineOption("singlemethodname", ref _singleMethodName, "Single method compilation: name of the method");
                syntax.DefineOptionList("singlemethodgenericarg", ref _singleMethodGenericArgs, "Single method compilation: generic arguments to the method");

                syntax.DefineParameterList("in", ref inputFiles, "Input file(s) to compile");
            });

            if (waitForDebugger)
            {
                Console.WriteLine("Waiting for debugger to attach. Press ENTER to continue");
                Console.ReadLine();
            }

            _optimizationMode = OptimizationMode.None;
            if (optimizeSpace)
            {
                if (optimizeTime)
                {
                    Console.WriteLine("Warning: overriding -Ot with -Os");
                }
                _optimizationMode = OptimizationMode.PreferSize;
            }
            else if (optimizeTime)
            {
                _optimizationMode = OptimizationMode.PreferSpeed;
            }
            else if (optimize)
            {
                _optimizationMode = OptimizationMode.Blended;
            }

            foreach (var input in inputFiles)
            {
                Helpers.AppendExpandedPaths(_inputFilePaths, input, true);
            }

            foreach (var reference in referenceFiles)
            {
                Helpers.AppendExpandedPaths(_referenceFilePaths, reference, false);
            }

            return(argSyntax);
        }
Esempio n. 8
0
        private ArgumentSyntax ParseCommandLine(string[] args)
        {
            IReadOnlyList <string> inputFiles     = Array.Empty <string>();
            IReadOnlyList <string> referenceFiles = Array.Empty <string>();

            bool optimize      = false;
            bool optimizeSpace = false;
            bool optimizeTime  = false;

            bool           waitForDebugger = false;
            AssemblyName   name            = typeof(Program).GetTypeInfo().Assembly.GetName();
            ArgumentSyntax argSyntax       = ArgumentSyntax.Parse(args, syntax =>
            {
                syntax.ApplicationName = name.Name.ToString();

                // HandleHelp writes to error, fails fast with crash dialog and lacks custom formatting.
                syntax.HandleHelp   = false;
                syntax.HandleErrors = true;

                syntax.DefineOption("h|help", ref _help, "Help message for ILC");
                syntax.DefineOptionList("r|reference", ref referenceFiles, "Reference file(s) for compilation");
                syntax.DefineOption("o|out", ref _outputFilePath, "Output file path");
                syntax.DefineOption("O", ref optimize, "Enable optimizations");
                syntax.DefineOption("Os", ref optimizeSpace, "Enable optimizations, favor code space");
                syntax.DefineOption("Ot", ref optimizeTime, "Enable optimizations, favor code speed");
                syntax.DefineOption("inputbubble", ref _isInputVersionBubble, "True when the entire input forms a version bubble (default = per-assembly bubble)");
                syntax.DefineOption("tuning", ref _tuning, "Generate IBC tuning image");
                syntax.DefineOption("partial", ref _partial, "Generate partial image driven by profile");
                syntax.DefineOption("compilebubblegenerics", ref _includeGenericsFromVersionBubble, "Compile instantiations from reference modules used in the current module");
                syntax.DefineOption("dgmllog", ref _dgmlLogFileName, "Save result of dependency analysis as DGML");
                syntax.DefineOption("fulllog", ref _generateFullDgmlLog, "Save detailed log of dependency analysis");
                syntax.DefineOption("verbose", ref _isVerbose, "Enable verbose logging");
                syntax.DefineOption("systemmodule", ref _systemModuleName, "System module name (default: System.Private.CoreLib)");
                syntax.DefineOption("waitfordebugger", ref waitForDebugger, "Pause to give opportunity to attach debugger");
                syntax.DefineOptionList("codegenopt", ref _codegenOptions, "Define a codegen option");
                syntax.DefineOption("resilient", ref _resilient, "Disable behavior where unexpected compilation failures cause overall compilation failure");

                syntax.DefineOption("targetarch", ref _targetArchitectureStr, "Target architecture for cross compilation");
                syntax.DefineOption("targetos", ref _targetOSStr, "Target OS for cross compilation");
                syntax.DefineOption("jitpath", ref _jitPath, "Path to JIT compiler library");

                syntax.DefineOption("singlemethodtypename", ref _singleMethodTypeName, "Single method compilation: name of the owning type");
                syntax.DefineOption("singlemethodname", ref _singleMethodName, "Single method compilation: name of the method");
                syntax.DefineOptionList("singlemethodgenericarg", ref _singleMethodGenericArgs, "Single method compilation: generic arguments to the method");

                syntax.DefineParameterList("in", ref inputFiles, "Input file(s) to compile");
            });

            if (waitForDebugger)
            {
                Console.WriteLine("Waiting for debugger to attach. Press ENTER to continue");
                Console.ReadLine();
            }

            if (_includeGenericsFromVersionBubble)
            {
                if (!_isInputVersionBubble)
                {
                    Console.WriteLine("Warning: ignoring --compilebubblegenerics because --inputbubble was not specified");
                    _includeGenericsFromVersionBubble = false;
                }
            }

            _optimizationMode = OptimizationMode.None;
            if (optimizeSpace)
            {
                if (optimizeTime)
                {
                    Console.WriteLine("Warning: overriding -Ot with -Os");
                }
                _optimizationMode = OptimizationMode.PreferSize;
            }
            else if (optimizeTime)
            {
                _optimizationMode = OptimizationMode.PreferSpeed;
            }
            else if (optimize)
            {
                _optimizationMode = OptimizationMode.Blended;
            }

            foreach (var input in inputFiles)
            {
                Helpers.AppendExpandedPaths(_inputFilePaths, input, true);
            }

            foreach (var reference in referenceFiles)
            {
                Helpers.AppendExpandedPaths(_referenceFilePaths, reference, false);
            }

            return(argSyntax);
        }