Exemple #1
0
        internal RyuJitCompilation(
            DependencyAnalyzerBase <NodeFactory> dependencyGraph,
            NodeFactory nodeFactory,
            IEnumerable <ICompilationRootProvider> roots,
            ILProvider ilProvider,
            DebugInformationProvider debugInformationProvider,
            Logger logger,
            DevirtualizationManager devirtualizationManager,
            InstructionSetSupport instructionSetSupport,
            RyuJitCompilationOptions options)
            : base(dependencyGraph, nodeFactory, roots, ilProvider, debugInformationProvider, devirtualizationManager, logger)
        {
            _compilationOptions     = options;
            _hardwareIntrinsicFlags = new ExternSymbolMappedField(nodeFactory.TypeSystemContext.GetWellKnownType(WellKnownType.Int32), "g_cpuFeatures");
            InstructionSetSupport   = instructionSetSupport;

            _instructionSetMap = new Dictionary <string, InstructionSet>();
            foreach (var instructionSetInfo in InstructionSetFlags.ArchitectureToValidInstructionSets(TypeSystemContext.Target.Architecture))
            {
                if (!instructionSetInfo.Specifiable)
                {
                    continue;
                }

                _instructionSetMap.Add(instructionSetInfo.ManagedName, instructionSetInfo.InstructionSet);
            }
        }
        protected Compilation(
            DependencyAnalyzerBase <NodeFactory> dependencyGraph,
            NodeFactory nodeFactory,
            IEnumerable <ICompilationRootProvider> compilationRoots,
            ILProvider ilProvider,
            DevirtualizationManager devirtualizationManager,
            IEnumerable <ModuleDesc> modulesBeingInstrumented,
            Logger logger,
            InstructionSetSupport instructionSetSupport)
        {
            InstructionSetSupport = instructionSetSupport;
            _dependencyGraph      = dependencyGraph;
            _nodeFactory          = nodeFactory;
            _logger = logger;
            _devirtualizationManager  = devirtualizationManager;
            _modulesBeingInstrumented = new HashSet <ModuleDesc>(modulesBeingInstrumented);

            _dependencyGraph.ComputeDependencyRoutine += ComputeDependencyNodeDependencies;
            NodeFactory.AttachToDependencyGraph(_dependencyGraph);

            var rootingService = new RootingServiceProvider(nodeFactory, _dependencyGraph.AddRoot);

            foreach (var rootProvider in compilationRoots)
            {
                rootProvider.AddCompilationRoots(rootingService);
            }

            _methodILCache = new ILCache(ilProvider, NodeFactory.CompilationModuleGroup);
        }
        public static int GetRuntimeRequiredIsaFlags(InstructionSetSupport instructionSetSupport)
        {
            int result = 0;

            switch (instructionSetSupport.Architecture)
            {
            case TargetArchitecture.X86:
            case TargetArchitecture.X64:
                foreach (InstructionSet instructionSet in instructionSetSupport.SupportedFlags)
                {
                    result |= XArchIntrinsicConstants.FromInstructionSet(instructionSet);
                }
                break;

            case TargetArchitecture.ARM64:
                foreach (InstructionSet instructionSet in instructionSetSupport.SupportedFlags)
                {
                    result |= Arm64IntrinsicConstants.FromInstructionSet(instructionSet);
                }
                break;

            default:
                Debug.Fail("Unsupported Architecture");
                break;
            }
            return(result);
        }
        internal RyuJitCompilation(
            DependencyAnalyzerBase <NodeFactory> dependencyGraph,
            NodeFactory nodeFactory,
            IEnumerable <ICompilationRootProvider> roots,
            ILProvider ilProvider,
            DebugInformationProvider debugInformationProvider,
            Logger logger,
            DevirtualizationManager devirtualizationManager,
            IInliningPolicy inliningPolicy,
            InstructionSetSupport instructionSetSupport,
            ProfileDataManager profileDataManager,
            MethodImportationErrorProvider errorProvider,
            RyuJitCompilationOptions options,
            int parallelism)
            : base(dependencyGraph, nodeFactory, roots, ilProvider, debugInformationProvider, devirtualizationManager, inliningPolicy, logger)
        {
            _compilationOptions     = options;
            _hardwareIntrinsicFlags = new ExternSymbolMappedField(nodeFactory.TypeSystemContext.GetWellKnownType(WellKnownType.Int32), "g_cpuFeatures");
            InstructionSetSupport   = instructionSetSupport;

            _instructionSetMap = new Dictionary <string, InstructionSet>();
            foreach (var instructionSetInfo in InstructionSetFlags.ArchitectureToValidInstructionSets(TypeSystemContext.Target.Architecture))
            {
                if (instructionSetInfo.ManagedName != "")
                {
                    _instructionSetMap.Add(instructionSetInfo.ManagedName, instructionSetInfo.InstructionSet);
                }
            }

            _profileDataManager = profileDataManager;

            _methodImportationErrorProvider = errorProvider;

            _parallelism = parallelism;
        }
Exemple #5
0
        internal ReadyToRunCodegenCompilation(
            DependencyAnalyzerBase <NodeFactory> dependencyGraph,
            NodeFactory nodeFactory,
            IEnumerable <ICompilationRootProvider> roots,
            ILProvider ilProvider,
            Logger logger,
            DevirtualizationManager devirtualizationManager,
            IEnumerable <string> inputFiles,
            string compositeRootPath,
            InstructionSetSupport instructionSetSupport,
            bool resilient,
            bool generateMapFile,
            bool generateMapCsvFile,
            bool generatePdbFile,
            string pdbPath,
            bool generatePerfMapFile,
            string perfMapPath,
            int parallelism,
            ProfileDataManager profileData,
            ReadyToRunMethodLayoutAlgorithm methodLayoutAlgorithm,
            ReadyToRunFileLayoutAlgorithm fileLayoutAlgorithm,
            int customPESectionAlignment,
            bool verifyTypeAndFieldLayout)
            : base(
                dependencyGraph,
                nodeFactory,
                roots,
                ilProvider,
                devirtualizationManager,
                modulesBeingInstrumented: nodeFactory.CompilationModuleGroup.CompilationModuleSet,
                logger,
                instructionSetSupport)
        {
            _resilient                = resilient;
            _parallelism              = parallelism;
            _generateMapFile          = generateMapFile;
            _generateMapCsvFile       = generateMapCsvFile;
            _generatePdbFile          = generatePdbFile;
            _pdbPath                  = pdbPath;
            _generatePerfMapFile      = generatePerfMapFile;
            _perfMapPath              = perfMapPath;
            _customPESectionAlignment = customPESectionAlignment;
            SymbolNodeFactory         = new ReadyToRunSymbolNodeFactory(nodeFactory, verifyTypeAndFieldLayout);
            _corInfoImpls             = new ConditionalWeakTable <Thread, CorInfoImpl>();
            _inputFiles               = inputFiles;
            _compositeRootPath        = compositeRootPath;
            CompilationModuleGroup    = (ReadyToRunCompilationModuleGroupBase)nodeFactory.CompilationModuleGroup;

            // Generate baseline support specification for InstructionSetSupport. This will prevent usage of the generated
            // code if the runtime environment doesn't support the specified instruction set
            string instructionSetSupportString = ReadyToRunInstructionSetSupportSignature.ToInstructionSetSupportString(instructionSetSupport);
            ReadyToRunInstructionSetSupportSignature instructionSetSupportSig = new ReadyToRunInstructionSetSupportSignature(instructionSetSupportString);

            _dependencyGraph.AddRoot(new Import(NodeFactory.EagerImports, instructionSetSupportSig), "Baseline instruction set support");

            _profileData = profileData;

            _fileLayoutOptimizer = new ReadyToRunFileLayoutOptimizer(methodLayoutAlgorithm, fileLayoutAlgorithm, profileData, _nodeFactory);
        }
