public FSharpCompiler(IFunctionMetadataResolver metadataResolver, OptimizationLevel optimizationLevel, TraceWriter traceWriter)
 {
     _metadataResolver = metadataResolver;
     _optimizationLevel = optimizationLevel;
     _traceWriter = traceWriter;
     _hashRRegex = new Regex(@"^\s*#r\s+", RegexOptions.Compiled | RegexOptions.IgnoreCase);
 }
Example #2
0
        public CodeGenerator(
            MethodSymbol method,
            BoundStatement boundBody,
            ILBuilder builder,
            PEModuleBuilder moduleBuilder,
            DiagnosticBag diagnostics,
            OptimizationLevel optimizations,
            bool emittingPdb)
        {
            Debug.Assert((object)method != null);
            Debug.Assert(boundBody != null);
            Debug.Assert(builder != null);
            Debug.Assert(moduleBuilder != null);
            Debug.Assert(diagnostics != null);

            _method = method;
            _boundBody = boundBody;
            _builder = builder;
            _module = moduleBuilder;
            _diagnostics = diagnostics;

            if (!method.GenerateDebugInfo)
            {
                // Always optimize synthesized methods that don't contain user code.
                // 
                // Specifically, always optimize synthesized explicit interface implementation methods
                // (aka bridge methods) with by-ref returns because peverify produces errors if we
                // return a ref local (which the return local will be in such cases).
                _ilEmitStyle = ILEmitStyle.Release;
            }
            else
            {
                if (optimizations == OptimizationLevel.Debug)
                {
                    _ilEmitStyle = ILEmitStyle.Debug;
                }
                else
                {
                    _ilEmitStyle = IsDebugPlus() ? 
                        ILEmitStyle.DebugFriendlyRelease : 
                        ILEmitStyle.Release;
                }
            }

            // Emit sequence points unless
            // - the PDBs are not being generated
            // - debug information for the method is not generated since the method does not contain
            //   user code that can be stepped through, or changed during EnC.
            // 
            // This setting only affects generating PDB sequence points, it shall not affect generated IL in any way.
            _emitPdbSequencePoints = emittingPdb && method.GenerateDebugInfo;

            _boundBody = Optimizer.Optimize(
                boundBody, 
                debugFriendly: _ilEmitStyle != ILEmitStyle.Release, 
                stackLocals: out _stackLocals);

            _methodBodySyntaxOpt = (method as SourceMethodSymbol)?.BodySyntax;
        }
Example #3
0
        internal ILBuilder(ITokenDeferral module, LocalSlotManager localSlotManager, OptimizationLevel optimizations)
        {
            Debug.Assert(BitConverter.IsLittleEndian);

            this.module = module;
            this.LocalSlotManager = localSlotManager;
            _emitState = default(EmitState);
            _scopeManager = new LocalScopeManager();

            leaderBlock = _currentBlock = _scopeManager.CreateBlock(this);

            _labelInfos = new SmallDictionary<object, LabelInfo>(ReferenceEqualityComparer.Instance);
            _optimizations = optimizations;
        }
Example #4
0
        private CodeGenerator(
            MethodSymbol method,
            BoundStatement block,
            ILBuilder builder,
            PEModuleBuilder moduleBuilder,
            DiagnosticBag diagnostics,
            OptimizationLevel optimizations,
            bool emittingPdbs)
        {
            this.method = method;
            this.block = block;
            this.builder = builder;
            this.module = moduleBuilder;
            this.diagnostics = diagnostics;

            // Always optimize synthesized methods that don't contain user code.
            // 
            // Specifically, always optimize synthesized explicit interface implementation methods
            // (aka bridge methods) with by-ref returns because peverify produces errors if we
            // return a ref local (which the return local will be in such cases).

            this.optimizations = method.GenerateDebugInfo ? optimizations : OptimizationLevel.Release;

            // Emit sequence points unless
            // - the PDBs are not being generated
            // - debug information for the method is not generated since the method does not contain
            //   user code that can be stepped thru, or changed during EnC.
            // 
            // This setting only affects generating PDB sequence points, it shall not affect generated IL in any way.
            this.emitPdbSequencePoints = emittingPdbs && method.GenerateDebugInfo;

            if (this.optimizations == OptimizationLevel.Release)
            {
                this.block = Optimizer.Optimize(block, out stackLocals);
            }

            Debug.Assert((object)method != null);
            Debug.Assert(block != null);
            Debug.Assert(builder != null);
            Debug.Assert(moduleBuilder != null);

            var asSourceMethod = method as SourceMethodSymbol;
            if ((object)asSourceMethod != null)
            {
                methodBlockSyntax = asSourceMethod.BlockSyntax;
            }
        }
        public void RazorViewEngineOptionsSetup_SetsOptimizationLevel(
            string environment,
            OptimizationLevel expectedOptimizationLevel)
        {
            // Arrange
            var options = new RazorViewEngineOptions();
            var hostingEnv = new Mock<IHostingEnvironment>();
            hostingEnv.SetupGet(e => e.EnvironmentName)
                  .Returns(environment);
            var optionsSetup = new RazorViewEngineOptionsSetup(hostingEnv.Object);

            // Act
            optionsSetup.Configure(options);

            // Assert
            Assert.Equal(expectedOptimizationLevel, options.CompilationOptions.OptimizationLevel);
        }
Example #6
0
 public CSharpProject(string projectFile)
 {
     if (!File.Exists(projectFile))
         throw new Exception(string.Format("project file not found \"{0}\"", projectFile));
     WriteLine(1, "compile project \"{0}\"", projectFile);
     _projectFile = projectFile;
     _projectDirectory = Path.GetDirectoryName(projectFile);
     _projectDocument = XDocument.Load(projectFile);
     _frameworkDirectory = GetValue("FrameworkDirectory");
     WriteLine(2, "  framework directory               : \"{0}\"", _frameworkDirectory);
     _assemblyName = GetValue("AssemblyName");
     WriteLine(2, "  assembly name                     : \"{0}\"", _assemblyName);
     string outputDirectory = PathCombine(_projectDirectory, GetValue("OutputDirectory"));
     WriteLine(2, "  output directory                  : \"{0}\"", outputDirectory);
     _languageVersion = GetLanguageVersion(GetValue("LanguageVersion"));
     WriteLine(2, "  language version                  : \"{0}\"", _languageVersion);
     _outputKind = GetOutputKind(GetValue("OutputKind"));
     WriteLine(2, "  output kind                       : \"{0}\"", _outputKind);
     _optimizationLevel = GetOptimizationLevel(GetValue("OptimizationLevel"));
     WriteLine(2, "  optimization level                : \"{0}\"", _optimizationLevel);
     _platform = GetPlatform(GetValue("Platform"));
     WriteLine(2, "  platform                          : \"{0}\"", _platform);
     _generalDiagnosticOption = ReportDiagnostic.Default;
     WriteLine(2, "  general diagnostic option         : \"{0}\"", _generalDiagnosticOption);
     _warningLevel = 4;
     WriteLine(2, "  warning level                     : \"{0}\"", _warningLevel);
     _outputPath = PathCombine(outputDirectory, GetValue("OutputPath"));
     WriteLine(2, "  output path                       : \"{0}\"", _outputPath);
     _pdbPath = PathCombine(outputDirectory, GetValue("PdbPath"));
     WriteLine(2, "  pdb path                          : \"{0}\"", _pdbPath);
     _win32ResourceFile = PathCombine(_projectDirectory, GetValue("Win32ResourceFile"));
     WriteLine(2, "  win32 resource file               : \"{0}\"", _win32ResourceFile);
     _preprocessorSymbols = GetPreprocessorSymbols();
     _sourceFiles = GetSources();
     _resourceFiles = GetResourceFiles();
     _assembliesFiles = GetAssembliesFiles();
 }
        public void DoesNotThrowArgumentNullExceptionForNonNullableParameterWhenNonNullValueIsPassed(OptimizationLevel optimizationLevel)
        {
            string sourceCode = @"
                using System.Collections.Generic;

                public static class Target
                {
                    public static IEnumerable<string?> TestMethod(string? value)
                    {
                        yield return value;
                    }
                }";

            Assembly   assembly   = this.WeaveAssembly(sourceCode, optimizationLevel);
            MethodInfo testMethod = assembly.GetType("Target") !.GetMethod("TestMethod") !;

            Assert.Null(Record.Exception(() => InvokeMethod(method: testMethod, parameters: new object?[] { "test-value" })));
        }
 public CompilationOptions WithOptimizationLevel(OptimizationLevel value)
 {
     return(CommonWithOptimizationLevel(value));
 }
 public CSharpCompilationService(IFunctionMetadataResolver metadataResolver, OptimizationLevel optimizationLevel)
 {
     _metadataResolver  = metadataResolver;
     _optimizationLevel = optimizationLevel;
 }
Example #10
0
        public async Task <Transaction> CreateTransaction(string spendAddress, string transferAddress, long amount,
                                                          uint anonymity = 6, string paymentId = "", OptimizationLevel optimization = OptimizationLevel.Normal)
        {
            string o;

            switch (optimization)
            {
            case OptimizationLevel.Minimal:
                o = "minimal";
                break;

            case OptimizationLevel.Aggressive:
                o = "aggressive";
                break;

            default:
                o = string.Empty;
                break;
            }

            CreateTransactionData.Request arg = new CreateTransactionData.Request()
            {
                spend_addresses = new string[] { spendAddress },
                change_address  = spendAddress,
                optimization    = o,
                transaction     = new CreateTransactionData.Request.Transaction()
                {
                    anonymity  = anonymity,
                    payment_id = paymentId ?? string.Empty,
                    transfers  = new List <Transfer>(1)
                    {
                        new Transfer()
                        {
                            Address = transferAddress,
                            Amount  = amount
                        }
                    }
                }
            };

            RpcRequest <CreateTransactionData.Request> request = new RpcRequest <CreateTransactionData.Request>()
            {
                Method    = "create_transaction",
                Arguments = arg
            };

            RpcResponse <CreateTransactionData.Response> response = await PostAsync <RpcResponse <CreateTransactionData.Response> >(request, Uri);

            if (response.Error != null)
            {
                throw new RpcException(response.Error.Message);
            }

            Transaction res = response.Result.transaction;

            res.TransactionHex = response.Result.binary_transaction;

            return(res);
        }
        private void VerifySynthesizedDebuggableAttribute(CSharpAttributeData attribute, SourceAssemblySymbol sourceAssembly, OptimizationLevel optimizations)
        {
            var expectedDebuggingMode = DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints;

            if (optimizations == OptimizationLevel.Debug)
            {
                expectedDebuggingMode |=
                    DebuggableAttribute.DebuggingModes.Default |
                    DebuggableAttribute.DebuggingModes.DisableOptimizations |
                    DebuggableAttribute.DebuggingModes.EnableEditAndContinue;
            }

            VerifyDebuggableAttribute(attribute, sourceAssembly, expectedDebuggingMode);
        }
Example #12
0
        private bool ExecuteInner()
        {
            string rustBinPath = VisualRust.Shared.Environment.FindInstallPath(VisualRust.Shared.Environment.DefaultTarget);

            if (rustBinPath == null)
            {
                Log.LogError("No Rust installation detected. You can download official Rust installer from rust-lang.org/install.");
                return(false);
            }
            StringBuilder sb = new StringBuilder();

            if (ConfigFlags.Length > 0)
            {
                sb.AppendFormat(" --cfg {0}", String.Join(",", ConfigFlags));
            }
            if (AdditionalLibPaths.Length > 0)
            {
                sb.AppendFormat(" -L {0}", String.Join(",", AdditionalLibPaths));
            }
            if (CrateType.Length > 0)
            {
                sb.AppendFormat(" --crate-type {0}", String.Join(",", CrateType));
            }
            if (Emit.Length > 0)
            {
                sb.AppendFormat(" --emit {0}", String.Join(",", Emit));
            }
            if (!String.IsNullOrWhiteSpace(CrateName))
            {
                sb.AppendFormat(" --crate-name {0}", CrateName);
            }
            if (DebugInfo)
            {
                sb.AppendFormat(" -g");
            }
            if (OutputFile != null)
            {
                sb.AppendFormat(" -o {0}", OutputFile);
            }
            if (optimizationLevel.HasValue)
            {
                sb.AppendFormat(" -C opt-level={0}", Shared.OptimizationLevelExtension.Parse(OptimizationLevel.ToString()).ToBuildString());
            }
            if (OutputDirectory != null)
            {
                sb.AppendFormat(" --out-dir {0}", OutputDirectory);
            }
            if (test.HasValue && test.Value)
            {
                sb.Append(" --test");
            }
            if (TargetTriple != null && !String.Equals(TargetTriple, Shared.Environment.DefaultTarget, StringComparison.OrdinalIgnoreCase))
            {
                sb.AppendFormat(" --target {0}", TargetTriple);
            }
            if (LintsAsWarnings.Length > 0)
            {
                sb.AppendFormat(" -W {0}", String.Join(",", LintsAsWarnings));
            }
            if (LintsAsAllowed.Length > 0)
            {
                sb.AppendFormat(" -A {0}", String.Join(",", LintsAsAllowed));
            }
            if (LintsAsDenied.Length > 0)
            {
                sb.AppendFormat(" -D {0}", String.Join(",", LintsAsDenied));
            }
            if (LintsAsForbidden.Length > 0)
            {
                sb.AppendFormat(" -F {0}", String.Join(",", LintsAsForbidden));
            }
            if (lto.HasValue && lto.Value)
            {
                sb.AppendFormat(" -C lto");
            }
            if (CodegenOptions != null)
            {
                sb.AppendFormat(" -C {0}", CodegenOptions);
            }
            sb.AppendFormat(" {0}", Input);
            string target      = TargetTriple ?? Shared.Environment.DefaultTarget;
            string installPath = Shared.Environment.FindInstallPath(target);

            if (installPath == null)
            {
                if (String.Equals(target, Shared.Environment.DefaultTarget, StringComparison.OrdinalIgnoreCase))
                {
                    Log.LogError("Could not find a Rust installation.");
                }
                else
                {
                    Log.LogError("Could not find a Rust installation that can compile target {0}.", target);
                }
                return(false);
            }
            var psi = new ProcessStartInfo()
            {
                CreateNoWindow        = true,
                FileName              = Path.Combine(installPath, "rustc.exe"),
                UseShellExecute       = false,
                WorkingDirectory      = WorkingDirectory,
                Arguments             = sb.ToString(),
                RedirectStandardError = true
            };

            Log.LogCommandLine(String.Join(" ", psi.FileName, psi.Arguments));
            try
            {
                Process process = new Process();
                process.StartInfo = psi;
                StringBuilder error = new StringBuilder();

                using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
                {
                    process.ErrorDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            errorWaitHandle.Set();
                        }
                        else
                        {
                            error.AppendLine(e.Data);
                        }
                    };

                    process.Start();
                    process.BeginErrorReadLine();
                    process.WaitForExit();
                    errorWaitHandle.WaitOne();
                }

                string errorOutput = error.ToString();
                // We found some warning or errors in the output, print them out
                IEnumerable <RustcParsedMessage> messages = ParseOutput(errorOutput);
                // We found some warning or errors in the output, print them out
                foreach (RustcParsedMessage msg in messages)
                {
                    LogRustcMessage(msg);
                }
                // rustc failed but we couldn't sniff anything from stderr
                // this could be an internal compiler error or a missing main() function (there are probably more errors without spans)
                if (process.ExitCode != 0 && !messages.Any())
                {
                    // FIXME: This automatically sets the file to VisualRust.Rust.targets. Is there a way to set no file instead?
                    this.Log.LogError(errorOutput);
                    return(false);
                }
                return(process.ExitCode == 0);
            }
            catch (Exception ex)
            {
                Log.LogErrorFromException(ex, true);
                return(false);
            }
        }
 protected override CompilationOptions CommonWithOptimizationLevel(OptimizationLevel value)
 {
     return(WithOptimizationLevel(value));
 }
Example #14
0
 public void Optimize(IR.MethodEntry method, OptimizationLevel level)
 {
     foreach (var op in method.FlatInstructionList)
         op.IsIndexChecked = true;
 }
Example #15
0
        public void WithOptimizationLevel_SameValueTwice_DoesNotCreateNewInstance(OptimizationLevel optimizationLevel)
        {
            var options = ScriptOptions.Default.WithOptimizationLevel(optimizationLevel);

            Assert.Same(options, options.WithOptimizationLevel(optimizationLevel));
        }
Example #16
0
 /// <summary>
 /// Creates a new test context instance.
 /// </summary>
 /// <param name="optimizationLevel">The optimization level to use.</param>
 protected CPUTestContext(OptimizationLevel optimizationLevel)
     : this(optimizationLevel, _ => { })
 {
 }