Exemple #6
0
        public static int GetRuntimeRequiredIsaFlags(InstructionSetSupport instructionSetSupport)
        {
            switch (instructionSetSupport.Architecture)
            {
            case TargetArchitecture.X86:
            case TargetArchitecture.X64:
                return(XArchIntrinsicConstants.FromInstructionSetFlags(instructionSetSupport.SupportedFlags));

            case TargetArchitecture.ARM64:
                return(Arm64IntrinsicConstants.FromInstructionSetFlags(instructionSetSupport.SupportedFlags));

            default:
                Debug.Fail("Unsupported Architecture");
                return(0);
            }
        }
Exemple #7
0
 internal RyuJitCompilation(
     DependencyAnalyzerBase <NodeFactory> dependencyGraph,
     NodeFactory nodeFactory,
     IEnumerable <ICompilationRootProvider> roots,
     ILProvider ilProvider,
     DebugInformationProvider debugInformationProvider,
     Logger logger,
     DevirtualizationManager devirtualizationManager,
     InstructionSetSupport instructionSetSupport,
     RyuJitCompilationOptions options)
     : base(dependencyGraph, nodeFactory, roots, ilProvider, debugInformationProvider, devirtualizationManager, logger)
 {
     _compilationOptions     = options;
     _hardwareIntrinsicFlags = new ExternSymbolMappedField(nodeFactory.TypeSystemContext.GetWellKnownType(WellKnownType.Int32), "g_cpuFeatures");
     InstructionSetSupport   = instructionSetSupport;
 }
Exemple #8
0
        /// <summary>
        /// Generates IL for the IsSupported property that reads this information from a field initialized by the runtime
        /// at startup. Only works for intrinsics that the code generator can generate detection code for.
        /// </summary>
        public static MethodIL EmitIsSupportedIL(MethodDesc method, FieldDesc isSupportedField)
        {
            Debug.Assert(IsIsSupportedMethod(method));
            Debug.Assert(isSupportedField.IsStatic && isSupportedField.FieldType.IsWellKnownType(WellKnownType.Int32));

            string id = InstructionSetSupport.GetHardwareIntrinsicId(method.Context.Target.Architecture, method.OwningType);

            Debug.Assert(method.Context.Target.Architecture == TargetArchitecture.X64 ||
                         method.Context.Target.Architecture == TargetArchitecture.X86);
            int flag = XArchIntrinsicConstants.FromHardwareIntrinsicId(id);

            var          emit       = new ILEmitter();
            ILCodeStream codeStream = emit.NewCodeStream();

            codeStream.Emit(ILOpcode.ldsfld, emit.NewToken(isSupportedField));
            codeStream.EmitLdc(flag);
            codeStream.Emit(ILOpcode.and);
            codeStream.EmitLdc(0);
            codeStream.Emit(ILOpcode.cgt_un);
            codeStream.Emit(ILOpcode.ret);

            return(emit.Link(method));
        }
        internal ReadyToRunCodegenCompilation(
            DependencyAnalyzerBase <NodeFactory> dependencyGraph,
            NodeFactory nodeFactory,
            IEnumerable <ICompilationRootProvider> roots,
            ILProvider ilProvider,
            Logger logger,
            DevirtualizationManager devirtualizationManager,
            IEnumerable <string> inputFiles,
            InstructionSetSupport instructionSetSupport,
            bool resilient,
            bool generateMapFile,
            int parallelism)
            : base(
                dependencyGraph,
                nodeFactory,
                roots,
                ilProvider,
                devirtualizationManager,
                modulesBeingInstrumented: nodeFactory.CompilationModuleGroup.CompilationModuleSet,
                logger,
                instructionSetSupport)
        {
            _resilient             = resilient;
            _parallelism           = parallelism;
            _generateMapFile       = generateMapFile;
            SymbolNodeFactory      = new ReadyToRunSymbolNodeFactory(nodeFactory);
            _corInfoImpls          = new ConditionalWeakTable <Thread, CorInfoImpl>();
            _inputFiles            = inputFiles;
            CompilationModuleGroup = (ReadyToRunCompilationModuleGroupBase)nodeFactory.CompilationModuleGroup;

            // Generate baseline support specification for InstructionSetSupport. This will prevent usage of the generated
            // code if the runtime environment doesn't support the specified instruction set
            string instructionSetSupportString = ReadyToRunInstructionSetSupportSignature.ToInstructionSetSupportString(instructionSetSupport);
            ReadyToRunInstructionSetSupportSignature instructionSetSupportSig = new ReadyToRunInstructionSetSupportSignature(instructionSetSupportString);

            _dependencyGraph.AddRoot(new Import(NodeFactory.EagerImports, instructionSetSupportSig), "Baseline instruction set support");
        }
Exemple #10
0
        private void RunSingleCompilation(Dictionary <string, string> inFilePaths, InstructionSetSupport instructionSetSupport, string compositeRootPath, Dictionary <string, string> unrootedInputFilePaths, HashSet <ModuleDesc> versionBubbleModulesHash, CompilerTypeSystemContext typeSystemContext)
        {
            //
            // Initialize output filename
            //
            string inFilePath         = inFilePaths.First().Value;
            string inputFileExtension = Path.GetExtension(inFilePath);
            string nearOutFilePath    = inputFileExtension switch
            {
                ".dll" => Path.ChangeExtension(inFilePath,
                                               _commandLineOptions.SingleFileCompilation && _commandLineOptions.InputBubble
                        ? ".ni.dll.tmp"
                        : ".ni.dll"),
                ".exe" => Path.ChangeExtension(inFilePath,
                                               _commandLineOptions.SingleFileCompilation && _commandLineOptions.InputBubble
                        ? ".ni.exe.tmp"
                        : ".ni.exe"),
                _ => throw new CommandLineException(string.Format(SR.UnsupportedInputFileExtension, inputFileExtension))
            };
            string outFile = _commandLineOptions.OutNearInput ? nearOutFilePath : _commandLineOptions.OutputFilePath;

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

                    foreach (var inputFile in inFilePaths)
                    {
                        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);
                    }

                    //
                    // 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;
                    }

                    CompositeImageSettings compositeImageSettings = new CompositeImageSettings();

                    if (_commandLineOptions.CompositeKeyFile != null)
                    {
                        ImmutableArray <byte> compositeStrongNameKey = File.ReadAllBytes(_commandLineOptions.CompositeKeyFile).ToImmutableArray();
                        if (!IsValidPublicKey(compositeStrongNameKey))
                        {
                            throw new Exception(string.Format(SR.ErrorCompositeKeyFileNotPublicKey));
                        }

                        compositeImageSettings.PublicKey = compositeStrongNameKey;
                    }

                    //
                    // 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, _commandLineOptions.PerfMapFormatVersion)
                    .UseProfileFile(jsonProfile != null)
                    .UseParallelism(_commandLineOptions.Parallelism)
                    .UseProfileData(profileDataManager)
                    .FileLayoutAlgorithms(_methodLayout, _fileLayout)
                    .UseCompositeImageSettings(compositeImageSettings)
                    .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();
            }
        }
Exemple #11
0
        private int Run(string[] args)
        {
            InitializeDefaultOptions();

            ProcessCommandLine(args);

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

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

            if (_commandLineOptions.SingleFileCompilation && !_commandLineOptions.OutNearInput)
            {
                throw new CommandLineException(SR.MissingOutNearInput);
            }

            ConfigureTarget();
            InstructionSetSupport instructionSetSupport = ConfigureInstructionSetSupport();

            SharedGenericsMode genericsMode = SharedGenericsMode.CanonicalReferenceTypes;

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

            bool versionBubbleIncludesCoreLib = false;

            if (_commandLineOptions.InputBubble)
            {
                versionBubbleIncludesCoreLib = true;
            }
            else
            {
                if (!_commandLineOptions.SingleFileCompilation)
                {
                    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;
                        }
                    }
                }
            }

            //
            // Initialize type system context
            //
            _typeSystemContext = new ReadyToRunCompilerContext(targetDetails, genericsMode, versionBubbleIncludesCoreLib);

            string compositeRootPath = _commandLineOptions.CompositeRootPath;

            // Collections for already loaded modules
            Dictionary <string, string> inputFilePaths           = new Dictionary <string, string>();
            Dictionary <string, string> unrootedInputFilePaths   = new Dictionary <string, string>();
            HashSet <ModuleDesc>        versionBubbleModulesHash = new HashSet <ModuleDesc>();

            using (PerfEventSource.StartStopEvents.LoadingEvents())
            {
                //
                // 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 = inFilePaths;
                //

                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.
                    }
                }

                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;

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

                foreach (var referenceFile in _referenceFilePaths.Values)
                {
                    try
                    {
                        EcmaModule module = _typeSystemContext.GetModuleFromPath(referenceFile);
                        _referenceableModules.Add(module);
                        if (_commandLineOptions.InputBubble && _inputbubblereferenceFilePaths.Count == 0)
                        {
                            // In large version bubble mode add reference paths to the compilation group
                            // Consider bubble as large if no explicit bubble references were passed
                            versionBubbleModulesHash.Add(module);
                        }
                    }
                    catch { } // Ignore non-managed pe files
                }

                if (_commandLineOptions.InputBubble)
                {
                    foreach (var referenceFile in _inputbubblereferenceFilePaths.Values)
                    {
                        try
                        {
                            EcmaModule module = _typeSystemContext.GetModuleFromPath(referenceFile);
                            versionBubbleModulesHash.Add(module);
                        }
                        catch { } // Ignore non-managed pe files
                    }
                }
            }

            string systemModuleName = _commandLineOptions.SystemModule ?? DefaultSystemModule;

            _typeSystemContext.SetSystemModule((EcmaModule)_typeSystemContext.GetModuleForSimpleName(systemModuleName));
            CompilerTypeSystemContext typeSystemContext = _typeSystemContext;

            if (_commandLineOptions.SingleFileCompilation)
            {
                var singleCompilationInputFilePaths = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

                foreach (var inputFile in inputFilePaths)
                {
                    var singleCompilationVersionBubbleModulesHash = new HashSet <ModuleDesc>(versionBubbleModulesHash);

                    singleCompilationInputFilePaths.Clear();
                    singleCompilationInputFilePaths.Add(inputFile.Key, inputFile.Value);
                    typeSystemContext.InputFilePaths = singleCompilationInputFilePaths;

                    if (!_commandLineOptions.InputBubble)
                    {
                        bool singleCompilationVersionBubbleIncludesCoreLib = versionBubbleIncludesCoreLib || (String.Compare(inputFile.Key, "System.Private.CoreLib", StringComparison.OrdinalIgnoreCase) == 0);

                        typeSystemContext = new ReadyToRunCompilerContext(targetDetails, genericsMode, singleCompilationVersionBubbleIncludesCoreLib, _typeSystemContext);
                        typeSystemContext.InputFilePaths     = singleCompilationInputFilePaths;
                        typeSystemContext.ReferenceFilePaths = _referenceFilePaths;
                        typeSystemContext.SetSystemModule((EcmaModule)typeSystemContext.GetModuleForSimpleName(systemModuleName));
                    }

                    RunSingleCompilation(singleCompilationInputFilePaths, instructionSetSupport, compositeRootPath, unrootedInputFilePaths, singleCompilationVersionBubbleModulesHash, typeSystemContext);
                }

                // In case of inputbubble ni.dll are created as ni.dll.tmp in order to not interfere with crossgen2, move them all to ni.dll
                // See https://github.com/dotnet/runtime/issues/55663#issuecomment-898161751 for more details
                if (_commandLineOptions.InputBubble)
                {
                    foreach (var inputFile in inputFilePaths)
                    {
                        var tmpOutFile = inputFile.Value.Replace(".dll", ".ni.dll.tmp");
                        var outFile    = inputFile.Value.Replace(".dll", ".ni.dll");
                        Console.WriteLine($@"Moving R2R PE file: {tmpOutFile} to {outFile}");
                        System.IO.File.Move(tmpOutFile, outFile);
                    }
                }
            }
            else
            {
                RunSingleCompilation(inputFilePaths, instructionSetSupport, compositeRootPath, unrootedInputFilePaths, versionBubbleModulesHash, typeSystemContext);
            }

            return(0);
        }
 public ReadyToRunCodegenCompilationBuilder UseInstructionSetSupport(InstructionSetSupport instructionSetSupport)
 {
     _instructionSetSupport = instructionSetSupport;
     return(this);
 }