Example #17
0
 public void WithOptimizationLevel_SetsOptimizationLevel(OptimizationLevel optimizationLevel)
 {
     Assert.Equal(ScriptOptions.Default.WithOptimizationLevel(optimizationLevel).OptimizationLevel, optimizationLevel);
     Assert.Equal(ScriptOptions.Default.OptimizationLevel, OptimizationLevel.Debug);
 }
 internal CompilationOptionsAdapter(OutputKind outputKind, bool reportSuppressedDiagnostics, string moduleName, string mainTypeName, string scriptClassName, string cryptoKeyContainer, string cryptoKeyFile, ImmutableArray <byte> cryptoPublicKey, bool?delaySign, bool publicSign, OptimizationLevel optimizationLevel, bool checkOverflow, Platform platform, ReportDiagnostic generalDiagnosticOption, int warningLevel, ImmutableDictionary <string, ReportDiagnostic> specificDiagnosticOptions, bool concurrentBuild, bool deterministic, DateTime currentLocalTime, bool debugPlusMode, XmlReferenceResolver xmlReferenceResolver, SourceReferenceResolver sourceReferenceResolver, MetadataReferenceResolver metadataReferenceResolver, AssemblyIdentityComparer assemblyIdentityComparer, StrongNameProvider strongNameProvider, MetadataImportOptions metadataImportOptions, bool referencesSupersedeLowerVersions)
     : base(outputKind, reportSuppressedDiagnostics, moduleName, mainTypeName, scriptClassName, cryptoKeyContainer, cryptoKeyFile, cryptoPublicKey, delaySign, publicSign, optimizationLevel, checkOverflow, platform, generalDiagnosticOption, warningLevel, specificDiagnosticOptions, concurrentBuild, deterministic, currentLocalTime, debugPlusMode, xmlReferenceResolver, sourceReferenceResolver, metadataReferenceResolver, assemblyIdentityComparer, strongNameProvider, metadataImportOptions, referencesSupersedeLowerVersions)
 {
 }
Example #19
0
        private static ContractCompilationResult Compile(IEnumerable <SyntaxTree> syntaxTrees, OptimizationLevel optimizationLevel)
        {
            CSharpCompilation compilation = CSharpCompilation.Create(
                AssemblyName,
                syntaxTrees,
                GetReferences(),
                new CSharpCompilationOptions(
                    OutputKind.DynamicallyLinkedLibrary,
                    checkOverflow: true,
                    optimizationLevel: optimizationLevel,
                    deterministic: true)
                );


            using (var dllStream = new MemoryStream())
            {
                EmitResult emitResult = compilation.Emit(dllStream);
                if (!emitResult.Success)
                {
                    return(ContractCompilationResult.Failed(emitResult.Diagnostics));
                }

                return(ContractCompilationResult.Succeeded(dllStream.ToArray()));
            }
        }
Example #20
0
 protected override CompilationOptions CommonWithOptimizationLevel(OptimizationLevel value) => WithOptimizationLevel(value);
        internal override void ValidateOptions(ArrayBuilder <Diagnostic> builder)
        {
            //  /main & /target:{library|netmodule|winmdobj}
            if (this.MainTypeName != null)
            {
                if (this.OutputKind.IsValid() && !this.OutputKind.IsApplication())
                {
                    builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_NoMainOnDLL));
                }

                if (!MainTypeName.IsValidClrTypeName())
                {
                    builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, "MainTypeName", MainTypeName));
                }
            }

            if (FileAlignment != 0 && !IsValidFileAlignment(FileAlignment))
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadFileAlignment, FileAlignment));
            }

            if (!Platform.IsValid())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadPlatformType, Platform.ToString()));
            }

            if (ModuleName != null)
            {
                Exception e = MetadataHelpers.CheckAssemblyOrModuleName(ModuleName, "ModuleName");
                if (e != null)
                {
                    builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOption, e.Message));
                }
            }

            if (!OutputKind.IsValid())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, "OutputKind", OutputKind.ToString()));
            }

            if (!OptimizationLevel.IsValid())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, "OptimizationLevel", OptimizationLevel.ToString()));
            }

            if (!SubsystemVersion.Equals(SubsystemVersion.None) && !SubsystemVersion.IsValid)
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadSubsystemVersion, SubsystemVersion.ToString()));
            }

            if (ScriptClassName == null || !ScriptClassName.IsValidClrTypeName())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, "ScriptClassName", ScriptClassName ?? "null"));
            }

            if (WarningLevel < 0 || WarningLevel > 4)
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, "WarningLevel", WarningLevel));
            }

            if (Usings != null && Usings.Any(u => !u.IsValidClrNamespaceName()))
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, "Usings", Usings.Where(u => !u.IsValidClrNamespaceName()).First() ?? "null"));
            }

            if (Platform == Platform.AnyCpu32BitPreferred && OutputKind.IsValid() && !(OutputKind == OutputKind.ConsoleApplication || OutputKind == OutputKind.WindowsApplication || OutputKind == OutputKind.WindowsRuntimeApplication))
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadPrefer32OnLib));
            }

            // TODO: add check for
            //          (kind == 'arm' || kind == 'appcontainer' || kind == 'winmdobj') &&
            //          (version >= "6.2")
        }
Example #22
0
 private static string OptimizationLevelToString(OptimizationLevel? optimizationLevel)
 {
     if(!optimizationLevel.HasValue)
         return null;
     return optimizationLevel.Value.ToBuildString();
 }
Example #23
0
 internal static bool IsValid(this OptimizationLevel value)
 {
     return(value >= OptimizationLevel.Debug && value <= OptimizationLevel.Release);
 }
        public static bool IsNamed(this SynthesizedLocalKind kind, OptimizationLevel optimizations)
        {
            if (optimizations == OptimizationLevel.Debug)
            {
                return IsLongLived(kind);
            }

            switch (kind)
            {
                // The following variables should always be named so that EE can recognize these variables by name. 
                case SynthesizedLocalKind.LambdaDisplayClass:
                    return true;

                default:
                    return false;
            }
        }
Example #25
0
        // Expects correct arguments.
        internal CompilationOptions(
            OutputKind outputKind,
            string moduleName,
            string mainTypeName,
            string scriptClassName,
            string cryptoKeyContainer,
            string cryptoKeyFile,
            bool?delaySign,
            OptimizationLevel optimizationLevel,
            bool checkOverflow,
            int fileAlignment,
            ulong baseAddress,
            Platform platform,
            ReportDiagnostic generalDiagnosticOption,
            int warningLevel,
            ImmutableDictionary <string, ReportDiagnostic> specificDiagnosticOptions,
            bool highEntropyVirtualAddressSpace,
            SubsystemVersion subsystemVersion,
            bool concurrentBuild,
            XmlReferenceResolver xmlReferenceResolver,
            SourceReferenceResolver sourceReferenceResolver,
            MetadataReferenceResolver metadataReferenceResolver,
            MetadataReferenceProvider metadataReferenceProvider,
            AssemblyIdentityComparer assemblyIdentityComparer,
            StrongNameProvider strongNameProvider,
            MetadataImportOptions metadataImportOptions,
            ImmutableArray <string> features)
        {
            this.OutputKind                     = outputKind;
            this.ModuleName                     = moduleName;
            this.MainTypeName                   = mainTypeName;
            this.ScriptClassName                = scriptClassName;
            this.CryptoKeyContainer             = cryptoKeyContainer;
            this.CryptoKeyFile                  = cryptoKeyFile;
            this.DelaySign                      = delaySign;
            this.CheckOverflow                  = checkOverflow;
            this.FileAlignment                  = fileAlignment;
            this.BaseAddress                    = baseAddress;
            this.Platform                       = platform;
            this.GeneralDiagnosticOption        = generalDiagnosticOption;
            this.WarningLevel                   = warningLevel;
            this.SpecificDiagnosticOptions      = specificDiagnosticOptions;
            this.HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace;
            this.OptimizationLevel              = optimizationLevel;
            this.ConcurrentBuild                = concurrentBuild;
            this.SubsystemVersion               = subsystemVersion;
            this.XmlReferenceResolver           = xmlReferenceResolver;
            this.SourceReferenceResolver        = sourceReferenceResolver;
            this.MetadataReferenceResolver      = metadataReferenceResolver;
            this.MetadataReferenceProvider      = metadataReferenceProvider;
            this.StrongNameProvider             = strongNameProvider;
            this.AssemblyIdentityComparer       = assemblyIdentityComparer ?? AssemblyIdentityComparer.Default;
            this.MetadataImportOptions          = metadataImportOptions;
            this.Features                       = features;

            this.lazyErrors = new Lazy <ImmutableArray <Diagnostic> >(() =>
            {
                var builder = ArrayBuilder <Diagnostic> .GetInstance();
                ValidateOptions(builder);
                return(builder.ToImmutableAndFree());
            });
        }