Exemple #13
0
        private int Run(string[] args)
        {
            InitializeDefaultOptions();

            ArgumentSyntax syntax = ParseCommandLine(args);

            if (_help)
            {
                Help(syntax.GetHelpText());
                return(1);
            }

            if (_outputFilePath == null)
            {
                throw new CommandLineException("Output filename must be specified (/out <file>)");
            }

            //
            // Set target Architecture and OS
            //
            if (_targetArchitectureStr != null)
            {
                if (_targetArchitectureStr.Equals("x86", StringComparison.OrdinalIgnoreCase))
                {
                    _targetArchitecture = TargetArchitecture.X86;
                }
                else if (_targetArchitectureStr.Equals("x64", StringComparison.OrdinalIgnoreCase))
                {
                    _targetArchitecture = TargetArchitecture.X64;
                }
                else if (_targetArchitectureStr.Equals("arm", StringComparison.OrdinalIgnoreCase))
                {
                    _targetArchitecture = TargetArchitecture.ARM;
                }
                else if (_targetArchitectureStr.Equals("armel", StringComparison.OrdinalIgnoreCase))
                {
                    _targetArchitecture = TargetArchitecture.ARM;
                }
                else if (_targetArchitectureStr.Equals("arm64", StringComparison.OrdinalIgnoreCase))
                {
                    _targetArchitecture = TargetArchitecture.ARM64;
                }
                else if (_targetArchitectureStr.Equals("wasm", StringComparison.OrdinalIgnoreCase))
                {
                    _targetArchitecture = TargetArchitecture.Wasm32;
                    _isWasmCodegen      = true;
                }
                else
                {
                    throw new CommandLineException("Target architecture is not supported");
                }
            }
            if (_targetOSStr != null)
            {
                if (_targetOSStr.Equals("windows", StringComparison.OrdinalIgnoreCase))
                {
                    _targetOS = TargetOS.Windows;
                }
                else if (_targetOSStr.Equals("linux", StringComparison.OrdinalIgnoreCase))
                {
                    _targetOS = TargetOS.Linux;
                }
                else if (_targetOSStr.Equals("osx", StringComparison.OrdinalIgnoreCase))
                {
                    _targetOS = TargetOS.OSX;
                }
                else
                {
                    throw new CommandLineException("Target OS is not supported");
                }
            }

            if (_isWasmCodegen)
            {
                _targetArchitecture = TargetArchitecture.Wasm32;
            }

            InstructionSetSupportBuilder instructionSetSupportBuilder = new InstructionSetSupportBuilder(_targetArchitecture);

            // The runtime expects certain baselines that the codegen can assume as well.
            if ((_targetArchitecture == TargetArchitecture.X86) || (_targetArchitecture == TargetArchitecture.X64))
            {
                instructionSetSupportBuilder.AddSupportedInstructionSet("sse");
                instructionSetSupportBuilder.AddSupportedInstructionSet("sse2");
            }
            else if (_targetArchitecture == TargetArchitecture.ARM64)
            {
                instructionSetSupportBuilder.AddSupportedInstructionSet("base");
                instructionSetSupportBuilder.AddSupportedInstructionSet("neon");
            }

            if (_instructionSet != null)
            {
                List <string> instructionSetParams = new List <string>();

                // Normalize instruction set format to include implied +.
                string[] instructionSetParamsInput = _instructionSet.Split(',');
                for (int i = 0; i < instructionSetParamsInput.Length; i++)
                {
                    string instructionSet = instructionSetParamsInput[i];

                    if (String.IsNullOrEmpty(instructionSet))
                    {
                        throw new CommandLineException("Instruction set must not be empty");
                    }

                    char firstChar = instructionSet[0];
                    if ((firstChar != '+') && (firstChar != '-'))
                    {
                        instructionSet = "+" + instructionSet;
                    }
                    instructionSetParams.Add(instructionSet);
                }

                Dictionary <string, bool> instructionSetSpecification = new Dictionary <string, bool>();
                foreach (string instructionSetSpecifier in instructionSetParams)
                {
                    string instructionSet = instructionSetSpecifier.Substring(1, instructionSetSpecifier.Length - 1);

                    bool enabled = instructionSetSpecifier[0] == '+' ? true : false;
                    if (enabled)
                    {
                        if (!instructionSetSupportBuilder.AddSupportedInstructionSet(instructionSet))
                        {
                            throw new CommandLineException($"Unrecognized instruction set '{instructionSet}'");
                        }
                    }
                    else
                    {
                        if (!instructionSetSupportBuilder.RemoveInstructionSetSupport(instructionSet))
                        {
                            throw new CommandLineException($"Unrecognized instruction set '{instructionSet}'");
                        }
                    }
                }
            }

            instructionSetSupportBuilder.ComputeInstructionSetFlags(out var supportedInstructionSet, out var unsupportedInstructionSet,
                                                                    (string specifiedInstructionSet, string impliedInstructionSet) =>
                                                                    throw new CommandLineException(String.Format("Unsupported combination of instruction sets: {0}/{1}", specifiedInstructionSet, impliedInstructionSet)));

            InstructionSetSupportBuilder optimisticInstructionSetSupportBuilder = new InstructionSetSupportBuilder(_targetArchitecture);

            // Optimistically assume some instruction sets are present.
            if ((_targetArchitecture == TargetArchitecture.X86) || (_targetArchitecture == TargetArchitecture.X64))
            {
                // We set these hardware features as enabled always, as most
                // of hardware in the wild supports them. Note that we do not indicate support for AVX, or any other
                // instruction set which uses the VEX encodings as the presence of those makes otherwise acceptable
                // code be unusable on hardware which does not support VEX encodings, as well as emulators that do not
                // support AVX instructions.
                //
                // The compiler is able to generate runtime IsSupported checks for the following instruction sets.
                optimisticInstructionSetSupportBuilder.AddSupportedInstructionSet("ssse3");
                optimisticInstructionSetSupportBuilder.AddSupportedInstructionSet("aes");
                optimisticInstructionSetSupportBuilder.AddSupportedInstructionSet("pclmul");
                optimisticInstructionSetSupportBuilder.AddSupportedInstructionSet("lzcnt");

                // NOTE: we don't optimistically enable SSE4.1/SSE4.2 because RyuJIT can opportunistically use
                // these instructions in e.g. optimizing Math.Round or Vector<T> operations without IsSupported guards.

                // If SSE4.2 was enabled, we can also opportunistically enable POPCNT
                Debug.Assert(InstructionSet.X64_SSE42 == InstructionSet.X86_SSE42);
                if (supportedInstructionSet.HasInstructionSet(InstructionSet.X64_SSE42))
                {
                    optimisticInstructionSetSupportBuilder.AddSupportedInstructionSet("popcnt");
                }

                // If AVX was enabled, we can opportunistically enable FMA/BMI
                Debug.Assert(InstructionSet.X64_AVX == InstructionSet.X86_AVX);
                if (supportedInstructionSet.HasInstructionSet(InstructionSet.X64_AVX))
                {
                    optimisticInstructionSetSupportBuilder.AddSupportedInstructionSet("fma");
                    optimisticInstructionSetSupportBuilder.AddSupportedInstructionSet("bmi1");
                    optimisticInstructionSetSupportBuilder.AddSupportedInstructionSet("bmi2");
                }
            }

            optimisticInstructionSetSupportBuilder.ComputeInstructionSetFlags(out var optimisticInstructionSet, out _,
                                                                              (string specifiedInstructionSet, string impliedInstructionSet) => throw new NotSupportedException());
            optimisticInstructionSet.Remove(unsupportedInstructionSet);
            optimisticInstructionSet.Add(supportedInstructionSet);

            var instructionSetSupport = new InstructionSetSupport(supportedInstructionSet,
                                                                  unsupportedInstructionSet,
                                                                  optimisticInstructionSet,
                                                                  InstructionSetSupportBuilder.GetNonSpecifiableInstructionSetsForArch(_targetArchitecture),
                                                                  _targetArchitecture);

            bool supportsReflection = !_disableReflection && _systemModuleName == DefaultSystemModule;

            //
            // Initialize type system context
            //

            SharedGenericsMode genericsMode = SharedGenericsMode.CanonicalReferenceTypes;

            var simdVectorLength = (_isCppCodegen || _isWasmCodegen) ? SimdVectorLength.None : instructionSetSupport.GetVectorTSimdVector();
            var targetAbi        = _isCppCodegen ? TargetAbi.CppCodegen : TargetAbi.CoreRT;
            var targetDetails    = new TargetDetails(_targetArchitecture, _targetOS, targetAbi, simdVectorLength);
            CompilerTypeSystemContext typeSystemContext =
                new CompilerTypeSystemContext(targetDetails, genericsMode, supportsReflection ? DelegateFeature.All : 0);

            //
            // 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> inputFilePaths = new Dictionary <string, string>();

            foreach (var inputFile in _inputFilePaths)
            {
                try
                {
                    var module = typeSystemContext.GetModuleFromPath(inputFile.Value);
                    inputFilePaths.Add(inputFile.Key, inputFile.Value);
                }
                catch (TypeSystemException.BadImageFormatException)
                {
                    // Keep calm and carry on.
                }
            }

            typeSystemContext.InputFilePaths     = inputFilePaths;
            typeSystemContext.ReferenceFilePaths = _referenceFilePaths;
            if (!typeSystemContext.InputFilePaths.ContainsKey(_systemModuleName) &&
                !typeSystemContext.ReferenceFilePaths.ContainsKey(_systemModuleName))
            {
                throw new CommandLineException($"System module {_systemModuleName} does not exists. Make sure that you specify --systemmodule");
            }

            typeSystemContext.SetSystemModule(typeSystemContext.GetModuleForSimpleName(_systemModuleName));

            if (typeSystemContext.InputFilePaths.Count == 0)
            {
                throw new CommandLineException("No input files specified");
            }

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

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

            CompilationModuleGroup          compilationGroup;
            List <ICompilationRootProvider> compilationRoots = new List <ICompilationRootProvider>();

            if (singleMethod != null)
            {
                // Compiling just a single method
                compilationGroup = new SingleMethodCompilationModuleGroup(singleMethod);
                compilationRoots.Add(new SingleMethodRootProvider(singleMethod));
            }
            else
            {
                // Either single file, or multifile library, or multifile consumption.
                EcmaModule entrypointModule          = null;
                bool       systemModuleIsInputModule = false;
                foreach (var inputFile in typeSystemContext.InputFilePaths)
                {
                    EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value);

                    if (module.PEReader.PEHeaders.IsExe)
                    {
                        if (entrypointModule != null)
                        {
                            throw new Exception("Multiple EXE modules");
                        }
                        entrypointModule = module;
                    }

                    if (module == typeSystemContext.SystemModule)
                    {
                        systemModuleIsInputModule = true;
                    }

                    compilationRoots.Add(new ExportedMethodsRootProvider(module));
                }

                if (entrypointModule != null)
                {
                    compilationRoots.Add(new MainMethodRootProvider(entrypointModule, CreateInitializerList(typeSystemContext)));
                    compilationRoots.Add(new RuntimeConfigurationRootProvider(_runtimeOptions));
                    compilationRoots.Add(new ExpectedIsaFeaturesRootProvider(instructionSetSupport));
                }

                if (_multiFile)
                {
                    List <EcmaModule> inputModules = new List <EcmaModule>();

                    foreach (var inputFile in typeSystemContext.InputFilePaths)
                    {
                        EcmaModule module = typeSystemContext.GetModuleFromPath(inputFile.Value);

                        if (entrypointModule == null)
                        {
                            // This is a multifile production build - we need to root all methods
                            compilationRoots.Add(new LibraryRootProvider(module));
                        }
                        inputModules.Add(module);
                    }

                    compilationGroup = new MultiFileSharedCompilationModuleGroup(typeSystemContext, inputModules);
                }
                else
                {
                    if (entrypointModule == null && !_nativeLib)
                    {
                        throw new Exception("No entrypoint module");
                    }

                    if (!systemModuleIsInputModule)
                    {
                        compilationRoots.Add(new ExportedMethodsRootProvider((EcmaModule)typeSystemContext.SystemModule));
                    }
                    compilationGroup = new SingleFileCompilationModuleGroup();
                }

                if (_nativeLib)
                {
                    // Set owning module of generated native library startup method to compiler generated module,
                    // to ensure the startup method is included in the object file during multimodule mode build
                    compilationRoots.Add(new NativeLibraryInitializerRootProvider(typeSystemContext.GeneratedAssembly, CreateInitializerList(typeSystemContext)));
                    compilationRoots.Add(new RuntimeConfigurationRootProvider(_runtimeOptions));
                    compilationRoots.Add(new ExpectedIsaFeaturesRootProvider(instructionSetSupport));
                }

                if (_rdXmlFilePaths.Count > 0)
                {
                    Console.WriteLine("Warning: RD.XML processing will change before release (https://github.com/dotnet/corert/issues/5001)");
                }
                foreach (var rdXmlFilePath in _rdXmlFilePaths)
                {
                    compilationRoots.Add(new RdXmlRootProvider(typeSystemContext, rdXmlFilePath));
                }
            }

            //
            // Compile
            //

            CompilationBuilder builder;

            if (_isWasmCodegen)
            {
                builder = new WebAssemblyCodegenCompilationBuilder(typeSystemContext, compilationGroup);
            }
            else if (_isCppCodegen)
            {
                builder = new CppCodegenCompilationBuilder(typeSystemContext, compilationGroup);
            }
            else
            {
                builder = new RyuJitCompilationBuilder(typeSystemContext, compilationGroup);
            }

            string compilationUnitPrefix = _multiFile ? System.IO.Path.GetFileNameWithoutExtension(_outputFilePath) : "";

            builder.UseCompilationUnitPrefix(compilationUnitPrefix);

            PInvokeILEmitterConfiguration pinvokePolicy;

            if (!_isCppCodegen && !_isWasmCodegen)
            {
                pinvokePolicy = new ConfigurablePInvokePolicy(typeSystemContext.Target);
            }
            else
            {
                pinvokePolicy = new DirectPInvokePolicy();
            }

            RemovedFeature removedFeatures = 0;

            foreach (string feature in _removedFeatures)
            {
                if (feature == "EventSource")
                {
                    removedFeatures |= RemovedFeature.Etw;
                }
                else if (feature == "FrameworkStrings")
                {
                    removedFeatures |= RemovedFeature.FrameworkResources;
                }
                else if (feature == "Globalization")
                {
                    removedFeatures |= RemovedFeature.Globalization;
                }
                else if (feature == "Comparers")
                {
                    removedFeatures |= RemovedFeature.Comparers;
                }
                else if (feature == "SerializationGuard")
                {
                    removedFeatures |= RemovedFeature.SerializationGuard;
                }
                else if (feature == "XmlNonFileStream")
                {
                    removedFeatures |= RemovedFeature.XmlDownloadNonFileStream;
                }
            }

            ILProvider ilProvider = new CoreRTILProvider();

            if (removedFeatures != 0)
            {
                ilProvider = new RemovingILProvider(ilProvider, removedFeatures);
            }

            var stackTracePolicy = _emitStackTraceData ?
                                   (StackTraceEmissionPolicy) new EcmaMethodStackTraceEmissionPolicy() : new NoStackTraceEmissionPolicy();

            MetadataBlockingPolicy              mdBlockingPolicy;
            ManifestResourceBlockingPolicy      resBlockingPolicy;
            UsageBasedMetadataGenerationOptions metadataGenerationOptions = UsageBasedMetadataGenerationOptions.IteropILScanning;

            if (supportsReflection)
            {
                mdBlockingPolicy = _noMetadataBlocking
                    ? (MetadataBlockingPolicy) new NoMetadataBlockingPolicy()
                    : new BlockedInternalsBlockingPolicy(typeSystemContext);

                resBlockingPolicy = (removedFeatures & RemovedFeature.FrameworkResources) != 0
                    ? new FrameworkStringResourceBlockingPolicy()
                    : (ManifestResourceBlockingPolicy) new NoManifestResourceBlockingPolicy();

                metadataGenerationOptions |= UsageBasedMetadataGenerationOptions.AnonymousTypeHeuristic;
                if (_completeTypesMetadata)
                {
                    metadataGenerationOptions |= UsageBasedMetadataGenerationOptions.CompleteTypesOnly;
                }
                if (_scanReflection)
                {
                    metadataGenerationOptions |= UsageBasedMetadataGenerationOptions.ReflectionILScanning;
                }
                if (_rootAllApplicationAssemblies)
                {
                    metadataGenerationOptions |= UsageBasedMetadataGenerationOptions.FullUserAssemblyRooting;
                }
            }
            else
            {
                mdBlockingPolicy  = new FullyBlockedMetadataBlockingPolicy();
                resBlockingPolicy = new FullyBlockedManifestResourceBlockingPolicy();
            }

            DynamicInvokeThunkGenerationPolicy invokeThunkGenerationPolicy = new DefaultDynamicInvokeThunkGenerationPolicy();

            MetadataManager metadataManager = new UsageBasedMetadataManager(
                compilationGroup,
                typeSystemContext,
                mdBlockingPolicy,
                resBlockingPolicy,
                _metadataLogFileName,
                stackTracePolicy,
                invokeThunkGenerationPolicy,
                ilProvider,
                metadataGenerationOptions);

            InteropStateManager interopStateManager = new InteropStateManager(typeSystemContext.GeneratedAssembly);
            InteropStubManager  interopStubManager  = new UsageBasedInteropStubManager(interopStateManager, pinvokePolicy);

            // Unless explicitly opted in at the command line, we enable scanner for retail builds by default.
            // We don't do this for CppCodegen and Wasm, because those codegens are behind.
            // We also don't do this for multifile because scanner doesn't simulate inlining (this would be
            // fixable by using a CompilationGroup for the scanner that has a bigger worldview, but
            // let's cross that bridge when we get there).
            bool useScanner = _useScanner ||
                              (_optimizationMode != OptimizationMode.None && !_isCppCodegen && !_isWasmCodegen && !_multiFile);

            useScanner &= !_noScanner;

            // Enable static data preinitialization in optimized builds.
            bool preinitStatics = _preinitStatics ||
                                  (_optimizationMode != OptimizationMode.None && !_isCppCodegen && !_multiFile);

            preinitStatics &= !_noPreinitStatics;

            var preinitManager = new PreinitializationManager(typeSystemContext, compilationGroup, ilProvider, preinitStatics);

            builder
            .UseILProvider(ilProvider)
            .UsePreinitializationManager(preinitManager);

            ILScanResults scanResults = null;

            if (useScanner)
            {
                ILScannerBuilder scannerBuilder = builder.GetILScannerBuilder()
                                                  .UseCompilationRoots(compilationRoots)
                                                  .UseMetadataManager(metadataManager)
                                                  .UseSingleThread(enable: _singleThreaded)
                                                  .UseInteropStubManager(interopStubManager);

                if (_scanDgmlLogFileName != null)
                {
                    scannerBuilder.UseDependencyTracking(_generateFullScanDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First);
                }

                IILScanner scanner = scannerBuilder.ToILScanner();

                scanResults = scanner.Scan();

                metadataManager = ((UsageBasedMetadataManager)metadataManager).ToAnalysisBasedMetadataManager();

                interopStubManager = scanResults.GetInteropStubManager(interopStateManager, pinvokePolicy);
            }

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

            DebugInformationProvider debugInfoProvider = _enableDebugInfo ?
                                                         (_ilDump == null ? new DebugInformationProvider() : new ILAssemblyGeneratingMethodDebugInfoProvider(_ilDump, new EcmaOnlyDebugInformationProvider())) :
                                                         new NullDebugInformationProvider();

            DependencyTrackingLevel trackingLevel = _dgmlLogFileName == null ?
                                                    DependencyTrackingLevel.None : (_generateFullDgmlLog ? DependencyTrackingLevel.All : DependencyTrackingLevel.First);

            compilationRoots.Add(metadataManager);
            compilationRoots.Add(interopStubManager);

            builder
            .UseInstructionSetSupport(instructionSetSupport)
            .UseBackendOptions(_codegenOptions)
            .UseMethodBodyFolding(enable: _methodBodyFolding)
            .UseSingleThread(enable: _singleThreaded)
            .UseMetadataManager(metadataManager)
            .UseInteropStubManager(interopStubManager)
            .UseLogger(logger)
            .UseDependencyTracking(trackingLevel)
            .UseCompilationRoots(compilationRoots)
            .UseOptimizationMode(_optimizationMode)
            .UseDebugInfoProvider(debugInfoProvider);

            if (scanResults != null)
            {
                // If we have a scanner, feed the vtable analysis results to the compilation.
                // This could be a command line switch if we really wanted to.
                builder.UseVTableSliceProvider(scanResults.GetVTableLayoutInfo());

                // If we have a scanner, feed the generic dictionary results to the compilation.
                // This could be a command line switch if we really wanted to.
                builder.UseGenericDictionaryLayoutProvider(scanResults.GetDictionaryLayoutInfo());

                // If we feed any outputs of the scanner into the compilation, it's essential
                // we use scanner's devirtualization manager. It prevents optimizing codegens
                // from accidentally devirtualizing cases that can never happen at runtime
                // (e.g. devirtualizing a method on a type that never gets allocated).
                builder.UseDevirtualizationManager(scanResults.GetDevirtualizationManager());
            }

            ICompilation compilation = builder.ToCompilation();

            ObjectDumper dumper = _mapFileName != null ? new ObjectDumper(_mapFileName) : null;

            CompilationResults compilationResults = compilation.Compile(_outputFilePath, dumper);

            if (_exportsFile != null)
            {
                ExportsFileWriter defFileWriter = new ExportsFileWriter(typeSystemContext, _exportsFile);
                foreach (var compilationRoot in compilationRoots)
                {
                    if (compilationRoot is ExportedMethodsRootProvider provider)
                    {
                        defFileWriter.AddExportedMethods(provider.ExportedMethods);
                    }
                }

                defFileWriter.EmitExportedMethods();
            }

            if (_dgmlLogFileName != null)
            {
                compilationResults.WriteDependencyLog(_dgmlLogFileName);
            }

            if (scanResults != null)
            {
                if (_scanDgmlLogFileName != null)
                {
                    scanResults.WriteDependencyLog(_scanDgmlLogFileName);
                }

                // If the scanner and compiler don't agree on what to compile, the outputs of the scanner might not actually be usable.
                // We are going to check this two ways:
                // 1. The methods and types generated during compilation are a subset of method and types scanned
                // 2. The methods and types scanned are a subset of methods and types compiled (this has a chance to hold for unoptimized builds only).

                // Check that methods and types generated during compilation are a subset of method and types scanned
                bool scanningFail = false;
                DiffCompilationResults(ref scanningFail, compilationResults.CompiledMethodBodies, scanResults.CompiledMethodBodies,
                                       "Methods", "compiled", "scanned", method => !(method.GetTypicalMethodDefinition() is EcmaMethod) || method.Name == "ThrowPlatformNotSupportedException" || method.Name == "ThrowArgumentOutOfRangeException");
                DiffCompilationResults(ref scanningFail, compilationResults.ConstructedEETypes, scanResults.ConstructedEETypes,
                                       "EETypes", "compiled", "scanned", type => !(type.GetTypeDefinition() is EcmaType));

                // If optimizations are enabled, the results will for sure not match in the other direction due to inlining, etc.
                // But there's at least some value in checking the scanner doesn't expand the universe too much in debug.
                if (_optimizationMode == OptimizationMode.None)
                {
                    // Check that methods and types scanned are a subset of methods and types compiled

                    // If we find diffs here, they're not critical, but still might be causing a Size on Disk regression.
                    bool dummy = false;

                    // We additionally skip methods in SIMD module because there's just too many intrisics to handle and IL scanner
                    // doesn't expand them. They would show up as noisy diffs.
                    DiffCompilationResults(ref dummy, scanResults.CompiledMethodBodies, compilationResults.CompiledMethodBodies,
                                           "Methods", "scanned", "compiled", method => !(method.GetTypicalMethodDefinition() is EcmaMethod) || method.OwningType.IsIntrinsic);
                    DiffCompilationResults(ref dummy, scanResults.ConstructedEETypes, compilationResults.ConstructedEETypes,
                                           "EETypes", "scanned", "compiled", type => !(type.GetTypeDefinition() is EcmaType));
                }

                if (scanningFail)
                {
                    throw new Exception("Scanning failure");
                }
            }

            if (debugInfoProvider is IDisposable)
            {
                ((IDisposable)debugInfoProvider).Dispose();
            }

            preinitManager.LogStatistics(logger);

            return(0);
        }
 /// <summary>
 /// Gets a value indicating whether this is a hardware intrinsic on the platform that we're compiling for.
 /// </summary>
 public static bool IsHardwareIntrinsic(MethodDesc method)
 {
     return(!string.IsNullOrEmpty(InstructionSetSupport.GetHardwareIntrinsicId(method.Context.Target.Architecture, method.OwningType)));
 }
Exemple #15
0
        private int Run()
        {
            using (PerfEventSource.StartStopEvents.CompilationEvents())
            {
                ICompilation compilation;
                using (PerfEventSource.StartStopEvents.LoadingEvents())
                {
                    InitializeDefaultOptions();

                    ProcessCommandLine();

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

                    CheckCustomPESectionAlignment();
                    ConfigureTarget();
                    InstructionSetSupport instructionSetSupport = ConfigureInstructionSetSupport();

                    //
                    // Initialize type system context
                    //

                    SharedGenericsMode genericsMode = SharedGenericsMode.CanonicalReferenceTypes;

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

                    string compositeRootPath = _commandLineOptions.CompositeRootPath?.FullName;

                    //
                    // 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)
                    {
                        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>();
                    if (_commandLineOptions.Mibc != null)
                    {
                        foreach (var file in _commandLineOptions.Mibc)
                        {
                            mibcFiles.Add(file.FullName);
                        }
                    }

                    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;
                            }
                        }
                    }

                    //
                    // 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)
                    .UseParallelism(_commandLineOptions.Parallelism)
                    .UseProfileData(profileDataManager)
                    .FileLayoutAlgorithms(_commandLineOptions.MethodLayout, _commandLineOptions.FileLayout)
                    .UseJitPath(_commandLineOptions.JitPath)
                    .UseInstructionSetSupport(instructionSetSupport)
                    .UseCustomPESectionAlignment(_commandLineOptions.CustomPESectionAlignment)
                    .UseVerifyTypeAndFieldLayout(_commandLineOptions.VerifyTypeAndFieldLayout)
                    .GenerateOutputFile(_commandLineOptions.OutputFilePath.FullName)
                    .UseILProvider(ilProvider)
                    .UseBackendOptions(_commandLineOptions.CodegenOptions)
                    .UseLogger(logger)
                    .UseDependencyTracking(trackingLevel)
                    .UseCompilationRoots(compilationRoots)
                    .UseOptimizationMode(_optimizationMode);

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

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

            return(0);
        }