Example #26
0
        public static void Run(MethodSymbol method, BoundStatement block, ILBuilder builder, PEModuleBuilder moduleBuilder, DiagnosticBag diagnostics, OptimizationLevel optimizations, bool emittingPdbs,
            out int asyncCatchHandlerOffset, out ImmutableArray<int> asyncYieldPoints, out ImmutableArray<int> asyncResumePoints)
        {
            CodeGenerator generator = new CodeGenerator(method, block, builder, moduleBuilder, diagnostics, optimizations, emittingPdbs);
            generator.Generate();

            if (!diagnostics.HasAnyErrors())
            {
                builder.Realize();
            }

            asyncCatchHandlerOffset = (generator.asyncCatchHandlerOffset < 0)
                ? -1
                : generator.builder.GetILOffsetFromMarker(generator.asyncCatchHandlerOffset);

            ArrayBuilder<int> yieldPoints = generator.asyncYieldPoints;
            ArrayBuilder<int> resumePoints = generator.asyncResumePoints;
            if (yieldPoints == null)
            {
                asyncYieldPoints = ImmutableArray<int>.Empty;
                asyncResumePoints = ImmutableArray<int>.Empty;
            }
            else
            {
                var yieldPointBuilder = ArrayBuilder<int>.GetInstance();
                var resumePointBuilder = ArrayBuilder<int>.GetInstance();
                int n = yieldPoints.Count;
                for (int i = 0; i < n; i++)
                {
                    int yieldOffset = generator.builder.GetILOffsetFromMarker(yieldPoints[i]);
                    int resumeOffset = generator.builder.GetILOffsetFromMarker(resumePoints[i]);
                    Debug.Assert(resumeOffset >= 0); // resume marker should always be reachable from dispatch

                    // yield point may not be reachable if the whole 
                    // await is not reachable; we just ignore such awaits
                    if (yieldOffset > 0)
                    {
                        yieldPointBuilder.Add(yieldOffset);
                        resumePointBuilder.Add(resumeOffset);
                    }
                }

                asyncYieldPoints = yieldPointBuilder.ToImmutableAndFree();
                asyncResumePoints = resumePointBuilder.ToImmutableAndFree();
                yieldPoints.Free();
                resumePoints.Free();
            }
        }
Example #27
0
        /// <summary>
        /// Adds general backend optimizations.
        /// </summary>
        /// <param name="builder">The transformation manager to populate.</param>
        /// <param name="acceleratorSpecializer">
        /// An instance of an <see cref="AcceleratorSpecializer"/> class.
        /// </param>
        /// <param name="inliningMode">The inlining mode to use.</param>
        /// <param name="level">The desired optimization level.</param>
        public static void AddBackendOptimizations <TPlacementStrategy>(
            this Transformer.Builder builder,
            AcceleratorSpecializer acceleratorSpecializer,
            InliningMode inliningMode,
            OptimizationLevel level)
            where TPlacementStrategy : struct, CodePlacement.IPlacementStrategy
        {
            // Specialize accelerator properties, arrays and views
            builder.Add(new LowerArrays(MemoryAddressSpace.Local));
            builder.Add(new LowerPointerViews());
            builder.Add(acceleratorSpecializer);

            // Perform an additional inlining pass to specialize small device-specific
            // functions that could have been introduced
            if (inliningMode != InliningMode.Disabled)
            {
                builder.Add(new Inliner());
            }

            // Apply UCE and DCE passes to avoid dead branches and fold conditionals that
            // do not affect the actual code being executed
            builder.Add(new UnreachableCodeElimination());
            builder.Add(new DeadCodeElimination());

            // Skip further optimizations in debug mode
            if (level < OptimizationLevel.O1)
            {
                return;
            }

            // Use experimental address-space specializer in O2 only
            if (level > OptimizationLevel.O1)
            {
                // Specialize all parameter address spaces
                builder.Add(new InferKernelAddressSpaces(MemoryAddressSpace.Global));
            }

            // Lower all value structures that could have been created during the
            // following passes:
            // LowerArrays, LowerPointerViews, AcceleratorSpecializer and
            // AddressSpaceSpecializer
            builder.Add(new LowerStructures());

            // Apply UCE and DCE phases in release mode to remove all dead values and
            // branches that could be have been created in prior passes
            builder.Add(new UnreachableCodeElimination());
            builder.Add(new DeadCodeElimination());

            // Converts local memory arrays into compile-time known structures
            builder.Add(new SSAStructureConstruction());

            // Infer all specialized address spaces
            if (level > OptimizationLevel.O1)
            {
                builder.Add(new InferLocalAddressSpaces());
            }
            else
            {
                builder.Add(new InferAddressSpaces());
            }

            // Final cleanup phases to improve performance
            builder.Add(new CleanupBlocks());
            builder.Add(new SimplifyControlFlow());

            if (level > OptimizationLevel.O1)
            {
                // Add additional code placement optimizations to reduce register
                // pressure and improve performance
                builder.Add(new DeadCodeElimination());
                builder.Add(new CodePlacement <TPlacementStrategy>(
                                CodePlacementMode.Aggressive));
                builder.Add(new LoopInvariantCodeMotion());
            }
        }
Example #28
0
        internal override void ValidateOptions(ArrayBuilder <Diagnostic> builder)
        {
            ValidateOptions(builder, MessageProvider.Instance);

            //  /main & /target:{library|netmodule|winmdobj}
            if (this.MainTypeName != null)
            {
                if (this.OutputKind.IsValid() && !this.OutputKind.IsApplication())
                {
                    builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_NoMainOnDLL));
                }

                if (!MainTypeName.IsValidClrTypeName())
                {
                    builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, nameof(MainTypeName), MainTypeName));
                }
            }

            if (!Platform.IsValid())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadPlatformType, Platform.ToString()));
            }

            if (ModuleName != null)
            {
                MetadataHelpers.CheckAssemblyOrModuleName(ModuleName, MessageProvider.Instance, (int)ErrorCode.ERR_BadModuleName, builder);
            }

            if (!OutputKind.IsValid())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, nameof(OutputKind), OutputKind.ToString()));
            }

            if (!OptimizationLevel.IsValid())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, nameof(OptimizationLevel), OptimizationLevel.ToString()));
            }

            if (ScriptClassName == null || !ScriptClassName.IsValidClrTypeName())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, nameof(ScriptClassName), ScriptClassName ?? "null"));
            }

            if (WarningLevel < 0)
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, nameof(WarningLevel), WarningLevel));
            }

            if (Usings != null && Usings.Any(static u => !u.IsValidClrNamespaceName()))
Example #29
0
 public ExecuteCodeCommandOptions(string code, string workingDirectory, string[] arguments, OptimizationLevel optimizationLevel, bool noCache, string[] packageSources)
 {
     Code              = code;
     WorkingDirectory  = workingDirectory;
     Arguments         = arguments;
     OptimizationLevel = optimizationLevel;
     NoCache           = noCache;
     PackageSources    = packageSources;
 }
Example #30
0
        private bool ExecuteInner()
        {
            var useJsonErrorFormat = rustcVersion.Major >= 1 && rustcVersion.Minor >= 12;

            StringBuilder sb = new StringBuilder();

            if (ConfigFlags.Length > 0)
            {
                sb.AppendFormat(" --cfg {0}", String.Join(",", ConfigFlags));
            }
            if (AdditionalLibPaths.Length > 0)
            {
                sb.AppendFormat(" -L {0}", String.Join(",", AdditionalLibPaths));
            }
            if (CrateType.Length > 0)
            {
                sb.AppendFormat(" --crate-type {0}", String.Join(",", CrateType));
            }
            if (Emit.Length > 0)
            {
                sb.AppendFormat(" --emit {0}", String.Join(",", Emit));
            }
            if (!String.IsNullOrWhiteSpace(CrateName))
            {
                sb.AppendFormat(" --crate-name {0}", CrateName);
            }
            if (DebugInfo)
            {
                sb.AppendFormat(" -g");
            }
            if (OutputFile != null)
            {
                sb.AppendFormat(" -o {0}", OutputFile);
            }
            if (optimizationLevel.HasValue)
            {
                sb.AppendFormat(" -C opt-level={0}", Shared.OptimizationLevelExtension.Parse(OptimizationLevel.ToString()).ToBuildString());
            }
            if (OutputDirectory != null)
            {
                sb.AppendFormat(" --out-dir {0}", OutputDirectory);
            }
            if (test.HasValue && test.Value)
            {
                sb.Append(" --test");
            }
            if (TargetTriple != null && !String.Equals(TargetTriple, Shared.Environment.DefaultTarget, StringComparison.OrdinalIgnoreCase))
            {
                sb.AppendFormat(" --target {0}", TargetTriple);
            }
            if (LintsAsWarnings.Length > 0)
            {
                sb.AppendFormat(" -W {0}", String.Join(",", LintsAsWarnings));
            }
            if (LintsAsAllowed.Length > 0)
            {
                sb.AppendFormat(" -A {0}", String.Join(",", LintsAsAllowed));
            }
            if (LintsAsDenied.Length > 0)
            {
                sb.AppendFormat(" -D {0}", String.Join(",", LintsAsDenied));
            }
            if (LintsAsForbidden.Length > 0)
            {
                sb.AppendFormat(" -F {0}", String.Join(",", LintsAsForbidden));
            }
            if (lto.HasValue && lto.Value)
            {
                sb.AppendFormat(" -C lto");
            }
            if (CodegenOptions != null)
            {
                sb.AppendFormat(" -C {0}", CodegenOptions);
            }
            if (useJsonErrorFormat)
            {
                sb.Append(" --error-format=json");
            }
            sb.AppendFormat(" {0}", Input);

            var process = CreateProcess(sb.ToString());

            Log.LogCommandLine(String.Join(" ", process.StartInfo.FileName, process.StartInfo.Arguments));
            try
            {
                StringBuilder error = new StringBuilder();

                using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
                {
                    process.ErrorDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            errorWaitHandle.Set();
                        }
                        else
                        {
                            error.AppendLine(e.Data);
                        }
                    };

                    process.Start();
                    process.BeginErrorReadLine();
                    process.WaitForExit();
                    errorWaitHandle.WaitOne();
                }

                string errorOutput = error.ToString();
                // We found some warning or errors in the output, print them out
                IEnumerable <RustcMessageHuman> messagesHuman = null;
                IEnumerable <RustcMessageJson>  messageJson   = null;
                bool haveAnyMessages = false;

                if (useJsonErrorFormat)
                {
                    messageJson = RustcMessageJsonParser.Parse(errorOutput);
                    foreach (var msg in messageJson)
                    {
                        LogRustcMessage(msg, WorkingDirectory, Log);
                        haveAnyMessages = true;
                    }
                }
                else
                {
                    messagesHuman = RustcMessageHumanParser.Parse(errorOutput);
                    foreach (var msg in messagesHuman)
                    {
                        LogRustcMessage(msg);
                        haveAnyMessages = true;
                    }
                }

                // rustc failed but we couldn't sniff anything from stderr
                // this could be an internal compiler error or a missing main() function (there are probably more errors without spans)
                if (process.ExitCode != 0 && !haveAnyMessages)
                {
                    // FIXME: This automatically sets the file to VisualRust.Rust.targets. Is there a way to set no file instead?
                    this.Log.LogError(errorOutput);
                    return(false);
                }
                return(process.ExitCode == 0);
            }
            catch (Exception ex)
            {
                Log.LogErrorFromException(ex, true);
                return(false);
            }
        }
Example #31
0
 /// <summary>
 /// Creates a new test context instance.
 /// </summary>
 /// <param name="optimizationLevel">The optimization level to use.</param>
 public CudaTestContext(OptimizationLevel optimizationLevel)
     : this(optimizationLevel, null)
 {
 }
Example #32
0
        /// <summary>
        /// Converts a optimization level enum value to JSON
        /// </summary>
        /// <param name="optimizationLevel">Optimization level enum value</param>
        /// <param name="level1OptimizationOptions">Level 1 optimization options</param>
        /// <param name="level2OptimizationOptions">Level 2 optimization options</param>
        /// <returns>Optimization level in JSON format</returns>
        internal static JToken ConvertOptimizationLevelEnumValueToJson(OptimizationLevel optimizationLevel,
                                                                       Level1OptimizationOptions level1OptimizationOptions, Level2OptimizationOptions level2OptimizationOptions)
        {
            JToken optimizationLevelJson;

            if (optimizationLevel == OptimizationLevel.Zero)
            {
                optimizationLevelJson = new JValue("0");
            }
            else if (optimizationLevel == OptimizationLevel.One || optimizationLevel == OptimizationLevel.Two)
            {
                var jObj = new JObject();
                jObj.Add("1", new JObject(
                             new JProperty("cleanupCharsets", level1OptimizationOptions.CleanupCharsets),
                             new JProperty("normalizeUrls", level1OptimizationOptions.NormalizeUrls),
                             new JProperty("optimizeBackground", level1OptimizationOptions.OptimizeBackground),
                             new JProperty("optimizeBorderRadius", level1OptimizationOptions.OptimizeBorderRadius),
                             new JProperty("optimizeFilter", level1OptimizationOptions.OptimizeFilter),
                             new JProperty("optimizeFont", level1OptimizationOptions.OptimizeFont),
                             new JProperty("optimizeFontWeight", level1OptimizationOptions.OptimizeFontWeight),
                             new JProperty("optimizeOutline", level1OptimizationOptions.OptimizeOutline),
                             new JProperty("removeEmpty", level1OptimizationOptions.RemoveEmpty),
                             new JProperty("removeNegativePaddings", level1OptimizationOptions.RemoveNegativePaddings),
                             new JProperty("removeQuotes", level1OptimizationOptions.RemoveQuotes),
                             new JProperty("removeWhitespace", level1OptimizationOptions.RemoveWhitespace),
                             new JProperty("replaceMultipleZeros", level1OptimizationOptions.ReplaceMultipleZeros),
                             new JProperty("replaceTimeUnits", level1OptimizationOptions.ReplaceTimeUnits),
                             new JProperty("replaceZeroUnits", level1OptimizationOptions.ReplaceZeroUnits),
                             new JProperty("roundingPrecision",
                                           ParseRoundingPrecision(level1OptimizationOptions.RoundingPrecision)),
                             new JProperty("selectorsSortingMethod", ConvertSelectorsSortingMethodEnumValueToCode(
                                               level1OptimizationOptions.SelectorsSortingMethod)),
                             new JProperty("specialComments", level1OptimizationOptions.SpecialComments),
                             new JProperty("tidyAtRules", level1OptimizationOptions.TidyAtRules),
                             new JProperty("tidyBlockScopes", level1OptimizationOptions.TidyBlockScopes),
                             new JProperty("tidySelectors", level1OptimizationOptions.TidySelectors)
                             ));

                if (optimizationLevel == OptimizationLevel.Two)
                {
                    jObj.Add("2", new JObject(
                                 new JProperty("mergeAdjacentRules", level2OptimizationOptions.MergeAdjacentRules),
                                 new JProperty("mergeIntoShorthands", level2OptimizationOptions.MergeIntoShorthands),
                                 new JProperty("mergeMedia", level2OptimizationOptions.MergeMedia),
                                 new JProperty("mergeNonAdjacentRules", level2OptimizationOptions.MergeNonAdjacentRules),
                                 new JProperty("mergeSemantically", level2OptimizationOptions.MergeSemantically),
                                 new JProperty("overrideProperties", level2OptimizationOptions.OverrideProperties),
                                 new JProperty("removeEmpty", level2OptimizationOptions.RemoveEmpty),
                                 new JProperty("reduceNonAdjacentRules", level2OptimizationOptions.ReduceNonAdjacentRules),
                                 new JProperty("removeDuplicateFontRules", level2OptimizationOptions.RemoveDuplicateFontRules),
                                 new JProperty("removeDuplicateMediaBlocks", level2OptimizationOptions.RemoveDuplicateMediaBlocks),
                                 new JProperty("removeDuplicateRules", level2OptimizationOptions.RemoveDuplicateRules),
                                 new JProperty("removeUnusedAtRules", level2OptimizationOptions.RemoveUnusedAtRules),
                                 new JProperty("restructureRules", level2OptimizationOptions.RestructureRules),
                                 new JProperty("skipProperties", ParseSkippingProperties(level2OptimizationOptions.SkipProperties))
                                 ));
                }

                optimizationLevelJson = jObj;
            }
            else
            {
                throw new InvalidCastException(string.Format(CoreStrings.Common_EnumValueToCodeConversionFailed,
                                                             optimizationLevel.ToString(), typeof(OptimizationLevel)));
            }

            return(optimizationLevelJson);
        }