Exemple #16
0
        private int Run()
        {
            InitializeDefaultOptions();

            ProcessCommandLine();

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

            //
            // Set target Architecture and OS
            //
            if (_commandLineOptions.TargetArch != null)
            {
                if (_commandLineOptions.TargetArch.Equals("x86", StringComparison.OrdinalIgnoreCase))
                {
                    _targetArchitecture = TargetArchitecture.X86;
                }
                else if (_commandLineOptions.TargetArch.Equals("x64", StringComparison.OrdinalIgnoreCase))
                {
                    _targetArchitecture = TargetArchitecture.X64;
                }
                else if (_commandLineOptions.TargetArch.Equals("arm", StringComparison.OrdinalIgnoreCase))
                {
                    _targetArchitecture = TargetArchitecture.ARM;
                }
                else if (_commandLineOptions.TargetArch.Equals("armel", StringComparison.OrdinalIgnoreCase))
                {
                    _targetArchitecture = TargetArchitecture.ARM;
                }
                else if (_commandLineOptions.TargetArch.Equals("arm64", StringComparison.OrdinalIgnoreCase))
                {
                    _targetArchitecture = TargetArchitecture.ARM64;
                }
                else
                {
                    throw new CommandLineException(SR.TargetArchitectureUnsupported);
                }
            }
            if (_commandLineOptions.TargetOS != null)
            {
                if (_commandLineOptions.TargetOS.Equals("windows", StringComparison.OrdinalIgnoreCase))
                {
                    _targetOS = TargetOS.Windows;
                }
                else if (_commandLineOptions.TargetOS.Equals("linux", StringComparison.OrdinalIgnoreCase))
                {
                    _targetOS = TargetOS.Linux;
                }
                else if (_commandLineOptions.TargetOS.Equals("osx", StringComparison.OrdinalIgnoreCase))
                {
                    _targetOS = TargetOS.OSX;
                }
                else
                {
                    throw new CommandLineException(SR.TargetOSUnsupported);
                }
            }

            InstructionSetSupportBuilder instructionSetSupportBuilder = new InstructionSetSupportBuilder(_targetArchitecture);

            // Ready to run images are built with certain instruction set baselines
            if ((_targetArchitecture == TargetArchitecture.X86) || (_targetArchitecture == TargetArchitecture.X64))
            {
                instructionSetSupportBuilder.AddSupportedInstructionSet("sse");
                instructionSetSupportBuilder.AddSupportedInstructionSet("sse2");
            }
            else if (_targetArchitecture == TargetArchitecture.ARM64)
            {
                instructionSetSupportBuilder.AddSupportedInstructionSet("base");
                instructionSetSupportBuilder.AddSupportedInstructionSet("neon");
            }


            if (_commandLineOptions.InstructionSet != null)
            {
                List <string> instructionSetParams = new List <string>();

                // At this time, instruction sets may only be specified with --input-bubble, as
                // we do not yet have a stable ABI for all vector parameter/return types.
                if (!_commandLineOptions.InputBubble)
                {
                    throw new CommandLineException(SR.InstructionSetWithoutInputBubble);
                }

                // Normalize instruction set format to include implied +.
                string[] instructionSetParamsInput = _commandLineOptions.InstructionSet.Split(",");
                for (int i = 0; i < instructionSetParamsInput.Length; i++)
                {
                    string instructionSet = instructionSetParamsInput[i];

                    if (String.IsNullOrEmpty(instructionSet))
                    {
                        throw new CommandLineException(String.Format(SR.InstructionSetMustNotBe, ""));
                    }

                    char firstChar = instructionSet[0];
                    if ((firstChar != '+') && (firstChar != '-'))
                    {
                        instructionSet = "+" + instructionSet;
                    }
                    instructionSetParams.Add(instructionSet);
                }

                Dictionary <string, bool> instructionSetSpecification = new Dictionary <string, bool>();
                foreach (string instructionSetSpecifier in instructionSetParams)
                {
                    string instructionSet = instructionSetSpecifier.Substring(1, instructionSetSpecifier.Length - 1);

                    bool enabled = instructionSetSpecifier[0] == '+' ? true : false;
                    if (enabled)
                    {
                        if (!instructionSetSupportBuilder.AddSupportedInstructionSet(instructionSet))
                        {
                            throw new CommandLineException(String.Format(SR.InstructionSetMustNotBe, instructionSet));
                        }
                    }
                    else
                    {
                        if (!instructionSetSupportBuilder.RemoveInstructionSetSupport(instructionSet))
                        {
                            throw new CommandLineException(String.Format(SR.InstructionSetMustNotBe, instructionSet));
                        }
                    }
                }
            }

            instructionSetSupportBuilder.ComputeInstructionSetFlags(out var supportedInstructionSet, out var unsupportedInstructionSet,
                                                                    (string specifiedInstructionSet, string impliedInstructionSet) =>
                                                                    throw new CommandLineException(String.Format(SR.InstructionSetInvalidImplication, specifiedInstructionSet, impliedInstructionSet)));

            InstructionSetSupportBuilder optimisticInstructionSetSupportBuilder = new InstructionSetSupportBuilder(_targetArchitecture);

            // Ready to run images are built with certain instruction sets that are optimistically assumed to be present
            if ((_targetArchitecture == TargetArchitecture.X86) || (_targetArchitecture == TargetArchitecture.X64))
            {
                // For ReadyToRun we set these hardware features as enabled always, as most
                // of hardware in the wild supports them. Note that we do not indicate support for AVX, or any other
                // instruction set which uses the VEX encodings as the presence of those makes otherwise acceptable
                // code be unusable on hardware which does not support VEX encodings, as well as emulators that do not
                // support AVX instructions. As the jit generates logic that depends on these features it will call
                // notifyInstructionSetUsage, which will result in generation of a fixup to verify the behavior of
                // code.
                //
                optimisticInstructionSetSupportBuilder.AddSupportedInstructionSet("sse");
                optimisticInstructionSetSupportBuilder.AddSupportedInstructionSet("sse2");
                optimisticInstructionSetSupportBuilder.AddSupportedInstructionSet("sse4.1");
                optimisticInstructionSetSupportBuilder.AddSupportedInstructionSet("sse4.2");
                optimisticInstructionSetSupportBuilder.AddSupportedInstructionSet("aes");
                optimisticInstructionSetSupportBuilder.AddSupportedInstructionSet("pclmul");
                optimisticInstructionSetSupportBuilder.AddSupportedInstructionSet("popcnt");
                optimisticInstructionSetSupportBuilder.AddSupportedInstructionSet("lzcnt");
            }

            optimisticInstructionSetSupportBuilder.ComputeInstructionSetFlags(out var optimisticInstructionSet, out _,
                                                                              (string specifiedInstructionSet, string impliedInstructionSet) => throw new NotSupportedException());
            optimisticInstructionSet.Remove(unsupportedInstructionSet);
            optimisticInstructionSet.Add(supportedInstructionSet);

            var instructionSetSupport = new InstructionSetSupport(supportedInstructionSet,
                                                                  unsupportedInstructionSet,
                                                                  optimisticInstructionSet,
                                                                  InstructionSetSupportBuilder.GetNonSpecifiableInstructionSetsForArch(_targetArchitecture),
                                                                  _targetArchitecture);

            using (PerfEventSource.StartStopEvents.CompilationEvents())
            {
                ICompilation compilation;
                using (PerfEventSource.StartStopEvents.LoadingEvents())
                {
                    //
                    // Initialize type system context
                    //

                    SharedGenericsMode genericsMode = SharedGenericsMode.CanonicalReferenceTypes;

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

                    //
                    // 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);
                        }
                        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);
                            }
                        }
                        catch (TypeSystemException.BadImageFormatException)
                        {
                            // Keep calm and carry on.
                        }
                    }

                    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)
                    {
                        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>();
                    if (_commandLineOptions.Mibc != null)
                    {
                        foreach (var file in _commandLineOptions.Mibc)
                        {
                            mibcFiles.Add(file.FullName);
                        }
                    }

                    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;
                            }
                        }
                    }

                    //
                    // Compile
                    //

                    ReadyToRunCodegenCompilationBuilder builder = new ReadyToRunCodegenCompilationBuilder(
                        typeSystemContext, compilationGroup, allInputFilePaths.Values);
                    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)
                    .UseParallelism(_commandLineOptions.Parallelism)
                    .UseProfileData(profileDataManager)
                    .FileLayoutAlgorithms(_commandLineOptions.MethodLayout, _commandLineOptions.FileLayout)
                    .UseJitPath(_commandLineOptions.JitPath)
                    .UseInstructionSetSupport(instructionSetSupport)
                    .GenerateOutputFile(_commandLineOptions.OutputFilePath.FullName)
                    .UseILProvider(ilProvider)
                    .UseBackendOptions(_commandLineOptions.CodegenOptions)
                    .UseLogger(logger)
                    .UseDependencyTracking(trackingLevel)
                    .UseCompilationRoots(compilationRoots)
                    .UseOptimizationMode(_optimizationMode);

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

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

            return(0);
        }