Example #33
0
 internal static CSharpCompilationOptions CreateTestOptions(OutputKind outputKind, OptimizationLevel optimizationLevel, bool allowUnsafe = false)
 => new CSharpCompilationOptions(outputKind, optimizationLevel: optimizationLevel, warningLevel: Diagnostic.MaxWarningLevel, allowUnsafe: allowUnsafe);
        internal CompilationOptions(
            OutputKind outputKind,
            bool reportSuppressedDiagnostics,
            string?moduleName,
            string?mainTypeName,
            string?scriptClassName,
            string?cryptoKeyContainer,
            string?cryptoKeyFile,
            ImmutableArray <byte> cryptoPublicKey,
            bool?delaySign,
            bool publicSign,
            OptimizationLevel optimizationLevel,
            bool checkOverflow,
            Platform platform,
            ReportDiagnostic generalDiagnosticOption,
            int warningLevel,
            ImmutableDictionary <string, ReportDiagnostic> specificDiagnosticOptions,
            bool concurrentBuild,
            bool deterministic,
            DateTime currentLocalTime,
            bool debugPlusMode,
            XmlReferenceResolver?xmlReferenceResolver,
            SourceReferenceResolver?sourceReferenceResolver,
            MetadataReferenceResolver?metadataReferenceResolver,
            AssemblyIdentityComparer?assemblyIdentityComparer,
            StrongNameProvider?strongNameProvider,
            MetadataImportOptions metadataImportOptions,
            bool referencesSupersedeLowerVersions)
        {
            this.OutputKind                       = outputKind;
            this.ModuleName                       = moduleName;
            this.MainTypeName                     = mainTypeName;
            this.ScriptClassName                  = scriptClassName ?? WellKnownMemberNames.DefaultScriptClassName;
            this.CryptoKeyContainer               = cryptoKeyContainer;
            this.CryptoKeyFile                    = string.IsNullOrEmpty(cryptoKeyFile) ? null : cryptoKeyFile;
            this.CryptoPublicKey                  = cryptoPublicKey.NullToEmpty();
            this.DelaySign                        = delaySign;
            this.CheckOverflow                    = checkOverflow;
            this.Platform                         = platform;
            this.GeneralDiagnosticOption          = generalDiagnosticOption;
            this.WarningLevel                     = warningLevel;
            this.SpecificDiagnosticOptions        = specificDiagnosticOptions;
            this.ReportSuppressedDiagnostics      = reportSuppressedDiagnostics;
            this.OptimizationLevel                = optimizationLevel;
            this.ConcurrentBuild                  = concurrentBuild;
            this.Deterministic                    = deterministic;
            this.CurrentLocalTime                 = currentLocalTime;
            this.DebugPlusMode                    = debugPlusMode;
            this.XmlReferenceResolver             = xmlReferenceResolver;
            this.SourceReferenceResolver          = sourceReferenceResolver;
            this.MetadataReferenceResolver        = metadataReferenceResolver;
            this.StrongNameProvider               = strongNameProvider;
            this.AssemblyIdentityComparer         = assemblyIdentityComparer ?? AssemblyIdentityComparer.Default;
            this.MetadataImportOptions            = metadataImportOptions;
            this.ReferencesSupersedeLowerVersions = referencesSupersedeLowerVersions;
            this.PublicSign                       = publicSign;

            _lazyErrors = new Lazy <ImmutableArray <Diagnostic> >(() =>
            {
                var builder = ArrayBuilder <Diagnostic> .GetInstance();
                ValidateOptions(builder);
                return(builder.ToImmutableAndFree());
            });
        }
        // Expects correct arguments.
        internal CompilationOptions(
            OutputKind outputKind,
            string moduleName,
            string mainTypeName,
            string scriptClassName,
            string cryptoKeyContainer,
            string cryptoKeyFile,
            bool? delaySign,
            OptimizationLevel optimizationLevel,
            bool checkOverflow,
            int fileAlignment,
            ulong baseAddress,
            Platform platform,
            ReportDiagnostic generalDiagnosticOption,
            int warningLevel,
            ImmutableDictionary<string, ReportDiagnostic> specificDiagnosticOptions,
            bool highEntropyVirtualAddressSpace,
            SubsystemVersion subsystemVersion,
            bool concurrentBuild,
            XmlReferenceResolver xmlReferenceResolver,
            SourceReferenceResolver sourceReferenceResolver,
            MetadataReferenceResolver metadataReferenceResolver,
            MetadataReferenceProvider metadataReferenceProvider,
            AssemblyIdentityComparer assemblyIdentityComparer,
            StrongNameProvider strongNameProvider,
            MetadataImportOptions metadataImportOptions,
            ImmutableArray<string> features)
        {
            this.OutputKind = outputKind;
            this.ModuleName = moduleName;
            this.MainTypeName = mainTypeName;
            this.ScriptClassName = scriptClassName;
            this.CryptoKeyContainer = cryptoKeyContainer;
            this.CryptoKeyFile = cryptoKeyFile;
            this.DelaySign = delaySign;
            this.CheckOverflow = checkOverflow;
            this.FileAlignment = fileAlignment;
            this.BaseAddress = baseAddress;
            this.Platform = platform;
            this.GeneralDiagnosticOption = generalDiagnosticOption;
            this.WarningLevel = warningLevel;
            this.SpecificDiagnosticOptions = specificDiagnosticOptions;
            this.HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace;
            this.OptimizationLevel = optimizationLevel;
            this.ConcurrentBuild = concurrentBuild;
            this.SubsystemVersion = subsystemVersion;
            this.XmlReferenceResolver = xmlReferenceResolver;
            this.SourceReferenceResolver = sourceReferenceResolver;
            this.MetadataReferenceResolver = metadataReferenceResolver;
            this.MetadataReferenceProvider = metadataReferenceProvider;
            this.StrongNameProvider = strongNameProvider;
            this.AssemblyIdentityComparer = assemblyIdentityComparer ?? AssemblyIdentityComparer.Default;
            this.MetadataImportOptions = metadataImportOptions;
            this.Features = features;

            this.lazyErrors = new Lazy<ImmutableArray<Diagnostic>>(() =>
            {
                var builder = ArrayBuilder<Diagnostic>.GetInstance();
                ValidateOptions(builder);
                return builder.ToImmutableAndFree();
            });
        }
 protected abstract CompilationOptions CommonWithOptimizationLevel(OptimizationLevel value);
Example #37
0
 public void Optimize(IR.MethodEntry method, OptimizationLevel level)
 {
     throw new InvalidOperationException("The register allocator must be invoked via the IRegisterAllocator interface instead of the IOptimizer interface");
 }