Exemple #17
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, _armelAbi ? TargetAbi.CoreRTArmel : 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>();
                    Guid?inputModuleMvid = null;

                    foreach (var inputFile in inputFilePaths)
                    {
                        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);
                    }

                    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);
                    }

                    // 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
                    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(_commandLineOptions.OutputFilePath)
                    .UseILProvider(ilProvider)
                    .UseBackendOptions(_commandLineOptions.CodegenOptions)
                    .UseLogger(logger)
                    .UseDependencyTracking(trackingLevel)
                    .UseCompilationRoots(compilationRoots)
                    .UseOptimizationMode(_optimizationMode);

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

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

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

                compilation.Dispose();
            }

            return(0);
        }
Exemple #18
0
 public static int GetRuntimeRequiredIsaFlags(InstructionSetSupport instructionSetSupport)
 {
     Debug.Assert(instructionSetSupport.Architecture == TargetArchitecture.X64 ||
                  instructionSetSupport.Architecture == TargetArchitecture.X86);
     return(XArchIntrinsicConstants.FromInstructionSetFlags(instructionSetSupport.SupportedFlags));
 }
 public ExpectedIsaFeaturesRootProvider(InstructionSetSupport isaSupport)
 {
     _isaSupport = isaSupport;
 }
 partial void InitializePartial()
 {
     _metadataManager       = new AnalysisBasedMetadataManager(_context);
     _instructionSetSupport = new InstructionSetSupport(default, default, _context.Target.Architecture);