Example #38
0
        internal override void ValidateOptions(ArrayBuilder <Diagnostic> builder)
        {
            ValidateOptions(builder, MessageProvider.Instance);

            //  /main & /target:{library|netmodule|winmdobj}
            if (this.MainTypeName != null)
            {
                if (this.OutputKind.IsValid() && !this.OutputKind.IsApplication())
                {
                    builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_NoMainOnDLL));
                }

                if (!MainTypeName.IsValidClrTypeName())
                {
                    builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, nameof(MainTypeName), MainTypeName));
                }
            }

            if (!Platform.IsValid())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadPlatformType, Platform.ToString()));
            }

            if (ModuleName != null)
            {
                MetadataHelpers.CheckAssemblyOrModuleName(ModuleName, MessageProvider.Instance, (int)ErrorCode.ERR_BadModuleName, builder);
            }

            if (!OutputKind.IsValid())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, nameof(OutputKind), OutputKind.ToString()));
            }

            if (!OptimizationLevel.IsValid())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, nameof(OptimizationLevel), OptimizationLevel.ToString()));
            }

            if (ScriptClassName == null || !ScriptClassName.IsValidClrTypeName())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, nameof(ScriptClassName), ScriptClassName ?? "null"));
            }

            if (WarningLevel < 0 || WarningLevel > 4)
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, nameof(WarningLevel), WarningLevel));
            }

            if (Usings != null && Usings.Any(u => !u.IsValidClrNamespaceName()))
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, nameof(Usings), Usings.Where(u => !u.IsValidClrNamespaceName()).First() ?? "null"));
            }

            if (Platform == Platform.AnyCpu32BitPreferred && OutputKind.IsValid() && !(OutputKind == OutputKind.ConsoleApplication || OutputKind == OutputKind.WindowsApplication || OutputKind == OutputKind.WindowsRuntimeApplication))
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadPrefer32OnLib));
            }

            if (!MetadataImportOptions.IsValid())
            {
                builder.Add(Diagnostic.Create(MessageProvider.Instance, (int)ErrorCode.ERR_BadCompilationOptionValue, nameof(MetadataImportOptions), MetadataImportOptions.ToString()));
            }

            // TODO: add check for
            //          (kind == 'arm' || kind == 'appcontainer' || kind == 'winmdobj') &&
            //          (version >= "6.2")
        }
        protected void ReadCompilationOptionsFrom(
            ObjectReader reader,
            out OutputKind outputKind,
            out bool reportSuppressedDiagnostics,
            out string moduleName,
            out string mainTypeName,
            out string scriptClassName,
            out OptimizationLevel optimizationLevel,
            out bool checkOverflow,
            out string cryptoKeyContainer,
            out string cryptoKeyFile,
            out ImmutableArray<byte> cryptoPublicKey,
            out bool? delaySign,
            out Platform platform,
            out ReportDiagnostic generalDiagnosticOption,
            out int warningLevel,
            out IEnumerable<KeyValuePair<string, ReportDiagnostic>> specificDiagnosticOptions,
            out bool concurrentBuild,
            out bool deterministic,
            out bool publicSign,
            out XmlReferenceResolver xmlReferenceResolver,
            out SourceReferenceResolver sourceReferenceResolver,
            out MetadataReferenceResolver metadataReferenceResolver,
            out AssemblyIdentityComparer assemblyIdentityComparer,
            out StrongNameProvider strongNameProvider,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            outputKind = (OutputKind)reader.ReadInt32();
            reportSuppressedDiagnostics = reader.ReadBoolean();
            moduleName = reader.ReadString();
            mainTypeName = reader.ReadString();

            scriptClassName = reader.ReadString();
            optimizationLevel = (OptimizationLevel)reader.ReadInt32();
            checkOverflow = reader.ReadBoolean();

            // REVIEW: is it okay this being not part of snapshot?
            cryptoKeyContainer = reader.ReadString();
            cryptoKeyFile = reader.ReadString();

            cryptoPublicKey = reader.ReadArray<byte>().ToImmutableArrayOrEmpty();

            delaySign = reader.ReadBoolean() ? (bool?)reader.ReadBoolean() : null;

            platform = (Platform)reader.ReadInt32();
            generalDiagnosticOption = (ReportDiagnostic)reader.ReadInt32();

            warningLevel = reader.ReadInt32();

            // REVIEW: I don't think there is a guarantee on ordering of elements in the immutable dictionary.
            //         unfortunately, we need to sort them to make it deterministic
            //         not sure why CompilationOptions uses SequencialEqual to check options equality
            //         when ordering can change result of it even if contents are same.
            var count = reader.ReadInt32();
            List<KeyValuePair<string, ReportDiagnostic>> specificDiagnosticOptionsList = null;

            if (count > 0)
            {
                specificDiagnosticOptionsList = new List<KeyValuePair<string, ReportDiagnostic>>(count);

                for (var i = 0; i < count; i++)
                {
                    var key = reader.ReadString();
                    var value = (ReportDiagnostic)reader.ReadInt32();

                    specificDiagnosticOptionsList.Add(KeyValuePair.Create(key, value));
                }
            }

            specificDiagnosticOptions = specificDiagnosticOptionsList ?? SpecializedCollections.EmptyEnumerable<KeyValuePair<string, ReportDiagnostic>>();

            concurrentBuild = reader.ReadBoolean();
            deterministic = reader.ReadBoolean();
            publicSign = reader.ReadBoolean();

            // REVIEW: What should I do with these. are these service required when compilation is built ourselves, not through
            //         compiler.
            xmlReferenceResolver = XmlFileResolver.Default;
            sourceReferenceResolver = SourceFileResolver.Default;
            metadataReferenceResolver = null;
            assemblyIdentityComparer = DesktopAssemblyIdentityComparer.Default;
            strongNameProvider = new DesktopStrongNameProvider();
        }
Example #40
0
		/// <summary>
		///     Sets a param for this HLSL program.
		/// </summary>
		/// <param name="name"></param>
		/// <param name="val"></param>
		/// <returns></returns>
		public override bool SetParam( string name, string val )
		{
			bool handled = true;

			switch ( name )
			{
				case "entry_point":
					entry = val;
					break;

				case "target":
					target = val.Split( ' ' )[ 0 ];
					break;

				case "preprocessor_defines":
					preprocessorDefines = val;
					break;

				case "column_major_matrices":
					columnMajorMatrices = StringConverter.ParseBool( val );
					break;

				case "optimisation_level":
				case "optimization_level":
					optimizationLevel = (OptimizationLevel)ScriptEnumAttribute.Lookup( val, typeof( OptimizationLevel ) );
					break;

				default:
					LogManager.Instance.Write( "HLSLProgram: Unrecognized parameter '{0}'", name );
					handled = false;
					break;
			}

			return handled;
		}
Example #41
0
 /// <summary>
 /// Creates a new options instance with optimizations enabled or disabled.
 /// </summary>
 public CompilationOptions WithOptimizationLevel(OptimizationLevel value)
 {
     return CommonWithOptimizationLevel(value);
 }
        protected void ReadCompilationOptionsFrom(
            ObjectReader reader,
            out OutputKind outputKind,
            out bool reportSuppressedDiagnostics,
            out string moduleName,
            out string mainTypeName,
            out string scriptClassName,
            out OptimizationLevel optimizationLevel,
            out bool checkOverflow,
            out string cryptoKeyContainer,
            out string cryptoKeyFile,
            out ImmutableArray <byte> cryptoPublicKey,
            out bool?delaySign,
            out Platform platform,
            out ReportDiagnostic generalDiagnosticOption,
            out int warningLevel,
            out IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions,
            out bool concurrentBuild,
            out bool deterministic,
            out bool publicSign,
            out XmlReferenceResolver xmlReferenceResolver,
            out SourceReferenceResolver sourceReferenceResolver,
            out MetadataReferenceResolver metadataReferenceResolver,
            out AssemblyIdentityComparer assemblyIdentityComparer,
            out StrongNameProvider strongNameProvider,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            outputKind = (OutputKind)reader.ReadInt32();
            reportSuppressedDiagnostics = reader.ReadBoolean();
            moduleName   = reader.ReadString();
            mainTypeName = reader.ReadString();

            scriptClassName   = reader.ReadString();
            optimizationLevel = (OptimizationLevel)reader.ReadInt32();
            checkOverflow     = reader.ReadBoolean();

            // REVIEW: is it okay this being not part of snapshot?
            cryptoKeyContainer = reader.ReadString();
            cryptoKeyFile      = reader.ReadString();

            cryptoPublicKey = reader.ReadArray <byte>().ToImmutableArrayOrEmpty();

            delaySign = reader.ReadBoolean() ? (bool?)reader.ReadBoolean() : null;

            platform = (Platform)reader.ReadInt32();
            generalDiagnosticOption = (ReportDiagnostic)reader.ReadInt32();

            warningLevel = reader.ReadInt32();

            // REVIEW: I don't think there is a guarantee on ordering of elements in the immutable dictionary.
            //         unfortunately, we need to sort them to make it deterministic
            //         not sure why CompilationOptions uses SequencialEqual to check options equality
            //         when ordering can change result of it even if contents are same.
            var count = reader.ReadInt32();
            List <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptionsList = null;

            if (count > 0)
            {
                specificDiagnosticOptionsList = new List <KeyValuePair <string, ReportDiagnostic> >(count);

                for (var i = 0; i < count; i++)
                {
                    var key   = reader.ReadString();
                    var value = (ReportDiagnostic)reader.ReadInt32();

                    specificDiagnosticOptionsList.Add(KeyValuePair.Create(key, value));
                }
            }

            specificDiagnosticOptions = specificDiagnosticOptionsList ?? SpecializedCollections.EmptyEnumerable <KeyValuePair <string, ReportDiagnostic> >();

            concurrentBuild = reader.ReadBoolean();
            deterministic   = reader.ReadBoolean();
            publicSign      = reader.ReadBoolean();

            // REVIEW: What should I do with these. are these service required when compilation is built ourselves, not through
            //         compiler.
            xmlReferenceResolver      = XmlFileResolver.Default;
            sourceReferenceResolver   = SourceFileResolver.Default;
            metadataReferenceResolver = null;
            assemblyIdentityComparer  = DesktopAssemblyIdentityComparer.Default;
            strongNameProvider        = new DesktopStrongNameProvider();
        }
 public CSharpCompilationService(IFunctionMetadataResolver metadataResolver, OptimizationLevel optimizationLevel)
 {
     _metadataResolver = metadataResolver;
     _optimizationLevel = optimizationLevel;
 }
Example #44
0
 public static bool IsSlotReusable(this SynthesizedLocalKind kind, OptimizationLevel optimizations)
 {
     return kind.IsSlotReusable(optimizations != OptimizationLevel.Release);
 }
Example #45
0
        public CodeGenerator(
            MethodSymbol method,
            BoundStatement boundBody,
            ILBuilder builder,
            PEModuleBuilder moduleBuilder,
            DiagnosticBag diagnostics,
            OptimizationLevel optimizations,
            bool emittingPdb
            )
        {
            Debug.Assert((object)method != null);
            Debug.Assert(boundBody != null);
            Debug.Assert(builder != null);
            Debug.Assert(moduleBuilder != null);
            Debug.Assert(diagnostics != null);

            _method      = method;
            _boundBody   = boundBody;
            _builder     = builder;
            _module      = moduleBuilder;
            _diagnostics = diagnostics;

            if (!method.GenerateDebugInfo)
            {
                // Always optimize synthesized methods that don't contain user code.
                //
                // Specifically, always optimize synthesized explicit interface implementation methods
                // (aka bridge methods) with by-ref returns because peverify produces errors if we
                // return a ref local (which the return local will be in such cases).
                _ilEmitStyle = ILEmitStyle.Release;
            }
            else
            {
                if (optimizations == OptimizationLevel.Debug)
                {
                    _ilEmitStyle = ILEmitStyle.Debug;
                }
                else
                {
                    _ilEmitStyle = IsDebugPlus()
                      ? ILEmitStyle.DebugFriendlyRelease
                      : ILEmitStyle.Release;
                }
            }

            // Emit sequence points unless
            // - the PDBs are not being generated
            // - debug information for the method is not generated since the method does not contain
            //   user code that can be stepped through, or changed during EnC.
            //
            // This setting only affects generating PDB sequence points, it shall not affect generated IL in any way.
            _emitPdbSequencePoints = emittingPdb && method.GenerateDebugInfo;

            try
            {
                _boundBody = Optimizer.Optimize(
                    boundBody,
                    debugFriendly: _ilEmitStyle != ILEmitStyle.Release,
                    stackLocals: out _stackLocals
                    );
            }
            catch (BoundTreeVisitor.CancelledByStackGuardException ex)
            {
                ex.AddAnError(diagnostics);
                _boundBody = boundBody;
            }

            var sourceMethod = method as SourceMemberMethodSymbol;

            (BlockSyntax blockBody, ArrowExpressionClauseSyntax expressionBody) =
                sourceMethod?.Bodies ?? default;
            _methodBodySyntaxOpt =
                (SyntaxNode)blockBody ?? expressionBody ?? sourceMethod?.SyntaxNode;
        }
Example #46
0
        public static bool IsSlotReusable(this SynthesizedLocalKind kind, OptimizationLevel optimizations)
        {
            if (optimizations == OptimizationLevel.Debug)
            {
                // Don't reuse any long-lived locals in debug builds to provide good debugging experience 
                // for user-defined locals and to allow EnC.
                return !IsLongLived(kind);
            }

            switch (kind)
            {
                // The following variables should always be non-reusable, EE depends on their value.
                case SynthesizedLocalKind.UserDefined:
                case SynthesizedLocalKind.LambdaDisplayClass:
                case SynthesizedLocalKind.With:
                    return false;

                default:
                    return true;
            }
        }
Example #47
0
        /// <summary>
        /// Uses the specified optimization level when compiling the pipelines.
        /// </summary>
        /// <param name="optimizationLevel">Optimization level to use.</param>
        /// <returns>This builder.</returns>
        public BlueprintCompilationBuilder UseOptimizationLevel(OptimizationLevel optimizationLevel)
        {
            this._blueprintApiBuilder.Options.GenerationRules.OptimizationLevel = optimizationLevel;

            return(this);
        }
Example #48
0
        // Expects correct arguments.
        internal CompilationOptions(
            OutputKind outputKind,
            bool reportSuppressedDiagnostics,
            string moduleName,
            string mainTypeName,
            string scriptClassName,
            string cryptoKeyContainer,
            string cryptoKeyFile,
            ImmutableArray<byte> cryptoPublicKey,
            bool? delaySign,
            OptimizationLevel optimizationLevel,
            bool checkOverflow,
            Platform platform,
            ReportDiagnostic generalDiagnosticOption,
            int warningLevel,
            ImmutableDictionary<string, ReportDiagnostic> specificDiagnosticOptions,
            bool concurrentBuild,
            bool extendedCustomDebugInformation,
            bool debugPlusMode,
            XmlReferenceResolver xmlReferenceResolver,
            SourceReferenceResolver sourceReferenceResolver,
            MetadataReferenceResolver metadataReferenceResolver,
            AssemblyIdentityComparer assemblyIdentityComparer,
            StrongNameProvider strongNameProvider,
            MetadataImportOptions metadataImportOptions)
        {
            this.OutputKind = outputKind;
            this.ModuleName = moduleName;
            this.MainTypeName = mainTypeName;
            this.ScriptClassName = scriptClassName ?? WellKnownMemberNames.DefaultScriptClassName;
            this.CryptoKeyContainer = cryptoKeyContainer;
            this.CryptoKeyFile = cryptoKeyFile;
            this.CryptoPublicKey = cryptoPublicKey.NullToEmpty();
            this.DelaySign = delaySign;
            this.CheckOverflow = checkOverflow;
            this.Platform = platform;
            this.GeneralDiagnosticOption = generalDiagnosticOption;
            this.WarningLevel = warningLevel;
            this.SpecificDiagnosticOptions = specificDiagnosticOptions;
            this.ReportSuppressedDiagnostics = reportSuppressedDiagnostics;
            this.OptimizationLevel = optimizationLevel;
            this.ConcurrentBuild = concurrentBuild;
            this.ExtendedCustomDebugInformation = extendedCustomDebugInformation;
            this.DebugPlusMode = debugPlusMode;
            this.XmlReferenceResolver = xmlReferenceResolver;
            this.SourceReferenceResolver = sourceReferenceResolver;
            this.MetadataReferenceResolver = metadataReferenceResolver;
            this.StrongNameProvider = strongNameProvider;
            this.AssemblyIdentityComparer = assemblyIdentityComparer ?? AssemblyIdentityComparer.Default;
            this.MetadataImportOptions = metadataImportOptions;

            _lazyErrors = new Lazy<ImmutableArray<Diagnostic>>(() =>
            {
                var builder = ArrayBuilder<Diagnostic>.GetInstance();
                ValidateOptions(builder);
                return builder.ToImmutableAndFree();
            });
        }
Example #49
0
 public CPUContextProvider(OptimizationLevel optimizationLevel)
     : base(optimizationLevel)
 {
 }
Example #50
0
 protected abstract CompilationOptions CommonWithOptimizationLevel(OptimizationLevel value);
Example #51
0
 /// <summary>
 /// Create a new <see cref="ScriptOptions"/> with the specified <see cref="OptimizationLevel"/>.
 /// </summary>
 /// <returns></returns>
 public ScriptOptions WithOptimizationLevel(OptimizationLevel optimizationLevel) =>
 optimizationLevel == OptimizationLevel ? this : new ScriptOptions(this)
 {
     OptimizationLevel = optimizationLevel
 };
        private void TestDebuggableAttributeCommon(
            string source,
            Action<CSharpCompilation> validator,
            bool includeMscorlibRef,
            bool compileAndVerify,
            OutputKind outputKind,
            OptimizationLevel optimizations)
        {
            var compilation = CSharpCompilation.Create("comp",
                new[] { Parse(source) },
                includeMscorlibRef ? new[] { MscorlibRef } : null,
                new CSharpCompilationOptions(outputKind, optimizationLevel: optimizations));

            validator(compilation);

            if (compileAndVerify)
            {
                // NYI: /addmodule support
                // TODO: PEVerify currently fails for netmodules with error: "The module X was expected to contain an assembly manifest".
                // TODO: Remove the 'verify' named argument once /addmodule support has been added.
                CompileAndVerify(compilation, verify: !outputKind.IsNetModule());
            }
        }
Example #53
0
        public static void Run(MethodSymbol method, BoundStatement block, ILBuilder builder, PEModuleBuilder moduleBuilder, DiagnosticBag diagnostics, OptimizationLevel optimizations, bool emittingPdbs)
        {
            CodeGenerator generator = new CodeGenerator(method, block, builder, moduleBuilder, diagnostics, optimizations, emittingPdbs);
            generator.Generate();
            Debug.Assert(generator.asyncCatchHandlerOffset < 0);
            Debug.Assert(generator.asyncYieldPoints == null);
            Debug.Assert(generator.asyncResumePoints == null);

            if (!diagnostics.HasAnyErrors())
            {
                builder.Realize();
            }
        }