text
stringlengths
2
1.04M
meta
dict
function parseFormat(reader) { var results = new ResultNode("PSD structure"); try { var stream = new DataStream(reader); var node; if (stream.readAsciiString(4) != "8BPS") { throw "This is not a valid PSD file."; } if (stream.readUShortBe() != 1) { throw "Only version-1 PSD files are supported."; } stream.seek(6, 1); var numChannels = stream.readUShortBe(); var imgHeight = stream.readUIntBe(); var imgWidth = stream.readUIntBe(); var imgBpp = stream.readUShortBe(); var colorMode = stream.readUShortBe(); if ((imgWidth < 1) || (imgHeight < 1) || (imgWidth > 32767) || (imgHeight > 32767)) { throw "This PSD file appears to have invalid dimensions."; } results.add("Width", imgWidth); results.add("Height", imgHeight); results.add("Number of channels", numChannels); results.add("Bits per pixel", imgBpp); node = results.add("Color mode", colorMode); var colorModeLength = stream.readUIntBe(); node.add("Length", colorModeLength); var colorModePtr = stream.position; stream.seek(colorModeLength, 1); var imageResourceLength = stream.readUIntBe(); var imageResourcePtr = stream.position; node = results.add("Image resources"); psdParseImageResources(reader, node, imageResourcePtr, imageResourceLength); // explicitly go to the end of the image resource section, in case something went wrong // while parsing image resources. stream.seek(imageResourcePtr + imageResourceLength, 0); // layer and mask info var layerAndMaskLength = stream.readUIntBe(); stream.seek(layerAndMaskLength, 1); node = results.add("Layer and mask section"); node.add("Length", layerAndMaskLength.toString(16)); var compression = stream.readUShortBe(); results.add("Compression", compression); //var bmpDataId = reader.createImageData(imgWidth, imgHeight); //var bmpData = bmpDataId.data; try { } catch (e) { // give a partial image, in case of error or eof } //reader.onGetPreviewBitmap(bmpDataId); } catch (e) { console.log("Error while reading PSD: " + e); } return results; } function psdParseImageResources(reader, results, imageResourceOffset, imageResourceLength) { var resolutionInfo = {}; var displayInfo = {}; var thumbnailInfo = {}; var globalAngle; var colorCount; var transparentIndex; try { var stream = new DataStream(reader); stream.seek(imageResourceOffset, 0); while (!stream.eof() && (stream.position - imageResourceOffset) < imageResourceLength) { var imgResType = stream.readAsciiString(4); if (psdIrbDesignators.indexOf(imgResType) == -1) { break; } var imgResId = stream.readUShortBe(); var sizeOfName = stream.readByte(); if (sizeOfName > 0) { if (sizeOfName % 2 != 0) { stream.seek(1, 1); } var imgResName = stream.readAsciiString(sizeOfName); } stream.skip(1, 1); var imgResSize = stream.readUIntBe(); if (imgResSize % 2 != 0) { imgResSize++; } var node = results.add("Image resource (" + imgResType + ")", imgResId); node.add("Size of name", sizeOfName); node.add("Total size", imgResSize); if (imgResId == 1005 && imgResSize == 16) { resolutionInfo.hRes = stream.readUShortBe(); resolutionInfo.hResUnit = stream.readUIntBe(); resolutionInfo.widthUnit = stream.readUShortBe(); resolutionInfo.vRes = stream.readUShortBe(); resolutionInfo.vResUnit = stream.readUIntBe(); resolutionInfo.heightUnit = stream.readUShortBe(); } else if (imgResId == 1007 && imgResSize == 14) { displayInfo.colorSpace = stream.readUShortBe(); displayInfo.color = []; displayInfo.color[0] = stream.readUShortBe(); displayInfo.color[1] = stream.readUShortBe(); displayInfo.color[2] = stream.readUShortBe(); displayInfo.color[3] = stream.readUShortBe(); displayInfo.opacity = stream.readUShortBe(); if (displayInfo.opacity > 100) { displayInfo.opacity = 100; } var tempByte = stream.readByte(); displayInfo.kind = (tempByte != 0); stream.skip(1, 1); } else if (imgResId == 1033 || imgResId == 1036) { thumbnailInfo.position = stream.position; thumbnailInfo.format = stream.readUIntBe(); thumbnailInfo.width = stream.readUIntBe(); thumbnailInfo.height = stream.readUIntBe(); thumbnailInfo.widthBytes = stream.readUIntBe(); thumbnailInfo.size = stream.readUIntBe(); thumbnailInfo.compressedSize = stream.readUIntBe(); thumbnailInfo.bitsPerPixel = stream.readUShortBe(); thumbnailInfo.numPlanes = stream.readUShortBe(); var thumbOffset = stream.position; if (stream.reader.byteAt(thumbOffset) == 0xFF && stream.reader.byteAt(thumbOffset + 1) == 0xD8) { // very likely a JPEG thumbnail var thumbString = "data:image/png;base64," + base64FromArrayBuffer(reader.dataView.buffer, thumbOffset, thumbnailInfo.size); var thumbHtml = "<img class='previewImage' src='" + thumbString + "' />"; node.add("Thumbnail", thumbHtml); reader.onGetPreviewImage(thumbString); node.addResult(parseJpgStructure(reader, thumbOffset)); } // skip over the rest stream.skip(imgResSize - 28, 1); } else if (imgResId == 1037 && imgResSize == 4) { globalAngle = stream.readUIntBe(); } else if (imgResId == 1046 && imgResSize == 4) { colorCount = stream.readUIntBe(); } else if (imgResId == 1047 && imgResSize == 4) { transparentIndex = stream.readUIntBe(); } else { stream.seek(imgResSize, 1); } } } catch(e) { console.log("Error while reading PSD image resources: " + e); } } var psdIrbDesignators = [ "8BIM", "PHUT", "DCSR", "AgHg" ];
{ "content_hash": "54030d341de97e36a94ecebc916dd26b", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 144, "avg_line_length": 38.46590909090909, "alnum_prop": 0.5641063515509601, "repo_name": "dbrant/fileviewer", "id": "9b29406faa4793f1ec2c759606d67133b9cb2c8e", "size": "7364", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/filePsd.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2184" }, { "name": "HTML", "bytes": "11440" }, { "name": "JavaScript", "bytes": "210927" } ], "symlink_target": "" }
using System; using Lucene.Net.Util; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using IndexWriter = Lucene.Net.Index.IndexWriter; using AttributeSource = Lucene.Net.Util.AttributeSource; namespace Lucene.Net.Analysis { /// <summary> A <c>TokenStream</c> enumerates the sequence of tokens, either from /// <see cref="Field" />s of a <see cref="Document" /> or from query text. /// <p/> /// This is an abstract class. Concrete subclasses are: /// <list type="bullet"> /// <item><see cref="Tokenizer" />, a <c>TokenStream</c> whose input is a Reader; and</item> /// <item><see cref="TokenFilter" />, a <c>TokenStream</c> whose input is another /// <c>TokenStream</c>.</item> /// </list> /// A new <c>TokenStream</c> API has been introduced with Lucene 2.9. This API /// has moved from being <see cref="Token" /> based to <see cref="IAttribute" /> based. While /// <see cref="Token" /> still exists in 2.9 as a convenience class, the preferred way /// to store the information of a <see cref="Token" /> is to use <see cref="Util.Attribute" />s. /// <p/> /// <c>TokenStream</c> now extends <see cref="AttributeSource" />, which provides /// access to all of the token <see cref="IAttribute" />s for the <c>TokenStream</c>. /// Note that only one instance per <see cref="Util.Attribute" /> is created and reused /// for every token. This approach reduces object creation and allows local /// caching of references to the <see cref="Util.Attribute" />s. See /// <see cref="IncrementToken()" /> for further details. /// <p/> /// <b>The workflow of the new <c>TokenStream</c> API is as follows:</b> /// <list type="bullet"> /// <item>Instantiation of <c>TokenStream</c>/<see cref="TokenFilter" />s which add/get /// attributes to/from the <see cref="AttributeSource" />.</item> /// <item>The consumer calls <see cref="TokenStream.Reset()" />.</item> /// <item>The consumer retrieves attributes from the stream and stores local /// references to all attributes it wants to access</item> /// <item>The consumer calls <see cref="IncrementToken()" /> until it returns false and /// consumes the attributes after each call.</item> /// <item>The consumer calls <see cref="End()" /> so that any end-of-stream operations /// can be performed.</item> /// <item>The consumer calls <see cref="Close()" /> to release any resource when finished /// using the <c>TokenStream</c></item> /// </list> /// To make sure that filters and consumers know which attributes are available, /// the attributes must be added during instantiation. Filters and consumers are /// not required to check for availability of attributes in /// <see cref="IncrementToken()" />. /// <p/> /// You can find some example code for the new API in the analysis package level /// Javadoc. /// <p/> /// Sometimes it is desirable to capture a current state of a <c>TokenStream</c> /// , e. g. for buffering purposes (see <see cref="CachingTokenFilter" />, /// <see cref="TeeSinkTokenFilter" />). For this usecase /// <see cref="AttributeSource.CaptureState" /> and <see cref="AttributeSource.RestoreState" /> /// can be used. /// </summary> public abstract class TokenStream : AttributeSource, IDisposable { /// <summary> A TokenStream using the default attribute factory.</summary> protected internal TokenStream() { } /// <summary> A TokenStream that uses the same attributes as the supplied one.</summary> protected internal TokenStream(AttributeSource input) : base(input) { } /// <summary> A TokenStream using the supplied AttributeFactory for creating new <see cref="IAttribute" /> instances.</summary> protected internal TokenStream(AttributeFactory factory) : base(factory) { } /// <summary> Consumers (i.e., <see cref="IndexWriter" />) use this method to advance the stream to /// the next token. Implementing classes must implement this method and update /// the appropriate <see cref="Util.Attribute" />s with the attributes of the next /// token. /// /// The producer must make no assumptions about the attributes after the /// method has been returned: the caller may arbitrarily change it. If the /// producer needs to preserve the state for subsequent calls, it can use /// <see cref="AttributeSource.CaptureState" /> to create a copy of the current attribute state. /// /// This method is called for every token of a document, so an efficient /// implementation is crucial for good performance. To avoid calls to /// <see cref="AttributeSource.AddAttribute{T}()" /> and <see cref="AttributeSource.GetAttribute{T}()" />, /// references to all <see cref="Util.Attribute" />s that this stream uses should be /// retrieved during instantiation. /// /// To ensure that filters and consumers know which attributes are available, /// the attributes must be added during instantiation. Filters and consumers /// are not required to check for availability of attributes in /// <see cref="IncrementToken()" />. /// /// </summary> /// <returns> false for end of stream; true otherwise</returns> public abstract bool IncrementToken(); /// <summary> This method is called by the consumer after the last token has been /// consumed, after <see cref="IncrementToken" /> returned <c>false</c> /// (using the new <c>TokenStream</c> API). Streams implementing the old API /// should upgrade to use this feature. /// <p/> /// This method can be used to perform any end-of-stream operations, such as /// setting the final offset of a stream. The final offset of a stream might /// differ from the offset of the last token eg in case one or more whitespaces /// followed after the last token, but a <see cref="WhitespaceTokenizer" /> was used. /// /// </summary> /// <throws> IOException </throws> public virtual void End() { // do nothing by default } /// <summary> Resets this stream to the beginning. This is an optional operation, so /// subclasses may or may not implement this method. <see cref="Reset()" /> is not needed for /// the standard indexing process. However, if the tokens of a /// <c>TokenStream</c> are intended to be consumed more than once, it is /// necessary to implement <see cref="Reset()" />. Note that if your TokenStream /// caches tokens and feeds them back again after a reset, it is imperative /// that you clone the tokens when you store them away (on the first pass) as /// well as when you return them (on future passes after <see cref="Reset()" />). /// </summary> public virtual void Reset() { } /// <summary>Releases resources associated with this stream. </summary> [Obsolete("Use Dispose() instead")] public void Close() { Dispose(); } public void Dispose() { Dispose(true); } protected abstract void Dispose(bool disposing); } }
{ "content_hash": "c954da1aa5b54caf895787268ad2e867", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 135, "avg_line_length": 51.29931972789116, "alnum_prop": 0.6316138443177297, "repo_name": "joshball/Lucene.In.Action.NET", "id": "4a446093a3fc7a056e222ad3c1d02c3cd93a8474", "size": "8341", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/lucene.net/src/core/Analysis/TokenStream.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "57388" } ], "symlink_target": "" }
<!-- title: frappe.desk.form.utils --><div class="dev-header"> <a class="btn btn-default btn-sm" disabled style="margin-bottom: 10px;"> Version 6.7.7</a> <a class="btn btn-default btn-sm" href="https://github.com/frappe/frappe/blob/develop/frappe/desk/form/utils.py" target="_blank" style="margin-left: 10px; margin-bottom: 10px;"><i class="octicon octicon-mark-github"></i> Source</a> </div> <p><span class="label label-info">Public API</span> <br><code>/api/method/frappe.desk.form.utils.add_comment</code> </p> <p class="docs-attr-name"> <a name="frappe.desk.form.utils.add_comment" href="#frappe.desk.form.utils.add_comment" class="text-muted small"> <i class="icon-link small" style="color: #ccc;"></i></a> frappe.desk.form.utils.<b>add_comment</b> <i class="text-muted">(doc)</i> </p> <div class="docs-attr-desc"><p>allow any logged user to post a comment</p> </div> <br> <p><span class="label label-info">Public API</span> <br><code>/api/method/frappe.desk.form.utils.get_fields</code> </p> <p class="docs-attr-name"> <a name="frappe.desk.form.utils.get_fields" href="#frappe.desk.form.utils.get_fields" class="text-muted small"> <i class="icon-link small" style="color: #ccc;"></i></a> frappe.desk.form.utils.<b>get_fields</b> <i class="text-muted">()</i> </p> <div class="docs-attr-desc"><p>get fields</p> </div> <br> <p><span class="label label-info">Public API</span> <br><code>/api/method/frappe.desk.form.utils.get_next</code> </p> <p class="docs-attr-name"> <a name="frappe.desk.form.utils.get_next" href="#frappe.desk.form.utils.get_next" class="text-muted small"> <i class="icon-link small" style="color: #ccc;"></i></a> frappe.desk.form.utils.<b>get_next</b> <i class="text-muted">(doctype, value, prev, filters=None, order_by=modified desc)</i> </p> <div class="docs-attr-desc"><p><span class="text-muted">No docs</span></p> </div> <br> <p><span class="label label-info">Public API</span> <br><code>/api/method/frappe.desk.form.utils.remove_attach</code> </p> <p class="docs-attr-name"> <a name="frappe.desk.form.utils.remove_attach" href="#frappe.desk.form.utils.remove_attach" class="text-muted small"> <i class="icon-link small" style="color: #ccc;"></i></a> frappe.desk.form.utils.<b>remove_attach</b> <i class="text-muted">()</i> </p> <div class="docs-attr-desc"><p>remove attachment</p> </div> <br> <p><span class="label label-info">Public API</span> <br><code>/api/method/frappe.desk.form.utils.validate_link</code> </p> <p class="docs-attr-name"> <a name="frappe.desk.form.utils.validate_link" href="#frappe.desk.form.utils.validate_link" class="text-muted small"> <i class="icon-link small" style="color: #ccc;"></i></a> frappe.desk.form.utils.<b>validate_link</b> <i class="text-muted">()</i> </p> <div class="docs-attr-desc"><p>validate link when updated by user</p> </div> <br> <!-- autodoc -->
{ "content_hash": "28a72fe4dae0d70ec0f2c245a7334eb2", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 125, "avg_line_length": 29.666666666666668, "alnum_prop": 0.6064294631710362, "repo_name": "sbktechnology/trufil-frappe", "id": "d486930c2499475692b6b15c9877c6d5362d2255", "size": "3204", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "frappe/docs/current/api/desk/form/frappe.desk.form.utils.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "270764" }, { "name": "HTML", "bytes": "1311954" }, { "name": "JavaScript", "bytes": "1086006" }, { "name": "Python", "bytes": "1218825" }, { "name": "Shell", "bytes": "517" } ], "symlink_target": "" }
import pathlib import ezdxf from ezdxf import colors from ezdxf.gfxattribs import GfxAttribs from ezdxf.render import forms CWD = pathlib.Path("~/Desktop/Outbox").expanduser() if not CWD.exists(): CWD = pathlib.Path(".") # ------------------------------------------------------------------------------ # This example shows how to use MeshTransformer class. # # docs: https://ezdxf.mozman.at/docs/render/mesh.html#meshtransformer # ------------------------------------------------------------------------------ def main(): # cube and cylinder are MeshTransformer instances: cube = forms.cube().scale_uniform(10).subdivide(2) cylinder = forms.cylinder(12, radius=5, top_center=(0, 0, 10)).translate( 0, 20 ) doc = ezdxf.new() msp = doc.modelspace() red = GfxAttribs(color=colors.RED) green = GfxAttribs(color=colors.GREEN) blue = GfxAttribs(color=colors.BLUE) # render the cube as MESH entity: cube.render_mesh(msp, dxfattribs=red) # translate the cube: cube.translate(20) # render the cube as POLYFACE entity, a POLYLINE entity in reality: cube.render_polyface(msp, dxfattribs=green) # translate the cube: cube.translate(20) # render the cube as 3DFACE entities: cube.render_3dfaces(msp, dxfattribs=blue) # render the cylinder as MESH entity: cylinder.render_mesh(msp, dxfattribs=red) # translate the cylinder: cylinder.translate(20) # render the cylinder as POLYFACE entity, a POLYLINE entity in reality: cylinder.render_polyface(msp, dxfattribs=green) # translate the cylinder: cylinder.translate(20) # render the cube as 3DFACE entities: cylinder.render_3dfaces(msp, dxfattribs=blue) doc.set_modelspace_vport(30, center=(30, 20)) doc.saveas(CWD / "meshes.dxf") if __name__ == "__main__": main()
{ "content_hash": "f9c3fb8c57993cd5d8de2fdf28185264", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 80, "avg_line_length": 27.70149253731343, "alnum_prop": 0.6287715517241379, "repo_name": "mozman/ezdxf", "id": "79d08eae99c29f37c3518df6d3c90570679d093e", "size": "1921", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/render/mesh_transformer.py", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "5745" }, { "name": "CSS", "bytes": "3565" }, { "name": "Common Lisp", "bytes": "727" }, { "name": "Cython", "bytes": "111923" }, { "name": "HTML", "bytes": "1417" }, { "name": "JavaScript", "bytes": "11132" }, { "name": "Python", "bytes": "6336553" } ], "symlink_target": "" }
require 'spec_helper' RSpec.describe 'Jubi integration specs' do let(:client) { Cryptoexchange::Client.new } let(:eth_cny_pair) { Cryptoexchange::Models::MarketPair.new(base: 'ETH', target: 'CNY', market: 'jubi') } it 'fetch pairs' do pairs = client.pairs('jubi') expect(pairs).not_to be_empty pair = pairs.first expect(pair.base).to_not be nil expect(pair.target).to_not be nil expect(pair.market).to eq 'jubi' end it 'fetch ticker' do pending ":error=> jubi's service is temporarily unavailable." ticker = client.ticker(eth_cny_pair) expect(ticker.base).to eq 'ETH' expect(ticker.target).to eq 'CNY' expect(ticker.market).to eq 'jubi' expect(ticker.last).to be_a Numeric expect(ticker.bid).to be_a Numeric expect(ticker.ask).to be_a Numeric expect(ticker.high).to be_a Numeric expect(ticker.volume).to be_a Numeric expect(ticker.timestamp).to be nil expect(ticker.payload).to_not be nil end end
{ "content_hash": "08b8fbf934b2e77c9b70ecd3adc2088d", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 107, "avg_line_length": 29.176470588235293, "alnum_prop": 0.6774193548387096, "repo_name": "coingecko/cryptoexchange", "id": "31f5a7a1cb43a09a7343aa42563d80f2ee738318", "size": "992", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/exchanges/jubi/integration/market_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "3283949" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
module RestfulSync module ApplicationHelper end end
{ "content_hash": "7f32ce55c50e4f6619f72878f9e9af1d", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 26, "avg_line_length": 11.4, "alnum_prop": 0.8070175438596491, "repo_name": "vala/restful_sync", "id": "14c5e66db103cd95a312473e3b8df72010f50927", "size": "57", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/helpers/restful_sync/application_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1576" }, { "name": "Ruby", "bytes": "56878" } ], "symlink_target": "" }
""" Utility that imports a function. """ # Future from __future__ import absolute_import, division, print_function, \ unicode_literals, with_statement def import_function(function): """Imports function given by qualified package name""" function = __import__(function, globals(), locals(), ['function'], 0).f # function = getattr(__import__(function["module"], globals(), locals(), ['function'], 0), function["name"]) TODO # Note that the following is equivalent: # from MyPackage.MyModule import f as function # Also note this always imports the function "f" as "function". return function
{ "content_hash": "6a441e04057187990bb303bd8c1ae532", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 117, "avg_line_length": 37.05882352941177, "alnum_prop": 0.6793650793650794, "repo_name": "cigroup-ol/metaopt", "id": "a4079b30827e9cff3c9775a894a951b5fdd022e9", "size": "654", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "metaopt/concurrent/worker/util/import_function.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "4967" }, { "name": "JavaScript", "bytes": "3271" }, { "name": "Makefile", "bytes": "4738" }, { "name": "Python", "bytes": "226232" } ], "symlink_target": "" }
package org.javersion.object.mapping; import static org.javersion.object.types.StringValueType.STRING; import org.javersion.object.DescribeContext; import org.javersion.object.TypeContext; import org.javersion.object.types.ValueType; import org.javersion.path.PropertyPath; import org.javersion.reflect.TypeDescriptor; public class StringTypeMapping implements TypeMapping { @Override public boolean applies(PropertyPath path, TypeContext typeContext) { return typeContext.type.getRawType().equals(String.class); } @Override public ValueType describe(PropertyPath path, TypeDescriptor type, DescribeContext context) { return STRING; } }
{ "content_hash": "6888f1e01980da3fa33aeea2e305b5b3", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 96, "avg_line_length": 28.458333333333332, "alnum_prop": 0.7833089311859444, "repo_name": "ssaarela/javersion", "id": "69208a1f02ac076f811fe46f1eb336514f01651b", "size": "1278", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "javersion-object/src/main/java/org/javersion/object/mapping/StringTypeMapping.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "2192" }, { "name": "CSS", "bytes": "4554" }, { "name": "Java", "bytes": "1054784" }, { "name": "JavaScript", "bytes": "377508" }, { "name": "Shell", "bytes": "1130" } ], "symlink_target": "" }
"""This module contains common helper functions.""" from __future__ import unicode_literals import base64 import os import platform import random import shlex import string import subprocess from creds.constants import (CMD_SUDO, RANDOM_FILE_EXT_LENGTH, LINUX_CMD_GROUP_ADD, LINUX_CMD_GROUP_DEL, LINUX_CMD_USERADD, LINUX_CMD_USERDEL, LINUX_CMD_USERMOD, FREEBSD_CMD_PW, LINUX_CMD_VISUDO) from external.six import (PY2, PY3, text_type) def sudo_check(): """Return the string 'sudo' if current user isn't root.""" sudo_cmd = '' if os.geteuid() != 0: sudo_cmd = CMD_SUDO return sudo_cmd def get_platform(): """Return platform name""" return platform.system() def get_missing_commands(_platform): """Check I can identify the necessary commands for managing users.""" missing = list() if _platform in ('Linux', 'OpenBSD'): if not LINUX_CMD_USERADD: missing.append('useradd') if not LINUX_CMD_USERMOD: missing.append('usermod') if not LINUX_CMD_USERDEL: missing.append('userdel') if not LINUX_CMD_GROUP_ADD: missing.append('groupadd') if not LINUX_CMD_GROUP_DEL: missing.append('groupdel') elif _platform == 'FreeBSD': # pragma: FreeBSD # FREEBSD COMMANDS if not FREEBSD_CMD_PW: missing.append('pw') if missing: print('\nMISSING = {0}'.format(missing)) return missing def execute_command(command=None): """Execute a command and return the stdout and stderr.""" process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stdin = process.communicate() process.wait() return (stdout, stdin), process.returncode def random_string(length=None): """Generate a random string of ASCII characters.""" return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(length)) def base64encode(_input=None): """Return base64 encoded representation of a string.""" if PY2: # pragma: no cover return base64.b64encode(_input) elif PY3: # pragma: no cover if isinstance(_input, bytes): return base64.b64encode(_input).decode('UTF-8') elif isinstance(_input, str): return base64.b64encode(bytearray(_input, encoding='UTF-8')).decode('UTF-8') def base64decode(_input=None): """Take a base64 encoded string and return the decoded string.""" missing_padding = 4 - len(_input) % 4 if missing_padding: _input += '=' * missing_padding if PY2: # pragma: no cover return base64.decodestring(_input) elif PY3: # pragma: no cover if isinstance(_input, bytes): return base64.b64decode(_input).decode('UTF-8') elif isinstance(_input, str): return base64.b64decode(bytearray(_input, encoding='UTF-8')).decode('UTF-8') def read_sudoers(): """ Read the sudoers entry for the specified user. args: username (str): username. returns:`r str: sudoers entry for the specified user. """ sudoers_path = '/etc/sudoers' rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH) tmp_sudoers_path = '/tmp/sudoers_{0}'.format(rnd_chars) sudoers_entries = list() copy_result = execute_command( shlex.split(str('{0} cp {1} {2}'.format(sudo_check(), sudoers_path, tmp_sudoers_path)))) result_message = copy_result[0][1].decode('UTF-8') if 'No such file or directory' not in result_message: execute_command(shlex.split(str('{0} chmod 755 {1}'.format(sudo_check(), tmp_sudoers_path)))) with open(tmp_sudoers_path) as tmp_sudoers_file: for line in tmp_sudoers_file: stripped = line.strip().replace(os.linesep, '') if stripped and not stripped.startswith('#'): sudoers_entries.append(stripped) execute_command(shlex.split(str('{0} rm {1}'.format(sudo_check(), tmp_sudoers_path)))) return sudoers_entries def write_sudoers_entry(username=None, sudoers_entry=None): """Write sudoers entry. args: user (User): Instance of User containing sudoers entry. returns: str: sudoers entry for the specified user. """ sudoers_path = '/etc/sudoers' rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH) tmp_sudoers_path = '/tmp/sudoers_{0}'.format(rnd_chars) execute_command( shlex.split(str('{0} cp {1} {2}'.format(sudo_check(), sudoers_path, tmp_sudoers_path)))) execute_command( shlex.split(str('{0} chmod 777 {1}'.format(sudo_check(), tmp_sudoers_path)))) with open(tmp_sudoers_path, mode=text_type('r')) as tmp_sudoers_file: sudoers_entries = tmp_sudoers_file.readlines() sudoers_output = list() for entry in sudoers_entries: if entry and not entry.startswith(username): sudoers_output.append(entry) if sudoers_entry: sudoers_output.append('{0} {1}'.format(username, sudoers_entry)) sudoers_output.append('\n') with open(tmp_sudoers_path, mode=text_type('w+')) as tmp_sudoers_file: tmp_sudoers_file.writelines(sudoers_output) sudoers_check_result = execute_command( shlex.split(str('{0} {1} -cf {2}'.format(sudo_check(), LINUX_CMD_VISUDO, tmp_sudoers_path)))) if sudoers_check_result[1] > 0: raise ValueError(sudoers_check_result[0][1]) execute_command( shlex.split(str('{0} cp {1} {2}'.format(sudo_check(), tmp_sudoers_path, sudoers_path)))) execute_command(shlex.split(str('{0} chown root:root {1}'.format(sudo_check(), sudoers_path)))) execute_command(shlex.split(str('{0} chmod 440 {1}'.format(sudo_check(), sudoers_path)))) execute_command(shlex.split(str('{0} rm {1}'.format(sudo_check(), tmp_sudoers_path)))) def remove_sudoers_entry(username=None): """Remove sudoers entry. args: user (User): Instance of User containing sudoers entry. returns: str: sudoers entry for the specified user. """ sudoers_path = '/etc/sudoers' rnd_chars = random_string(length=RANDOM_FILE_EXT_LENGTH) tmp_sudoers_path = '/tmp/sudoers_{0}'.format(rnd_chars) execute_command( shlex.split(str('{0} cp {1} {2}'.format(sudo_check(), sudoers_path, tmp_sudoers_path)))) execute_command( shlex.split(str('{0} chmod 777 {1}'.format(sudo_check(), tmp_sudoers_path)))) with open(tmp_sudoers_path, mode=text_type('r')) as tmp_sudoers_file: sudoers_entries = tmp_sudoers_file.readlines() sudoers_output = list() for entry in sudoers_entries: if not entry.startswith(username): sudoers_output.append(entry) with open(tmp_sudoers_path, mode=text_type('w+')) as tmp_sudoers_file: tmp_sudoers_file.writelines(sudoers_output) execute_command( shlex.split(str('{0} cp {1} {2}'.format(sudo_check(), tmp_sudoers_path, sudoers_path)))) execute_command(shlex.split(str('{0} chown root:root {1}'.format(sudo_check(), sudoers_path)))) execute_command(shlex.split(str('{0} chmod 440 {1}'.format(sudo_check(), sudoers_path)))) execute_command(shlex.split(str('{0} rm {1}'.format(sudo_check(), tmp_sudoers_path)))) def get_sudoers_entry(username=None, sudoers_entries=None): """ Find the sudoers entry in the sudoers file for the specified user. args: username (str): username. sudoers_entries (list): list of lines from the sudoers file. returns:`r str: sudoers entry for the specified user. """ for entry in sudoers_entries: if entry.startswith(username): return entry.replace(username, '').strip()
{ "content_hash": "e1e76ac60c3dcb966f7b346aaaa0282e", "timestamp": "", "source": "github", "line_count": 202, "max_line_length": 119, "avg_line_length": 38.42574257425743, "alnum_prop": 0.6415872197887142, "repo_name": "jonhadfield/creds", "id": "a06a2d317d36947f8684f6ad3aca3518dcf84155", "size": "7786", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/creds/utils.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "82259" } ], "symlink_target": "" }
package fr.leomoldo.android.bunkerwar.activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.SoundPool; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import fr.leomoldo.android.bunkerwar.BombshellAnimatorAsyncTask; import fr.leomoldo.android.bunkerwar.BuildConfig; import fr.leomoldo.android.bunkerwar.R; /** * Created by leomoldo on 08/06/2016. */ public class MainActivity extends AppCompatActivity implements AudioManager.OnAudioFocusChangeListener, SeekBar.OnSeekBarChangeListener { private final static String LOG_TAG = MainActivity.class.getSimpleName(); private final static float SOUNDTRACK_VOLUME = 1.0f; private final static float SOUNDTRACK_DUCKING_VOLUME = 0.5f; private final static float SOUND_EFFECTS_BUTTONS_VOLUME = 0.15f; // Audio : private MediaPlayer mMediaPlayerSoundtrack; private boolean mShouldPlaySoundtrack; private SoundPool mSoundPool; private int mSoundIdButtonHigh; private int mSoundIdButtonLow; // Views : private LinearLayout mLinearLayoutButtons; private RelativeLayout mRelativeLayoutSettings; private RelativeLayout mRelativeLayoutCredits; private CheckBox mCheckBoxSettingsWindChange; private SeekBar mSeekBarSettingsGameSpeed; private TextView mTextViewSettingsGameSpeed; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Retrieve and initialize useful views. mLinearLayoutButtons = (LinearLayout) findViewById(R.id.linearLayoutButtons); mRelativeLayoutSettings = (RelativeLayout) findViewById(R.id.relativeLayoutSettings); mRelativeLayoutCredits = (RelativeLayout) findViewById(R.id.relativeLayoutCredits); mCheckBoxSettingsWindChange = (CheckBox) findViewById(R.id.checkBoxSettingsWindChange); mSeekBarSettingsGameSpeed = (SeekBar) findViewById(R.id.seekBarSettingsGameSpeed); mSeekBarSettingsGameSpeed.setMax(BombshellAnimatorAsyncTask.MAX_GAME_SPEED); mSeekBarSettingsGameSpeed.setOnSeekBarChangeListener(this); mTextViewSettingsGameSpeed = (TextView) findViewById(R.id.textViewSettingsGameSpeed); // Retrieve SharedPreferences. SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.shared_preferences_name), Context.MODE_PRIVATE); int gameSpeedValue = sharedPreferences.getInt(getString(R.string.shared_preferences_key_game_speed), BombshellAnimatorAsyncTask.DEFAULT_GAME_SPEED); boolean shouldChangeWindAtEveryTurn = sharedPreferences.getBoolean(getString(R.string.shared_preferences_key_wind_change), true); mCheckBoxSettingsWindChange.setChecked(shouldChangeWindAtEveryTurn); mSeekBarSettingsGameSpeed.setProgress(gameSpeedValue); mTextViewSettingsGameSpeed.setText(String.valueOf(gameSpeedValue)); // Display app version on the credits screen. TextView textViewAppVersion = (TextView) findViewById(R.id.textViewCreditsAppVersion); String appVersionString = " " + getString(R.string.credits_app_version) + BuildConfig.VERSION_NAME; textViewAppVersion.setText(appVersionString); } @Override protected void onStart() { super.onStart(); mShouldPlaySoundtrack = true; AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { startPlayingSoundtrack(); } if (android.os.Build.VERSION.SDK_INT < 21) { mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); } else { SoundPool.Builder builder = new SoundPool.Builder(); mSoundPool = builder.build(); } mSoundIdButtonHigh = mSoundPool.load(this, R.raw.button_high, 1); mSoundIdButtonLow = mSoundPool.load(this, R.raw.button_low, 1); } @Override protected void onStop() { stopPlayingSoundtrack(); mShouldPlaySoundtrack = false; mSoundPool.release(); mSoundPool = null; super.onStop(); } @Override protected void onDestroy() { if (mMediaPlayerSoundtrack != null) { mMediaPlayerSoundtrack.reset(); mMediaPlayerSoundtrack.release(); mMediaPlayerSoundtrack = null; } super.onDestroy(); } public void onAudioFocusChange(int focusChange) { switch (focusChange) { case AudioManager.AUDIOFOCUS_GAIN: if (mShouldPlaySoundtrack) { startPlayingSoundtrack(); mMediaPlayerSoundtrack.setVolume(SOUNDTRACK_VOLUME, SOUNDTRACK_VOLUME); } break; case AudioManager.AUDIOFOCUS_LOSS: stopPlayingSoundtrack(); break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: if (mMediaPlayerSoundtrack != null && mMediaPlayerSoundtrack.isPlaying()) { mMediaPlayerSoundtrack.pause(); } break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: if (mMediaPlayerSoundtrack != null && mMediaPlayerSoundtrack.isPlaying()) { mMediaPlayerSoundtrack.setVolume(SOUNDTRACK_DUCKING_VOLUME, SOUNDTRACK_DUCKING_VOLUME); } break; } } public void onButtonClickedStartNewGame(View view) { mSoundPool.play(mSoundIdButtonHigh, SOUND_EFFECTS_BUTTONS_VOLUME, SOUND_EFFECTS_BUTTONS_VOLUME, 0, 0, 1f); Intent intent = new Intent(this, TwoPlayerGameActivity.class); startActivity(intent); } public void onButtonClickedSettings(View view) { mSoundPool.play(mSoundIdButtonLow, SOUND_EFFECTS_BUTTONS_VOLUME, SOUND_EFFECTS_BUTTONS_VOLUME, 0, 0, 1f); mRelativeLayoutSettings.setVisibility(View.VISIBLE); mLinearLayoutButtons.setVisibility(View.GONE); } public void onButtonClickedCredits(View view) { mSoundPool.play(mSoundIdButtonLow, SOUND_EFFECTS_BUTTONS_VOLUME, SOUND_EFFECTS_BUTTONS_VOLUME, 0, 0, 1f); mRelativeLayoutCredits.setVisibility(View.VISIBLE); mLinearLayoutButtons.setVisibility(View.GONE); } public void onButtonClickedCloseSettings(View view) { mSoundPool.play(mSoundIdButtonHigh, SOUND_EFFECTS_BUTTONS_VOLUME, SOUND_EFFECTS_BUTTONS_VOLUME, 0, 0, 1f); mLinearLayoutButtons.setVisibility(View.VISIBLE); mRelativeLayoutSettings.setVisibility(View.GONE); } public void onButtonClickedCloseCredits(View view) { mSoundPool.play(mSoundIdButtonHigh, SOUND_EFFECTS_BUTTONS_VOLUME, SOUND_EFFECTS_BUTTONS_VOLUME, 0, 0, 1f); mLinearLayoutButtons.setVisibility(View.VISIBLE); mRelativeLayoutCredits.setVisibility(View.GONE); } public void onButtonClickedCreditsWebLink(View view) { Intent intent = new Intent(Intent.ACTION_VIEW); switch (view.getId()) { case R.id.buttonLinkSourceCode: intent.setData(Uri.parse(getString(R.string.credits_link_source_code))); break; case R.id.buttonLinkLeo: intent.setData(Uri.parse(getString(R.string.credits_link_pulsarjericho))); break; case R.id.buttonLinkElodie: intent.setData(Uri.parse(getString(R.string.credits_link_elodie))); break; case R.id.buttonLinkSamples01: intent.setData(Uri.parse(getString(R.string.credits_link_samples_01))); break; case R.id.buttonLinkSamples02: intent.setData(Uri.parse(getString(R.string.credits_link_samples_02))); break; default: return; } startActivity(intent); } public void onCheckboxClickedSettingsWindChange(View view) { mSoundPool.play(mSoundIdButtonLow, SOUND_EFFECTS_BUTTONS_VOLUME, SOUND_EFFECTS_BUTTONS_VOLUME, 0, 0, 1f); boolean shouldChangeWindAtEveryTurn = false; if (mCheckBoxSettingsWindChange.isChecked()) { shouldChangeWindAtEveryTurn = true; } SharedPreferences sharedPref = getSharedPreferences(getString(R.string.shared_preferences_name), Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putBoolean(getString(R.string.shared_preferences_key_wind_change), shouldChangeWindAtEveryTurn); editor.commit(); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { mTextViewSettingsGameSpeed.setText(String.valueOf(progress)); SharedPreferences sharedPref = getSharedPreferences(getString(R.string.shared_preferences_name), Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(getString(R.string.shared_preferences_key_game_speed), progress); editor.commit(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } private void startPlayingSoundtrack() { if (mMediaPlayerSoundtrack == null || !mMediaPlayerSoundtrack.isPlaying()) { mMediaPlayerSoundtrack = MediaPlayer.create(this, R.raw.soundtrack_menu); mMediaPlayerSoundtrack.setLooping(true); mMediaPlayerSoundtrack.start(); } } private void stopPlayingSoundtrack() { if (mMediaPlayerSoundtrack != null && mMediaPlayerSoundtrack.isPlaying()) { mMediaPlayerSoundtrack.stop(); mMediaPlayerSoundtrack.reset(); mMediaPlayerSoundtrack.release(); mMediaPlayerSoundtrack = null; } } }
{ "content_hash": "735826c7a676d92307749b8f5ef979e8", "timestamp": "", "source": "github", "line_count": 240, "max_line_length": 156, "avg_line_length": 43.266666666666666, "alnum_prop": 0.6953967642526965, "repo_name": "leomoldo/bunkerwar", "id": "df77b6c0e759c8a75174d93a580cc87c0ec9ac12", "size": "10384", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/fr/leomoldo/android/bunkerwar/activity/MainActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "70821" } ], "symlink_target": "" }
<html> <head></head> <script> const worker = new Worker('/back_forward_cache/worker_with_importscripts.js'); window.receivedMessagePromise = new Promise(resolve => { worker.addEventListener('message', (msg) => { resolve(msg.data); }); }); </script> </html>
{ "content_hash": "e2e1ae7a9faa13c7acf7069bb4a6d9b6", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 78, "avg_line_length": 22.166666666666668, "alnum_prop": 0.6766917293233082, "repo_name": "scheib/chromium", "id": "8fa30a40c5a54ead2464145616d23883da034d05", "size": "266", "binary": false, "copies": "9", "ref": "refs/heads/main", "path": "content/test/data/back_forward_cache/page_with_dedicated_worker_and_importscripts.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX FlowGraph XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif #include "allocacheck.h" // for alloca #include "lower.h" // for LowerRange() /*****************************************************************************/ void Compiler::fgInit() { impInit(); /* Initialization for fgWalkTreePre() and fgWalkTreePost() */ fgFirstBBScratch = nullptr; #ifdef DEBUG fgPrintInlinedMethods = JitConfig.JitPrintInlinedMethods() == 1; #endif // DEBUG /* We haven't yet computed the bbPreds lists */ fgComputePredsDone = false; /* We haven't yet computed the bbCheapPreds lists */ fgCheapPredsValid = false; /* We haven't yet computed the edge weight */ fgEdgeWeightsComputed = false; fgHaveValidEdgeWeights = false; fgSlopUsedInEdgeWeights = false; fgRangeUsedInEdgeWeights = true; fgNeedsUpdateFlowGraph = false; fgCalledCount = BB_ZERO_WEIGHT; /* We haven't yet computed the dominator sets */ fgDomsComputed = false; #ifdef DEBUG fgReachabilitySetsValid = false; #endif // DEBUG /* We don't know yet which loops will always execute calls */ fgLoopCallMarked = false; /* We haven't created GC Poll blocks yet. */ fgGCPollsCreated = false; /* Initialize the basic block list */ fgFirstBB = nullptr; fgLastBB = nullptr; fgFirstColdBlock = nullptr; #if FEATURE_EH_FUNCLETS fgFirstFuncletBB = nullptr; fgFuncletsCreated = false; #endif // FEATURE_EH_FUNCLETS fgBBcount = 0; #ifdef DEBUG fgBBcountAtCodegen = 0; #endif // DEBUG fgBBNumMax = 0; fgEdgeCount = 0; fgDomBBcount = 0; fgBBVarSetsInited = false; fgReturnCount = 0; // Initialize BlockSet data. fgCurBBEpoch = 0; fgCurBBEpochSize = 0; fgBBSetCountInSizeTUnits = 0; genReturnBB = nullptr; /* We haven't reached the global morphing phase */ fgGlobalMorph = false; fgModified = false; #ifdef DEBUG fgSafeBasicBlockCreation = true; #endif // DEBUG fgLocalVarLivenessDone = false; /* Statement list is not threaded yet */ fgStmtListThreaded = false; // Initialize the logic for adding code. This is used to insert code such // as the code that raises an exception when an array range check fails. fgAddCodeList = nullptr; fgAddCodeModf = false; for (int i = 0; i < SCK_COUNT; i++) { fgExcptnTargetCache[i] = nullptr; } /* Keep track of the max count of pointer arguments */ fgPtrArgCntMax = 0; /* This global flag is set whenever we remove a statement */ fgStmtRemoved = false; /* This global flag is set whenever we add a throw block for a RngChk */ fgRngChkThrowAdded = false; /* reset flag for fgIsCodeAdded() */ /* We will record a list of all BBJ_RETURN blocks here */ fgReturnBlocks = nullptr; /* This is set by fgComputeReachability */ fgEnterBlks = BlockSetOps::UninitVal(); #ifdef DEBUG fgEnterBlksSetValid = false; #endif // DEBUG #if !FEATURE_EH_FUNCLETS ehMaxHndNestingCount = 0; #endif // !FEATURE_EH_FUNCLETS /* Init the fgBigOffsetMorphingTemps to be BAD_VAR_NUM. */ for (int i = 0; i < TYP_COUNT; i++) { fgBigOffsetMorphingTemps[i] = BAD_VAR_NUM; } fgNoStructPromotion = false; fgNoStructParamPromotion = false; optValnumCSE_phase = false; // referenced in fgMorphSmpOp() #ifdef DEBUG fgNormalizeEHDone = false; #endif // DEBUG #ifdef DEBUG if (!compIsForInlining()) { if ((JitConfig.JitNoStructPromotion() & 1) == 1) { fgNoStructPromotion = true; } if ((JitConfig.JitNoStructPromotion() & 2) == 2) { fgNoStructParamPromotion = true; } } #endif // DEBUG if (!compIsForInlining()) { m_promotedStructDeathVars = nullptr; } #ifdef FEATURE_SIMD fgPreviousCandidateSIMDFieldAsgStmt = nullptr; #endif } bool Compiler::fgHaveProfileData() { if (compIsForInlining() || compIsForImportOnly()) { return false; } return (fgBlockCounts != nullptr); } bool Compiler::fgGetProfileWeightForBasicBlock(IL_OFFSET offset, unsigned* weightWB) { noway_assert(weightWB != nullptr); unsigned weight = 0; #ifdef DEBUG unsigned hashSeed = fgStressBBProf(); if (hashSeed != 0) { unsigned hash = (info.compMethodHash() * hashSeed) ^ (offset * 1027); // We need to especially stress the procedure splitting codepath. Therefore // one third the time we should return a weight of zero. // Otherwise we should return some random weight (usually between 0 and 288). // The below gives a weight of zero, 44% of the time if (hash % 3 == 0) { weight = 0; } else if (hash % 11 == 0) { weight = (hash % 23) * (hash % 29) * (hash % 31); } else { weight = (hash % 17) * (hash % 19); } // The first block is never given a weight of zero if ((offset == 0) && (weight == 0)) { weight = 1 + (hash % 5); } *weightWB = weight; return true; } #endif // DEBUG if (fgHaveProfileData() == false) { return false; } noway_assert(!compIsForInlining()); for (UINT32 i = 0; i < fgBlockCountsCount; i++) { if (fgBlockCounts[i].ILOffset == offset) { weight = fgBlockCounts[i].ExecutionCount; *weightWB = weight; return true; } } *weightWB = 0; return true; } void Compiler::fgInstrumentMethod() { noway_assert(!compIsForInlining()); // Count the number of basic blocks in the method int countOfBlocks = 0; BasicBlock* block; for (block = fgFirstBB; (block != nullptr); block = block->bbNext) { if (!(block->bbFlags & BBF_IMPORTED) || (block->bbFlags & BBF_INTERNAL)) { continue; } countOfBlocks++; } // Allocate the profile buffer ICorJitInfo::BlockCounts* profileBlockCountsStart; HRESULT res = info.compCompHnd->allocMethodBlockCounts(countOfBlocks, &profileBlockCountsStart); GenTreeStmt* stmt; if (!SUCCEEDED(res)) { // The E_NOTIMPL status is returned when we are profiling a generic method from a different assembly if (res == E_NOTIMPL) { // In such cases we still want to add the method entry callback node GenTreeArgList* args = gtNewArgList(gtNewIconEmbMethHndNode(info.compMethodHnd)); GenTree* call = gtNewHelperCallNode(CORINFO_HELP_BBT_FCN_ENTER, TYP_VOID, args); stmt = gtNewStmt(call); } else { noway_assert(!"Error: failed to allocate profileBlockCounts"); return; } } else { // For each BasicBlock (non-Internal) // 1. Assign the blocks bbCodeOffs to the ILOffset field of this blocks profile data. // 2. Add an operation that increments the ExecutionCount field at the beginning of the block. // Each (non-Internal) block has it own BlockCounts tuple [ILOffset, ExecutionCount] // To start we initialize our current one with the first one that we allocated // ICorJitInfo::BlockCounts* currentBlockCounts = profileBlockCountsStart; for (block = fgFirstBB; (block != nullptr); block = block->bbNext) { if (!(block->bbFlags & BBF_IMPORTED) || (block->bbFlags & BBF_INTERNAL)) { continue; } // Assign the current block's IL offset into the profile data currentBlockCounts->ILOffset = block->bbCodeOffs; assert(currentBlockCounts->ExecutionCount == 0); // This value should already be zero-ed out size_t addrOfCurrentExecutionCount = (size_t)&currentBlockCounts->ExecutionCount; // Read Basic-Block count value GenTree* valueNode = gtNewIndOfIconHandleNode(TYP_INT, addrOfCurrentExecutionCount, GTF_ICON_BBC_PTR, false); // Increment value by 1 GenTree* rhsNode = gtNewOperNode(GT_ADD, TYP_INT, valueNode, gtNewIconNode(1)); // Write new Basic-Block count value GenTree* lhsNode = gtNewIndOfIconHandleNode(TYP_INT, addrOfCurrentExecutionCount, GTF_ICON_BBC_PTR, false); GenTree* asgNode = gtNewAssignNode(lhsNode, rhsNode); fgInsertStmtAtBeg(block, asgNode); // Advance to the next BlockCounts tuple [ILOffset, ExecutionCount] currentBlockCounts++; // One less block countOfBlocks--; } // Check that we allocated and initialized the same number of BlockCounts tuples noway_assert(countOfBlocks == 0); // Add the method entry callback node GenTree* arg; #ifdef FEATURE_READYTORUN_COMPILER if (opts.IsReadyToRun()) { mdMethodDef currentMethodToken = info.compCompHnd->getMethodDefFromMethod(info.compMethodHnd); CORINFO_RESOLVED_TOKEN resolvedToken; resolvedToken.tokenContext = MAKE_METHODCONTEXT(info.compMethodHnd); resolvedToken.tokenScope = info.compScopeHnd; resolvedToken.token = currentMethodToken; resolvedToken.tokenType = CORINFO_TOKENKIND_Method; info.compCompHnd->resolveToken(&resolvedToken); arg = impTokenToHandle(&resolvedToken); } else #endif { arg = gtNewIconEmbMethHndNode(info.compMethodHnd); } GenTreeArgList* args = gtNewArgList(arg); GenTree* call = gtNewHelperCallNode(CORINFO_HELP_BBT_FCN_ENTER, TYP_VOID, args); // Get the address of the first blocks ExecutionCount size_t addrOfFirstExecutionCount = (size_t)&profileBlockCountsStart->ExecutionCount; // Read Basic-Block count value GenTree* valueNode = gtNewIndOfIconHandleNode(TYP_INT, addrOfFirstExecutionCount, GTF_ICON_BBC_PTR, false); // Compare Basic-Block count value against zero GenTree* relop = gtNewOperNode(GT_NE, TYP_INT, valueNode, gtNewIconNode(0, TYP_INT)); GenTree* colon = new (this, GT_COLON) GenTreeColon(TYP_VOID, gtNewNothingNode(), call); GenTree* cond = gtNewQmarkNode(TYP_VOID, relop, colon); stmt = gtNewStmt(cond); } fgEnsureFirstBBisScratch(); fgInsertStmtAtEnd(fgFirstBB, stmt); } /***************************************************************************** * * Create a basic block and append it to the current BB list. */ BasicBlock* Compiler::fgNewBasicBlock(BBjumpKinds jumpKind) { // This method must not be called after the exception table has been // constructed, because it doesn't not provide support for patching // the exception table. noway_assert(compHndBBtabCount == 0); BasicBlock* block; /* Allocate the block descriptor */ block = bbNewBasicBlock(jumpKind); noway_assert(block->bbJumpKind == jumpKind); /* Append the block to the end of the global basic block list */ if (fgFirstBB) { fgLastBB->setNext(block); } else { fgFirstBB = block; block->bbPrev = nullptr; } fgLastBB = block; return block; } /***************************************************************************** * * Ensures that fgFirstBB is a scratch BasicBlock that we have added. * This can be used to add initialization code (without worrying * about other blocks jumping to it). * * Callers have to be careful that they do not mess up the order of things * added to fgEnsureFirstBBisScratch in a way as to change semantics. */ void Compiler::fgEnsureFirstBBisScratch() { // This method does not update predecessor lists and so must only be called before they are computed. assert(!fgComputePredsDone); // Have we already allocated a scratch block? if (fgFirstBBisScratch()) { return; } assert(fgFirstBBScratch == nullptr); BasicBlock* block = bbNewBasicBlock(BBJ_NONE); if (fgFirstBB != nullptr) { // If we have profile data the new block will inherit fgFirstBlock's weight if (fgFirstBB->hasProfileWeight()) { block->inheritWeight(fgFirstBB); } fgInsertBBbefore(fgFirstBB, block); } else { noway_assert(fgLastBB == nullptr); fgFirstBB = block; fgLastBB = block; } noway_assert(fgLastBB != nullptr); block->bbFlags |= (BBF_INTERNAL | BBF_IMPORTED); fgFirstBBScratch = fgFirstBB; #ifdef DEBUG if (verbose) { printf("New scratch " FMT_BB "\n", block->bbNum); } #endif } bool Compiler::fgFirstBBisScratch() { if (fgFirstBBScratch != nullptr) { assert(fgFirstBBScratch == fgFirstBB); assert(fgFirstBBScratch->bbFlags & BBF_INTERNAL); assert(fgFirstBBScratch->countOfInEdges() == 1); // Normally, the first scratch block is a fall-through block. However, if the block after it was an empty // BBJ_ALWAYS block, it might get removed, and the code that removes it will make the first scratch block // a BBJ_ALWAYS block. assert((fgFirstBBScratch->bbJumpKind == BBJ_NONE) || (fgFirstBBScratch->bbJumpKind == BBJ_ALWAYS)); return true; } else { return false; } } bool Compiler::fgBBisScratch(BasicBlock* block) { return fgFirstBBisScratch() && (block == fgFirstBB); } #ifdef DEBUG // Check to see if block contains a statement but don't spend more than a certain // budget doing this per method compiled. // If the budget is exceeded, return 'answerOnBoundExceeded' as the answer. /* static */ bool Compiler::fgBlockContainsStatementBounded(BasicBlock* block, GenTreeStmt* stmt, bool answerOnBoundExceeded /*= true*/) { const __int64 maxLinks = 1000000000; __int64* numTraversed = &JitTls::GetCompiler()->compNumStatementLinksTraversed; if (*numTraversed > maxLinks) { return answerOnBoundExceeded; } GenTree* curr = block->firstStmt(); do { (*numTraversed)++; if (curr == stmt) { break; } curr = curr->gtNext; } while (curr); return curr != nullptr; } #endif // DEBUG //------------------------------------------------------------------------ // fgInsertStmtAtBeg: Insert the given tree or statement at the start of the given basic block. // // Arguments: // block - The block into which 'stmt' will be inserted. // node - The node to be inserted. // // Return Value: // Returns the new (potentially) GT_STMT node. // // Notes: // If 'stmt' is not already a statement, a new statement is created from it. // We always insert phi statements at the beginning. // In other cases, if there are any phi assignments and/or an assignment of // the GT_CATCH_ARG, we insert after those. GenTreeStmt* Compiler::fgInsertStmtAtBeg(BasicBlock* block, GenTree* node) { GenTreeStmt* stmt; if (node->gtOper == GT_STMT) { stmt = node->AsStmt(); } else { stmt = gtNewStmt(node); } GenTree* list = block->firstStmt(); if (!stmt->IsPhiDefnStmt()) { GenTreeStmt* insertBeforeStmt = block->FirstNonPhiDefOrCatchArgAsg(); if (insertBeforeStmt != nullptr) { return fgInsertStmtBefore(block, insertBeforeStmt, stmt); } else if (list != nullptr) { return fgInsertStmtAtEnd(block, stmt); } // Otherwise, we will simply insert at the beginning, below. } /* The new tree will now be the first one of the block */ block->bbTreeList = stmt; stmt->gtNext = list; /* Are there any statements in the block? */ if (list) { GenTree* last; /* There is at least one statement already */ last = list->gtPrev; noway_assert(last && last->gtNext == nullptr); /* Insert the statement in front of the first one */ list->gtPrev = stmt; stmt->gtPrev = last; } else { /* The block was completely empty */ stmt->gtPrev = stmt; } return stmt; } /***************************************************************************** * * Insert the given tree or statement at the end of the given basic block. * Returns the (potentially) new GT_STMT node. * If the block can be a conditional block, use fgInsertStmtNearEnd. */ GenTreeStmt* Compiler::fgInsertStmtAtEnd(BasicBlock* block, GenTree* node) { GenTree* list = block->firstStmt(); GenTreeStmt* stmt; if (node->gtOper != GT_STMT) { stmt = gtNewStmt(node); } else { stmt = node->AsStmt(); } assert(stmt->gtNext == nullptr); // We don't set it, and it needs to be this after the insert if (list) { GenTree* last; /* There is at least one statement already */ last = list->gtPrev; noway_assert(last && last->gtNext == nullptr); /* Append the statement after the last one */ last->gtNext = stmt; stmt->gtPrev = last; list->gtPrev = stmt; } else { /* The block is completely empty */ block->bbTreeList = stmt; stmt->gtPrev = stmt; } return stmt; } /***************************************************************************** * * Insert the given tree or statement at the end of the given basic block, but before * the GT_JTRUE, if present. * Returns the (potentially) new GT_STMT node. */ GenTreeStmt* Compiler::fgInsertStmtNearEnd(BasicBlock* block, GenTree* node) { GenTreeStmt* stmt; // This routine can only be used when in tree order. assert(fgOrder == FGOrderTree); if ((block->bbJumpKind == BBJ_COND) || (block->bbJumpKind == BBJ_SWITCH) || (block->bbJumpKind == BBJ_RETURN)) { if (node->gtOper != GT_STMT) { stmt = gtNewStmt(node); } else { stmt = node->AsStmt(); } GenTreeStmt* first = block->firstStmt(); noway_assert(first); GenTreeStmt* last = block->lastStmt(); noway_assert(last && last->gtNext == nullptr); GenTree* after = last->gtPrev; #if DEBUG if (block->bbJumpKind == BBJ_COND) { noway_assert(last->gtStmtExpr->gtOper == GT_JTRUE); } else if (block->bbJumpKind == BBJ_RETURN) { noway_assert((last->gtStmtExpr->gtOper == GT_RETURN) || (last->gtStmtExpr->gtOper == GT_JMP) || // BBJ_RETURN blocks in functions returning void do not get a GT_RETURN node if they // have a .tail prefix (even if canTailCall returns false for these calls) // code:Compiler::impImportBlockCode (search for the RET: label) // Ditto for real tail calls (all code after them has been removed) ((last->gtStmtExpr->gtOper == GT_CALL) && ((info.compRetType == TYP_VOID) || last->gtStmtExpr->AsCall()->IsTailCall()))); } else { noway_assert(block->bbJumpKind == BBJ_SWITCH); noway_assert(last->gtStmtExpr->gtOper == GT_SWITCH); } #endif // DEBUG /* Append 'stmt' before 'last' */ stmt->gtNext = last; last->gtPrev = stmt; if (first == last) { /* There is only one stmt in the block */ block->bbTreeList = stmt; stmt->gtPrev = last; } else { noway_assert(after && (after->gtNext == last)); /* Append 'stmt' after 'after' */ after->gtNext = stmt; stmt->gtPrev = after; } return stmt; } else { return fgInsertStmtAtEnd(block, node); } } /***************************************************************************** * * Insert the given statement "stmt" after GT_STMT node "insertionPoint". * Returns the newly inserted GT_STMT node. * Note that the gtPrev list of statement nodes is circular, but the gtNext list is not. */ GenTreeStmt* Compiler::fgInsertStmtAfter(BasicBlock* block, GenTreeStmt* insertionPoint, GenTreeStmt* stmt) { assert(block->bbTreeList != nullptr); assert(fgBlockContainsStatementBounded(block, insertionPoint)); assert(!fgBlockContainsStatementBounded(block, stmt, false)); if (insertionPoint->gtNext == nullptr) { // Ok, we want to insert after the last statement of the block. stmt->gtNext = nullptr; stmt->gtPrev = insertionPoint; insertionPoint->gtNext = stmt; // Update the backward link of the first statement of the block // to point to the new last statement. assert(block->bbTreeList->gtPrev == insertionPoint); block->bbTreeList->gtPrev = stmt; } else { stmt->gtNext = insertionPoint->gtNext; stmt->gtPrev = insertionPoint; insertionPoint->gtNext->gtPrev = stmt; insertionPoint->gtNext = stmt; } return stmt; } // Insert the given tree or statement before GT_STMT node "insertionPoint". // Returns the newly inserted GT_STMT node. GenTreeStmt* Compiler::fgInsertStmtBefore(BasicBlock* block, GenTreeStmt* insertionPoint, GenTreeStmt* stmt) { assert(block->bbTreeList != nullptr); assert(fgBlockContainsStatementBounded(block, insertionPoint)); assert(!fgBlockContainsStatementBounded(block, stmt, false)); if (insertionPoint == block->bbTreeList) { // We're inserting before the first statement in the block. GenTree* list = block->bbTreeList; GenTree* last = list->gtPrev; stmt->gtNext = list; stmt->gtPrev = last; block->bbTreeList = stmt; list->gtPrev = stmt; } else { stmt->gtNext = insertionPoint; stmt->gtPrev = insertionPoint->gtPrev; insertionPoint->gtPrev->gtNext = stmt; insertionPoint->gtPrev = stmt; } return stmt; } /***************************************************************************** * * Insert the list of statements stmtList after the stmtAfter in block. * Return the last statement stmtList. */ GenTreeStmt* Compiler::fgInsertStmtListAfter(BasicBlock* block, // the block where stmtAfter is in. GenTreeStmt* stmtAfter, // the statement where stmtList should be inserted // after. GenTreeStmt* stmtList) { // Currently we can handle when stmtAfter and stmtList are non-NULL. This makes everything easy. noway_assert(stmtAfter); noway_assert(stmtList); GenTreeStmt* stmtLast = stmtList->getPrevStmt(); // Last statement in a non-empty list, circular in the gtPrev list. noway_assert(stmtLast); noway_assert(stmtLast->gtNext == nullptr); GenTreeStmt* stmtNext = stmtAfter->getNextStmt(); if (stmtNext == nullptr) { stmtAfter->gtNext = stmtList; stmtList->gtPrev = stmtAfter; block->bbTreeList->gtPrev = stmtLast; goto _Done; } stmtAfter->gtNext = stmtList; stmtList->gtPrev = stmtAfter; stmtLast->gtNext = stmtNext; stmtNext->gtPrev = stmtLast; _Done: noway_assert(block->bbTreeList == nullptr || block->bbTreeList->gtPrev->gtNext == nullptr); return stmtLast; } /* Removes a block from the return block list */ void Compiler::fgRemoveReturnBlock(BasicBlock* block) { if (fgReturnBlocks == nullptr) { return; } if (fgReturnBlocks->block == block) { // It's the 1st entry, assign new head of list. fgReturnBlocks = fgReturnBlocks->next; return; } for (BasicBlockList* retBlocks = fgReturnBlocks; retBlocks->next != nullptr; retBlocks = retBlocks->next) { if (retBlocks->next->block == block) { // Found it; splice it out. retBlocks->next = retBlocks->next->next; return; } } } //------------------------------------------------------------------------ // fgGetPredForBlock: Find and return the predecessor edge corresponding to a given predecessor block. // // Arguments: // block -- The block with the predecessor list to operate on. // blockPred -- The predecessor block to find in the predecessor list. // // Return Value: // The flowList edge corresponding to "blockPred". If "blockPred" is not in the predecessor list of "block", // then returns nullptr. // // Assumptions: // -- This only works on the full predecessor lists, not the cheap preds lists. flowList* Compiler::fgGetPredForBlock(BasicBlock* block, BasicBlock* blockPred) { assert(block); assert(blockPred); assert(!fgCheapPredsValid); flowList* pred; for (pred = block->bbPreds; pred != nullptr; pred = pred->flNext) { if (blockPred == pred->flBlock) { return pred; } } return nullptr; } //------------------------------------------------------------------------ // fgGetPredForBlock: Find and return the predecessor edge corresponding to a given predecessor block. // Also returns the address of the pointer that points to this edge, to make it possible to remove this edge from the // predecessor list without doing another linear search over the edge list. // // Arguments: // block -- The block with the predecessor list to operate on. // blockPred -- The predecessor block to find in the predecessor list. // ptrToPred -- Out parameter: set to the address of the pointer that points to the returned predecessor edge. // // Return Value: // The flowList edge corresponding to "blockPred". If "blockPred" is not in the predecessor list of "block", // then returns nullptr. // // Assumptions: // -- This only works on the full predecessor lists, not the cheap preds lists. flowList* Compiler::fgGetPredForBlock(BasicBlock* block, BasicBlock* blockPred, flowList*** ptrToPred) { assert(block); assert(blockPred); assert(ptrToPred); assert(!fgCheapPredsValid); flowList** predPrevAddr; flowList* pred; for (predPrevAddr = &block->bbPreds, pred = *predPrevAddr; pred != nullptr; predPrevAddr = &pred->flNext, pred = *predPrevAddr) { if (blockPred == pred->flBlock) { *ptrToPred = predPrevAddr; return pred; } } *ptrToPred = nullptr; return nullptr; } //------------------------------------------------------------------------ // fgSpliceOutPred: Removes a predecessor edge for a block from the predecessor list. // // Arguments: // block -- The block with the predecessor list to operate on. // blockPred -- The predecessor block to remove from the predecessor list. It must be a predecessor of "block". // // Return Value: // The flowList edge that was removed. // // Assumptions: // -- "blockPred" must be a predecessor block of "block". // -- This simply splices out the flowList object. It doesn't update block ref counts, handle duplicate counts, etc. // For that, use fgRemoveRefPred() or fgRemoveAllRefPred(). // -- This only works on the full predecessor lists, not the cheap preds lists. // // Notes: // -- This must walk the predecessor list to find the block in question. If the predecessor edge // is found using fgGetPredForBlock(), consider using the version that hands back the predecessor pointer // address instead, to avoid this search. // -- Marks fgModified = true, since the flow graph has changed. flowList* Compiler::fgSpliceOutPred(BasicBlock* block, BasicBlock* blockPred) { assert(!fgCheapPredsValid); noway_assert(block->bbPreds); flowList* oldEdge = nullptr; // Is this the first block in the pred list? if (blockPred == block->bbPreds->flBlock) { oldEdge = block->bbPreds; block->bbPreds = block->bbPreds->flNext; } else { flowList* pred; for (pred = block->bbPreds; (pred->flNext != nullptr) && (blockPred != pred->flNext->flBlock); pred = pred->flNext) { // empty } oldEdge = pred->flNext; if (oldEdge == nullptr) { noway_assert(!"Should always find the blockPred"); } pred->flNext = pred->flNext->flNext; } // Any changes to the flow graph invalidate the dominator sets. fgModified = true; return oldEdge; } //------------------------------------------------------------------------ // fgAddRefPred: Increment block->bbRefs by one and add "blockPred" to the predecessor list of "block". // // Arguments: // block -- A block to operate on. // blockPred -- The predecessor block to add to the predecessor list. // oldEdge -- Optional (default: nullptr). If non-nullptr, and a new edge is created (and the dup count // of an existing edge is not just incremented), the edge weights are copied from this edge. // initializingPreds -- Optional (default: false). Only set to "true" when the initial preds computation is // happening. // // Return Value: // The flow edge representing the predecessor. // // Assumptions: // -- This only works on the full predecessor lists, not the cheap preds lists. // // Notes: // -- block->bbRefs is incremented by one to account for the reduction in incoming edges. // -- block->bbRefs is adjusted even if preds haven't been computed. If preds haven't been computed, // the preds themselves aren't touched. // -- fgModified is set if a new flow edge is created (but not if an existing flow edge dup count is incremented), // indicating that the flow graph shape has changed. flowList* Compiler::fgAddRefPred(BasicBlock* block, BasicBlock* blockPred, flowList* oldEdge /* = nullptr */, bool initializingPreds /* = false */) { assert(block != nullptr); assert(blockPred != nullptr); block->bbRefs++; if (!fgComputePredsDone && !initializingPreds) { // Why is someone trying to update the preds list when the preds haven't been created? // Ignore them! This can happen when fgMorph is called before the preds list is created. return nullptr; } assert(!fgCheapPredsValid); flowList* flow; // Keep the predecessor list in lowest to highest bbNum order. This allows us to discover the loops in // optFindNaturalLoops from innermost to outermost. // // TODO-Throughput: Inserting an edge for a block in sorted order requires searching every existing edge. // Thus, inserting all the edges for a block is quadratic in the number of edges. We need to either // not bother sorting for debuggable code, or sort in optFindNaturalLoops, or better, make the code in // optFindNaturalLoops not depend on order. This also requires ensuring that nobody else has taken a // dependency on this order. Note also that we don't allow duplicates in the list; we maintain a flDupCount // count of duplication. This also necessitates walking the flow list for every edge we add. flowList** listp = &block->bbPreds; while ((*listp != nullptr) && ((*listp)->flBlock->bbNum < blockPred->bbNum)) { listp = &(*listp)->flNext; } if ((*listp != nullptr) && ((*listp)->flBlock == blockPred)) { // The predecessor block already exists in the flow list; simply add to its duplicate count. flow = *listp; noway_assert(flow->flDupCount > 0); flow->flDupCount++; } else { flow = new (this, CMK_FlowList) flowList(); #if MEASURE_BLOCK_SIZE genFlowNodeCnt += 1; genFlowNodeSize += sizeof(flowList); #endif // MEASURE_BLOCK_SIZE // Any changes to the flow graph invalidate the dominator sets. fgModified = true; // Insert the new edge in the list in the correct ordered location. flow->flNext = *listp; *listp = flow; flow->flBlock = blockPred; flow->flDupCount = 1; if (fgHaveValidEdgeWeights) { // We are creating an edge from blockPred to block // and we have already computed the edge weights, so // we will try to setup this new edge with valid edge weights. // if (oldEdge != nullptr) { // If our caller has given us the old edge weights // then we will use them. // flow->flEdgeWeightMin = oldEdge->flEdgeWeightMin; flow->flEdgeWeightMax = oldEdge->flEdgeWeightMax; } else { // Set the max edge weight to be the minimum of block's or blockPred's weight // flow->flEdgeWeightMax = min(block->bbWeight, blockPred->bbWeight); // If we are inserting a conditional block the minimum weight is zero, // otherwise it is the same as the edge's max weight. if (blockPred->NumSucc() > 1) { flow->flEdgeWeightMin = BB_ZERO_WEIGHT; } else { flow->flEdgeWeightMin = flow->flEdgeWeightMax; } } } else { flow->flEdgeWeightMin = BB_ZERO_WEIGHT; flow->flEdgeWeightMax = BB_MAX_WEIGHT; } } return flow; } //------------------------------------------------------------------------ // fgRemoveRefPred: Decrements the reference count of a predecessor edge from "blockPred" to "block", // removing the edge if it is no longer necessary. // // Arguments: // block -- A block to operate on. // blockPred -- The predecessor block to remove from the predecessor list. It must be a predecessor of "block". // // Return Value: // If the flow edge was removed (the predecessor has a "dup count" of 1), // returns the flow graph edge that was removed. This means "blockPred" is no longer a predecessor of "block". // Otherwise, returns nullptr. This means that "blockPred" is still a predecessor of "block" (because "blockPred" // is a switch with multiple cases jumping to "block", or a BBJ_COND with both conditional and fall-through // paths leading to "block"). // // Assumptions: // -- "blockPred" must be a predecessor block of "block". // -- This only works on the full predecessor lists, not the cheap preds lists. // // Notes: // -- block->bbRefs is decremented by one to account for the reduction in incoming edges. // -- block->bbRefs is adjusted even if preds haven't been computed. If preds haven't been computed, // the preds themselves aren't touched. // -- fgModified is set if a flow edge is removed (but not if an existing flow edge dup count is decremented), // indicating that the flow graph shape has changed. flowList* Compiler::fgRemoveRefPred(BasicBlock* block, BasicBlock* blockPred) { noway_assert(block != nullptr); noway_assert(blockPred != nullptr); noway_assert(block->countOfInEdges() > 0); block->bbRefs--; // Do nothing if we haven't calculated the predecessor list yet. // Yes, this does happen. // For example the predecessor lists haven't been created yet when we do fgMorph. // But fgMorph calls fgFoldConditional, which in turn calls fgRemoveRefPred. if (!fgComputePredsDone) { return nullptr; } assert(!fgCheapPredsValid); flowList** ptrToPred; flowList* pred = fgGetPredForBlock(block, blockPred, &ptrToPred); noway_assert(pred); noway_assert(pred->flDupCount > 0); pred->flDupCount--; if (pred->flDupCount == 0) { // Splice out the predecessor edge since it's no longer necessary. *ptrToPred = pred->flNext; // Any changes to the flow graph invalidate the dominator sets. fgModified = true; return pred; } else { return nullptr; } } //------------------------------------------------------------------------ // fgRemoveAllRefPreds: Removes a predecessor edge from one block to another, no matter what the "dup count" is. // // Arguments: // block -- A block to operate on. // blockPred -- The predecessor block to remove from the predecessor list. It must be a predecessor of "block". // // Return Value: // Returns the flow graph edge that was removed. The dup count on the edge is no longer valid. // // Assumptions: // -- "blockPred" must be a predecessor block of "block". // -- This only works on the full predecessor lists, not the cheap preds lists. // // Notes: // block->bbRefs is decremented to account for the reduction in incoming edges. flowList* Compiler::fgRemoveAllRefPreds(BasicBlock* block, BasicBlock* blockPred) { assert(block != nullptr); assert(blockPred != nullptr); assert(fgComputePredsDone); assert(!fgCheapPredsValid); assert(block->countOfInEdges() > 0); flowList** ptrToPred; flowList* pred = fgGetPredForBlock(block, blockPred, &ptrToPred); assert(pred != nullptr); assert(pred->flDupCount > 0); assert(block->bbRefs >= pred->flDupCount); block->bbRefs -= pred->flDupCount; // Now splice out the predecessor edge. *ptrToPred = pred->flNext; // Any changes to the flow graph invalidate the dominator sets. fgModified = true; return pred; } //------------------------------------------------------------------------ // fgRemoveAllRefPreds: Remove a predecessor edge, given the address of a pointer to it in the // predecessor list, no matter what the "dup count" is. // // Arguments: // block -- A block with the predecessor list to operate on. // ptrToPred -- The address of a pointer to the predecessor to remove. // // Return Value: // The removed predecessor edge. The dup count on the edge is no longer valid. // // Assumptions: // -- The predecessor edge must be in the predecessor list for "block". // -- This only works on the full predecessor lists, not the cheap preds lists. // // Notes: // block->bbRefs is decremented by the dup count of the predecessor edge, to account for the reduction in incoming // edges. flowList* Compiler::fgRemoveAllRefPreds(BasicBlock* block, flowList** ptrToPred) { assert(block != nullptr); assert(ptrToPred != nullptr); assert(fgComputePredsDone); assert(!fgCheapPredsValid); assert(block->countOfInEdges() > 0); flowList* pred = *ptrToPred; assert(pred != nullptr); assert(pred->flDupCount > 0); assert(block->bbRefs >= pred->flDupCount); block->bbRefs -= pred->flDupCount; // Now splice out the predecessor edge. *ptrToPred = pred->flNext; // Any changes to the flow graph invalidate the dominator sets. fgModified = true; return pred; } /* Removes all the appearances of block as predecessor of others */ void Compiler::fgRemoveBlockAsPred(BasicBlock* block) { assert(!fgCheapPredsValid); PREFIX_ASSUME(block != nullptr); BasicBlock* bNext; switch (block->bbJumpKind) { case BBJ_CALLFINALLY: if (!(block->bbFlags & BBF_RETLESS_CALL)) { assert(block->isBBCallAlwaysPair()); /* The block after the BBJ_CALLFINALLY block is not reachable */ bNext = block->bbNext; /* bNext is an unreachable BBJ_ALWAYS block */ noway_assert(bNext->bbJumpKind == BBJ_ALWAYS); while (bNext->countOfInEdges() > 0) { fgRemoveRefPred(bNext, bNext->bbPreds->flBlock); } } __fallthrough; case BBJ_COND: case BBJ_ALWAYS: case BBJ_EHCATCHRET: /* Update the predecessor list for 'block->bbJumpDest' and 'block->bbNext' */ fgRemoveRefPred(block->bbJumpDest, block); if (block->bbJumpKind != BBJ_COND) { break; } /* If BBJ_COND fall through */ __fallthrough; case BBJ_NONE: /* Update the predecessor list for 'block->bbNext' */ fgRemoveRefPred(block->bbNext, block); break; case BBJ_EHFILTERRET: block->bbJumpDest->bbRefs++; // To compensate the bbRefs-- inside fgRemoveRefPred fgRemoveRefPred(block->bbJumpDest, block); break; case BBJ_EHFINALLYRET: { /* Remove block as the predecessor of the bbNext of all BBJ_CALLFINALLY blocks calling this finally. No need to look for BBJ_CALLFINALLY for fault handlers. */ unsigned hndIndex = block->getHndIndex(); EHblkDsc* ehDsc = ehGetDsc(hndIndex); if (ehDsc->HasFinallyHandler()) { BasicBlock* begBlk; BasicBlock* endBlk; ehGetCallFinallyBlockRange(hndIndex, &begBlk, &endBlk); BasicBlock* finBeg = ehDsc->ebdHndBeg; for (BasicBlock* bcall = begBlk; bcall != endBlk; bcall = bcall->bbNext) { if ((bcall->bbFlags & BBF_REMOVED) || bcall->bbJumpKind != BBJ_CALLFINALLY || bcall->bbJumpDest != finBeg) { continue; } assert(bcall->isBBCallAlwaysPair()); fgRemoveRefPred(bcall->bbNext, block); } } } break; case BBJ_THROW: case BBJ_RETURN: break; case BBJ_SWITCH: { unsigned jumpCnt = block->bbJumpSwt->bbsCount; BasicBlock** jumpTab = block->bbJumpSwt->bbsDstTab; do { fgRemoveRefPred(*jumpTab, block); } while (++jumpTab, --jumpCnt); break; } default: noway_assert(!"Block doesn't have a valid bbJumpKind!!!!"); break; } } /***************************************************************************** * fgChangeSwitchBlock: * * We have a BBJ_SWITCH jump at 'oldSwitchBlock' and we want to move this * switch jump over to 'newSwitchBlock'. All of the blocks that are jumped * to from jumpTab[] need to have their predecessor lists updated by removing * the 'oldSwitchBlock' and adding 'newSwitchBlock'. */ void Compiler::fgChangeSwitchBlock(BasicBlock* oldSwitchBlock, BasicBlock* newSwitchBlock) { noway_assert(oldSwitchBlock != nullptr); noway_assert(newSwitchBlock != nullptr); noway_assert(oldSwitchBlock->bbJumpKind == BBJ_SWITCH); unsigned jumpCnt = oldSwitchBlock->bbJumpSwt->bbsCount; BasicBlock** jumpTab = oldSwitchBlock->bbJumpSwt->bbsDstTab; unsigned i; // Walk the switch's jump table, updating the predecessor for each branch. for (i = 0; i < jumpCnt; i++) { BasicBlock* bJump = jumpTab[i]; noway_assert(bJump != nullptr); // Note that if there are duplicate branch targets in the switch jump table, // fgRemoveRefPred()/fgAddRefPred() will do the right thing: the second and // subsequent duplicates will simply subtract from and add to the duplicate // count (respectively). // // Remove the old edge [oldSwitchBlock => bJump] // fgRemoveRefPred(bJump, oldSwitchBlock); // // Create the new edge [newSwitchBlock => bJump] // fgAddRefPred(bJump, newSwitchBlock); } if (m_switchDescMap != nullptr) { SwitchUniqueSuccSet uniqueSuccSet; // If already computed and cached the unique descriptors for the old block, let's // update those for the new block. if (m_switchDescMap->Lookup(oldSwitchBlock, &uniqueSuccSet)) { m_switchDescMap->Set(newSwitchBlock, uniqueSuccSet, BlockToSwitchDescMap::Overwrite); } else { fgInvalidateSwitchDescMapEntry(newSwitchBlock); } fgInvalidateSwitchDescMapEntry(oldSwitchBlock); } } /***************************************************************************** * fgReplaceSwitchJumpTarget: * * We have a BBJ_SWITCH at 'blockSwitch' and we want to replace all entries * in the jumpTab[] such that so that jumps that previously went to * 'oldTarget' now go to 'newTarget'. * We also must update the predecessor lists for 'oldTarget' and 'newPred'. */ void Compiler::fgReplaceSwitchJumpTarget(BasicBlock* blockSwitch, BasicBlock* newTarget, BasicBlock* oldTarget) { noway_assert(blockSwitch != nullptr); noway_assert(newTarget != nullptr); noway_assert(oldTarget != nullptr); noway_assert(blockSwitch->bbJumpKind == BBJ_SWITCH); // For the jump targets values that match oldTarget of our BBJ_SWITCH // replace predecessor 'blockSwitch' with 'newTarget' // unsigned jumpCnt = blockSwitch->bbJumpSwt->bbsCount; BasicBlock** jumpTab = blockSwitch->bbJumpSwt->bbsDstTab; unsigned i = 0; // Walk the switch's jump table looking for blocks to update the preds for while (i < jumpCnt) { if (jumpTab[i] == oldTarget) // We will update when jumpTab[i] matches { // Remove the old edge [oldTarget from blockSwitch] // fgRemoveAllRefPreds(oldTarget, blockSwitch); // // Change the jumpTab entry to branch to the new location // jumpTab[i] = newTarget; // // Create the new edge [newTarget from blockSwitch] // flowList* newEdge = fgAddRefPred(newTarget, blockSwitch); // Now set the correct value of newEdge->flDupCount // and replace any other jumps in jumpTab[] that go to oldTarget. // i++; while (i < jumpCnt) { if (jumpTab[i] == oldTarget) { // // We also must update this entry in the jumpTab // jumpTab[i] = newTarget; newTarget->bbRefs++; // // Increment the flDupCount // newEdge->flDupCount++; } i++; // Check the next entry in jumpTab[] } // Maintain, if necessary, the set of unique targets of "block." UpdateSwitchTableTarget(blockSwitch, oldTarget, newTarget); // Make sure the new target has the proper bits set for being a branch target. newTarget->bbFlags |= BBF_HAS_LABEL | BBF_JMP_TARGET; return; // We have replaced the jumps to oldTarget with newTarget } i++; // Check the next entry in jumpTab[] for a match } noway_assert(!"Did not find oldTarget in jumpTab[]"); } //------------------------------------------------------------------------ // Compiler::fgReplaceJumpTarget: For a given block, replace the target 'oldTarget' with 'newTarget'. // // Arguments: // block - the block in which a jump target will be replaced. // newTarget - the new branch target of the block. // oldTarget - the old branch target of the block. // // Notes: // 1. Only branches are changed: BBJ_ALWAYS, the non-fallthrough path of BBJ_COND, BBJ_SWITCH, etc. // We ignore other block types. // 2. Only the first target found is updated. If there are multiple ways for a block // to reach 'oldTarget' (e.g., multiple arms of a switch), only the first one found is changed. // 3. The predecessor lists are not changed. // 4. The switch table "unique successor" cache is invalidated. // // This function is most useful early, before the full predecessor lists have been computed. // void Compiler::fgReplaceJumpTarget(BasicBlock* block, BasicBlock* newTarget, BasicBlock* oldTarget) { assert(block != nullptr); switch (block->bbJumpKind) { case BBJ_CALLFINALLY: case BBJ_COND: case BBJ_ALWAYS: case BBJ_EHCATCHRET: case BBJ_EHFILTERRET: case BBJ_LEAVE: // This function will be called before import, so we still have BBJ_LEAVE if (block->bbJumpDest == oldTarget) { block->bbJumpDest = newTarget; } break; case BBJ_NONE: case BBJ_EHFINALLYRET: case BBJ_THROW: case BBJ_RETURN: break; case BBJ_SWITCH: unsigned jumpCnt; jumpCnt = block->bbJumpSwt->bbsCount; BasicBlock** jumpTab; jumpTab = block->bbJumpSwt->bbsDstTab; for (unsigned i = 0; i < jumpCnt; i++) { if (jumpTab[i] == oldTarget) { jumpTab[i] = newTarget; break; } } break; default: assert(!"Block doesn't have a valid bbJumpKind!!!!"); unreached(); break; } } /***************************************************************************** * Updates the predecessor list for 'block' by replacing 'oldPred' with 'newPred'. * Note that a block can only appear once in the preds list (for normal preds, not * cheap preds): if a predecessor has multiple ways to get to this block, then * flDupCount will be >1, but the block will still appear exactly once. Thus, this * function assumes that all branches from the predecessor (practically, that all * switch cases that target this block) are changed to branch from the new predecessor, * with the same dup count. * * Note that the block bbRefs is not changed, since 'block' has the same number of * references as before, just from a different predecessor block. */ void Compiler::fgReplacePred(BasicBlock* block, BasicBlock* oldPred, BasicBlock* newPred) { noway_assert(block != nullptr); noway_assert(oldPred != nullptr); noway_assert(newPred != nullptr); assert(!fgCheapPredsValid); flowList* pred; for (pred = block->bbPreds; pred != nullptr; pred = pred->flNext) { if (oldPred == pred->flBlock) { pred->flBlock = newPred; break; } } } /***************************************************************************** * * Returns true if block b1 dominates block b2. */ bool Compiler::fgDominate(BasicBlock* b1, BasicBlock* b2) { noway_assert(fgDomsComputed); assert(!fgCheapPredsValid); // // If the fgModified flag is false then we made some modifications to // the flow graph, like adding a new block or changing a conditional branch // into an unconditional branch. // // We can continue to use the dominator and reachable information to // unmark loops as long as we haven't renumbered the blocks or we aren't // asking for information about a new block // if (b2->bbNum > fgDomBBcount) { if (b1 == b2) { return true; } for (flowList* pred = b2->bbPreds; pred != nullptr; pred = pred->flNext) { if (!fgDominate(b1, pred->flBlock)) { return false; } } return b2->bbPreds != nullptr; } if (b1->bbNum > fgDomBBcount) { // if b1 is a loop preheader and Succ is its only successor, then all predecessors of // Succ either are b1 itself or are dominated by Succ. Under these conditions, b1 // dominates b2 if and only if Succ dominates b2 (or if b2 == b1, but we already tested // for this case) if (b1->bbFlags & BBF_LOOP_PREHEADER) { noway_assert(b1->bbFlags & BBF_INTERNAL); noway_assert(b1->bbJumpKind == BBJ_NONE); return fgDominate(b1->bbNext, b2); } // unknown dominators; err on the safe side and return false return false; } /* Check if b1 dominates b2 */ unsigned numA = b1->bbNum; noway_assert(numA <= fgDomBBcount); unsigned numB = b2->bbNum; noway_assert(numB <= fgDomBBcount); // What we want to ask here is basically if A is in the middle of the path from B to the root (the entry node) // in the dominator tree. Turns out that can be translated as: // // A dom B <-> preorder(A) <= preorder(B) && postorder(A) >= postorder(B) // // where the equality holds when you ask if A dominates itself. bool treeDom = fgDomTreePreOrder[numA] <= fgDomTreePreOrder[numB] && fgDomTreePostOrder[numA] >= fgDomTreePostOrder[numB]; return treeDom; } /***************************************************************************** * * Returns true if block b1 can reach block b2. */ bool Compiler::fgReachable(BasicBlock* b1, BasicBlock* b2) { noway_assert(fgDomsComputed); assert(!fgCheapPredsValid); // // If the fgModified flag is false then we made some modifications to // the flow graph, like adding a new block or changing a conditional branch // into an unconditional branch. // // We can continue to use the dominator and reachable information to // unmark loops as long as we haven't renumbered the blocks or we aren't // asking for information about a new block // if (b2->bbNum > fgDomBBcount) { if (b1 == b2) { return true; } for (flowList* pred = b2->bbPreds; pred != nullptr; pred = pred->flNext) { if (fgReachable(b1, pred->flBlock)) { return true; } } return false; } if (b1->bbNum > fgDomBBcount) { noway_assert(b1->bbJumpKind == BBJ_NONE || b1->bbJumpKind == BBJ_ALWAYS || b1->bbJumpKind == BBJ_COND); if (b1->bbFallsThrough() && fgReachable(b1->bbNext, b2)) { return true; } if (b1->bbJumpKind == BBJ_ALWAYS || b1->bbJumpKind == BBJ_COND) { return fgReachable(b1->bbJumpDest, b2); } return false; } /* Check if b1 can reach b2 */ assert(fgReachabilitySetsValid); assert(BasicBlockBitSetTraits::GetSize(this) == fgDomBBcount + 1); return BlockSetOps::IsMember(this, b2->bbReach, b1->bbNum); } /***************************************************************************** * Update changed flow graph information. * * If the flow graph has changed, we need to recompute various information if we want to use * it again. */ void Compiler::fgUpdateChangedFlowGraph() { // We need to clear this so we don't hit an assert calling fgRenumberBlocks(). fgDomsComputed = false; JITDUMP("\nRenumbering the basic blocks for fgUpdateChangeFlowGraph\n"); fgRenumberBlocks(); fgComputePreds(); fgComputeEnterBlocksSet(); fgComputeReachabilitySets(); fgComputeDoms(); } /***************************************************************************** * Compute the bbReach sets. * * This can be called to recompute the bbReach sets after the flow graph changes, such as when the * number of BasicBlocks change (and thus, the BlockSet epoch changes). * * Finally, this also sets the BBF_GC_SAFE_POINT flag on blocks. * * Assumes the predecessor lists are correct. * * TODO-Throughput: This algorithm consumes O(n^2) because we're using dense bitsets to * represent reachability. While this yields O(1) time queries, it bloats the memory usage * for large code. We can do better if we try to approach reachability by * computing the strongly connected components of the flow graph. That way we only need * linear memory to label every block with its SCC. */ void Compiler::fgComputeReachabilitySets() { assert(fgComputePredsDone); assert(!fgCheapPredsValid); #ifdef DEBUG fgReachabilitySetsValid = false; #endif // DEBUG BasicBlock* block; for (block = fgFirstBB; block != nullptr; block = block->bbNext) { // Initialize the per-block bbReach sets. It creates a new empty set, // because the block epoch could change since the previous initialization // and the old set could have wrong size. block->bbReach = BlockSetOps::MakeEmpty(this); /* Mark block as reaching itself */ BlockSetOps::AddElemD(this, block->bbReach, block->bbNum); } /* Find the reachable blocks */ // Also, set BBF_GC_SAFE_POINT. bool change; BlockSet newReach(BlockSetOps::MakeEmpty(this)); do { change = false; for (block = fgFirstBB; block != nullptr; block = block->bbNext) { BlockSetOps::Assign(this, newReach, block->bbReach); bool predGcSafe = (block->bbPreds != nullptr); // Do all of our predecessor blocks have a GC safe bit? for (flowList* pred = block->bbPreds; pred != nullptr; pred = pred->flNext) { BasicBlock* predBlock = pred->flBlock; /* Union the predecessor's reachability set into newReach */ BlockSetOps::UnionD(this, newReach, predBlock->bbReach); if (!(predBlock->bbFlags & BBF_GC_SAFE_POINT)) { predGcSafe = false; } } if (predGcSafe) { block->bbFlags |= BBF_GC_SAFE_POINT; } if (!BlockSetOps::Equal(this, newReach, block->bbReach)) { BlockSetOps::Assign(this, block->bbReach, newReach); change = true; } } } while (change); #ifdef DEBUG if (verbose) { printf("\nAfter computing reachability sets:\n"); fgDispReach(); } fgReachabilitySetsValid = true; #endif // DEBUG } /***************************************************************************** * Compute the entry blocks set. * * Initialize fgEnterBlks to the set of blocks for which we don't have explicit control * flow edges. These are the entry basic block and each of the EH handler blocks. * For ARM, also include the BBJ_ALWAYS block of a BBJ_CALLFINALLY/BBJ_ALWAYS pair, * to avoid creating "retless" calls, since we need the BBJ_ALWAYS for the purpose * of unwinding, even if the call doesn't return (due to an explicit throw, for example). */ void Compiler::fgComputeEnterBlocksSet() { #ifdef DEBUG fgEnterBlksSetValid = false; #endif // DEBUG fgEnterBlks = BlockSetOps::MakeEmpty(this); /* Now set the entry basic block */ BlockSetOps::AddElemD(this, fgEnterBlks, fgFirstBB->bbNum); assert(fgFirstBB->bbNum == 1); if (compHndBBtabCount > 0) { /* Also 'or' in the handler basic blocks */ EHblkDsc* HBtab; EHblkDsc* HBtabEnd; for (HBtab = compHndBBtab, HBtabEnd = compHndBBtab + compHndBBtabCount; HBtab < HBtabEnd; HBtab++) { if (HBtab->HasFilter()) { BlockSetOps::AddElemD(this, fgEnterBlks, HBtab->ebdFilter->bbNum); } BlockSetOps::AddElemD(this, fgEnterBlks, HBtab->ebdHndBeg->bbNum); } } #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) // TODO-ARM-Cleanup: The ARM code here to prevent creating retless calls by adding the BBJ_ALWAYS // to the enter blocks is a bit of a compromise, because sometimes the blocks are already reachable, // and it messes up DFS ordering to have them marked as enter block. We should prevent the // creation of retless calls some other way. for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext) { if (block->bbJumpKind == BBJ_CALLFINALLY) { assert(block->isBBCallAlwaysPair()); // Don't remove the BBJ_ALWAYS block that is only here for the unwinder. It might be dead // if the finally is no-return, so mark it as an entry point. BlockSetOps::AddElemD(this, fgEnterBlks, block->bbNext->bbNum); } } #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) #ifdef DEBUG if (verbose) { printf("Enter blocks: "); BlockSetOps::Iter iter(this, fgEnterBlks); unsigned bbNum = 0; while (iter.NextElem(&bbNum)) { printf(FMT_BB " ", bbNum); } printf("\n"); } #endif // DEBUG #ifdef DEBUG fgEnterBlksSetValid = true; #endif // DEBUG } /***************************************************************************** * Remove unreachable blocks. * * Return true if any unreachable blocks were removed. */ bool Compiler::fgRemoveUnreachableBlocks() { assert(!fgCheapPredsValid); assert(fgReachabilitySetsValid); bool hasLoops = false; bool hasUnreachableBlocks = false; BasicBlock* block; /* Record unreachable blocks */ for (block = fgFirstBB; block != nullptr; block = block->bbNext) { /* Internal throw blocks are also reachable */ if (fgIsThrowHlpBlk(block)) { goto SKIP_BLOCK; } else if (block == genReturnBB) { // Don't remove statements for the genReturnBB block, as we might have special hookups there. // For example, <BUGNUM> in VSW 364383, </BUGNUM> // the profiler hookup needs to have the "void GT_RETURN" statement // to properly set the info.compProfilerCallback flag. goto SKIP_BLOCK; } else { // If any of the entry blocks can reach this block, then we skip it. if (!BlockSetOps::IsEmptyIntersection(this, fgEnterBlks, block->bbReach)) { goto SKIP_BLOCK; } } // Remove all the code for the block fgUnreachableBlock(block); // Make sure that the block was marked as removed */ noway_assert(block->bbFlags & BBF_REMOVED); // Some blocks mark the end of trys and catches // and can't be removed. We convert these into // empty blocks of type BBJ_THROW if (block->bbFlags & BBF_DONT_REMOVE) { bool bIsBBCallAlwaysPair = block->isBBCallAlwaysPair(); /* Unmark the block as removed, */ /* clear BBF_INTERNAL as well and set BBJ_IMPORTED */ block->bbFlags &= ~(BBF_REMOVED | BBF_INTERNAL | BBF_NEEDS_GCPOLL); block->bbFlags |= BBF_IMPORTED; block->bbJumpKind = BBJ_THROW; block->bbSetRunRarely(); #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) // If this is a <BBJ_CALLFINALLY, BBJ_ALWAYS> pair, we have to clear BBF_FINALLY_TARGET flag on // the target node (of BBJ_ALWAYS) since BBJ_CALLFINALLY node is getting converted to a BBJ_THROW. if (bIsBBCallAlwaysPair) { noway_assert(block->bbNext->bbJumpKind == BBJ_ALWAYS); fgClearFinallyTargetBit(block->bbNext->bbJumpDest); } #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) } else { /* We have to call fgRemoveBlock next */ hasUnreachableBlocks = true; } continue; SKIP_BLOCK:; // if (block->isRunRarely()) // continue; if (block->bbJumpKind == BBJ_RETURN) { continue; } /* Set BBF_LOOP_HEAD if we have backwards branches to this block */ unsigned blockNum = block->bbNum; for (flowList* pred = block->bbPreds; pred != nullptr; pred = pred->flNext) { BasicBlock* predBlock = pred->flBlock; if (blockNum <= predBlock->bbNum) { if (predBlock->bbJumpKind == BBJ_CALLFINALLY) { continue; } /* If block can reach predBlock then we have a loop head */ if (BlockSetOps::IsMember(this, predBlock->bbReach, blockNum)) { hasLoops = true; /* Set the BBF_LOOP_HEAD flag */ block->bbFlags |= BBF_LOOP_HEAD; break; } } } } fgHasLoops = hasLoops; if (hasUnreachableBlocks) { // Now remove the unreachable blocks for (block = fgFirstBB; block != nullptr; block = block->bbNext) { // If we mark the block with BBF_REMOVED then // we need to call fgRemovedBlock() on it if (block->bbFlags & BBF_REMOVED) { fgRemoveBlock(block, true); // When we have a BBJ_CALLFINALLY, BBJ_ALWAYS pair; fgRemoveBlock will remove // both blocks, so we must advance 1 extra place in the block list // if (block->isBBCallAlwaysPair()) { block = block->bbNext; } } } } return hasUnreachableBlocks; } /***************************************************************************** * * Function called to compute the dominator and reachable sets. * * Assumes the predecessor lists are computed and correct. */ void Compiler::fgComputeReachability() { #ifdef DEBUG if (verbose) { printf("*************** In fgComputeReachability\n"); } fgVerifyHandlerTab(); // Make sure that the predecessor lists are accurate assert(fgComputePredsDone); fgDebugCheckBBlist(); #endif // DEBUG /* Create a list of all BBJ_RETURN blocks. The head of the list is 'fgReturnBlocks'. */ fgReturnBlocks = nullptr; for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext) { // If this is a BBJ_RETURN block, add it to our list of all BBJ_RETURN blocks. This list is only // used to find return blocks. if (block->bbJumpKind == BBJ_RETURN) { fgReturnBlocks = new (this, CMK_Reachability) BasicBlockList(block, fgReturnBlocks); } } // Compute reachability and then delete blocks determined to be unreachable. If we delete blocks, we // need to loop, as that might have caused more blocks to become unreachable. This can happen in the // case where a call to a finally is unreachable and deleted (maybe the call to the finally is // preceded by a throw or an infinite loop), making the blocks following the finally unreachable. // However, all EH entry blocks are considered global entry blocks, causing the blocks following the // call to the finally to stay rooted, until a second round of reachability is done. // The dominator algorithm expects that all blocks can be reached from the fgEnterBlks set. unsigned passNum = 1; bool changed; do { // Just to be paranoid, avoid infinite loops; fall back to minopts. if (passNum > 10) { noway_assert(!"Too many unreachable block removal loops"); } /* Walk the flow graph, reassign block numbers to keep them in ascending order */ JITDUMP("\nRenumbering the basic blocks for fgComputeReachability pass #%u\n", passNum); passNum++; fgRenumberBlocks(); // // Compute fgEnterBlks // fgComputeEnterBlocksSet(); // // Compute bbReach // fgComputeReachabilitySets(); // // Use reachability information to delete unreachable blocks. // Also, determine if the flow graph has loops and set 'fgHasLoops' accordingly. // Set the BBF_LOOP_HEAD flag on the block target of backwards branches. // changed = fgRemoveUnreachableBlocks(); } while (changed); #ifdef DEBUG if (verbose) { printf("\nAfter computing reachability:\n"); fgDispBasicBlocks(verboseTrees); printf("\n"); } fgVerifyHandlerTab(); fgDebugCheckBBlist(true); #endif // DEBUG // // Now, compute the dominators // fgComputeDoms(); } /** In order to be able to compute dominance, we need to first get a DFS reverse post order sort on the basic flow graph * for the dominance algorithm to operate correctly. The reason why we need the DFS sort is because * we will build the dominance sets using the partial order induced by the DFS sorting. With this * precondition not holding true, the algorithm doesn't work properly. */ void Compiler::fgDfsInvPostOrder() { // NOTE: This algorithm only pays attention to the actual blocks. It ignores the imaginary entry block. // visited : Once we run the DFS post order sort recursive algorithm, we mark the nodes we visited to avoid // backtracking. BlockSet visited(BlockSetOps::MakeEmpty(this)); // We begin by figuring out which basic blocks don't have incoming edges and mark them as // start nodes. Later on we run the recursive algorithm for each node that we // mark in this step. BlockSet_ValRet_T startNodes = fgDomFindStartNodes(); // Make sure fgEnterBlks are still there in startNodes, even if they participate in a loop (i.e., there is // an incoming edge into the block). assert(fgEnterBlksSetValid); #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) // // BlockSetOps::UnionD(this, startNodes, fgEnterBlks); // // This causes problems on ARM, because we for BBJ_CALLFINALLY/BBJ_ALWAYS pairs, we add the BBJ_ALWAYS // to the enter blocks set to prevent flow graph optimizations from removing it and creating retless call finallies // (BBF_RETLESS_CALL). This leads to an incorrect DFS ordering in some cases, because we start the recursive walk // from the BBJ_ALWAYS, which is reachable from other blocks. A better solution would be to change ARM to avoid // creating retless calls in a different way, not by adding BBJ_ALWAYS to fgEnterBlks. // // So, let us make sure at least fgFirstBB is still there, even if it participates in a loop. BlockSetOps::AddElemD(this, startNodes, 1); assert(fgFirstBB->bbNum == 1); #else BlockSetOps::UnionD(this, startNodes, fgEnterBlks); #endif assert(BlockSetOps::IsMember(this, startNodes, fgFirstBB->bbNum)); // Call the flowgraph DFS traversal helper. unsigned postIndex = 1; for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext) { // If the block has no predecessors, and we haven't already visited it (because it's in fgEnterBlks but also // reachable from the first block), go ahead and traverse starting from this block. if (BlockSetOps::IsMember(this, startNodes, block->bbNum) && !BlockSetOps::IsMember(this, visited, block->bbNum)) { fgDfsInvPostOrderHelper(block, visited, &postIndex); } } // After the DFS reverse postorder is completed, we must have visited all the basic blocks. noway_assert(postIndex == fgBBcount + 1); noway_assert(fgBBNumMax == fgBBcount); #ifdef DEBUG if (0 && verbose) { printf("\nAfter doing a post order traversal of the BB graph, this is the ordering:\n"); for (unsigned i = 1; i <= fgBBNumMax; ++i) { printf("%02u -> " FMT_BB "\n", i, fgBBInvPostOrder[i]->bbNum); } printf("\n"); } #endif // DEBUG } BlockSet_ValRet_T Compiler::fgDomFindStartNodes() { unsigned j; BasicBlock* block; // startNodes :: A set that represents which basic blocks in the flow graph don't have incoming edges. // We begin assuming everything is a start block and remove any block that is being referenced by another in its // successor list. BlockSet startNodes(BlockSetOps::MakeFull(this)); for (block = fgFirstBB; block != nullptr; block = block->bbNext) { unsigned cSucc = block->NumSucc(this); for (j = 0; j < cSucc; ++j) { BasicBlock* succ = block->GetSucc(j, this); BlockSetOps::RemoveElemD(this, startNodes, succ->bbNum); } } #ifdef DEBUG if (verbose) { printf("\nDominator computation start blocks (those blocks with no incoming edges):\n"); BlockSetOps::Iter iter(this, startNodes); unsigned bbNum = 0; while (iter.NextElem(&bbNum)) { printf(FMT_BB " ", bbNum); } printf("\n"); } #endif // DEBUG return startNodes; } //------------------------------------------------------------------------ // fgDfsInvPostOrderHelper: Helper to assign post-order numbers to blocks. // // Arguments: // block - The starting entry block // visited - The set of visited blocks // count - Pointer to the Dfs counter // // Notes: // Compute a non-recursive DFS traversal of the flow graph using an // evaluation stack to assign post-order numbers. void Compiler::fgDfsInvPostOrderHelper(BasicBlock* block, BlockSet& visited, unsigned* count) { // Assume we haven't visited this node yet (callers ensure this). assert(!BlockSetOps::IsMember(this, visited, block->bbNum)); // Allocate a local stack to hold the DFS traversal actions necessary // to compute pre/post-ordering of the control flowgraph. ArrayStack<DfsBlockEntry> stack(getAllocator(CMK_ArrayStack)); // Push the first block on the stack to seed the traversal. stack.Push(DfsBlockEntry(DSS_Pre, block)); // Flag the node we just visited to avoid backtracking. BlockSetOps::AddElemD(this, visited, block->bbNum); // The search is terminated once all the actions have been processed. while (!stack.Empty()) { DfsBlockEntry current = stack.Pop(); BasicBlock* currentBlock = current.dfsBlock; if (current.dfsStackState == DSS_Pre) { // This is a pre-visit that corresponds to the first time the // node is encountered in the spanning tree and receives pre-order // numberings. By pushing the post-action on the stack here we // are guaranteed to only process it after all of its successors // pre and post actions are processed. stack.Push(DfsBlockEntry(DSS_Post, currentBlock)); unsigned cSucc = currentBlock->NumSucc(this); for (unsigned j = 0; j < cSucc; ++j) { BasicBlock* succ = currentBlock->GetSucc(j, this); // If this is a node we haven't seen before, go ahead and process if (!BlockSetOps::IsMember(this, visited, succ->bbNum)) { // Push a pre-visit action for this successor onto the stack and // mark it as visited in case this block has multiple successors // to the same node (multi-graph). stack.Push(DfsBlockEntry(DSS_Pre, succ)); BlockSetOps::AddElemD(this, visited, succ->bbNum); } } } else { // This is a post-visit that corresponds to the last time the // node is visited in the spanning tree and only happens after // all descendents in the spanning tree have had pre and post // actions applied. assert(current.dfsStackState == DSS_Post); unsigned invCount = fgBBcount - *count + 1; assert(1 <= invCount && invCount <= fgBBNumMax); fgBBInvPostOrder[invCount] = currentBlock; currentBlock->bbDfsNum = invCount; ++(*count); } } } void Compiler::fgComputeDoms() { assert(!fgCheapPredsValid); #ifdef DEBUG if (verbose) { printf("*************** In fgComputeDoms\n"); } fgVerifyHandlerTab(); // Make sure that the predecessor lists are accurate. // Also check that the blocks are properly, densely numbered (so calling fgRenumberBlocks is not necessary). fgDebugCheckBBlist(true); // Assert things related to the BlockSet epoch. assert(fgBBcount == fgBBNumMax); assert(BasicBlockBitSetTraits::GetSize(this) == fgBBNumMax + 1); #endif // DEBUG BlockSet processedBlks(BlockSetOps::MakeEmpty(this)); fgBBInvPostOrder = new (this, CMK_DominatorMemory) BasicBlock*[fgBBNumMax + 1]; memset(fgBBInvPostOrder, 0, sizeof(BasicBlock*) * (fgBBNumMax + 1)); fgDfsInvPostOrder(); noway_assert(fgBBInvPostOrder[0] == nullptr); // flRoot and bbRoot represent an imaginary unique entry point in the flow graph. // All the orphaned EH blocks and fgFirstBB will temporarily have its predecessors list // (with bbRoot as the only basic block in it) set as flRoot. // Later on, we clear their predecessors and let them to be nullptr again. // Since we number basic blocks starting at one, the imaginary entry block is conveniently numbered as zero. flowList flRoot; BasicBlock bbRoot; bbRoot.bbPreds = nullptr; bbRoot.bbNum = 0; bbRoot.bbIDom = &bbRoot; bbRoot.bbDfsNum = 0; bbRoot.bbFlags = 0; flRoot.flNext = nullptr; flRoot.flBlock = &bbRoot; fgBBInvPostOrder[0] = &bbRoot; // Mark both bbRoot and fgFirstBB processed BlockSetOps::AddElemD(this, processedBlks, 0); // bbRoot == block #0 BlockSetOps::AddElemD(this, processedBlks, 1); // fgFirstBB == block #1 assert(fgFirstBB->bbNum == 1); // Special case fgFirstBB to say its IDom is bbRoot. fgFirstBB->bbIDom = &bbRoot; BasicBlock* block = nullptr; for (block = fgFirstBB->bbNext; block != nullptr; block = block->bbNext) { // If any basic block has no predecessors then we flag it as processed and temporarily // mark its precedessor list to be flRoot. This makes the flowgraph connected, // a precondition that is needed by the dominance algorithm to operate properly. if (block->bbPreds == nullptr) { block->bbPreds = &flRoot; block->bbIDom = &bbRoot; BlockSetOps::AddElemD(this, processedBlks, block->bbNum); } else { block->bbIDom = nullptr; } } // Mark the EH blocks as entry blocks and also flag them as processed. if (compHndBBtabCount > 0) { EHblkDsc* HBtab; EHblkDsc* HBtabEnd; for (HBtab = compHndBBtab, HBtabEnd = compHndBBtab + compHndBBtabCount; HBtab < HBtabEnd; HBtab++) { if (HBtab->HasFilter()) { HBtab->ebdFilter->bbIDom = &bbRoot; BlockSetOps::AddElemD(this, processedBlks, HBtab->ebdFilter->bbNum); } HBtab->ebdHndBeg->bbIDom = &bbRoot; BlockSetOps::AddElemD(this, processedBlks, HBtab->ebdHndBeg->bbNum); } } // Now proceed to compute the immediate dominators for each basic block. bool changed = true; while (changed) { changed = false; for (unsigned i = 1; i <= fgBBNumMax; ++i) // Process each actual block; don't process the imaginary predecessor block. { flowList* first = nullptr; BasicBlock* newidom = nullptr; block = fgBBInvPostOrder[i]; // If we have a block that has bbRoot as its bbIDom // it means we flag it as processed and as an entry block so // in this case we're all set. if (block->bbIDom == &bbRoot) { continue; } // Pick up the first processed predecesor of the current block. for (first = block->bbPreds; first != nullptr; first = first->flNext) { if (BlockSetOps::IsMember(this, processedBlks, first->flBlock->bbNum)) { break; } } noway_assert(first != nullptr); // We assume the first processed predecessor will be the // immediate dominator and then compute the forward flow analysis. newidom = first->flBlock; for (flowList* p = block->bbPreds; p != nullptr; p = p->flNext) { if (p->flBlock == first->flBlock) { continue; } if (p->flBlock->bbIDom != nullptr) { // fgIntersectDom is basically the set intersection between // the dominance sets of the new IDom and the current predecessor // Since the nodes are ordered in DFS inverse post order and // IDom induces a tree, fgIntersectDom actually computes // the lowest common ancestor in the dominator tree. newidom = fgIntersectDom(p->flBlock, newidom); } } // If the Immediate dominator changed, assign the new one // to the current working basic block. if (block->bbIDom != newidom) { noway_assert(newidom != nullptr); block->bbIDom = newidom; changed = true; } BlockSetOps::AddElemD(this, processedBlks, block->bbNum); } } // As stated before, once we have computed immediate dominance we need to clear // all the basic blocks whose predecessor list was set to flRoot. This // reverts that and leaves the blocks the same as before. for (block = fgFirstBB; block != nullptr; block = block->bbNext) { if (block->bbPreds == &flRoot) { block->bbPreds = nullptr; } } fgCompDominatedByExceptionalEntryBlocks(); #ifdef DEBUG if (verbose) { fgDispDoms(); } #endif fgBuildDomTree(); fgModified = false; fgDomBBcount = fgBBcount; assert(fgBBcount == fgBBNumMax); assert(BasicBlockBitSetTraits::GetSize(this) == fgDomBBcount + 1); fgDomsComputed = true; } void Compiler::fgBuildDomTree() { unsigned i; BasicBlock* block; #ifdef DEBUG if (verbose) { printf("\nInside fgBuildDomTree\n"); } #endif // DEBUG // domTree :: The dominance tree represented using adjacency lists. We use BasicBlockList to represent edges. // Indexed by basic block number. unsigned bbArraySize = fgBBNumMax + 1; BasicBlockList** domTree = new (this, CMK_DominatorMemory) BasicBlockList*[bbArraySize]; fgDomTreePreOrder = new (this, CMK_DominatorMemory) unsigned[bbArraySize]; fgDomTreePostOrder = new (this, CMK_DominatorMemory) unsigned[bbArraySize]; // Initialize all the data structures. for (i = 0; i < bbArraySize; ++i) { domTree[i] = nullptr; fgDomTreePreOrder[i] = fgDomTreePostOrder[i] = 0; } // Build the dominance tree. for (block = fgFirstBB; block != nullptr; block = block->bbNext) { // If the immediate dominator is not the imaginary root (bbRoot) // we proceed to append this block to the children of the dominator node. if (block->bbIDom->bbNum != 0) { int bbNum = block->bbIDom->bbNum; domTree[bbNum] = new (this, CMK_DominatorMemory) BasicBlockList(block, domTree[bbNum]); } else { // This means this block had bbRoot set as its IDom. We clear it out // and convert the tree back to a forest. block->bbIDom = nullptr; } } #ifdef DEBUG if (verbose) { printf("\nAfter computing the Dominance Tree:\n"); fgDispDomTree(domTree); } #endif // DEBUG // Get the bitset that represents the roots of the dominance tree. // Something to note here is that the dominance tree has been converted from a forest to a tree // by using the bbRoot trick on fgComputeDoms. The reason we have a forest instead of a real tree // is because we treat the EH blocks as entry nodes so the real dominance tree is not necessarily connected. BlockSet_ValRet_T domTreeEntryNodes = fgDomTreeEntryNodes(domTree); // The preorder and postorder numbers. // We start from 1 to match the bbNum ordering. unsigned preNum = 1; unsigned postNum = 1; // There will be nodes in the dominance tree that will not be reachable: // the catch blocks that return since they don't have any predecessor. // For that matter we'll keep track of how many nodes we can // reach and assert at the end that we visited all of them. unsigned domTreeReachable = fgBBcount; // Once we have the dominance tree computed, we need to traverse it // to get the preorder and postorder numbers for each node. The purpose of // this is to achieve O(1) queries for of the form A dominates B. for (i = 1; i <= fgBBNumMax; ++i) { if (BlockSetOps::IsMember(this, domTreeEntryNodes, i)) { if (domTree[i] == nullptr) { // If this is an entry node but there's no children on this // node, it means it's unreachable so we decrement the reachable // counter. --domTreeReachable; } else { // Otherwise, we do a DFS traversal of the dominator tree. fgTraverseDomTree(i, domTree, &preNum, &postNum); } } } noway_assert(preNum == domTreeReachable + 1); noway_assert(postNum == domTreeReachable + 1); // Once we have all the reachable nodes numbered, we proceed to // assign numbers to the non-reachable ones, just assign incrementing // values. We must reach fgBBcount at the end. for (i = 1; i <= fgBBNumMax; ++i) { if (BlockSetOps::IsMember(this, domTreeEntryNodes, i)) { if (domTree[i] == nullptr) { fgDomTreePreOrder[i] = preNum++; fgDomTreePostOrder[i] = postNum++; } } } noway_assert(preNum == fgBBNumMax + 1); noway_assert(postNum == fgBBNumMax + 1); noway_assert(fgDomTreePreOrder[0] == 0); // Unused first element noway_assert(fgDomTreePostOrder[0] == 0); // Unused first element #ifdef DEBUG if (0 && verbose) { printf("\nAfter traversing the dominance tree:\n"); printf("PreOrder:\n"); for (i = 1; i <= fgBBNumMax; ++i) { printf(FMT_BB " : %02u\n", i, fgDomTreePreOrder[i]); } printf("PostOrder:\n"); for (i = 1; i <= fgBBNumMax; ++i) { printf(FMT_BB " : %02u\n", i, fgDomTreePostOrder[i]); } } #endif // DEBUG } BlockSet_ValRet_T Compiler::fgDomTreeEntryNodes(BasicBlockList** domTree) { // domTreeEntryNodes :: Set that represents which basic blocks are roots of the dominator forest. BlockSet domTreeEntryNodes(BlockSetOps::MakeFull(this)); // First of all we need to find all the roots of the dominance forest. for (unsigned i = 1; i <= fgBBNumMax; ++i) { for (BasicBlockList* current = domTree[i]; current != nullptr; current = current->next) { BlockSetOps::RemoveElemD(this, domTreeEntryNodes, current->block->bbNum); } } return domTreeEntryNodes; } #ifdef DEBUG void Compiler::fgDispDomTree(BasicBlockList** domTree) { for (unsigned i = 1; i <= fgBBNumMax; ++i) { if (domTree[i] != nullptr) { printf(FMT_BB " : ", i); for (BasicBlockList* current = domTree[i]; current != nullptr; current = current->next) { assert(current->block); printf(FMT_BB " ", current->block->bbNum); } printf("\n"); } } printf("\n"); } #endif // DEBUG //------------------------------------------------------------------------ // fgTraverseDomTree: Assign pre/post-order numbers to the dominator tree. // // Arguments: // bbNum - The basic block number of the starting block // domTree - The dominator tree (as child block lists) // preNum - Pointer to the pre-number counter // postNum - Pointer to the post-number counter // // Notes: // Runs a non-recursive DFS traversal of the dominator tree using an // evaluation stack to assign pre-order and post-order numbers. // These numberings are used to provide constant time lookup for // ancestor/descendent tests between pairs of nodes in the tree. void Compiler::fgTraverseDomTree(unsigned bbNum, BasicBlockList** domTree, unsigned* preNum, unsigned* postNum) { noway_assert(bbNum <= fgBBNumMax); // If the block preorder number is not zero it means we already visited // that node, so we skip it. if (fgDomTreePreOrder[bbNum] == 0) { // If this is the first time we visit this node, both preorder and postnumber // values must be zero. noway_assert(fgDomTreePostOrder[bbNum] == 0); // Allocate a local stack to hold the Dfs traversal actions necessary // to compute pre/post-ordering of the dominator tree. ArrayStack<DfsNumEntry> stack(getAllocator(CMK_ArrayStack)); // Push the first entry number on the stack to seed the traversal. stack.Push(DfsNumEntry(DSS_Pre, bbNum)); // The search is terminated once all the actions have been processed. while (!stack.Empty()) { DfsNumEntry current = stack.Pop(); unsigned currentNum = current.dfsNum; if (current.dfsStackState == DSS_Pre) { // This pre-visit action corresponds to the first time the // node is encountered during the spanning traversal. noway_assert(fgDomTreePreOrder[currentNum] == 0); noway_assert(fgDomTreePostOrder[currentNum] == 0); // Assign the preorder number on the first visit. fgDomTreePreOrder[currentNum] = (*preNum)++; // Push this nodes post-action on the stack such that all successors // pre-order visits occur before this nodes post-action. We will assign // its post-order numbers when we pop off the stack. stack.Push(DfsNumEntry(DSS_Post, currentNum)); // For each child in the dominator tree process its pre-actions. for (BasicBlockList* child = domTree[currentNum]; child != nullptr; child = child->next) { unsigned childNum = child->block->bbNum; // This is a tree so never could have been visited assert(fgDomTreePreOrder[childNum] == 0); // Push the successor in the dominator tree for pre-actions. stack.Push(DfsNumEntry(DSS_Pre, childNum)); } } else { // This post-visit action corresponds to the last time the node // is encountered and only after all descendents in the spanning // tree have had pre and post-order numbers assigned. assert(current.dfsStackState == DSS_Post); assert(fgDomTreePreOrder[currentNum] != 0); assert(fgDomTreePostOrder[currentNum] == 0); // Now assign this nodes post-order number. fgDomTreePostOrder[currentNum] = (*postNum)++; } } } } // This code finds the lowest common ancestor in the // dominator tree between two basic blocks. The LCA in the Dominance tree // represents the closest dominator between the two basic blocks. Used to // adjust the IDom value in fgComputDoms. BasicBlock* Compiler::fgIntersectDom(BasicBlock* a, BasicBlock* b) { BasicBlock* finger1 = a; BasicBlock* finger2 = b; while (finger1 != finger2) { while (finger1->bbDfsNum > finger2->bbDfsNum) { finger1 = finger1->bbIDom; } while (finger2->bbDfsNum > finger1->bbDfsNum) { finger2 = finger2->bbIDom; } } return finger1; } // Return a BlockSet containing all the blocks that dominate 'block'. BlockSet_ValRet_T Compiler::fgGetDominatorSet(BasicBlock* block) { assert(block != nullptr); BlockSet domSet(BlockSetOps::MakeEmpty(this)); do { BlockSetOps::AddElemD(this, domSet, block->bbNum); if (block == block->bbIDom) { break; // We found a cycle in the IDom list, so we're done. } block = block->bbIDom; } while (block != nullptr); return domSet; } /***************************************************************************** * * fgComputeCheapPreds: Function called to compute the BasicBlock::bbCheapPreds lists. * * No other block data is changed (e.g., bbRefs, bbFlags). * * The cheap preds lists are similar to the normal (bbPreds) predecessor lists, but are cheaper to * compute and store, as follows: * 1. A flow edge is typed BasicBlockList, which only has a block pointer and 'next' pointer. It doesn't * have weights or a dup count. * 2. The preds list for a block is not sorted by block number. * 3. The predecessors of the block following a BBJ_CALLFINALLY (the corresponding BBJ_ALWAYS, * for normal, non-retless calls to the finally) are not computed. * 4. The cheap preds lists will contain duplicates if a single switch table has multiple branches * to the same block. Thus, we don't spend the time looking for duplicates for every edge we insert. */ void Compiler::fgComputeCheapPreds() { noway_assert(!fgComputePredsDone); // We can't do this if we've got the full preds. noway_assert(fgFirstBB != nullptr); BasicBlock* block; #ifdef DEBUG if (verbose) { printf("\n*************** In fgComputeCheapPreds()\n"); fgDispBasicBlocks(); printf("\n"); } #endif // DEBUG // Clear out the cheap preds lists. fgRemovePreds(); for (block = fgFirstBB; block != nullptr; block = block->bbNext) { switch (block->bbJumpKind) { case BBJ_COND: fgAddCheapPred(block->bbJumpDest, block); fgAddCheapPred(block->bbNext, block); break; case BBJ_CALLFINALLY: case BBJ_LEAVE: // If fgComputeCheapPreds is called before all blocks are imported, BBJ_LEAVE blocks are // still in the BB list. case BBJ_ALWAYS: case BBJ_EHCATCHRET: fgAddCheapPred(block->bbJumpDest, block); break; case BBJ_NONE: fgAddCheapPred(block->bbNext, block); break; case BBJ_EHFILTERRET: // Connect end of filter to catch handler. // In a well-formed program, this cannot be null. Tolerate here, so that we can call // fgComputeCheapPreds before fgImport on an ill-formed program; the problem will be detected in // fgImport. if (block->bbJumpDest != nullptr) { fgAddCheapPred(block->bbJumpDest, block); } break; case BBJ_SWITCH: unsigned jumpCnt; jumpCnt = block->bbJumpSwt->bbsCount; BasicBlock** jumpTab; jumpTab = block->bbJumpSwt->bbsDstTab; do { fgAddCheapPred(*jumpTab, block); } while (++jumpTab, --jumpCnt); break; case BBJ_EHFINALLYRET: // It's expensive to compute the preds for this case, so we don't for the cheap // preds. case BBJ_THROW: case BBJ_RETURN: break; default: noway_assert(!"Unexpected bbJumpKind"); break; } } fgCheapPredsValid = true; #ifdef DEBUG if (verbose) { printf("\n*************** After fgComputeCheapPreds()\n"); fgDispBasicBlocks(); printf("\n"); } #endif } /***************************************************************************** * Add 'blockPred' to the cheap predecessor list of 'block'. */ void Compiler::fgAddCheapPred(BasicBlock* block, BasicBlock* blockPred) { assert(!fgComputePredsDone); assert(block != nullptr); assert(blockPred != nullptr); block->bbCheapPreds = new (this, CMK_FlowList) BasicBlockList(blockPred, block->bbCheapPreds); #if MEASURE_BLOCK_SIZE genFlowNodeCnt += 1; genFlowNodeSize += sizeof(BasicBlockList); #endif // MEASURE_BLOCK_SIZE } /***************************************************************************** * Remove 'blockPred' from the cheap predecessor list of 'block'. * If there are duplicate edges, only remove one of them. */ void Compiler::fgRemoveCheapPred(BasicBlock* block, BasicBlock* blockPred) { assert(!fgComputePredsDone); assert(fgCheapPredsValid); flowList* oldEdge = nullptr; assert(block != nullptr); assert(blockPred != nullptr); assert(block->bbCheapPreds != nullptr); /* Is this the first block in the pred list? */ if (blockPred == block->bbCheapPreds->block) { block->bbCheapPreds = block->bbCheapPreds->next; } else { BasicBlockList* pred; for (pred = block->bbCheapPreds; pred->next != nullptr; pred = pred->next) { if (blockPred == pred->next->block) { break; } } noway_assert(pred->next != nullptr); // we better have found it! pred->next = pred->next->next; // splice it out } } void Compiler::fgRemovePreds() { C_ASSERT(offsetof(BasicBlock, bbPreds) == offsetof(BasicBlock, bbCheapPreds)); // bbPreds and bbCheapPreds are at the same place in a union, C_ASSERT(sizeof(((BasicBlock*)nullptr)->bbPreds) == sizeof(((BasicBlock*)nullptr)->bbCheapPreds)); // and are the same size. So, this function removes both. for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext) { block->bbPreds = nullptr; } fgComputePredsDone = false; fgCheapPredsValid = false; } /***************************************************************************** * * Function called to compute the bbPreds lists. */ void Compiler::fgComputePreds() { noway_assert(fgFirstBB); BasicBlock* block; #ifdef DEBUG if (verbose) { printf("\n*************** In fgComputePreds()\n"); fgDispBasicBlocks(); printf("\n"); } #endif // DEBUG // reset the refs count for each basic block for (block = fgFirstBB; block; block = block->bbNext) { block->bbRefs = 0; } /* the first block is always reachable! */ fgFirstBB->bbRefs = 1; /* Treat the initial block as a jump target */ fgFirstBB->bbFlags |= BBF_JMP_TARGET | BBF_HAS_LABEL; fgRemovePreds(); for (block = fgFirstBB; block; block = block->bbNext) { switch (block->bbJumpKind) { case BBJ_CALLFINALLY: if (!(block->bbFlags & BBF_RETLESS_CALL)) { assert(block->isBBCallAlwaysPair()); /* Mark the next block as being a jump target, since the call target will return there */ PREFIX_ASSUME(block->bbNext != nullptr); block->bbNext->bbFlags |= (BBF_JMP_TARGET | BBF_HAS_LABEL); } __fallthrough; case BBJ_LEAVE: // Sometimes fgComputePreds is called before all blocks are imported, so BBJ_LEAVE // blocks are still in the BB list. case BBJ_COND: case BBJ_ALWAYS: case BBJ_EHCATCHRET: /* Mark the jump dest block as being a jump target */ block->bbJumpDest->bbFlags |= BBF_JMP_TARGET | BBF_HAS_LABEL; fgAddRefPred(block->bbJumpDest, block, nullptr, true); /* Is the next block reachable? */ if (block->bbJumpKind != BBJ_COND) { break; } noway_assert(block->bbNext); /* Fall through, the next block is also reachable */ __fallthrough; case BBJ_NONE: fgAddRefPred(block->bbNext, block, nullptr, true); break; case BBJ_EHFILTERRET: // Connect end of filter to catch handler. // In a well-formed program, this cannot be null. Tolerate here, so that we can call // fgComputePreds before fgImport on an ill-formed program; the problem will be detected in fgImport. if (block->bbJumpDest != nullptr) { fgAddRefPred(block->bbJumpDest, block, nullptr, true); } break; case BBJ_EHFINALLYRET: { /* Connect the end of the finally to the successor of the call to this finally */ if (!block->hasHndIndex()) { NO_WAY("endfinally outside a finally/fault block."); } unsigned hndIndex = block->getHndIndex(); EHblkDsc* ehDsc = ehGetDsc(hndIndex); if (!ehDsc->HasFinallyOrFaultHandler()) { NO_WAY("endfinally outside a finally/fault block."); } if (ehDsc->HasFinallyHandler()) { // Find all BBJ_CALLFINALLY that branched to this finally handler. BasicBlock* begBlk; BasicBlock* endBlk; ehGetCallFinallyBlockRange(hndIndex, &begBlk, &endBlk); BasicBlock* finBeg = ehDsc->ebdHndBeg; for (BasicBlock* bcall = begBlk; bcall != endBlk; bcall = bcall->bbNext) { if (bcall->bbJumpKind != BBJ_CALLFINALLY || bcall->bbJumpDest != finBeg) { continue; } noway_assert(bcall->isBBCallAlwaysPair()); fgAddRefPred(bcall->bbNext, block, nullptr, true); } } } break; case BBJ_THROW: case BBJ_RETURN: break; case BBJ_SWITCH: unsigned jumpCnt; jumpCnt = block->bbJumpSwt->bbsCount; BasicBlock** jumpTab; jumpTab = block->bbJumpSwt->bbsDstTab; do { /* Mark the target block as being a jump target */ (*jumpTab)->bbFlags |= BBF_JMP_TARGET | BBF_HAS_LABEL; fgAddRefPred(*jumpTab, block, nullptr, true); } while (++jumpTab, --jumpCnt); break; default: noway_assert(!"Unexpected bbJumpKind"); break; } } for (unsigned EHnum = 0; EHnum < compHndBBtabCount; EHnum++) { EHblkDsc* ehDsc = ehGetDsc(EHnum); if (ehDsc->HasFilter()) { ehDsc->ebdFilter->bbFlags |= BBF_JMP_TARGET | BBF_HAS_LABEL; // The first block of a filter has an artifical extra refcount. ehDsc->ebdFilter->bbRefs++; } ehDsc->ebdHndBeg->bbFlags |= BBF_JMP_TARGET | BBF_HAS_LABEL; // The first block of a handler has an artificial extra refcount. ehDsc->ebdHndBeg->bbRefs++; } fgModified = false; fgComputePredsDone = true; #ifdef DEBUG if (verbose) { printf("\n*************** After fgComputePreds()\n"); fgDispBasicBlocks(); printf("\n"); } #endif } unsigned Compiler::fgNSuccsOfFinallyRet(BasicBlock* block) { BasicBlock* bb; unsigned res; fgSuccOfFinallyRetWork(block, ~0, &bb, &res); return res; } BasicBlock* Compiler::fgSuccOfFinallyRet(BasicBlock* block, unsigned i) { BasicBlock* bb; unsigned res; fgSuccOfFinallyRetWork(block, i, &bb, &res); return bb; } void Compiler::fgSuccOfFinallyRetWork(BasicBlock* block, unsigned i, BasicBlock** bres, unsigned* nres) { assert(block->hasHndIndex()); // Otherwise, endfinally outside a finally/fault block? unsigned hndIndex = block->getHndIndex(); EHblkDsc* ehDsc = ehGetDsc(hndIndex); assert(ehDsc->HasFinallyOrFaultHandler()); // Otherwise, endfinally outside a finally/fault block. *bres = nullptr; unsigned succNum = 0; if (ehDsc->HasFinallyHandler()) { BasicBlock* begBlk; BasicBlock* endBlk; ehGetCallFinallyBlockRange(hndIndex, &begBlk, &endBlk); BasicBlock* finBeg = ehDsc->ebdHndBeg; for (BasicBlock* bcall = begBlk; bcall != endBlk; bcall = bcall->bbNext) { if (bcall->bbJumpKind != BBJ_CALLFINALLY || bcall->bbJumpDest != finBeg) { continue; } assert(bcall->isBBCallAlwaysPair()); if (succNum == i) { *bres = bcall->bbNext; return; } succNum++; } } assert(i == ~0u || ehDsc->HasFaultHandler()); // Should reach here only for fault blocks. if (i == ~0u) { *nres = succNum; } } Compiler::SwitchUniqueSuccSet Compiler::GetDescriptorForSwitch(BasicBlock* switchBlk) { assert(switchBlk->bbJumpKind == BBJ_SWITCH); BlockToSwitchDescMap* switchMap = GetSwitchDescMap(); SwitchUniqueSuccSet res; if (switchMap->Lookup(switchBlk, &res)) { return res; } else { // We must compute the descriptor. Find which are dups, by creating a bit set with the unique successors. // We create a temporary bitset of blocks to compute the unique set of successor blocks, // since adding a block's number twice leaves just one "copy" in the bitset. Note that // we specifically don't use the BlockSet type, because doing so would require making a // call to EnsureBasicBlockEpoch() to make sure the epoch is up-to-date. However, that // can create a new epoch, thus invalidating all existing BlockSet objects, such as // reachability information stored in the blocks. To avoid that, we just use a local BitVec. BitVecTraits blockVecTraits(fgBBNumMax + 1, this); BitVec uniqueSuccBlocks(BitVecOps::MakeEmpty(&blockVecTraits)); BasicBlock** jumpTable = switchBlk->bbJumpSwt->bbsDstTab; unsigned jumpCount = switchBlk->bbJumpSwt->bbsCount; for (unsigned i = 0; i < jumpCount; i++) { BasicBlock* targ = jumpTable[i]; BitVecOps::AddElemD(&blockVecTraits, uniqueSuccBlocks, targ->bbNum); } // Now we have a set of unique successors. unsigned numNonDups = BitVecOps::Count(&blockVecTraits, uniqueSuccBlocks); BasicBlock** nonDups = new (getAllocator()) BasicBlock*[numNonDups]; unsigned nonDupInd = 0; // At this point, all unique targets are in "uniqueSuccBlocks". As we encounter each, // add to nonDups, remove from "uniqueSuccBlocks". for (unsigned i = 0; i < jumpCount; i++) { BasicBlock* targ = jumpTable[i]; if (BitVecOps::IsMember(&blockVecTraits, uniqueSuccBlocks, targ->bbNum)) { nonDups[nonDupInd] = targ; nonDupInd++; BitVecOps::RemoveElemD(&blockVecTraits, uniqueSuccBlocks, targ->bbNum); } } assert(nonDupInd == numNonDups); assert(BitVecOps::Count(&blockVecTraits, uniqueSuccBlocks) == 0); res.numDistinctSuccs = numNonDups; res.nonDuplicates = nonDups; switchMap->Set(switchBlk, res); return res; } } void Compiler::SwitchUniqueSuccSet::UpdateTarget(CompAllocator alloc, BasicBlock* switchBlk, BasicBlock* from, BasicBlock* to) { assert(switchBlk->bbJumpKind == BBJ_SWITCH); // Precondition. unsigned jmpTabCnt = switchBlk->bbJumpSwt->bbsCount; BasicBlock** jmpTab = switchBlk->bbJumpSwt->bbsDstTab; // Is "from" still in the switch table (because it had more than one entry before?) bool fromStillPresent = false; for (unsigned i = 0; i < jmpTabCnt; i++) { if (jmpTab[i] == from) { fromStillPresent = true; break; } } // Is "to" already in "this"? bool toAlreadyPresent = false; for (unsigned i = 0; i < numDistinctSuccs; i++) { if (nonDuplicates[i] == to) { toAlreadyPresent = true; break; } } // Four cases: // If "from" is still present, and "to" is already present, do nothing // If "from" is still present, and "to" is not, must reallocate to add an entry. // If "from" is not still present, and "to" is not present, write "to" where "from" was. // If "from" is not still present, but "to" is present, remove "from". if (fromStillPresent && toAlreadyPresent) { return; } else if (fromStillPresent && !toAlreadyPresent) { // reallocate to add an entry BasicBlock** newNonDups = new (alloc) BasicBlock*[numDistinctSuccs + 1]; memcpy(newNonDups, nonDuplicates, numDistinctSuccs * sizeof(BasicBlock*)); newNonDups[numDistinctSuccs] = to; numDistinctSuccs++; nonDuplicates = newNonDups; } else if (!fromStillPresent && !toAlreadyPresent) { #ifdef DEBUG // write "to" where "from" was bool foundFrom = false; #endif // DEBUG for (unsigned i = 0; i < numDistinctSuccs; i++) { if (nonDuplicates[i] == from) { nonDuplicates[i] = to; #ifdef DEBUG foundFrom = true; #endif // DEBUG break; } } assert(foundFrom); } else { assert(!fromStillPresent && toAlreadyPresent); #ifdef DEBUG // remove "from". bool foundFrom = false; #endif // DEBUG for (unsigned i = 0; i < numDistinctSuccs; i++) { if (nonDuplicates[i] == from) { nonDuplicates[i] = nonDuplicates[numDistinctSuccs - 1]; numDistinctSuccs--; #ifdef DEBUG foundFrom = true; #endif // DEBUG break; } } assert(foundFrom); } } /***************************************************************************** * * Simple utility function to remove an entry for a block in the switch desc * map. So it can be called from other phases. * */ void Compiler::fgInvalidateSwitchDescMapEntry(BasicBlock* block) { // Check if map has no entries yet. if (m_switchDescMap != nullptr) { m_switchDescMap->Remove(block); } } void Compiler::UpdateSwitchTableTarget(BasicBlock* switchBlk, BasicBlock* from, BasicBlock* to) { if (m_switchDescMap == nullptr) { return; // No mappings, nothing to do. } // Otherwise... BlockToSwitchDescMap* switchMap = GetSwitchDescMap(); SwitchUniqueSuccSet* res = switchMap->LookupPointer(switchBlk); if (res != nullptr) { // If no result, nothing to do. Otherwise, update it. res->UpdateTarget(getAllocator(), switchBlk, from, to); } } /***************************************************************************** * For a block that is in a handler region, find the first block of the most-nested * handler containing the block. */ BasicBlock* Compiler::fgFirstBlockOfHandler(BasicBlock* block) { assert(block->hasHndIndex()); return ehGetDsc(block->getHndIndex())->ebdHndBeg; } /***************************************************************************** * * Function called to find back edges and return blocks and mark them as needing GC Polls. This marks all * blocks. */ void Compiler::fgMarkGCPollBlocks() { if (GCPOLL_NONE == opts.compGCPollType) { return; } #ifdef DEBUG /* Check that the flowgraph data (bbNum, bbRefs, bbPreds) is up-to-date */ fgDebugCheckBBlist(); #endif BasicBlock* block; // Return blocks always need GC polls. In addition, all back edges (including those from switch // statements) need GC polls. The poll is on the block with the outgoing back edge (or ret), rather than // on the destination or on the edge itself. for (block = fgFirstBB; block; block = block->bbNext) { bool blockNeedsPoll = false; switch (block->bbJumpKind) { case BBJ_COND: case BBJ_ALWAYS: blockNeedsPoll = (block->bbJumpDest->bbNum <= block->bbNum); break; case BBJ_RETURN: blockNeedsPoll = true; break; case BBJ_SWITCH: unsigned jumpCnt; jumpCnt = block->bbJumpSwt->bbsCount; BasicBlock** jumpTab; jumpTab = block->bbJumpSwt->bbsDstTab; do { if ((*jumpTab)->bbNum <= block->bbNum) { blockNeedsPoll = true; break; } } while (++jumpTab, --jumpCnt); break; default: break; } if (blockNeedsPoll) { block->bbFlags |= BBF_NEEDS_GCPOLL; } } } void Compiler::fgInitBlockVarSets() { for (BasicBlock* block = fgFirstBB; block; block = block->bbNext) { block->InitVarSets(this); } fgBBVarSetsInited = true; } /***************************************************************************** * * The following does the final pass on BBF_NEEDS_GCPOLL and then actually creates the GC Polls. */ void Compiler::fgCreateGCPolls() { if (GCPOLL_NONE == opts.compGCPollType) { return; } bool createdPollBlocks = false; #ifdef DEBUG if (verbose) { printf("*************** In fgCreateGCPolls() for %s\n", info.compFullName); } #endif // DEBUG if (opts.OptimizationEnabled()) { // Remove polls from well formed loops with a constant upper bound. for (unsigned lnum = 0; lnum < optLoopCount; ++lnum) { // Look for constant counted loops that run for a short duration. This logic is very similar to // what's in code:Compiler::optUnrollLoops, since they have similar constraints. However, this // logic is much more permissive since we're not doing a complex transformation. /* TODO-Cleanup: * I feel bad cloning so much logic from optUnrollLoops */ // Filter out loops not meeting the obvious preconditions. // if (optLoopTable[lnum].lpFlags & LPFLG_REMOVED) { continue; } if (!(optLoopTable[lnum].lpFlags & LPFLG_CONST)) { continue; } BasicBlock* head = optLoopTable[lnum].lpHead; BasicBlock* bottom = optLoopTable[lnum].lpBottom; // Loops dominated by GC_SAFE_POINT won't have this set. if (!(bottom->bbFlags & BBF_NEEDS_GCPOLL)) { continue; } /* Get the loop data: - initial constant - limit constant - iterator - iterator increment - increment operation type (i.e. ASG_ADD, ASG_SUB, etc...) - loop test type (i.e. GT_GE, GT_LT, etc...) */ int lbeg = optLoopTable[lnum].lpConstInit; int llim = optLoopTable[lnum].lpConstLimit(); genTreeOps testOper = optLoopTable[lnum].lpTestOper(); int lvar = optLoopTable[lnum].lpIterVar(); int iterInc = optLoopTable[lnum].lpIterConst(); genTreeOps iterOper = optLoopTable[lnum].lpIterOper(); var_types iterOperType = optLoopTable[lnum].lpIterOperType(); bool unsTest = (optLoopTable[lnum].lpTestTree->gtFlags & GTF_UNSIGNED) != 0; if (lvaTable[lvar].lvAddrExposed) { // Can't reason about the value of the iteration variable. continue; } unsigned totalIter; /* Find the number of iterations - the function returns false if not a constant number */ if (!optComputeLoopRep(lbeg, llim, iterInc, iterOper, iterOperType, testOper, unsTest, // The value here doesn't matter for this variation of the optimization true, &totalIter)) { #ifdef DEBUG if (verbose) { printf("Could not compute loop iterations for loop from " FMT_BB " to " FMT_BB, head->bbNum, bottom->bbNum); } #endif // DEBUG (void)head; // suppress gcc error. continue; } /* Forget it if there are too many repetitions or not a constant loop */ static const unsigned ITER_LIMIT = 256; if (totalIter > ITER_LIMIT) { continue; } // It is safe to elminate the poll from this loop. bottom->bbFlags &= ~BBF_NEEDS_GCPOLL; #ifdef DEBUG if (verbose) { printf("Removing poll in block " FMT_BB " because it forms a bounded counted loop\n", bottom->bbNum); } #endif // DEBUG } } // Final chance to optimize the polls. Move all polls in loops from the bottom of the loop up to the // loop head. Also eliminate all epilog polls in non-leaf methods. This only works if we have dominator // information. if (fgDomsComputed) { for (BasicBlock* block = fgFirstBB; block; block = block->bbNext) { if (!(block->bbFlags & BBF_NEEDS_GCPOLL)) { continue; } if (block->bbJumpKind == BBJ_COND || block->bbJumpKind == BBJ_ALWAYS) { // make sure that this is loop-like if (!fgReachable(block->bbJumpDest, block)) { block->bbFlags &= ~BBF_NEEDS_GCPOLL; #ifdef DEBUG if (verbose) { printf("Removing poll in block " FMT_BB " because it is not loop\n", block->bbNum); } #endif // DEBUG continue; } } else if (!(block->bbJumpKind == BBJ_RETURN || block->bbJumpKind == BBJ_SWITCH)) { noway_assert(!"GC Poll on a block that has no control transfer."); #ifdef DEBUG if (verbose) { printf("Removing poll in block " FMT_BB " because it is not a jump\n", block->bbNum); } #endif // DEBUG block->bbFlags &= ~BBF_NEEDS_GCPOLL; continue; } // Because of block compaction, it's possible to end up with a block that is both poll and safe. // Clean those up now. if (block->bbFlags & BBF_GC_SAFE_POINT) { #ifdef DEBUG if (verbose) { printf("Removing poll in return block " FMT_BB " because it is GC Safe\n", block->bbNum); } #endif // DEBUG block->bbFlags &= ~BBF_NEEDS_GCPOLL; continue; } if (block->bbJumpKind == BBJ_RETURN) { if (!optReachWithoutCall(fgFirstBB, block)) { // check to see if there is a call along the path between the first block and the return // block. block->bbFlags &= ~BBF_NEEDS_GCPOLL; #ifdef DEBUG if (verbose) { printf("Removing poll in return block " FMT_BB " because it dominated by a call\n", block->bbNum); } #endif // DEBUG continue; } } } } noway_assert(!fgGCPollsCreated); BasicBlock* block; fgGCPollsCreated = true; // Walk through the blocks and hunt for a block that has BBF_NEEDS_GCPOLL for (block = fgFirstBB; block; block = block->bbNext) { // Because of block compaction, it's possible to end up with a block that is both poll and safe. // And if !fgDomsComputed, we won't have cleared them, so skip them now if (!(block->bbFlags & BBF_NEEDS_GCPOLL) || (block->bbFlags & BBF_GC_SAFE_POINT)) { continue; } // This block needs a poll. We either just insert a callout or we split the block and inline part of // the test. This depends on the value of opts.compGCPollType. // If we're doing GCPOLL_CALL, just insert a GT_CALL node before the last node in the block. CLANG_FORMAT_COMMENT_ANCHOR; #ifdef DEBUG switch (block->bbJumpKind) { case BBJ_RETURN: case BBJ_ALWAYS: case BBJ_COND: case BBJ_SWITCH: break; default: noway_assert(!"Unknown block type for BBF_NEEDS_GCPOLL"); } #endif // DEBUG noway_assert(opts.compGCPollType); GCPollType pollType = opts.compGCPollType; // pollType is set to either CALL or INLINE at this point. Below is the list of places where we // can't or don't want to emit an inline check. Check all of those. If after all of that we still // have INLINE, then emit an inline check. if (opts.OptimizationDisabled()) { #ifdef DEBUG if (verbose) { printf("Selecting CALL poll in block " FMT_BB " because of debug/minopts\n", block->bbNum); } #endif // DEBUG // Don't split blocks and create inlined polls unless we're optimizing. pollType = GCPOLL_CALL; } else if (genReturnBB == block) { #ifdef DEBUG if (verbose) { printf("Selecting CALL poll in block " FMT_BB " because it is the single return block\n", block->bbNum); } #endif // DEBUG // we don't want to split the single return block pollType = GCPOLL_CALL; } else if (BBJ_SWITCH == block->bbJumpKind) { #ifdef DEBUG if (verbose) { printf("Selecting CALL poll in block " FMT_BB " because it is a loop formed by a SWITCH\n", block->bbNum); } #endif // DEBUG // I don't want to deal with all the outgoing edges of a switch block. pollType = GCPOLL_CALL; } // TODO-Cleanup: potentially don't split if we're in an EH region. createdPollBlocks |= fgCreateGCPoll(pollType, block); } // If we split a block to create a GC Poll, then rerun fgReorderBlocks to push the rarely run blocks out // past the epilog. We should never split blocks unless we're optimizing. if (createdPollBlocks) { noway_assert(opts.OptimizationEnabled()); fgReorderBlocks(); } } /***************************************************************************** * * Actually create a GCPoll in the given block. Returns true if it created * a basic block. */ bool Compiler::fgCreateGCPoll(GCPollType pollType, BasicBlock* block) { assert(!(block->bbFlags & BBF_GC_SAFE_POINT)); bool createdPollBlocks; void* addrTrap; void* pAddrOfCaptureThreadGlobal; addrTrap = info.compCompHnd->getAddrOfCaptureThreadGlobal(&pAddrOfCaptureThreadGlobal); #ifdef ENABLE_FAST_GCPOLL_HELPER // I never want to split blocks if we've got two indirections here. // This is a size trade-off assuming the VM has ENABLE_FAST_GCPOLL_HELPER. // So don't do it when that is off if (pAddrOfCaptureThreadGlobal != NULL) { pollType = GCPOLL_CALL; } #endif // ENABLE_FAST_GCPOLL_HELPER if (GCPOLL_CALL == pollType) { createdPollBlocks = false; GenTreeCall* call = gtNewHelperCallNode(CORINFO_HELP_POLL_GC, TYP_VOID); // for BBJ_ALWAYS I don't need to insert it before the condition. Just append it. if (block->bbJumpKind == BBJ_ALWAYS) { fgInsertStmtAtEnd(block, call); } else { GenTreeStmt* newStmt = fgInsertStmtNearEnd(block, call); // For DDB156656, we need to associate the GC Poll with the IL offset (and therefore sequence // point) of the tree before which we inserted the poll. One example of when this is a // problem: // if (...) { //1 // ... // } //2 // else { //3 // ... // } // (gcpoll) //4 // return. //5 // // If we take the if statement at 1, we encounter a jump at 2. This jumps over the else // and lands at 4. 4 is where we inserted the gcpoll. However, that is associated with // the sequence point a 3. Therefore, the debugger displays the wrong source line at the // gc poll location. // // More formally, if control flow targets an instruction, that instruction must be the // start of a new sequence point. GenTreeStmt* nextStmt = newStmt->getNextStmt(); if (nextStmt != nullptr) { // Is it possible for gtNext to be NULL? newStmt->gtStmtILoffsx = nextStmt->gtStmtILoffsx; } } block->bbFlags |= BBF_GC_SAFE_POINT; #ifdef DEBUG if (verbose) { printf("*** creating GC Poll in block " FMT_BB "\n", block->bbNum); gtDispTreeList(block->bbTreeList); } #endif // DEBUG } else { createdPollBlocks = true; // if we're doing GCPOLL_INLINE, then: // 1) Create two new blocks: Poll and Bottom. The original block is called Top. // I want to create: // top -> poll -> bottom (lexically) // so that we jump over poll to get to bottom. BasicBlock* top = block; BasicBlock* poll = fgNewBBafter(BBJ_NONE, top, true); BasicBlock* bottom = fgNewBBafter(top->bbJumpKind, poll, true); BBjumpKinds oldJumpKind = top->bbJumpKind; // Update block flags const unsigned __int64 originalFlags = top->bbFlags | BBF_GC_SAFE_POINT; // Unlike Fei's inliner from puclr, I'm allowed to split loops. // And we keep a few other flags... noway_assert((originalFlags & (BBF_SPLIT_NONEXIST & ~(BBF_LOOP_HEAD | BBF_LOOP_CALL0 | BBF_LOOP_CALL1))) == 0); top->bbFlags = originalFlags & (~BBF_SPLIT_LOST | BBF_GC_SAFE_POINT); bottom->bbFlags |= originalFlags & (BBF_SPLIT_GAINED | BBF_IMPORTED | BBF_GC_SAFE_POINT); bottom->inheritWeight(top); poll->bbFlags |= originalFlags & (BBF_SPLIT_GAINED | BBF_IMPORTED | BBF_GC_SAFE_POINT); // 9) Mark Poll as rarely run. poll->bbSetRunRarely(); // 5) Bottom gets all the outgoing edges and inherited flags of Original. bottom->bbJumpDest = top->bbJumpDest; // 2) Add a GC_CALL node to Poll. GenTreeCall* call = gtNewHelperCallNode(CORINFO_HELP_POLL_GC, TYP_VOID); fgInsertStmtAtEnd(poll, call); // 3) Remove the last statement from Top and add it to Bottom. if (oldJumpKind != BBJ_ALWAYS) { // if I'm always jumping to the target, then this is not a condition that needs moving. GenTreeStmt* stmt = top->firstStmt(); while (stmt->gtNext) { stmt = stmt->gtNextStmt; } fgRemoveStmt(top, stmt); fgInsertStmtAtEnd(bottom, stmt); } // for BBJ_ALWAYS blocks, bottom is an empty block. // 4) Create a GT_EQ node that checks against g_TrapReturningThreads. True jumps to Bottom, // false falls through to poll. Add this to the end of Top. Top is now BBJ_COND. Bottom is // now a jump target CLANG_FORMAT_COMMENT_ANCHOR; #ifdef ENABLE_FAST_GCPOLL_HELPER // Prefer the fast gc poll helepr over the double indirection noway_assert(pAddrOfCaptureThreadGlobal == nullptr); #endif GenTree* value; // The value of g_TrapReturningThreads if (pAddrOfCaptureThreadGlobal != nullptr) { // Use a double indirection GenTree* addr = gtNewIndOfIconHandleNode(TYP_I_IMPL, (size_t)pAddrOfCaptureThreadGlobal, GTF_ICON_PTR_HDL, true); value = gtNewOperNode(GT_IND, TYP_INT, addr); // This indirection won't cause an exception. value->gtFlags |= GTF_IND_NONFAULTING; } else { // Use a single indirection value = gtNewIndOfIconHandleNode(TYP_INT, (size_t)addrTrap, GTF_ICON_PTR_HDL, false); } // Treat the reading of g_TrapReturningThreads as volatile. value->gtFlags |= GTF_IND_VOLATILE; // Compare for equal to zero GenTree* trapRelop = gtNewOperNode(GT_EQ, TYP_INT, value, gtNewIconNode(0, TYP_INT)); trapRelop->gtFlags |= GTF_RELOP_JMP_USED | GTF_DONT_CSE; GenTree* trapCheck = gtNewOperNode(GT_JTRUE, TYP_VOID, trapRelop); fgInsertStmtAtEnd(top, trapCheck); top->bbJumpDest = bottom; top->bbJumpKind = BBJ_COND; bottom->bbFlags |= BBF_JMP_TARGET; // 7) Bottom has Top and Poll as its predecessors. Poll has just Top as a predecessor. fgAddRefPred(bottom, poll); fgAddRefPred(bottom, top); fgAddRefPred(poll, top); // 8) Replace Top with Bottom in the predecessor list of all outgoing edges from Bottom (1 for // jumps, 2 for conditional branches, N for switches). switch (oldJumpKind) { case BBJ_RETURN: // no successors break; case BBJ_COND: // replace predecessor in the fall through block. noway_assert(bottom->bbNext); fgReplacePred(bottom->bbNext, top, bottom); // fall through for the jump target __fallthrough; case BBJ_ALWAYS: fgReplacePred(bottom->bbJumpDest, top, bottom); break; case BBJ_SWITCH: NO_WAY("SWITCH should be a call rather than an inlined poll."); break; default: NO_WAY("Unknown block type for updating predecessor lists."); } top->bbFlags &= ~BBF_NEEDS_GCPOLL; noway_assert(!(poll->bbFlags & BBF_NEEDS_GCPOLL)); noway_assert(!(bottom->bbFlags & BBF_NEEDS_GCPOLL)); if (compCurBB == top) { compCurBB = bottom; } #ifdef DEBUG if (verbose) { printf("*** creating inlined GC Poll in top block " FMT_BB "\n", top->bbNum); gtDispTreeList(top->bbTreeList); printf(" poll block is " FMT_BB "\n", poll->bbNum); gtDispTreeList(poll->bbTreeList); printf(" bottom block is " FMT_BB "\n", bottom->bbNum); gtDispTreeList(bottom->bbTreeList); } #endif // DEBUG } return createdPollBlocks; } /***************************************************************************** * * The following helps find a basic block given its PC offset. */ void Compiler::fgInitBBLookup() { BasicBlock** dscBBptr; BasicBlock* tmpBBdesc; /* Allocate the basic block table */ dscBBptr = fgBBs = new (this, CMK_BasicBlock) BasicBlock*[fgBBcount]; /* Walk all the basic blocks, filling in the table */ for (tmpBBdesc = fgFirstBB; tmpBBdesc; tmpBBdesc = tmpBBdesc->bbNext) { *dscBBptr++ = tmpBBdesc; } noway_assert(dscBBptr == fgBBs + fgBBcount); } BasicBlock* Compiler::fgLookupBB(unsigned addr) { unsigned lo; unsigned hi; /* Do a binary search */ for (lo = 0, hi = fgBBcount - 1;;) { AGAIN:; if (lo > hi) { break; } unsigned mid = (lo + hi) / 2; BasicBlock* dsc = fgBBs[mid]; // We introduce internal blocks for BBJ_CALLFINALLY. Skip over these. while (dsc->bbFlags & BBF_INTERNAL) { dsc = dsc->bbNext; mid++; // We skipped over too many, Set hi back to the original mid - 1 if (mid > hi) { mid = (lo + hi) / 2; hi = mid - 1; goto AGAIN; } } unsigned pos = dsc->bbCodeOffs; if (pos < addr) { if ((lo == hi) && (lo == (fgBBcount - 1))) { noway_assert(addr == dsc->bbCodeOffsEnd); return nullptr; // NULL means the end of method } lo = mid + 1; continue; } if (pos > addr) { hi = mid - 1; continue; } return dsc; } #ifdef DEBUG printf("ERROR: Couldn't find basic block at offset %04X\n", addr); #endif // DEBUG NO_WAY("fgLookupBB failed."); } //------------------------------------------------------------------------ // FgStack: simple stack model for the inlinee's evaluation stack. // // Model the inputs available to various operations in the inline body. // Tracks constants, arguments, array lengths. class FgStack { public: FgStack() : slot0(SLOT_INVALID), slot1(SLOT_INVALID), depth(0) { // Empty } void Clear() { depth = 0; } void PushUnknown() { Push(SLOT_UNKNOWN); } void PushConstant() { Push(SLOT_CONSTANT); } void PushArrayLen() { Push(SLOT_ARRAYLEN); } void PushArgument(unsigned arg) { Push(SLOT_ARGUMENT + arg); } unsigned GetSlot0() const { assert(depth >= 1); return slot0; } unsigned GetSlot1() const { assert(depth >= 2); return slot1; } static bool IsConstant(unsigned value) { return value == SLOT_CONSTANT; } static bool IsArrayLen(unsigned value) { return value == SLOT_ARRAYLEN; } static bool IsArgument(unsigned value) { return value >= SLOT_ARGUMENT; } static unsigned SlotTypeToArgNum(unsigned value) { assert(IsArgument(value)); return value - SLOT_ARGUMENT; } bool IsStackTwoDeep() const { return depth == 2; } bool IsStackOneDeep() const { return depth == 1; } bool IsStackAtLeastOneDeep() const { return depth >= 1; } private: enum { SLOT_INVALID = UINT_MAX, SLOT_UNKNOWN = 0, SLOT_CONSTANT = 1, SLOT_ARRAYLEN = 2, SLOT_ARGUMENT = 3 }; void Push(int type) { switch (depth) { case 0: ++depth; slot0 = type; break; case 1: ++depth; __fallthrough; case 2: slot1 = slot0; slot0 = type; } } unsigned slot0; unsigned slot1; unsigned depth; }; //------------------------------------------------------------------------ // fgCanSwitchToOptimized: Determines if conditions are met to allow switching the opt level to optimized // // Return Value: // True if the opt level may be switched from tier 0 to optimized, false otherwise // // Assumptions: // - compInitOptions() has been called // - compSetOptimizationLevel() has not been called // // Notes: // This method is to be called at some point before compSetOptimizationLevel() to determine if the opt level may be // changed based on information gathered in early phases. bool Compiler::fgCanSwitchToOptimized() { bool result = opts.jitFlags->IsSet(JitFlags::JIT_FLAG_TIER0) && !opts.jitFlags->IsSet(JitFlags::JIT_FLAG_MIN_OPT) && !opts.compDbgCode && !compIsForInlining(); if (result) { // Ensure that it would be safe to change the opt level assert(opts.compFlags == CLFLG_MINOPT); assert(!opts.IsMinOptsSet()); } return result; } //------------------------------------------------------------------------ // fgSwitchToOptimized: Switch the opt level from tier 0 to optimized // // Assumptions: // - fgCanSwitchToOptimized() is true // - compSetOptimizationLevel() has not been called // // Notes: // This method is to be called at some point before compSetOptimizationLevel() to switch the opt level to optimized // based on information gathered in early phases. void Compiler::fgSwitchToOptimized() { assert(fgCanSwitchToOptimized()); // Switch to optimized and re-init options assert(opts.jitFlags->IsSet(JitFlags::JIT_FLAG_TIER0)); opts.jitFlags->Clear(JitFlags::JIT_FLAG_TIER0); compInitOptions(opts.jitFlags); // Notify the VM of the change info.compCompHnd->setMethodAttribs(info.compMethodHnd, CORINFO_FLG_SWITCHED_TO_OPTIMIZED); } //------------------------------------------------------------------------ // fgMayExplicitTailCall: Estimates conservatively for an explicit tail call, if the importer may actually use a tail // call. // // Return Value: // - False if a tail call will not be generated // - True if a tail call *may* be generated // // Assumptions: // - compInitOptions() has been called // - info.compIsVarArgs has been initialized // - An explicit tail call has been seen // - compSetOptimizationLevel() has not been called bool Compiler::fgMayExplicitTailCall() { assert(!compIsForInlining()); if (info.compFlags & CORINFO_FLG_SYNCH) { // Caller is synchronized return false; } #if !FEATURE_FIXED_OUT_ARGS if (info.compIsVarArgs) { // Caller is varargs return false; } #endif // FEATURE_FIXED_OUT_ARGS return true; } //------------------------------------------------------------------------ // fgFindJumpTargets: walk the IL stream, determining jump target offsets // // Arguments: // codeAddr - base address of the IL code buffer // codeSize - number of bytes in the IL code buffer // jumpTarget - [OUT] bit vector for flagging jump targets // // Notes: // If inlining or prejitting the root, this method also makes // various observations about the method that factor into inline // decisions. // // May throw an exception if the IL is malformed. // // jumpTarget[N] is set to 1 if IL offset N is a jump target in the method. // // Also sets lvAddrExposed and lvHasILStoreOp, ilHasMultipleILStoreOp in lvaTable[]. #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable : 21000) // Suppress PREFast warning about overly large function #endif void Compiler::fgFindJumpTargets(const BYTE* codeAddr, IL_OFFSET codeSize, FixedBitVect* jumpTarget) { const BYTE* codeBegp = codeAddr; const BYTE* codeEndp = codeAddr + codeSize; unsigned varNum; bool seenJump = false; var_types varType = DUMMY_INIT(TYP_UNDEF); // TYP_ type typeInfo ti; // Verifier type. bool typeIsNormed = false; FgStack pushedStack; const bool isForceInline = (info.compFlags & CORINFO_FLG_FORCEINLINE) != 0; const bool makeInlineObservations = (compInlineResult != nullptr); const bool isInlining = compIsForInlining(); unsigned retBlocks = 0; if (makeInlineObservations) { // Observe force inline state and code size. compInlineResult->NoteBool(InlineObservation::CALLEE_IS_FORCE_INLINE, isForceInline); compInlineResult->NoteInt(InlineObservation::CALLEE_IL_CODE_SIZE, codeSize); // Determine if call site is within a try. if (isInlining && impInlineInfo->iciBlock->hasTryIndex()) { compInlineResult->Note(InlineObservation::CALLSITE_IN_TRY_REGION); } // Determine if the call site is in a loop. if (isInlining && ((impInlineInfo->iciBlock->bbFlags & BBF_BACKWARD_JUMP) != 0)) { compInlineResult->Note(InlineObservation::CALLSITE_IN_LOOP); } #ifdef DEBUG // If inlining, this method should still be a candidate. if (isInlining) { assert(compInlineResult->IsCandidate()); } #endif // DEBUG // note that we're starting to look at the opcodes. compInlineResult->Note(InlineObservation::CALLEE_BEGIN_OPCODE_SCAN); } while (codeAddr < codeEndp) { OPCODE opcode = (OPCODE)getU1LittleEndian(codeAddr); codeAddr += sizeof(__int8); opts.instrCount++; typeIsNormed = false; DECODE_OPCODE: if ((unsigned)opcode >= CEE_COUNT) { BADCODE3("Illegal opcode", ": %02X", (int)opcode); } if ((opcode >= CEE_LDARG_0 && opcode <= CEE_STLOC_S) || (opcode >= CEE_LDARG && opcode <= CEE_STLOC)) { opts.lvRefCount++; } if (makeInlineObservations && (opcode >= CEE_LDNULL) && (opcode <= CEE_LDC_R8)) { pushedStack.PushConstant(); } unsigned sz = opcodeSizes[opcode]; switch (opcode) { case CEE_PREFIX1: { if (codeAddr >= codeEndp) { goto TOO_FAR; } opcode = (OPCODE)(256 + getU1LittleEndian(codeAddr)); codeAddr += sizeof(__int8); goto DECODE_OPCODE; } case CEE_PREFIX2: case CEE_PREFIX3: case CEE_PREFIX4: case CEE_PREFIX5: case CEE_PREFIX6: case CEE_PREFIX7: case CEE_PREFIXREF: { BADCODE3("Illegal opcode", ": %02X", (int)opcode); } case CEE_CALL: case CEE_CALLVIRT: { // There has to be code after the call, otherwise the inlinee is unverifiable. if (isInlining) { noway_assert(codeAddr < codeEndp - sz); } // If the method has a call followed by a ret, assume that // it is a wrapper method. if (makeInlineObservations) { if ((OPCODE)getU1LittleEndian(codeAddr + sz) == CEE_RET) { compInlineResult->Note(InlineObservation::CALLEE_LOOKS_LIKE_WRAPPER); } } } break; case CEE_LEAVE: case CEE_LEAVE_S: case CEE_BR: case CEE_BR_S: case CEE_BRFALSE: case CEE_BRFALSE_S: case CEE_BRTRUE: case CEE_BRTRUE_S: case CEE_BEQ: case CEE_BEQ_S: case CEE_BGE: case CEE_BGE_S: case CEE_BGE_UN: case CEE_BGE_UN_S: case CEE_BGT: case CEE_BGT_S: case CEE_BGT_UN: case CEE_BGT_UN_S: case CEE_BLE: case CEE_BLE_S: case CEE_BLE_UN: case CEE_BLE_UN_S: case CEE_BLT: case CEE_BLT_S: case CEE_BLT_UN: case CEE_BLT_UN_S: case CEE_BNE_UN: case CEE_BNE_UN_S: { seenJump = true; if (codeAddr > codeEndp - sz) { goto TOO_FAR; } // Compute jump target address signed jmpDist = (sz == 1) ? getI1LittleEndian(codeAddr) : getI4LittleEndian(codeAddr); if (compIsForInlining() && jmpDist == 0 && (opcode == CEE_LEAVE || opcode == CEE_LEAVE_S || opcode == CEE_BR || opcode == CEE_BR_S)) { break; /* NOP */ } unsigned jmpAddr = (IL_OFFSET)(codeAddr - codeBegp) + sz + jmpDist; // Make sure target is reasonable if (jmpAddr >= codeSize) { BADCODE3("code jumps to outer space", " at offset %04X", (IL_OFFSET)(codeAddr - codeBegp)); } // Mark the jump target jumpTarget->bitVectSet(jmpAddr); // See if jump might be sensitive to inlining if (makeInlineObservations && (opcode != CEE_BR_S) && (opcode != CEE_BR)) { fgObserveInlineConstants(opcode, pushedStack, isInlining); } } break; case CEE_SWITCH: { seenJump = true; if (makeInlineObservations) { compInlineResult->Note(InlineObservation::CALLEE_HAS_SWITCH); // Fail fast, if we're inlining and can't handle this. if (isInlining && compInlineResult->IsFailure()) { return; } } // Make sure we don't go past the end reading the number of cases if (codeAddr > codeEndp - sizeof(DWORD)) { goto TOO_FAR; } // Read the number of cases unsigned jmpCnt = getU4LittleEndian(codeAddr); codeAddr += sizeof(DWORD); if (jmpCnt > codeSize / sizeof(DWORD)) { goto TOO_FAR; } // Find the end of the switch table unsigned jmpBase = (unsigned)((codeAddr - codeBegp) + jmpCnt * sizeof(DWORD)); // Make sure there is more code after the switch if (jmpBase >= codeSize) { goto TOO_FAR; } // jmpBase is also the target of the default case, so mark it jumpTarget->bitVectSet(jmpBase); // Process table entries while (jmpCnt > 0) { unsigned jmpAddr = jmpBase + getI4LittleEndian(codeAddr); codeAddr += 4; if (jmpAddr >= codeSize) { BADCODE3("jump target out of range", " at offset %04X", (IL_OFFSET)(codeAddr - codeBegp)); } jumpTarget->bitVectSet(jmpAddr); jmpCnt--; } // We've advanced past all the bytes in this instruction sz = 0; } break; case CEE_UNALIGNED: case CEE_CONSTRAINED: case CEE_READONLY: case CEE_VOLATILE: case CEE_TAILCALL: { if (codeAddr >= codeEndp) { goto TOO_FAR; } } break; case CEE_STARG: case CEE_STARG_S: { noway_assert(sz == sizeof(BYTE) || sz == sizeof(WORD)); if (codeAddr > codeEndp - sz) { goto TOO_FAR; } varNum = (sz == sizeof(BYTE)) ? getU1LittleEndian(codeAddr) : getU2LittleEndian(codeAddr); if (isInlining) { if (varNum < impInlineInfo->argCnt) { impInlineInfo->inlArgInfo[varNum].argHasStargOp = true; } } else { // account for possible hidden param varNum = compMapILargNum(varNum); // This check is only intended to prevent an AV. Bad varNum values will later // be handled properly by the verifier. if (varNum < lvaTableCnt) { // In non-inline cases, note written-to arguments. lvaTable[varNum].lvHasILStoreOp = 1; } } } break; case CEE_STLOC_0: case CEE_STLOC_1: case CEE_STLOC_2: case CEE_STLOC_3: varNum = (opcode - CEE_STLOC_0); goto STLOC; case CEE_STLOC: case CEE_STLOC_S: { noway_assert(sz == sizeof(BYTE) || sz == sizeof(WORD)); if (codeAddr > codeEndp - sz) { goto TOO_FAR; } varNum = (sz == sizeof(BYTE)) ? getU1LittleEndian(codeAddr) : getU2LittleEndian(codeAddr); STLOC: if (isInlining) { InlLclVarInfo& lclInfo = impInlineInfo->lclVarInfo[varNum + impInlineInfo->argCnt]; if (lclInfo.lclHasStlocOp) { lclInfo.lclHasMultipleStlocOp = 1; } else { lclInfo.lclHasStlocOp = 1; } } else { varNum += info.compArgsCount; // This check is only intended to prevent an AV. Bad varNum values will later // be handled properly by the verifier. if (varNum < lvaTableCnt) { // In non-inline cases, note written-to locals. if (lvaTable[varNum].lvHasILStoreOp) { lvaTable[varNum].lvHasMultipleILStoreOp = 1; } else { lvaTable[varNum].lvHasILStoreOp = 1; } } } } break; case CEE_LDARGA: case CEE_LDARGA_S: case CEE_LDLOCA: case CEE_LDLOCA_S: { // Handle address-taken args or locals noway_assert(sz == sizeof(BYTE) || sz == sizeof(WORD)); if (codeAddr > codeEndp - sz) { goto TOO_FAR; } varNum = (sz == sizeof(BYTE)) ? getU1LittleEndian(codeAddr) : getU2LittleEndian(codeAddr); if (isInlining) { if (opcode == CEE_LDLOCA || opcode == CEE_LDLOCA_S) { varType = impInlineInfo->lclVarInfo[varNum + impInlineInfo->argCnt].lclTypeInfo; ti = impInlineInfo->lclVarInfo[varNum + impInlineInfo->argCnt].lclVerTypeInfo; impInlineInfo->lclVarInfo[varNum + impInlineInfo->argCnt].lclHasLdlocaOp = true; } else { noway_assert(opcode == CEE_LDARGA || opcode == CEE_LDARGA_S); varType = impInlineInfo->lclVarInfo[varNum].lclTypeInfo; ti = impInlineInfo->lclVarInfo[varNum].lclVerTypeInfo; impInlineInfo->inlArgInfo[varNum].argHasLdargaOp = true; pushedStack.PushArgument(varNum); } } else { if (opcode == CEE_LDLOCA || opcode == CEE_LDLOCA_S) { if (varNum >= info.compMethodInfo->locals.numArgs) { BADCODE("bad local number"); } varNum += info.compArgsCount; } else { noway_assert(opcode == CEE_LDARGA || opcode == CEE_LDARGA_S); if (varNum >= info.compILargsCount) { BADCODE("bad argument number"); } varNum = compMapILargNum(varNum); // account for possible hidden param } varType = (var_types)lvaTable[varNum].lvType; ti = lvaTable[varNum].lvVerTypeInfo; // Determine if the next instruction will consume // the address. If so we won't mark this var as // address taken. // // We will put structs on the stack and changing // the addrTaken of a local requires an extra pass // in the morpher so we won't apply this // optimization to structs. // // Debug code spills for every IL instruction, and // therefore it will split statements, so we will // need the address. Note that this optimization // is based in that we know what trees we will // generate for this ldfld, and we require that we // won't need the address of this local at all noway_assert(varNum < lvaTableCnt); const bool notStruct = !varTypeIsStruct(&lvaTable[varNum]); const bool notLastInstr = (codeAddr < codeEndp - sz); const bool notDebugCode = !opts.compDbgCode; if (notStruct && notLastInstr && notDebugCode && impILConsumesAddr(codeAddr + sz, impTokenLookupContextHandle, info.compScopeHnd)) { // We can skip the addrtaken, as next IL instruction consumes // the address. } else { lvaTable[varNum].lvHasLdAddrOp = 1; if (!info.compIsStatic && (varNum == 0)) { // Addr taken on "this" pointer is significant, // go ahead to mark it as permanently addr-exposed here. lvaSetVarAddrExposed(0); // This may be conservative, but probably not very. } } } // isInlining typeIsNormed = ti.IsValueClass() && !varTypeIsStruct(varType); } break; #if !defined(FEATURE_CORECLR) case CEE_CALLI: // CEE_CALLI should not be inlined if the call indirect target has a calling convention other than // CORINFO_CALLCONV_DEFAULT. In the case where we have a no-marshal CALLI P/Invoke we end up calling // the IL stub. We don't NGEN these stubs, so we'll have to JIT an IL stub for a trivial func. // It's almost certainly a better choice to leave out the inline candidate so we can generate an inlined // call frame. // Consider skipping this bail-out for force inlines. if (makeInlineObservations) { if (codeAddr > codeEndp - sizeof(DWORD)) { goto TOO_FAR; } CORINFO_SIG_INFO calliSig; eeGetSig(getU4LittleEndian(codeAddr), info.compScopeHnd, impTokenLookupContextHandle, &calliSig); if (calliSig.getCallConv() != CORINFO_CALLCONV_DEFAULT) { compInlineResult->Note(InlineObservation::CALLEE_UNSUPPORTED_OPCODE); // Fail fast if we're inlining if (isInlining) { assert(compInlineResult->IsFailure()); return; } } } break; #endif // FEATURE_CORECLR case CEE_JMP: retBlocks++; #if !defined(_TARGET_X86_) && !defined(_TARGET_ARM_) if (!isInlining) { // We transform this into a set of ldarg's + tail call and // thus may push more onto the stack than originally thought. // This doesn't interfere with verification because CEE_JMP // is never verifiable, and there's nothing unsafe you can // do with a an IL stack overflow if the JIT is expecting it. info.compMaxStack = max(info.compMaxStack, info.compILargsCount); break; } #endif // !_TARGET_X86_ && !_TARGET_ARM_ // If we are inlining, we need to fail for a CEE_JMP opcode, just like // the list of other opcodes (for all platforms). __fallthrough; case CEE_MKREFANY: case CEE_RETHROW: if (makeInlineObservations) { // Arguably this should be NoteFatal, but the legacy behavior is // to ignore this for the prejit root. compInlineResult->Note(InlineObservation::CALLEE_UNSUPPORTED_OPCODE); // Fail fast if we're inlining... if (isInlining) { assert(compInlineResult->IsFailure()); return; } } break; case CEE_LOCALLOC: // We now allow localloc callees to become candidates in some cases. if (makeInlineObservations) { compInlineResult->Note(InlineObservation::CALLEE_HAS_LOCALLOC); if (isInlining && compInlineResult->IsFailure()) { return; } } break; case CEE_LDARG_0: case CEE_LDARG_1: case CEE_LDARG_2: case CEE_LDARG_3: if (makeInlineObservations) { pushedStack.PushArgument(opcode - CEE_LDARG_0); } break; case CEE_LDARG_S: case CEE_LDARG: { if (codeAddr > codeEndp - sz) { goto TOO_FAR; } varNum = (sz == sizeof(BYTE)) ? getU1LittleEndian(codeAddr) : getU2LittleEndian(codeAddr); if (makeInlineObservations) { pushedStack.PushArgument(varNum); } } break; case CEE_LDLEN: if (makeInlineObservations) { pushedStack.PushArrayLen(); } break; case CEE_CEQ: case CEE_CGT: case CEE_CGT_UN: case CEE_CLT: case CEE_CLT_UN: if (makeInlineObservations) { fgObserveInlineConstants(opcode, pushedStack, isInlining); } break; case CEE_RET: retBlocks++; default: break; } // Skip any remaining operands this opcode may have codeAddr += sz; // Note the opcode we just saw if (makeInlineObservations) { InlineObservation obs = typeIsNormed ? InlineObservation::CALLEE_OPCODE_NORMED : InlineObservation::CALLEE_OPCODE; compInlineResult->NoteInt(obs, opcode); } } if (codeAddr != codeEndp) { TOO_FAR: BADCODE3("Code ends in the middle of an opcode, or there is a branch past the end of the method", " at offset %04X", (IL_OFFSET)(codeAddr - codeBegp)); } if (makeInlineObservations) { compInlineResult->Note(InlineObservation::CALLEE_END_OPCODE_SCAN); // If there are no return blocks we know it does not return, however if there // return blocks we don't know it returns as it may be counting unreachable code. // However we will still make the CALLEE_DOES_NOT_RETURN observation. compInlineResult->NoteBool(InlineObservation::CALLEE_DOES_NOT_RETURN, retBlocks == 0); if (retBlocks == 0 && isInlining) { // Mark the call node as "no return" as it can impact caller's code quality. impInlineInfo->iciCall->gtCallMoreFlags |= GTF_CALL_M_DOES_NOT_RETURN; } // If the inline is viable and discretionary, do the // profitability screening. if (compInlineResult->IsDiscretionaryCandidate()) { // Make some callsite specific observations that will feed // into the profitability model. impMakeDiscretionaryInlineObservations(impInlineInfo, compInlineResult); // None of those observations should have changed the // inline's viability. assert(compInlineResult->IsCandidate()); if (isInlining) { // Assess profitability... CORINFO_METHOD_INFO* methodInfo = &impInlineInfo->inlineCandidateInfo->methInfo; compInlineResult->DetermineProfitability(methodInfo); if (compInlineResult->IsFailure()) { impInlineRoot()->m_inlineStrategy->NoteUnprofitable(); JITDUMP("\n\nInline expansion aborted, inline not profitable\n"); return; } else { // The inline is still viable. assert(compInlineResult->IsCandidate()); } } else { // Prejit root case. Profitability assessment for this // is done over in compCompileHelper. } } } // None of the local vars in the inlinee should have address taken or been written to. // Therefore we should NOT need to enter this "if" statement. if (!isInlining && !info.compIsStatic) { fgAdjustForAddressExposedOrWrittenThis(); } // Now that we've seen the IL, set lvSingleDef for root method // locals. // // We could also do this for root method arguments but single-def // arguments are set by the caller and so we don't know anything // about the possible values or types. // // For inlinees we do this over in impInlineFetchLocal and // impInlineFetchArg (here args are included as we somtimes get // new information about the types of inlinee args). if (!isInlining) { const unsigned firstLcl = info.compArgsCount; const unsigned lastLcl = firstLcl + info.compMethodInfo->locals.numArgs; for (unsigned lclNum = firstLcl; lclNum < lastLcl; lclNum++) { LclVarDsc* lclDsc = lvaGetDesc(lclNum); assert(lclDsc->lvSingleDef == 0); // could restrict this to TYP_REF lclDsc->lvSingleDef = !lclDsc->lvHasMultipleILStoreOp && !lclDsc->lvHasLdAddrOp; if (lclDsc->lvSingleDef) { JITDUMP("Marked V%02u as a single def local\n", lclNum); } } } } #ifdef _PREFAST_ #pragma warning(pop) #endif //------------------------------------------------------------------------ // fgAdjustForAddressExposedOrWrittenThis: update var table for cases // where the this pointer value can change. // // Notes: // Modifies lvaArg0Var to refer to a temp if the value of 'this' can // change. The original this (info.compThisArg) then remains // unmodified in the method. fgAddInternal is reponsible for // adding the code to copy the initial this into the temp. void Compiler::fgAdjustForAddressExposedOrWrittenThis() { // Optionally enable adjustment during stress. if (!tiVerificationNeeded && compStressCompile(STRESS_GENERIC_VARN, 15)) { lvaTable[info.compThisArg].lvHasILStoreOp = true; } // If this is exposed or written to, create a temp for the modifiable this if (lvaTable[info.compThisArg].lvAddrExposed || lvaTable[info.compThisArg].lvHasILStoreOp) { // If there is a "ldarga 0" or "starg 0", grab and use the temp. lvaArg0Var = lvaGrabTemp(false DEBUGARG("Address-exposed, or written this pointer")); noway_assert(lvaArg0Var > (unsigned)info.compThisArg); lvaTable[lvaArg0Var].lvType = lvaTable[info.compThisArg].TypeGet(); lvaTable[lvaArg0Var].lvAddrExposed = lvaTable[info.compThisArg].lvAddrExposed; lvaTable[lvaArg0Var].lvDoNotEnregister = lvaTable[info.compThisArg].lvDoNotEnregister; #ifdef DEBUG lvaTable[lvaArg0Var].lvVMNeedsStackAddr = lvaTable[info.compThisArg].lvVMNeedsStackAddr; lvaTable[lvaArg0Var].lvLiveInOutOfHndlr = lvaTable[info.compThisArg].lvLiveInOutOfHndlr; lvaTable[lvaArg0Var].lvLclFieldExpr = lvaTable[info.compThisArg].lvLclFieldExpr; lvaTable[lvaArg0Var].lvLiveAcrossUCall = lvaTable[info.compThisArg].lvLiveAcrossUCall; #endif lvaTable[lvaArg0Var].lvHasILStoreOp = lvaTable[info.compThisArg].lvHasILStoreOp; lvaTable[lvaArg0Var].lvVerTypeInfo = lvaTable[info.compThisArg].lvVerTypeInfo; // Clear the TI_FLAG_THIS_PTR in the original 'this' pointer. noway_assert(lvaTable[lvaArg0Var].lvVerTypeInfo.IsThisPtr()); lvaTable[info.compThisArg].lvVerTypeInfo.ClearThisPtr(); lvaTable[info.compThisArg].lvAddrExposed = false; lvaTable[info.compThisArg].lvHasILStoreOp = false; } } //------------------------------------------------------------------------ // fgObserveInlineConstants: look for operations that might get optimized // if this method were to be inlined, and report these to the inliner. // // Arguments: // opcode -- MSIL opcode under consideration // stack -- abstract stack model at this point in the IL // isInlining -- true if we're inlining (vs compiling a prejit root) // // Notes: // Currently only invoked on compare and branch opcodes. // // If we're inlining we also look at the argument values supplied by // the caller at this call site. // // The crude stack model may overestimate stack depth. void Compiler::fgObserveInlineConstants(OPCODE opcode, const FgStack& stack, bool isInlining) { // We should be able to record inline observations. assert(compInlineResult != nullptr); // The stack only has to be 1 deep for BRTRUE/FALSE bool lookForBranchCases = stack.IsStackAtLeastOneDeep(); if (lookForBranchCases) { if (opcode == CEE_BRFALSE || opcode == CEE_BRFALSE_S || opcode == CEE_BRTRUE || opcode == CEE_BRTRUE_S) { unsigned slot0 = stack.GetSlot0(); if (FgStack::IsArgument(slot0)) { compInlineResult->Note(InlineObservation::CALLEE_ARG_FEEDS_CONSTANT_TEST); if (isInlining) { // Check for the double whammy of an incoming constant argument // feeding a constant test. unsigned varNum = FgStack::SlotTypeToArgNum(slot0); if (impInlineInfo->inlArgInfo[varNum].argNode->OperIsConst()) { compInlineResult->Note(InlineObservation::CALLSITE_CONSTANT_ARG_FEEDS_TEST); } } } return; } } // Remaining cases require at least two things on the stack. if (!stack.IsStackTwoDeep()) { return; } unsigned slot0 = stack.GetSlot0(); unsigned slot1 = stack.GetSlot1(); // Arg feeds constant test if ((FgStack::IsConstant(slot0) && FgStack::IsArgument(slot1)) || (FgStack::IsConstant(slot1) && FgStack::IsArgument(slot0))) { compInlineResult->Note(InlineObservation::CALLEE_ARG_FEEDS_CONSTANT_TEST); } // Arg feeds range check if ((FgStack::IsArrayLen(slot0) && FgStack::IsArgument(slot1)) || (FgStack::IsArrayLen(slot1) && FgStack::IsArgument(slot0))) { compInlineResult->Note(InlineObservation::CALLEE_ARG_FEEDS_RANGE_CHECK); } // Check for an incoming arg that's a constant if (isInlining) { if (FgStack::IsArgument(slot0)) { compInlineResult->Note(InlineObservation::CALLEE_ARG_FEEDS_TEST); unsigned varNum = FgStack::SlotTypeToArgNum(slot0); if (impInlineInfo->inlArgInfo[varNum].argNode->OperIsConst()) { compInlineResult->Note(InlineObservation::CALLSITE_CONSTANT_ARG_FEEDS_TEST); } } if (FgStack::IsArgument(slot1)) { compInlineResult->Note(InlineObservation::CALLEE_ARG_FEEDS_TEST); unsigned varNum = FgStack::SlotTypeToArgNum(slot1); if (impInlineInfo->inlArgInfo[varNum].argNode->OperIsConst()) { compInlineResult->Note(InlineObservation::CALLSITE_CONSTANT_ARG_FEEDS_TEST); } } } } /***************************************************************************** * * Finally link up the bbJumpDest of the blocks together */ void Compiler::fgMarkBackwardJump(BasicBlock* startBlock, BasicBlock* endBlock) { noway_assert(startBlock->bbNum <= endBlock->bbNum); for (BasicBlock* block = startBlock; block != endBlock->bbNext; block = block->bbNext) { if ((block->bbFlags & BBF_BACKWARD_JUMP) == 0) { block->bbFlags |= BBF_BACKWARD_JUMP; fgHasBackwardJump = true; } } } /***************************************************************************** * * Finally link up the bbJumpDest of the blocks together */ void Compiler::fgLinkBasicBlocks() { /* Create the basic block lookup tables */ fgInitBBLookup(); /* First block is always reachable */ fgFirstBB->bbRefs = 1; /* Walk all the basic blocks, filling in the target addresses */ for (BasicBlock* curBBdesc = fgFirstBB; curBBdesc; curBBdesc = curBBdesc->bbNext) { switch (curBBdesc->bbJumpKind) { case BBJ_COND: case BBJ_ALWAYS: case BBJ_LEAVE: curBBdesc->bbJumpDest = fgLookupBB(curBBdesc->bbJumpOffs); curBBdesc->bbJumpDest->bbRefs++; if (curBBdesc->bbJumpDest->bbNum <= curBBdesc->bbNum) { fgMarkBackwardJump(curBBdesc->bbJumpDest, curBBdesc); } /* Is the next block reachable? */ if (curBBdesc->bbJumpKind == BBJ_ALWAYS || curBBdesc->bbJumpKind == BBJ_LEAVE) { break; } if (!curBBdesc->bbNext) { BADCODE("Fall thru the end of a method"); } // Fall through, the next block is also reachable case BBJ_NONE: curBBdesc->bbNext->bbRefs++; break; case BBJ_EHFINALLYRET: case BBJ_EHFILTERRET: case BBJ_THROW: case BBJ_RETURN: break; case BBJ_SWITCH: unsigned jumpCnt; jumpCnt = curBBdesc->bbJumpSwt->bbsCount; BasicBlock** jumpPtr; jumpPtr = curBBdesc->bbJumpSwt->bbsDstTab; do { *jumpPtr = fgLookupBB((unsigned)*(size_t*)jumpPtr); (*jumpPtr)->bbRefs++; if ((*jumpPtr)->bbNum <= curBBdesc->bbNum) { fgMarkBackwardJump(*jumpPtr, curBBdesc); } } while (++jumpPtr, --jumpCnt); /* Default case of CEE_SWITCH (next block), is at end of jumpTab[] */ noway_assert(*(jumpPtr - 1) == curBBdesc->bbNext); break; case BBJ_CALLFINALLY: // BBJ_CALLFINALLY and BBJ_EHCATCHRET don't appear until later case BBJ_EHCATCHRET: default: noway_assert(!"Unexpected bbJumpKind"); break; } } } //------------------------------------------------------------------------ // fgMakeBasicBlocks: walk the IL creating basic blocks, and look for // operations that might get optimized if this method were to be inlined. // // Arguments: // codeAddr -- starting address of the method's IL stream // codeSize -- length of the IL stream // jumpTarget -- [in] bit vector of jump targets found by fgFindJumpTargets // // Returns: // number of return blocks (BBJ_RETURN) in the method (may be zero) // // Notes: // Invoked for prejited and jitted methods, and for all inlinees unsigned Compiler::fgMakeBasicBlocks(const BYTE* codeAddr, IL_OFFSET codeSize, FixedBitVect* jumpTarget) { unsigned retBlocks = 0; const BYTE* codeBegp = codeAddr; const BYTE* codeEndp = codeAddr + codeSize; bool tailCall = false; unsigned curBBoffs = 0; BasicBlock* curBBdesc; // Keep track of where we are in the scope lists, as we will also // create blocks at scope boundaries. if (opts.compDbgCode && (info.compVarScopesCount > 0)) { compResetScopeLists(); // Ignore scopes beginning at offset 0 while (compGetNextEnterScope(0)) { /* do nothing */ } while (compGetNextExitScope(0)) { /* do nothing */ } } do { unsigned jmpAddr = DUMMY_INIT(BAD_IL_OFFSET); unsigned bbFlags = 0; BBswtDesc* swtDsc = nullptr; unsigned nxtBBoffs; OPCODE opcode = (OPCODE)getU1LittleEndian(codeAddr); codeAddr += sizeof(__int8); BBjumpKinds jmpKind = BBJ_NONE; DECODE_OPCODE: /* Get the size of additional parameters */ noway_assert((unsigned)opcode < CEE_COUNT); unsigned sz = opcodeSizes[opcode]; switch (opcode) { signed jmpDist; case CEE_PREFIX1: if (jumpTarget->bitVectTest((UINT)(codeAddr - codeBegp))) { BADCODE3("jump target between prefix 0xFE and opcode", " at offset %04X", (IL_OFFSET)(codeAddr - codeBegp)); } opcode = (OPCODE)(256 + getU1LittleEndian(codeAddr)); codeAddr += sizeof(__int8); goto DECODE_OPCODE; /* Check to see if we have a jump/return opcode */ case CEE_BRFALSE: case CEE_BRFALSE_S: case CEE_BRTRUE: case CEE_BRTRUE_S: case CEE_BEQ: case CEE_BEQ_S: case CEE_BGE: case CEE_BGE_S: case CEE_BGE_UN: case CEE_BGE_UN_S: case CEE_BGT: case CEE_BGT_S: case CEE_BGT_UN: case CEE_BGT_UN_S: case CEE_BLE: case CEE_BLE_S: case CEE_BLE_UN: case CEE_BLE_UN_S: case CEE_BLT: case CEE_BLT_S: case CEE_BLT_UN: case CEE_BLT_UN_S: case CEE_BNE_UN: case CEE_BNE_UN_S: jmpKind = BBJ_COND; goto JMP; case CEE_LEAVE: case CEE_LEAVE_S: // We need to check if we are jumping out of a finally-protected try. jmpKind = BBJ_LEAVE; goto JMP; case CEE_BR: case CEE_BR_S: jmpKind = BBJ_ALWAYS; goto JMP; JMP: /* Compute the target address of the jump */ jmpDist = (sz == 1) ? getI1LittleEndian(codeAddr) : getI4LittleEndian(codeAddr); if (compIsForInlining() && jmpDist == 0 && (opcode == CEE_BR || opcode == CEE_BR_S)) { continue; /* NOP */ } jmpAddr = (IL_OFFSET)(codeAddr - codeBegp) + sz + jmpDist; break; case CEE_SWITCH: { unsigned jmpBase; unsigned jmpCnt; // # of switch cases (excluding default) BasicBlock** jmpTab; BasicBlock** jmpPtr; /* Allocate the switch descriptor */ swtDsc = new (this, CMK_BasicBlock) BBswtDesc; /* Read the number of entries in the table */ jmpCnt = getU4LittleEndian(codeAddr); codeAddr += 4; /* Compute the base offset for the opcode */ jmpBase = (IL_OFFSET)((codeAddr - codeBegp) + jmpCnt * sizeof(DWORD)); /* Allocate the jump table */ jmpPtr = jmpTab = new (this, CMK_BasicBlock) BasicBlock*[jmpCnt + 1]; /* Fill in the jump table */ for (unsigned count = jmpCnt; count; count--) { jmpDist = getI4LittleEndian(codeAddr); codeAddr += 4; // store the offset in the pointer. We change these in fgLinkBasicBlocks(). *jmpPtr++ = (BasicBlock*)(size_t)(jmpBase + jmpDist); } /* Append the default label to the target table */ *jmpPtr++ = (BasicBlock*)(size_t)jmpBase; /* Make sure we found the right number of labels */ noway_assert(jmpPtr == jmpTab + jmpCnt + 1); /* Compute the size of the switch opcode operands */ sz = sizeof(DWORD) + jmpCnt * sizeof(DWORD); /* Fill in the remaining fields of the switch descriptor */ swtDsc->bbsCount = jmpCnt + 1; swtDsc->bbsDstTab = jmpTab; /* This is definitely a jump */ jmpKind = BBJ_SWITCH; fgHasSwitch = true; if (opts.compProcedureSplitting) { // TODO-CQ: We might need to create a switch table; we won't know for sure until much later. // However, switch tables don't work with hot/cold splitting, currently. The switch table data needs // a relocation such that if the base (the first block after the prolog) and target of the switch // branch are put in different sections, the difference stored in the table is updated. However, our // relocation implementation doesn't support three different pointers (relocation address, base, and // target). So, we need to change our switch table implementation to be more like // JIT64: put the table in the code section, in the same hot/cold section as the switch jump itself // (maybe immediately after the switch jump), and make the "base" address be also in that section, // probably the address after the switch jump. opts.compProcedureSplitting = false; JITDUMP("Turning off procedure splitting for this method, as it might need switch tables; " "implementation limitation.\n"); } } goto GOT_ENDP; case CEE_ENDFILTER: bbFlags |= BBF_DONT_REMOVE; jmpKind = BBJ_EHFILTERRET; break; case CEE_ENDFINALLY: jmpKind = BBJ_EHFINALLYRET; break; case CEE_TAILCALL: if (compIsForInlining()) { // TODO-CQ: We can inline some callees with explicit tail calls if we can guarantee that the calls // can be dispatched as tail calls from the caller. compInlineResult->NoteFatal(InlineObservation::CALLEE_EXPLICIT_TAIL_PREFIX); retBlocks++; return retBlocks; } __fallthrough; case CEE_READONLY: case CEE_CONSTRAINED: case CEE_VOLATILE: case CEE_UNALIGNED: // fgFindJumpTargets should have ruled out this possibility // (i.e. a prefix opcodes as last intruction in a block) noway_assert(codeAddr < codeEndp); if (jumpTarget->bitVectTest((UINT)(codeAddr - codeBegp))) { BADCODE3("jump target between prefix and an opcode", " at offset %04X", (IL_OFFSET)(codeAddr - codeBegp)); } break; case CEE_CALL: case CEE_CALLVIRT: case CEE_CALLI: { if (compIsForInlining() || // Ignore tail call in the inlinee. Period. (!tailCall && !compTailCallStress()) // A new BB with BBJ_RETURN would have been created // after a tailcall statement. // We need to keep this invariant if we want to stress the tailcall. // That way, the potential (tail)call statement is always the last // statement in the block. // Otherwise, we will assert at the following line in fgMorphCall() // noway_assert(fgMorphStmt->gtNext == NULL); ) { // Neither .tailcall prefix, no tailcall stress. So move on. break; } // Make sure the code sequence is legal for the tail call. // If so, mark this BB as having a BBJ_RETURN. if (codeAddr >= codeEndp - sz) { BADCODE3("No code found after the call instruction", " at offset %04X", (IL_OFFSET)(codeAddr - codeBegp)); } if (tailCall) { bool isCallPopAndRet = false; // impIsTailCallILPattern uses isRecursive flag to determine whether ret in a fallthrough block is // allowed. We don't know at this point whether the call is recursive so we conservatively pass // false. This will only affect explicit tail calls when IL verification is not needed for the // method. bool isRecursive = false; if (!impIsTailCallILPattern(tailCall, opcode, codeAddr + sz, codeEndp, isRecursive, &isCallPopAndRet)) { #if !defined(FEATURE_CORECLR) && defined(_TARGET_AMD64_) BADCODE3("tail call not followed by ret or pop+ret", " at offset %04X", (IL_OFFSET)(codeAddr - codeBegp)); #else BADCODE3("tail call not followed by ret", " at offset %04X", (IL_OFFSET)(codeAddr - codeBegp)); #endif // !FEATURE_CORECLR && _TARGET_AMD64_ } if (fgCanSwitchToOptimized() && fgMayExplicitTailCall()) { // Method has an explicit tail call that may run like a loop or may not be generated as a tail // call in tier 0, switch to optimized to avoid spending too much time running slower code and // to avoid stack overflow from recursion fgSwitchToOptimized(); } #if !defined(FEATURE_CORECLR) && defined(_TARGET_AMD64_) if (isCallPopAndRet) { // By breaking here, we let pop and ret opcodes to be // imported after tail call. If tail prefix is honored, // stmts corresponding to pop and ret will be removed // in fgMorphCall(). break; } #endif // !FEATURE_CORECLR && _TARGET_AMD64_ } else { OPCODE nextOpcode = (OPCODE)getU1LittleEndian(codeAddr + sz); if (nextOpcode != CEE_RET) { noway_assert(compTailCallStress()); // Next OPCODE is not a CEE_RET, bail the attempt to stress the tailcall. // (I.e. We will not make a new BB after the "call" statement.) break; } } } /* For tail call, we just call CORINFO_HELP_TAILCALL, and it jumps to the target. So we don't need an epilog - just like CORINFO_HELP_THROW. Make the block BBJ_RETURN, but we will change it to BBJ_THROW if the tailness of the call is satisfied. NOTE : The next instruction is guaranteed to be a CEE_RET and it will create another BasicBlock. But there may be an jump directly to that CEE_RET. If we want to avoid creating an unnecessary block, we need to check if the CEE_RETURN is the target of a jump. */ // fall-through case CEE_JMP: /* These are equivalent to a return from the current method But instead of directly returning to the caller we jump and execute something else in between */ case CEE_RET: retBlocks++; jmpKind = BBJ_RETURN; break; case CEE_THROW: case CEE_RETHROW: jmpKind = BBJ_THROW; break; #ifdef DEBUG // make certain we did not forget any flow of control instructions // by checking the 'ctrl' field in opcode.def. First filter out all // non-ctrl instructions #define BREAK(name) \ case name: \ break; #define NEXT(name) \ case name: \ break; #define CALL(name) #define THROW(name) #undef RETURN // undef contract RETURN macro #define RETURN(name) #define META(name) #define BRANCH(name) #define COND_BRANCH(name) #define PHI(name) #define OPDEF(name, string, pop, push, oprType, opcType, l, s1, s2, ctrl) ctrl(name) #include "opcode.def" #undef OPDEF #undef PHI #undef BREAK #undef CALL #undef NEXT #undef THROW #undef RETURN #undef META #undef BRANCH #undef COND_BRANCH // These ctrl-flow opcodes don't need any special handling case CEE_NEWOBJ: // CTRL_CALL break; // what's left are forgotten instructions default: BADCODE("Unrecognized control Opcode"); break; #else // !DEBUG default: break; #endif // !DEBUG } /* Jump over the operand */ codeAddr += sz; GOT_ENDP: tailCall = (opcode == CEE_TAILCALL); /* Make sure a jump target isn't in the middle of our opcode */ if (sz) { IL_OFFSET offs = (IL_OFFSET)(codeAddr - codeBegp) - sz; // offset of the operand for (unsigned i = 0; i < sz; i++, offs++) { if (jumpTarget->bitVectTest(offs)) { BADCODE3("jump into the middle of an opcode", " at offset %04X", (IL_OFFSET)(codeAddr - codeBegp)); } } } /* Compute the offset of the next opcode */ nxtBBoffs = (IL_OFFSET)(codeAddr - codeBegp); bool foundScope = false; if (opts.compDbgCode && (info.compVarScopesCount > 0)) { while (compGetNextEnterScope(nxtBBoffs)) { foundScope = true; } while (compGetNextExitScope(nxtBBoffs)) { foundScope = true; } } /* Do we have a jump? */ if (jmpKind == BBJ_NONE) { /* No jump; make sure we don't fall off the end of the function */ if (codeAddr == codeEndp) { BADCODE3("missing return opcode", " at offset %04X", (IL_OFFSET)(codeAddr - codeBegp)); } /* If a label follows this opcode, we'll have to make a new BB */ bool makeBlock = jumpTarget->bitVectTest(nxtBBoffs); if (!makeBlock && foundScope) { makeBlock = true; #ifdef DEBUG if (verbose) { printf("Splitting at BBoffs = %04u\n", nxtBBoffs); } #endif // DEBUG } if (!makeBlock) { continue; } } /* We need to create a new basic block */ curBBdesc = fgNewBasicBlock(jmpKind); curBBdesc->bbFlags |= bbFlags; curBBdesc->bbRefs = 0; curBBdesc->bbCodeOffs = curBBoffs; curBBdesc->bbCodeOffsEnd = nxtBBoffs; unsigned profileWeight; if (fgGetProfileWeightForBasicBlock(curBBoffs, &profileWeight)) { curBBdesc->setBBProfileWeight(profileWeight); if (profileWeight == 0) { curBBdesc->bbSetRunRarely(); } else { // Note that bbNewBasicBlock (called from fgNewBasicBlock) may have // already marked the block as rarely run. In that case (and when we know // that the block profile weight is non-zero) we want to unmark that. curBBdesc->bbFlags &= ~BBF_RUN_RARELY; } } switch (jmpKind) { case BBJ_SWITCH: curBBdesc->bbJumpSwt = swtDsc; break; case BBJ_COND: case BBJ_ALWAYS: case BBJ_LEAVE: noway_assert(jmpAddr != DUMMY_INIT(BAD_IL_OFFSET)); curBBdesc->bbJumpOffs = jmpAddr; break; default: break; } DBEXEC(verbose, curBBdesc->dspBlockHeader(this, false, false, false)); /* Remember where the next BB will start */ curBBoffs = nxtBBoffs; } while (codeAddr < codeEndp); noway_assert(codeAddr == codeEndp); /* Finally link up the bbJumpDest of the blocks together */ fgLinkBasicBlocks(); return retBlocks; } /***************************************************************************** * * Main entry point to discover the basic blocks for the current function. */ void Compiler::fgFindBasicBlocks() { #ifdef DEBUG if (verbose) { printf("*************** In fgFindBasicBlocks() for %s\n", info.compFullName); } #endif // Allocate the 'jump target' bit vector FixedBitVect* jumpTarget = FixedBitVect::bitVectInit(info.compILCodeSize + 1, this); // Walk the instrs to find all jump targets fgFindJumpTargets(info.compCode, info.compILCodeSize, jumpTarget); if (compDonotInline()) { return; } unsigned XTnum; /* Are there any exception handlers? */ if (info.compXcptnsCount > 0) { noway_assert(!compIsForInlining()); /* Check and mark all the exception handlers */ for (XTnum = 0; XTnum < info.compXcptnsCount; XTnum++) { CORINFO_EH_CLAUSE clause; info.compCompHnd->getEHinfo(info.compMethodHnd, XTnum, &clause); noway_assert(clause.HandlerLength != (unsigned)-1); if (clause.TryLength <= 0) { BADCODE("try block length <=0"); } /* Mark the 'try' block extent and the handler itself */ if (clause.TryOffset > info.compILCodeSize) { BADCODE("try offset is > codesize"); } jumpTarget->bitVectSet(clause.TryOffset); if (clause.TryOffset + clause.TryLength > info.compILCodeSize) { BADCODE("try end is > codesize"); } jumpTarget->bitVectSet(clause.TryOffset + clause.TryLength); if (clause.HandlerOffset > info.compILCodeSize) { BADCODE("handler offset > codesize"); } jumpTarget->bitVectSet(clause.HandlerOffset); if (clause.HandlerOffset + clause.HandlerLength > info.compILCodeSize) { BADCODE("handler end > codesize"); } jumpTarget->bitVectSet(clause.HandlerOffset + clause.HandlerLength); if (clause.Flags & CORINFO_EH_CLAUSE_FILTER) { if (clause.FilterOffset > info.compILCodeSize) { BADCODE("filter offset > codesize"); } jumpTarget->bitVectSet(clause.FilterOffset); } } } #ifdef DEBUG if (verbose) { bool anyJumpTargets = false; printf("Jump targets:\n"); for (unsigned i = 0; i < info.compILCodeSize + 1; i++) { if (jumpTarget->bitVectTest(i)) { anyJumpTargets = true; printf(" IL_%04x\n", i); } } if (!anyJumpTargets) { printf(" none\n"); } } #endif // DEBUG /* Now create the basic blocks */ unsigned retBlocks = fgMakeBasicBlocks(info.compCode, info.compILCodeSize, jumpTarget); if (compIsForInlining()) { #ifdef DEBUG // If fgFindJumpTargets marked the call as "no return" there // really should be no BBJ_RETURN blocks in the method. bool markedNoReturn = (impInlineInfo->iciCall->gtCallMoreFlags & GTF_CALL_M_DOES_NOT_RETURN) != 0; assert((markedNoReturn && (retBlocks == 0)) || (!markedNoReturn && (retBlocks >= 1))); #endif // DEBUG if (compInlineResult->IsFailure()) { return; } noway_assert(info.compXcptnsCount == 0); compHndBBtab = impInlineInfo->InlinerCompiler->compHndBBtab; compHndBBtabAllocCount = impInlineInfo->InlinerCompiler->compHndBBtabAllocCount; // we probably only use the table, not add to it. compHndBBtabCount = impInlineInfo->InlinerCompiler->compHndBBtabCount; info.compXcptnsCount = impInlineInfo->InlinerCompiler->info.compXcptnsCount; // Use a spill temp for the return value if there are multiple return blocks, // or if the inlinee has GC ref locals. if ((info.compRetNativeType != TYP_VOID) && ((retBlocks > 1) || impInlineInfo->HasGcRefLocals())) { // If we've spilled the ret expr to a temp we can reuse the temp // as the inlinee return spill temp. // // Todo: see if it is even better to always use this existing temp // for return values, even if we otherwise wouldn't need a return spill temp... lvaInlineeReturnSpillTemp = impInlineInfo->inlineCandidateInfo->preexistingSpillTemp; if (lvaInlineeReturnSpillTemp != BAD_VAR_NUM) { // This temp should already have the type of the return value. JITDUMP("\nInliner: re-using pre-existing spill temp V%02u\n", lvaInlineeReturnSpillTemp); if (info.compRetType == TYP_REF) { // We may have co-opted an existing temp for the return spill. // We likely assumed it was single-def at the time, but now // we can see it has multiple definitions. if ((retBlocks > 1) && (lvaTable[lvaInlineeReturnSpillTemp].lvSingleDef == 1)) { // Make sure it is no longer marked single def. This is only safe // to do if we haven't ever updated the type. assert(!lvaTable[lvaInlineeReturnSpillTemp].lvClassInfoUpdated); JITDUMP("Marked return spill temp V%02u as NOT single def temp\n", lvaInlineeReturnSpillTemp); lvaTable[lvaInlineeReturnSpillTemp].lvSingleDef = 0; } } } else { // The lifetime of this var might expand multiple BBs. So it is a long lifetime compiler temp. lvaInlineeReturnSpillTemp = lvaGrabTemp(false DEBUGARG("Inline return value spill temp")); lvaTable[lvaInlineeReturnSpillTemp].lvType = info.compRetNativeType; // If the method returns a ref class, set the class of the spill temp // to the method's return value. We may update this later if it turns // out we can prove the method returns a more specific type. if (info.compRetType == TYP_REF) { // The return spill temp is single def only if the method has a single return block. if (retBlocks == 1) { lvaTable[lvaInlineeReturnSpillTemp].lvSingleDef = 1; JITDUMP("Marked return spill temp V%02u as a single def temp\n", lvaInlineeReturnSpillTemp); } CORINFO_CLASS_HANDLE retClassHnd = impInlineInfo->inlineCandidateInfo->methInfo.args.retTypeClass; if (retClassHnd != nullptr) { lvaSetClass(lvaInlineeReturnSpillTemp, retClassHnd); } } } } return; } /* Mark all blocks within 'try' blocks as such */ if (info.compXcptnsCount == 0) { return; } if (info.compXcptnsCount > MAX_XCPTN_INDEX) { IMPL_LIMITATION("too many exception clauses"); } /* Allocate the exception handler table */ fgAllocEHTable(); /* Assume we don't need to sort the EH table (such that nested try/catch * appear before their try or handler parent). The EH verifier will notice * when we do need to sort it. */ fgNeedToSortEHTable = false; verInitEHTree(info.compXcptnsCount); EHNodeDsc* initRoot = ehnNext; // remember the original root since // it may get modified during insertion // Annotate BBs with exception handling information required for generating correct eh code // as well as checking for correct IL EHblkDsc* HBtab; for (XTnum = 0, HBtab = compHndBBtab; XTnum < compHndBBtabCount; XTnum++, HBtab++) { CORINFO_EH_CLAUSE clause; info.compCompHnd->getEHinfo(info.compMethodHnd, XTnum, &clause); noway_assert(clause.HandlerLength != (unsigned)-1); // @DEPRECATED #ifdef DEBUG if (verbose) { dispIncomingEHClause(XTnum, clause); } #endif // DEBUG IL_OFFSET tryBegOff = clause.TryOffset; IL_OFFSET tryEndOff = tryBegOff + clause.TryLength; IL_OFFSET filterBegOff = 0; IL_OFFSET hndBegOff = clause.HandlerOffset; IL_OFFSET hndEndOff = hndBegOff + clause.HandlerLength; if (clause.Flags & CORINFO_EH_CLAUSE_FILTER) { filterBegOff = clause.FilterOffset; } if (tryEndOff > info.compILCodeSize) { BADCODE3("end of try block beyond end of method for try", " at offset %04X", tryBegOff); } if (hndEndOff > info.compILCodeSize) { BADCODE3("end of hnd block beyond end of method for try", " at offset %04X", tryBegOff); } HBtab->ebdTryBegOffset = tryBegOff; HBtab->ebdTryEndOffset = tryEndOff; HBtab->ebdFilterBegOffset = filterBegOff; HBtab->ebdHndBegOffset = hndBegOff; HBtab->ebdHndEndOffset = hndEndOff; /* Convert the various addresses to basic blocks */ BasicBlock* tryBegBB = fgLookupBB(tryBegOff); BasicBlock* tryEndBB = fgLookupBB(tryEndOff); // note: this can be NULL if the try region is at the end of the function BasicBlock* hndBegBB = fgLookupBB(hndBegOff); BasicBlock* hndEndBB = nullptr; BasicBlock* filtBB = nullptr; BasicBlock* block; // // Assert that the try/hnd beginning blocks are set up correctly // if (tryBegBB == nullptr) { BADCODE("Try Clause is invalid"); } if (hndBegBB == nullptr) { BADCODE("Handler Clause is invalid"); } tryBegBB->bbFlags |= BBF_HAS_LABEL; hndBegBB->bbFlags |= BBF_HAS_LABEL | BBF_JMP_TARGET; #if HANDLER_ENTRY_MUST_BE_IN_HOT_SECTION // This will change the block weight from 0 to 1 // and clear the rarely run flag hndBegBB->makeBlockHot(); #else hndBegBB->bbSetRunRarely(); // handler entry points are rarely executed #endif if (hndEndOff < info.compILCodeSize) { hndEndBB = fgLookupBB(hndEndOff); } if (clause.Flags & CORINFO_EH_CLAUSE_FILTER) { filtBB = HBtab->ebdFilter = fgLookupBB(clause.FilterOffset); filtBB->bbCatchTyp = BBCT_FILTER; filtBB->bbFlags |= BBF_HAS_LABEL | BBF_JMP_TARGET; hndBegBB->bbCatchTyp = BBCT_FILTER_HANDLER; #if HANDLER_ENTRY_MUST_BE_IN_HOT_SECTION // This will change the block weight from 0 to 1 // and clear the rarely run flag filtBB->makeBlockHot(); #else filtBB->bbSetRunRarely(); // filter entry points are rarely executed #endif // Mark all BBs that belong to the filter with the XTnum of the corresponding handler for (block = filtBB; /**/; block = block->bbNext) { if (block == nullptr) { BADCODE3("Missing endfilter for filter", " at offset %04X", filtBB->bbCodeOffs); return; } // Still inside the filter block->setHndIndex(XTnum); if (block->bbJumpKind == BBJ_EHFILTERRET) { // Mark catch handler as successor. block->bbJumpDest = hndBegBB; assert(block->bbJumpDest->bbCatchTyp == BBCT_FILTER_HANDLER); break; } } if (!block->bbNext || block->bbNext != hndBegBB) { BADCODE3("Filter does not immediately precede handler for filter", " at offset %04X", filtBB->bbCodeOffs); } } else { HBtab->ebdTyp = clause.ClassToken; /* Set bbCatchTyp as appropriate */ if (clause.Flags & CORINFO_EH_CLAUSE_FINALLY) { hndBegBB->bbCatchTyp = BBCT_FINALLY; } else { if (clause.Flags & CORINFO_EH_CLAUSE_FAULT) { hndBegBB->bbCatchTyp = BBCT_FAULT; } else { hndBegBB->bbCatchTyp = clause.ClassToken; // These values should be non-zero value that will // not collide with real tokens for bbCatchTyp if (clause.ClassToken == 0) { BADCODE("Exception catch type is Null"); } noway_assert(clause.ClassToken != BBCT_FAULT); noway_assert(clause.ClassToken != BBCT_FINALLY); noway_assert(clause.ClassToken != BBCT_FILTER); noway_assert(clause.ClassToken != BBCT_FILTER_HANDLER); } } } /* Mark the initial block and last blocks in the 'try' region */ tryBegBB->bbFlags |= BBF_TRY_BEG | BBF_HAS_LABEL; /* Prevent future optimizations of removing the first block */ /* of a TRY block and the first block of an exception handler */ tryBegBB->bbFlags |= BBF_DONT_REMOVE; hndBegBB->bbFlags |= BBF_DONT_REMOVE; hndBegBB->bbRefs++; // The first block of a handler gets an extra, "artificial" reference count. if (clause.Flags & CORINFO_EH_CLAUSE_FILTER) { filtBB->bbFlags |= BBF_DONT_REMOVE; filtBB->bbRefs++; // The first block of a filter gets an extra, "artificial" reference count. } tryBegBB->bbFlags |= BBF_DONT_REMOVE; hndBegBB->bbFlags |= BBF_DONT_REMOVE; // // Store the info to the table of EH block handlers // HBtab->ebdHandlerType = ToEHHandlerType(clause.Flags); HBtab->ebdTryBeg = tryBegBB; HBtab->ebdTryLast = (tryEndBB == nullptr) ? fgLastBB : tryEndBB->bbPrev; HBtab->ebdHndBeg = hndBegBB; HBtab->ebdHndLast = (hndEndBB == nullptr) ? fgLastBB : hndEndBB->bbPrev; // // Assert that all of our try/hnd blocks are setup correctly. // if (HBtab->ebdTryLast == nullptr) { BADCODE("Try Clause is invalid"); } if (HBtab->ebdHndLast == nullptr) { BADCODE("Handler Clause is invalid"); } // // Verify that it's legal // verInsertEhNode(&clause, HBtab); } // end foreach handler table entry fgSortEHTable(); // Next, set things related to nesting that depend on the sorting being complete. for (XTnum = 0, HBtab = compHndBBtab; XTnum < compHndBBtabCount; XTnum++, HBtab++) { /* Mark all blocks in the finally/fault or catch clause */ BasicBlock* tryBegBB = HBtab->ebdTryBeg; BasicBlock* hndBegBB = HBtab->ebdHndBeg; IL_OFFSET tryBegOff = HBtab->ebdTryBegOffset; IL_OFFSET tryEndOff = HBtab->ebdTryEndOffset; IL_OFFSET hndBegOff = HBtab->ebdHndBegOffset; IL_OFFSET hndEndOff = HBtab->ebdHndEndOffset; BasicBlock* block; for (block = hndBegBB; block && (block->bbCodeOffs < hndEndOff); block = block->bbNext) { if (!block->hasHndIndex()) { block->setHndIndex(XTnum); } // All blocks in a catch handler or filter are rarely run, except the entry if ((block != hndBegBB) && (hndBegBB->bbCatchTyp != BBCT_FINALLY)) { block->bbSetRunRarely(); } } /* Mark all blocks within the covered range of the try */ for (block = tryBegBB; block && (block->bbCodeOffs < tryEndOff); block = block->bbNext) { /* Mark this BB as belonging to a 'try' block */ if (!block->hasTryIndex()) { block->setTryIndex(XTnum); } #ifdef DEBUG /* Note: the BB can't span the 'try' block */ if (!(block->bbFlags & BBF_INTERNAL)) { noway_assert(tryBegOff <= block->bbCodeOffs); noway_assert(tryEndOff >= block->bbCodeOffsEnd || tryEndOff == tryBegOff); } #endif } /* Init ebdHandlerNestingLevel of current clause, and bump up value for all * enclosed clauses (which have to be before it in the table). * Innermost try-finally blocks must precede outermost * try-finally blocks. */ #if !FEATURE_EH_FUNCLETS HBtab->ebdHandlerNestingLevel = 0; #endif // !FEATURE_EH_FUNCLETS HBtab->ebdEnclosingTryIndex = EHblkDsc::NO_ENCLOSING_INDEX; HBtab->ebdEnclosingHndIndex = EHblkDsc::NO_ENCLOSING_INDEX; noway_assert(XTnum < compHndBBtabCount); noway_assert(XTnum == ehGetIndex(HBtab)); for (EHblkDsc* xtab = compHndBBtab; xtab < HBtab; xtab++) { #if !FEATURE_EH_FUNCLETS if (jitIsBetween(xtab->ebdHndBegOffs(), hndBegOff, hndEndOff)) { xtab->ebdHandlerNestingLevel++; } #endif // !FEATURE_EH_FUNCLETS /* If we haven't recorded an enclosing try index for xtab then see * if this EH region should be recorded. We check if the * first offset in the xtab lies within our region. If so, * the last offset also must lie within the region, due to * nesting rules. verInsertEhNode(), below, will check for proper nesting. */ if (xtab->ebdEnclosingTryIndex == EHblkDsc::NO_ENCLOSING_INDEX) { bool begBetween = jitIsBetween(xtab->ebdTryBegOffs(), tryBegOff, tryEndOff); if (begBetween) { // Record the enclosing scope link xtab->ebdEnclosingTryIndex = (unsigned short)XTnum; } } /* Do the same for the enclosing handler index. */ if (xtab->ebdEnclosingHndIndex == EHblkDsc::NO_ENCLOSING_INDEX) { bool begBetween = jitIsBetween(xtab->ebdTryBegOffs(), hndBegOff, hndEndOff); if (begBetween) { // Record the enclosing scope link xtab->ebdEnclosingHndIndex = (unsigned short)XTnum; } } } } // end foreach handler table entry #if !FEATURE_EH_FUNCLETS EHblkDsc* HBtabEnd; for (HBtab = compHndBBtab, HBtabEnd = compHndBBtab + compHndBBtabCount; HBtab < HBtabEnd; HBtab++) { if (ehMaxHndNestingCount <= HBtab->ebdHandlerNestingLevel) ehMaxHndNestingCount = HBtab->ebdHandlerNestingLevel + 1; } #endif // !FEATURE_EH_FUNCLETS #ifndef DEBUG if (tiVerificationNeeded) #endif { // always run these checks for a debug build verCheckNestingLevel(initRoot); } #ifndef DEBUG // fgNormalizeEH assumes that this test has been passed. And Ssa assumes that fgNormalizeEHTable // has been run. So do this unless we're in minOpts mode (and always in debug). if (tiVerificationNeeded || !opts.MinOpts()) #endif { fgCheckBasicBlockControlFlow(); } #ifdef DEBUG if (verbose) { JITDUMP("*************** After fgFindBasicBlocks() has created the EH table\n"); fgDispHandlerTab(); } // We can't verify the handler table until all the IL legality checks have been done (above), since bad IL // (such as illegal nesting of regions) will trigger asserts here. fgVerifyHandlerTab(); #endif fgNormalizeEH(); } /***************************************************************************** * Check control flow constraints for well formed IL. Bail if any of the constraints * are violated. */ void Compiler::fgCheckBasicBlockControlFlow() { assert(!fgNormalizeEHDone); // These rules aren't quite correct after EH normalization has introduced new blocks EHblkDsc* HBtab; for (BasicBlock* blk = fgFirstBB; blk; blk = blk->bbNext) { if (blk->bbFlags & BBF_INTERNAL) { continue; } switch (blk->bbJumpKind) { case BBJ_NONE: // block flows into the next one (no jump) fgControlFlowPermitted(blk, blk->bbNext); break; case BBJ_ALWAYS: // block does unconditional jump to target fgControlFlowPermitted(blk, blk->bbJumpDest); break; case BBJ_COND: // block conditionally jumps to the target fgControlFlowPermitted(blk, blk->bbNext); fgControlFlowPermitted(blk, blk->bbJumpDest); break; case BBJ_RETURN: // block ends with 'ret' if (blk->hasTryIndex() || blk->hasHndIndex()) { BADCODE3("Return from a protected block", ". Before offset %04X", blk->bbCodeOffsEnd); } break; case BBJ_EHFINALLYRET: case BBJ_EHFILTERRET: if (!blk->hasHndIndex()) // must be part of a handler { BADCODE3("Missing handler", ". Before offset %04X", blk->bbCodeOffsEnd); } HBtab = ehGetDsc(blk->getHndIndex()); // Endfilter allowed only in a filter block if (blk->bbJumpKind == BBJ_EHFILTERRET) { if (!HBtab->HasFilter()) { BADCODE("Unexpected endfilter"); } } // endfinally allowed only in a finally/fault block else if (!HBtab->HasFinallyOrFaultHandler()) { BADCODE("Unexpected endfinally"); } // The handler block should be the innermost block // Exception blocks are listed, innermost first. if (blk->hasTryIndex() && (blk->getTryIndex() < blk->getHndIndex())) { BADCODE("endfinally / endfilter in nested try block"); } break; case BBJ_THROW: // block ends with 'throw' /* throw is permitted from every BB, so nothing to check */ /* importer makes sure that rethrow is done from a catch */ break; case BBJ_LEAVE: // block always jumps to the target, maybe out of guarded // region. Used temporarily until importing fgControlFlowPermitted(blk, blk->bbJumpDest, TRUE); break; case BBJ_SWITCH: // block ends with a switch statement BBswtDesc* swtDesc; swtDesc = blk->bbJumpSwt; assert(swtDesc); unsigned i; for (i = 0; i < swtDesc->bbsCount; i++) { fgControlFlowPermitted(blk, swtDesc->bbsDstTab[i]); } break; case BBJ_EHCATCHRET: // block ends with a leave out of a catch (only #if FEATURE_EH_FUNCLETS) case BBJ_CALLFINALLY: // block always calls the target finally default: noway_assert(!"Unexpected bbJumpKind"); // these blocks don't get created until importing break; } } } /**************************************************************************** * Check that the leave from the block is legal. * Consider removing this check here if we can do it cheaply during importing */ void Compiler::fgControlFlowPermitted(BasicBlock* blkSrc, BasicBlock* blkDest, BOOL isLeave) { assert(!fgNormalizeEHDone); // These rules aren't quite correct after EH normalization has introduced new blocks unsigned srcHndBeg, destHndBeg; unsigned srcHndEnd, destHndEnd; bool srcInFilter, destInFilter; bool srcInCatch = false; EHblkDsc* srcHndTab; srcHndTab = ehInitHndRange(blkSrc, &srcHndBeg, &srcHndEnd, &srcInFilter); ehInitHndRange(blkDest, &destHndBeg, &destHndEnd, &destInFilter); /* Impose the rules for leaving or jumping from handler blocks */ if (blkSrc->hasHndIndex()) { srcInCatch = srcHndTab->HasCatchHandler() && srcHndTab->InHndRegionILRange(blkSrc); /* Are we jumping within the same handler index? */ if (BasicBlock::sameHndRegion(blkSrc, blkDest)) { /* Do we have a filter clause? */ if (srcHndTab->HasFilter()) { /* filters and catch handlers share same eh index */ /* we need to check for control flow between them. */ if (srcInFilter != destInFilter) { if (!jitIsBetween(blkDest->bbCodeOffs, srcHndBeg, srcHndEnd)) { BADCODE3("Illegal control flow between filter and handler", ". Before offset %04X", blkSrc->bbCodeOffsEnd); } } } } else { /* The handler indexes of blkSrc and blkDest are different */ if (isLeave) { /* Any leave instructions must not enter the dest handler from outside*/ if (!jitIsBetween(srcHndBeg, destHndBeg, destHndEnd)) { BADCODE3("Illegal use of leave to enter handler", ". Before offset %04X", blkSrc->bbCodeOffsEnd); } } else { /* We must use a leave to exit a handler */ BADCODE3("Illegal control flow out of a handler", ". Before offset %04X", blkSrc->bbCodeOffsEnd); } /* Do we have a filter clause? */ if (srcHndTab->HasFilter()) { /* It is ok to leave from the handler block of a filter, */ /* but not from the filter block of a filter */ if (srcInFilter != destInFilter) { BADCODE3("Illegal to leave a filter handler", ". Before offset %04X", blkSrc->bbCodeOffsEnd); } } /* We should never leave a finally handler */ if (srcHndTab->HasFinallyHandler()) { BADCODE3("Illegal to leave a finally handler", ". Before offset %04X", blkSrc->bbCodeOffsEnd); } /* We should never leave a fault handler */ if (srcHndTab->HasFaultHandler()) { BADCODE3("Illegal to leave a fault handler", ". Before offset %04X", blkSrc->bbCodeOffsEnd); } } } else if (blkDest->hasHndIndex()) { /* blkSrc was not inside a handler, but blkDst is inside a handler */ BADCODE3("Illegal control flow into a handler", ". Before offset %04X", blkSrc->bbCodeOffsEnd); } /* Are we jumping from a catch handler into the corresponding try? */ /* VB uses this for "on error goto " */ if (isLeave && srcInCatch) { // inspect all handlers containing the jump source bool bValidJumpToTry = false; // are we jumping in a valid way from a catch to the corresponding try? bool bCatchHandlerOnly = true; // false if we are jumping out of a non-catch handler EHblkDsc* ehTableEnd; EHblkDsc* ehDsc; for (ehDsc = compHndBBtab, ehTableEnd = compHndBBtab + compHndBBtabCount; bCatchHandlerOnly && ehDsc < ehTableEnd; ehDsc++) { if (ehDsc->InHndRegionILRange(blkSrc)) { if (ehDsc->HasCatchHandler()) { if (ehDsc->InTryRegionILRange(blkDest)) { // If we already considered the jump for a different try/catch, // we would have two overlapping try regions with two overlapping catch // regions, which is illegal. noway_assert(!bValidJumpToTry); // Allowed if it is the first instruction of an inner try // (and all trys in between) // // try { // .. // _tryAgain: // .. // try { // _tryNestedInner: // .. // try { // _tryNestedIllegal: // .. // } catch { // .. // } // .. // } catch { // .. // } // .. // } catch { // .. // leave _tryAgain // Allowed // .. // leave _tryNestedInner // Allowed // .. // leave _tryNestedIllegal // Not Allowed // .. // } // // Note: The leave is allowed also from catches nested inside the catch shown above. /* The common case where leave is to the corresponding try */ if (ehDsc->ebdIsSameTry(this, blkDest->getTryIndex()) || /* Also allowed is a leave to the start of a try which starts in the handler's try */ fgFlowToFirstBlockOfInnerTry(ehDsc->ebdTryBeg, blkDest, false)) { bValidJumpToTry = true; } } } else { // We are jumping from a handler which is not a catch handler. // If it's a handler, but not a catch handler, it must be either a finally or fault if (!ehDsc->HasFinallyOrFaultHandler()) { BADCODE3("Handlers must be catch, finally, or fault", ". Before offset %04X", blkSrc->bbCodeOffsEnd); } // Are we jumping out of this handler? if (!ehDsc->InHndRegionILRange(blkDest)) { bCatchHandlerOnly = false; } } } else if (ehDsc->InFilterRegionILRange(blkSrc)) { // Are we jumping out of a filter? if (!ehDsc->InFilterRegionILRange(blkDest)) { bCatchHandlerOnly = false; } } } if (bCatchHandlerOnly) { if (bValidJumpToTry) { return; } else { // FALL THROUGH // This is either the case of a leave to outside the try/catch, // or a leave to a try not nested in this try/catch. // The first case is allowed, the second one will be checked // later when we check the try block rules (it is illegal if we // jump to the middle of the destination try). } } else { BADCODE3("illegal leave to exit a finally, fault or filter", ". Before offset %04X", blkSrc->bbCodeOffsEnd); } } /* Check all the try block rules */ IL_OFFSET srcTryBeg; IL_OFFSET srcTryEnd; IL_OFFSET destTryBeg; IL_OFFSET destTryEnd; ehInitTryRange(blkSrc, &srcTryBeg, &srcTryEnd); ehInitTryRange(blkDest, &destTryBeg, &destTryEnd); /* Are we jumping between try indexes? */ if (!BasicBlock::sameTryRegion(blkSrc, blkDest)) { // Are we exiting from an inner to outer try? if (jitIsBetween(srcTryBeg, destTryBeg, destTryEnd) && jitIsBetween(srcTryEnd - 1, destTryBeg, destTryEnd)) { if (!isLeave) { BADCODE3("exit from try block without a leave", ". Before offset %04X", blkSrc->bbCodeOffsEnd); } } else if (jitIsBetween(destTryBeg, srcTryBeg, srcTryEnd)) { // check that the dest Try is first instruction of an inner try if (!fgFlowToFirstBlockOfInnerTry(blkSrc, blkDest, false)) { BADCODE3("control flow into middle of try", ". Before offset %04X", blkSrc->bbCodeOffsEnd); } } else // there is no nesting relationship between src and dest { if (isLeave) { // check that the dest Try is first instruction of an inner try sibling if (!fgFlowToFirstBlockOfInnerTry(blkSrc, blkDest, true)) { BADCODE3("illegal leave into middle of try", ". Before offset %04X", blkSrc->bbCodeOffsEnd); } } else { BADCODE3("illegal control flow in to/out of try block", ". Before offset %04X", blkSrc->bbCodeOffsEnd); } } } } /***************************************************************************** * Check that blkDest is the first block of an inner try or a sibling * with no intervening trys in between */ bool Compiler::fgFlowToFirstBlockOfInnerTry(BasicBlock* blkSrc, BasicBlock* blkDest, bool sibling) { assert(!fgNormalizeEHDone); // These rules aren't quite correct after EH normalization has introduced new blocks noway_assert(blkDest->hasTryIndex()); unsigned XTnum = blkDest->getTryIndex(); unsigned lastXTnum = blkSrc->hasTryIndex() ? blkSrc->getTryIndex() : compHndBBtabCount; noway_assert(XTnum < compHndBBtabCount); noway_assert(lastXTnum <= compHndBBtabCount); EHblkDsc* HBtab = ehGetDsc(XTnum); // check that we are not jumping into middle of try if (HBtab->ebdTryBeg != blkDest) { return false; } if (sibling) { noway_assert(!BasicBlock::sameTryRegion(blkSrc, blkDest)); // find the l.u.b of the two try ranges // Set lastXTnum to the l.u.b. HBtab = ehGetDsc(lastXTnum); for (lastXTnum++, HBtab++; lastXTnum < compHndBBtabCount; lastXTnum++, HBtab++) { if (jitIsBetweenInclusive(blkDest->bbNum, HBtab->ebdTryBeg->bbNum, HBtab->ebdTryLast->bbNum)) { break; } } } // now check there are no intervening trys between dest and l.u.b // (it is ok to have intervening trys as long as they all start at // the same code offset) HBtab = ehGetDsc(XTnum); for (XTnum++, HBtab++; XTnum < lastXTnum; XTnum++, HBtab++) { if (HBtab->ebdTryBeg->bbNum < blkDest->bbNum && blkDest->bbNum <= HBtab->ebdTryLast->bbNum) { return false; } } return true; } /***************************************************************************** * Returns the handler nesting level of the block. * *pFinallyNesting is set to the nesting level of the inner-most * finally-protected try the block is in. */ unsigned Compiler::fgGetNestingLevel(BasicBlock* block, unsigned* pFinallyNesting) { unsigned curNesting = 0; // How many handlers is the block in unsigned tryFin = (unsigned)-1; // curNesting when we see innermost finally-protected try unsigned XTnum; EHblkDsc* HBtab; /* We find the block's handler nesting level by walking over the complete exception table and find enclosing clauses. */ for (XTnum = 0, HBtab = compHndBBtab; XTnum < compHndBBtabCount; XTnum++, HBtab++) { noway_assert(HBtab->ebdTryBeg && HBtab->ebdHndBeg); if (HBtab->HasFinallyHandler() && (tryFin == (unsigned)-1) && bbInTryRegions(XTnum, block)) { tryFin = curNesting; } else if (bbInHandlerRegions(XTnum, block)) { curNesting++; } } if (tryFin == (unsigned)-1) { tryFin = curNesting; } if (pFinallyNesting) { *pFinallyNesting = curNesting - tryFin; } return curNesting; } /***************************************************************************** * * Import the basic blocks of the procedure. */ void Compiler::fgImport() { impImport(fgFirstBB); if (!opts.jitFlags->IsSet(JitFlags::JIT_FLAG_SKIP_VERIFICATION)) { CorInfoMethodRuntimeFlags verFlag; verFlag = tiIsVerifiableCode ? CORINFO_FLG_VERIFIABLE : CORINFO_FLG_UNVERIFIABLE; info.compCompHnd->setMethodAttribs(info.compMethodHnd, verFlag); } // Estimate how much of method IL was actually imported. // // Note this includes (to some extent) the impact of importer folded // branches, provided the folded tree covered the entire block's IL. unsigned importedILSize = 0; for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext) { if ((block->bbFlags & BBF_IMPORTED) != 0) { // Assume if we generate any IR for the block we generate IR for the entire block. if (!block->isEmpty()) { IL_OFFSET beginOffset = block->bbCodeOffs; IL_OFFSET endOffset = block->bbCodeOffsEnd; if ((beginOffset != BAD_IL_OFFSET) && (endOffset != BAD_IL_OFFSET) && (endOffset > beginOffset)) { unsigned blockILSize = endOffset - beginOffset; importedILSize += blockILSize; } } } } // Could be tripped up if we ever duplicate blocks assert(importedILSize <= info.compILCodeSize); // Leave a note if we only did a partial import. if (importedILSize != info.compILCodeSize) { JITDUMP("\n** Note: %s IL was partially imported -- imported %u of %u bytes of method IL\n", compIsForInlining() ? "inlinee" : "root method", importedILSize, info.compILCodeSize); } // Record this for diagnostics and for the inliner's budget computations info.compILImportSize = importedILSize; if (compIsForInlining()) { compInlineResult->SetImportedILSize(info.compILImportSize); } } /***************************************************************************** * This function returns true if tree is a node with a call * that unconditionally throws an exception */ bool Compiler::fgIsThrow(GenTree* tree) { if ((tree->gtOper != GT_CALL) || (tree->gtCall.gtCallType != CT_HELPER)) { return false; } // TODO-Throughput: Replace all these calls to eeFindHelper() with a table based lookup if ((tree->gtCall.gtCallMethHnd == eeFindHelper(CORINFO_HELP_OVERFLOW)) || (tree->gtCall.gtCallMethHnd == eeFindHelper(CORINFO_HELP_VERIFICATION)) || (tree->gtCall.gtCallMethHnd == eeFindHelper(CORINFO_HELP_RNGCHKFAIL)) || (tree->gtCall.gtCallMethHnd == eeFindHelper(CORINFO_HELP_THROWDIVZERO)) || (tree->gtCall.gtCallMethHnd == eeFindHelper(CORINFO_HELP_THROWNULLREF)) || (tree->gtCall.gtCallMethHnd == eeFindHelper(CORINFO_HELP_THROW)) || (tree->gtCall.gtCallMethHnd == eeFindHelper(CORINFO_HELP_RETHROW)) || (tree->gtCall.gtCallMethHnd == eeFindHelper(CORINFO_HELP_THROW_TYPE_NOT_SUPPORTED)) || (tree->gtCall.gtCallMethHnd == eeFindHelper(CORINFO_HELP_THROW_PLATFORM_NOT_SUPPORTED))) { noway_assert(tree->gtFlags & GTF_CALL); noway_assert(tree->gtFlags & GTF_EXCEPT); return true; } // TODO-CQ: there are a bunch of managed methods in [mscorlib]System.ThrowHelper // that would be nice to recognize. return false; } /***************************************************************************** * This function returns true for blocks that are in different hot-cold regions. * It returns false when the blocks are both in the same regions */ bool Compiler::fgInDifferentRegions(BasicBlock* blk1, BasicBlock* blk2) { noway_assert(blk1 != nullptr); noway_assert(blk2 != nullptr); if (fgFirstColdBlock == nullptr) { return false; } // If one block is Hot and the other is Cold then we are in different regions return ((blk1->bbFlags & BBF_COLD) != (blk2->bbFlags & BBF_COLD)); } bool Compiler::fgIsBlockCold(BasicBlock* blk) { noway_assert(blk != nullptr); if (fgFirstColdBlock == nullptr) { return false; } return ((blk->bbFlags & BBF_COLD) != 0); } /***************************************************************************** * This function returns true if tree is a GT_COMMA node with a call * that unconditionally throws an exception */ bool Compiler::fgIsCommaThrow(GenTree* tree, bool forFolding /* = false */) { // Instead of always folding comma throws, // with stress enabled we only fold half the time if (forFolding && compStressCompile(STRESS_FOLD, 50)) { return false; /* Don't fold */ } /* Check for cast of a GT_COMMA with a throw overflow */ if ((tree->gtOper == GT_COMMA) && (tree->gtFlags & GTF_CALL) && (tree->gtFlags & GTF_EXCEPT)) { return (fgIsThrow(tree->gtOp.gtOp1)); } return false; } //------------------------------------------------------------------------ // fgIsIndirOfAddrOfLocal: Determine whether "tree" is an indirection of a local. // // Arguments: // tree - The tree node under consideration // // Return Value: // If "tree" is a indirection (GT_IND, GT_BLK, or GT_OBJ) whose arg is an ADDR, // whose arg in turn is a LCL_VAR, return that LCL_VAR node, else nullptr. // // static GenTree* Compiler::fgIsIndirOfAddrOfLocal(GenTree* tree) { GenTree* res = nullptr; if (tree->OperIsIndir()) { GenTree* addr = tree->AsIndir()->Addr(); // Post rationalization, we can have Indir(Lea(..) trees. Therefore to recognize // Indir of addr of a local, skip over Lea in Indir(Lea(base, index, scale, offset)) // to get to base variable. if (addr->OperGet() == GT_LEA) { // We use this method in backward dataflow after liveness computation - fgInterBlockLocalVarLiveness(). // Therefore it is critical that we don't miss 'uses' of any local. It may seem this method overlooks // if the index part of the LEA has indir( someAddrOperator ( lclVar ) ) to search for a use but it's // covered by the fact we're traversing the expression in execution order and we also visit the index. GenTreeAddrMode* lea = addr->AsAddrMode(); GenTree* base = lea->Base(); if (base != nullptr) { if (base->OperGet() == GT_IND) { return fgIsIndirOfAddrOfLocal(base); } // else use base as addr addr = base; } } if (addr->OperGet() == GT_ADDR) { GenTree* lclvar = addr->gtOp.gtOp1; if (lclvar->OperGet() == GT_LCL_VAR) { res = lclvar; } } else if (addr->OperGet() == GT_LCL_VAR_ADDR) { res = addr; } } return res; } GenTreeCall* Compiler::fgGetStaticsCCtorHelper(CORINFO_CLASS_HANDLE cls, CorInfoHelpFunc helper) { bool bNeedClassID = true; unsigned callFlags = 0; var_types type = TYP_BYREF; // This is sort of ugly, as we have knowledge of what the helper is returning. // We need the return type. switch (helper) { case CORINFO_HELP_GETSHARED_GCSTATIC_BASE_NOCTOR: bNeedClassID = false; __fallthrough; case CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE_NOCTOR: callFlags |= GTF_CALL_HOISTABLE; __fallthrough; case CORINFO_HELP_GETSHARED_GCSTATIC_BASE: case CORINFO_HELP_GETSHARED_GCSTATIC_BASE_DYNAMICCLASS: case CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_DYNAMICCLASS: case CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE: case CORINFO_HELP_GETSHARED_GCTHREADSTATIC_BASE_DYNAMICCLASS: // type = TYP_BYREF; break; case CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_NOCTOR: bNeedClassID = false; __fallthrough; case CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE_NOCTOR: callFlags |= GTF_CALL_HOISTABLE; __fallthrough; case CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE: case CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE: case CORINFO_HELP_GETSHARED_NONGCTHREADSTATIC_BASE_DYNAMICCLASS: case CORINFO_HELP_CLASSINIT_SHARED_DYNAMICCLASS: type = TYP_I_IMPL; break; default: assert(!"unknown shared statics helper"); break; } GenTreeArgList* argList = nullptr; GenTree* opModuleIDArg; GenTree* opClassIDArg; // Get the class ID unsigned clsID; size_t moduleID; void* pclsID; void* pmoduleID; clsID = info.compCompHnd->getClassDomainID(cls, &pclsID); moduleID = info.compCompHnd->getClassModuleIdForStatics(cls, nullptr, &pmoduleID); if (!(callFlags & GTF_CALL_HOISTABLE)) { if (info.compCompHnd->getClassAttribs(cls) & CORINFO_FLG_BEFOREFIELDINIT) { callFlags |= GTF_CALL_HOISTABLE; } } if (pmoduleID) { opModuleIDArg = gtNewIndOfIconHandleNode(TYP_I_IMPL, (size_t)pmoduleID, GTF_ICON_CIDMID_HDL, true); } else { opModuleIDArg = gtNewIconNode((size_t)moduleID, TYP_I_IMPL); } if (bNeedClassID) { if (pclsID) { opClassIDArg = gtNewIndOfIconHandleNode(TYP_INT, (size_t)pclsID, GTF_ICON_CIDMID_HDL, true); } else { opClassIDArg = gtNewIconNode(clsID, TYP_INT); } // call the helper to get the base argList = gtNewArgList(opModuleIDArg, opClassIDArg); } else { argList = gtNewArgList(opModuleIDArg); } GenTreeCall* result = gtNewHelperCallNode(helper, type, argList); result->gtFlags |= callFlags; // If we're importing the special EqualityComparer<T>.Default // intrinsic, flag the helper call. Later during inlining, we can // remove the helper call if the associated field lookup is unused. if ((info.compFlags & CORINFO_FLG_JIT_INTRINSIC) != 0) { NamedIntrinsic ni = lookupNamedIntrinsic(info.compMethodHnd); if (ni == NI_System_Collections_Generic_EqualityComparer_get_Default) { JITDUMP("\nmarking helper call [06%u] as special dce...\n", result->gtTreeID); result->gtCallMoreFlags |= GTF_CALL_M_HELPER_SPECIAL_DCE; } } return result; } GenTreeCall* Compiler::fgGetSharedCCtor(CORINFO_CLASS_HANDLE cls) { #ifdef FEATURE_READYTORUN_COMPILER if (opts.IsReadyToRun()) { CORINFO_RESOLVED_TOKEN resolvedToken; memset(&resolvedToken, 0, sizeof(resolvedToken)); resolvedToken.hClass = cls; return impReadyToRunHelperToTree(&resolvedToken, CORINFO_HELP_READYTORUN_STATIC_BASE, TYP_BYREF); } #endif // Call the shared non gc static helper, as its the fastest return fgGetStaticsCCtorHelper(cls, info.compCompHnd->getSharedCCtorHelper(cls)); } //------------------------------------------------------------------------------ // fgAddrCouldBeNull : Check whether the address tree can represent null. // // // Arguments: // addr - Address to check // // Return Value: // True if address could be null; false otherwise bool Compiler::fgAddrCouldBeNull(GenTree* addr) { addr = addr->gtEffectiveVal(); if ((addr->gtOper == GT_CNS_INT) && addr->IsIconHandle()) { return false; } else if (addr->gtOper == GT_LCL_VAR) { unsigned varNum = addr->AsLclVarCommon()->GetLclNum(); if (lvaIsImplicitByRefLocal(varNum)) { return false; } LclVarDsc* varDsc = &lvaTable[varNum]; if (varDsc->lvStackByref) { return false; } } else if (addr->gtOper == GT_ADDR) { if (addr->gtOp.gtOp1->gtOper == GT_CNS_INT) { GenTree* cns1Tree = addr->gtOp.gtOp1; if (!cns1Tree->IsIconHandle()) { // Indirection of some random constant... // It is safest just to return true return true; } } return false; // we can't have a null address } else if (addr->gtOper == GT_ADD) { if (addr->gtOp.gtOp1->gtOper == GT_CNS_INT) { GenTree* cns1Tree = addr->gtOp.gtOp1; if (!cns1Tree->IsIconHandle()) { if (!fgIsBigOffset(cns1Tree->gtIntCon.gtIconVal)) { // Op1 was an ordinary small constant return fgAddrCouldBeNull(addr->gtOp.gtOp2); } } else // Op1 was a handle represented as a constant { // Is Op2 also a constant? if (addr->gtOp.gtOp2->gtOper == GT_CNS_INT) { GenTree* cns2Tree = addr->gtOp.gtOp2; // Is this an addition of a handle and constant if (!cns2Tree->IsIconHandle()) { if (!fgIsBigOffset(cns2Tree->gtIntCon.gtIconVal)) { // Op2 was an ordinary small constant return false; // we can't have a null address } } } } } else { // Op1 is not a constant // What about Op2? if (addr->gtOp.gtOp2->gtOper == GT_CNS_INT) { GenTree* cns2Tree = addr->gtOp.gtOp2; // Is this an addition of a small constant if (!cns2Tree->IsIconHandle()) { if (!fgIsBigOffset(cns2Tree->gtIntCon.gtIconVal)) { // Op2 was an ordinary small constant return fgAddrCouldBeNull(addr->gtOp.gtOp1); } } } } } return true; // default result: addr could be null } //------------------------------------------------------------------------------ // fgOptimizeDelegateConstructor: try and optimize construction of a delegate // // Arguments: // call -- call to original delegate constructor // exactContextHnd -- [out] context handle to update // ldftnToken -- [in] resolved token for the method the delegate will invoke, // if known, or nullptr if not known // // Return Value: // Original call tree if no optimization applies. // Updated call tree if optimized. GenTree* Compiler::fgOptimizeDelegateConstructor(GenTreeCall* call, CORINFO_CONTEXT_HANDLE* ExactContextHnd, CORINFO_RESOLVED_TOKEN* ldftnToken) { JITDUMP("\nfgOptimizeDelegateConstructor: "); noway_assert(call->gtCallType == CT_USER_FUNC); CORINFO_METHOD_HANDLE methHnd = call->gtCallMethHnd; CORINFO_CLASS_HANDLE clsHnd = info.compCompHnd->getMethodClass(methHnd); GenTree* targetMethod = call->gtCallArgs->Rest()->Current(); noway_assert(targetMethod->TypeGet() == TYP_I_IMPL); genTreeOps oper = targetMethod->OperGet(); CORINFO_METHOD_HANDLE targetMethodHnd = nullptr; GenTree* qmarkNode = nullptr; if (oper == GT_FTN_ADDR) { targetMethodHnd = targetMethod->gtFptrVal.gtFptrMethod; } else if (oper == GT_CALL && targetMethod->gtCall.gtCallMethHnd == eeFindHelper(CORINFO_HELP_VIRTUAL_FUNC_PTR)) { GenTree* handleNode = targetMethod->gtCall.gtCallArgs->Rest()->Rest()->Current(); if (handleNode->OperGet() == GT_CNS_INT) { // it's a ldvirtftn case, fetch the methodhandle off the helper for ldvirtftn. It's the 3rd arg targetMethodHnd = CORINFO_METHOD_HANDLE(handleNode->gtIntCon.gtCompileTimeHandle); } // Sometimes the argument to this is the result of a generic dictionary lookup, which shows // up as a GT_QMARK. else if (handleNode->OperGet() == GT_QMARK) { qmarkNode = handleNode; } } // Sometimes we don't call CORINFO_HELP_VIRTUAL_FUNC_PTR but instead just call // CORINFO_HELP_RUNTIMEHANDLE_METHOD directly. else if (oper == GT_QMARK) { qmarkNode = targetMethod; } if (qmarkNode) { noway_assert(qmarkNode->OperGet() == GT_QMARK); // The argument is actually a generic dictionary lookup. For delegate creation it looks // like: // GT_QMARK // GT_COLON // op1 -> call // Arg 1 -> token (has compile time handle) // op2 -> lclvar // // // In this case I can find the token (which is a method handle) and that is the compile time // handle. noway_assert(qmarkNode->gtOp.gtOp2->OperGet() == GT_COLON); noway_assert(qmarkNode->gtOp.gtOp2->gtOp.gtOp1->OperGet() == GT_CALL); GenTreeCall* runtimeLookupCall = qmarkNode->gtOp.gtOp2->gtOp.gtOp1->AsCall(); // This could be any of CORINFO_HELP_RUNTIMEHANDLE_(METHOD|CLASS)(_LOG?) GenTree* tokenNode = runtimeLookupCall->gtCallArgs->gtOp.gtOp2->gtOp.gtOp1; noway_assert(tokenNode->OperGet() == GT_CNS_INT); targetMethodHnd = CORINFO_METHOD_HANDLE(tokenNode->gtIntCon.gtCompileTimeHandle); } // Verify using the ldftnToken gives us all of what we used to get // via the above pattern match, and more... if (ldftnToken != nullptr) { assert(ldftnToken->hMethod != nullptr); if (targetMethodHnd != nullptr) { assert(targetMethodHnd == ldftnToken->hMethod); } targetMethodHnd = ldftnToken->hMethod; } else { assert(targetMethodHnd == nullptr); } #ifdef FEATURE_READYTORUN_COMPILER if (opts.IsReadyToRun()) { if (IsTargetAbi(CORINFO_CORERT_ABI)) { if (ldftnToken != nullptr) { JITDUMP("optimized\n"); GenTree* thisPointer = call->gtCallObjp; GenTree* targetObjPointers = call->gtCallArgs->Current(); GenTreeArgList* helperArgs = nullptr; CORINFO_LOOKUP pLookup; CORINFO_CONST_LOOKUP entryPoint; info.compCompHnd->getReadyToRunDelegateCtorHelper(ldftnToken, clsHnd, &pLookup); if (!pLookup.lookupKind.needsRuntimeLookup) { helperArgs = gtNewArgList(thisPointer, targetObjPointers); entryPoint = pLookup.constLookup; } else { assert(oper != GT_FTN_ADDR); CORINFO_CONST_LOOKUP genericLookup; info.compCompHnd->getReadyToRunHelper(ldftnToken, &pLookup.lookupKind, CORINFO_HELP_READYTORUN_GENERIC_HANDLE, &genericLookup); GenTree* ctxTree = getRuntimeContextTree(pLookup.lookupKind.runtimeLookupKind); helperArgs = gtNewArgList(thisPointer, targetObjPointers, ctxTree); entryPoint = genericLookup; } call = gtNewHelperCallNode(CORINFO_HELP_READYTORUN_DELEGATE_CTOR, TYP_VOID, helperArgs); call->setEntryPoint(entryPoint); } else { JITDUMP("not optimized, CORERT no ldftnToken\n"); } } // ReadyToRun has this optimization for a non-virtual function pointers only for now. else if (oper == GT_FTN_ADDR) { JITDUMP("optimized\n"); GenTree* thisPointer = call->gtCallObjp; GenTree* targetObjPointers = call->gtCallArgs->Current(); GenTreeArgList* helperArgs = gtNewArgList(thisPointer, targetObjPointers); call = gtNewHelperCallNode(CORINFO_HELP_READYTORUN_DELEGATE_CTOR, TYP_VOID, helperArgs); CORINFO_LOOKUP entryPoint; info.compCompHnd->getReadyToRunDelegateCtorHelper(ldftnToken, clsHnd, &entryPoint); assert(!entryPoint.lookupKind.needsRuntimeLookup); call->setEntryPoint(entryPoint.constLookup); } else { JITDUMP("not optimized, R2R virtual case\n"); } } else #endif if (targetMethodHnd != nullptr) { CORINFO_METHOD_HANDLE alternateCtor = nullptr; DelegateCtorArgs ctorData; ctorData.pMethod = info.compMethodHnd; ctorData.pArg3 = nullptr; ctorData.pArg4 = nullptr; ctorData.pArg5 = nullptr; alternateCtor = info.compCompHnd->GetDelegateCtor(methHnd, clsHnd, targetMethodHnd, &ctorData); if (alternateCtor != methHnd) { JITDUMP("optimized\n"); // we erase any inline info that may have been set for generics has it is not needed here, // and in fact it will pass the wrong info to the inliner code *ExactContextHnd = nullptr; call->gtCallMethHnd = alternateCtor; noway_assert(call->gtCallArgs->Rest()->Rest() == nullptr); GenTreeArgList* addArgs = nullptr; if (ctorData.pArg5) { GenTree* arg5 = gtNewIconHandleNode(size_t(ctorData.pArg5), GTF_ICON_FTN_ADDR); addArgs = gtNewListNode(arg5, addArgs); } if (ctorData.pArg4) { GenTree* arg4 = gtNewIconHandleNode(size_t(ctorData.pArg4), GTF_ICON_FTN_ADDR); addArgs = gtNewListNode(arg4, addArgs); } if (ctorData.pArg3) { GenTree* arg3 = gtNewIconHandleNode(size_t(ctorData.pArg3), GTF_ICON_FTN_ADDR); addArgs = gtNewListNode(arg3, addArgs); } call->gtCallArgs->Rest()->Rest() = addArgs; } else { JITDUMP("not optimized, no alternate ctor\n"); } } else { JITDUMP("not optimized, no target method\n"); } return call; } bool Compiler::fgCastNeeded(GenTree* tree, var_types toType) { // // If tree is a relop and we need an 4-byte integer // then we never need to insert a cast // if ((tree->OperKind() & GTK_RELOP) && (genActualType(toType) == TYP_INT)) { return false; } var_types fromType; // // Is the tree as GT_CAST or a GT_CALL ? // if (tree->OperGet() == GT_CAST) { fromType = tree->CastToType(); } else if (tree->OperGet() == GT_CALL) { fromType = (var_types)tree->gtCall.gtReturnType; } else { fromType = tree->TypeGet(); } // // If both types are the same then an additional cast is not necessary // if (toType == fromType) { return false; } // // If the sign-ness of the two types are different then a cast is necessary // if (varTypeIsUnsigned(toType) != varTypeIsUnsigned(fromType)) { return true; } // // If the from type is the same size or smaller then an additional cast is not necessary // if (genTypeSize(toType) >= genTypeSize(fromType)) { return false; } // // Looks like we will need the cast // return true; } // If assigning to a local var, add a cast if the target is // marked as NormalizedOnStore. Returns true if any change was made GenTree* Compiler::fgDoNormalizeOnStore(GenTree* tree) { // // Only normalize the stores in the global morph phase // if (fgGlobalMorph) { noway_assert(tree->OperGet() == GT_ASG); GenTree* op1 = tree->gtOp.gtOp1; GenTree* op2 = tree->gtOp.gtOp2; if (op1->gtOper == GT_LCL_VAR && genActualType(op1->TypeGet()) == TYP_INT) { // Small-typed arguments and aliased locals are normalized on load. // Other small-typed locals are normalized on store. // If it is an assignment to one of the latter, insert the cast on RHS unsigned varNum = op1->gtLclVarCommon.gtLclNum; LclVarDsc* varDsc = &lvaTable[varNum]; if (varDsc->lvNormalizeOnStore()) { noway_assert(op1->gtType <= TYP_INT); op1->gtType = TYP_INT; if (fgCastNeeded(op2, varDsc->TypeGet())) { op2 = gtNewCastNode(TYP_INT, op2, false, varDsc->TypeGet()); tree->gtOp.gtOp2 = op2; // Propagate GTF_COLON_COND op2->gtFlags |= (tree->gtFlags & GTF_COLON_COND); } } } } return tree; } /***************************************************************************** * * Mark whether the edge "srcBB -> dstBB" forms a loop that will always * execute a call or not. */ inline void Compiler::fgLoopCallTest(BasicBlock* srcBB, BasicBlock* dstBB) { /* Bail if this is not a backward edge */ if (srcBB->bbNum < dstBB->bbNum) { return; } /* Unless we already know that there is a loop without a call here ... */ if (!(dstBB->bbFlags & BBF_LOOP_CALL0)) { /* Check whether there is a loop path that doesn't call */ if (optReachWithoutCall(dstBB, srcBB)) { dstBB->bbFlags |= BBF_LOOP_CALL0; dstBB->bbFlags &= ~BBF_LOOP_CALL1; } else { dstBB->bbFlags |= BBF_LOOP_CALL1; } } // if this loop will always call, then we can omit the GC Poll if ((GCPOLL_NONE != opts.compGCPollType) && (dstBB->bbFlags & BBF_LOOP_CALL1)) { srcBB->bbFlags &= ~BBF_NEEDS_GCPOLL; } } /***************************************************************************** * * Mark which loops are guaranteed to execute a call. */ void Compiler::fgLoopCallMark() { BasicBlock* block; /* If we've already marked all the block, bail */ if (fgLoopCallMarked) { return; } fgLoopCallMarked = true; /* Walk the blocks, looking for backward edges */ for (block = fgFirstBB; block; block = block->bbNext) { switch (block->bbJumpKind) { case BBJ_COND: case BBJ_CALLFINALLY: case BBJ_ALWAYS: case BBJ_EHCATCHRET: fgLoopCallTest(block, block->bbJumpDest); break; case BBJ_SWITCH: unsigned jumpCnt; jumpCnt = block->bbJumpSwt->bbsCount; BasicBlock** jumpPtr; jumpPtr = block->bbJumpSwt->bbsDstTab; do { fgLoopCallTest(block, *jumpPtr); } while (++jumpPtr, --jumpCnt); break; default: break; } } } /***************************************************************************** * * Note the fact that the given block is a loop header. */ inline void Compiler::fgMarkLoopHead(BasicBlock* block) { #ifdef DEBUG if (verbose) { printf("fgMarkLoopHead: Checking loop head block " FMT_BB ": ", block->bbNum); } #endif /* Have we decided to generate fully interruptible code already? */ if (genInterruptible) { #ifdef DEBUG if (verbose) { printf("method is already fully interruptible\n"); } #endif return; } /* Is the loop head block known to execute a method call? */ if (block->bbFlags & BBF_GC_SAFE_POINT) { #ifdef DEBUG if (verbose) { printf("this block will execute a call\n"); } #endif // single block loops that contain GC safe points don't need polls. block->bbFlags &= ~BBF_NEEDS_GCPOLL; return; } /* Are dominator sets available? */ if (fgDomsComputed) { /* Make sure that we know which loops will always execute calls */ if (!fgLoopCallMarked) { fgLoopCallMark(); } /* Will every trip through our loop execute a call? */ if (block->bbFlags & BBF_LOOP_CALL1) { #ifdef DEBUG if (verbose) { printf("this block dominates a block that will execute a call\n"); } #endif return; } } /* * We have to make this method fully interruptible since we can not * ensure that this loop will execute a call every time it loops. * * We'll also need to generate a full register map for this method. */ assert(!codeGen->isGCTypeFixed()); if (!compCanEncodePtrArgCntMax()) { #ifdef DEBUG if (verbose) { printf("a callsite with more than 1023 pushed args exists\n"); } #endif return; } #ifdef DEBUG if (verbose) { printf("no guaranteed callsite exits, marking method as fully interruptible\n"); } #endif // only enable fully interruptible code for if we're hijacking. if (GCPOLL_NONE == opts.compGCPollType) { genInterruptible = true; } } GenTree* Compiler::fgGetCritSectOfStaticMethod() { noway_assert(!compIsForInlining()); noway_assert(info.compIsStatic); // This method should only be called for static methods. GenTree* tree = nullptr; CORINFO_LOOKUP_KIND kind = info.compCompHnd->getLocationOfThisType(info.compMethodHnd); if (!kind.needsRuntimeLookup) { void *critSect = nullptr, **pCrit = nullptr; critSect = info.compCompHnd->getMethodSync(info.compMethodHnd, (void**)&pCrit); noway_assert((!critSect) != (!pCrit)); tree = gtNewIconEmbHndNode(critSect, pCrit, GTF_ICON_METHOD_HDL, info.compMethodHnd); } else { // Collectible types requires that for shared generic code, if we use the generic context paramter // that we report it. (This is a conservative approach, we could detect some cases particularly when the // context parameter is this that we don't need the eager reporting logic.) lvaGenericsContextUseCount++; switch (kind.runtimeLookupKind) { case CORINFO_LOOKUP_THISOBJ: { noway_assert(!"Should never get this for static method."); break; } case CORINFO_LOOKUP_CLASSPARAM: { // In this case, the hidden param is the class handle. tree = gtNewLclvNode(info.compTypeCtxtArg, TYP_I_IMPL); break; } case CORINFO_LOOKUP_METHODPARAM: { // In this case, the hidden param is the method handle. tree = gtNewLclvNode(info.compTypeCtxtArg, TYP_I_IMPL); // Call helper CORINFO_HELP_GETCLASSFROMMETHODPARAM to get the class handle // from the method handle. tree = gtNewHelperCallNode(CORINFO_HELP_GETCLASSFROMMETHODPARAM, TYP_I_IMPL, gtNewArgList(tree)); break; } default: { noway_assert(!"Unknown LOOKUP_KIND"); break; } } noway_assert(tree); // tree should now contain the CORINFO_CLASS_HANDLE for the exact class. // Given the class handle, get the pointer to the Monitor. tree = gtNewHelperCallNode(CORINFO_HELP_GETSYNCFROMCLASSHANDLE, TYP_I_IMPL, gtNewArgList(tree)); } noway_assert(tree); return tree; } #if FEATURE_EH_FUNCLETS /***************************************************************************** * * Add monitor enter/exit calls for synchronized methods, and a try/fault * to ensure the 'exit' is called if the 'enter' was successful. On x86, we * generate monitor enter/exit calls and tell the VM the code location of * these calls. When an exception occurs between those locations, the VM * automatically releases the lock. For non-x86 platforms, the JIT is * responsible for creating a try/finally to protect the monitor enter/exit, * and the VM doesn't need to know anything special about the method during * exception processing -- it's just a normal try/finally. * * We generate the following code: * * void Foo() * { * unsigned byte acquired = 0; * try { * JIT_MonEnterWorker(<lock object>, &acquired); * * *** all the preexisting user code goes here *** * * JIT_MonExitWorker(<lock object>, &acquired); * } fault { * JIT_MonExitWorker(<lock object>, &acquired); * } * L_return: * ret * } * * If the lock is actually acquired, then the 'acquired' variable is set to 1 * by the helper call. During normal exit, the finally is called, 'acquired' * is 1, and the lock is released. If an exception occurs before the lock is * acquired, but within the 'try' (extremely unlikely, but possible), 'acquired' * will be 0, and the monitor exit call will quickly return without attempting * to release the lock. Otherwise, 'acquired' will be 1, and the lock will be * released during exception processing. * * For synchronized methods, we generate a single return block. * We can do this without creating additional "step" blocks because "ret" blocks * must occur at the top-level (of the original code), not nested within any EH * constructs. From the CLI spec, 12.4.2.8.2.3 "ret": "Shall not be enclosed in any * protected block, filter, or handler." Also, 3.57: "The ret instruction cannot be * used to transfer control out of a try, filter, catch, or finally block. From within * a try or catch, use the leave instruction with a destination of a ret instruction * that is outside all enclosing exception blocks." * * In addition, we can add a "fault" at the end of a method and be guaranteed that no * control falls through. From the CLI spec, section 12.4 "Control flow": "Control is not * permitted to simply fall through the end of a method. All paths shall terminate with one * of these instructions: ret, throw, jmp, or (tail. followed by call, calli, or callvirt)." * * We only need to worry about "ret" and "throw", as the CLI spec prevents any other * alternatives. Section 15.4.3.3 "Implementation information" states about exiting * synchronized methods: "Exiting a synchronized method using a tail. call shall be * implemented as though the tail. had not been specified." Section 3.37 "jmp" states: * "The jmp instruction cannot be used to transferred control out of a try, filter, * catch, fault or finally block; or out of a synchronized region." And, "throw" will * be handled naturally; no additional work is required. */ void Compiler::fgAddSyncMethodEnterExit() { assert((info.compFlags & CORINFO_FLG_SYNCH) != 0); // We need to do this transformation before funclets are created. assert(!fgFuncletsCreated); // Assume we don't need to update the bbPreds lists. assert(!fgComputePredsDone); #if !FEATURE_EH // If we don't support EH, we can't add the EH needed by synchronized methods. // Of course, we could simply ignore adding the EH constructs, since we don't // support exceptions being thrown in this mode, but we would still need to add // the monitor enter/exit, and that doesn't seem worth it for this minor case. // By the time EH is working, we can just enable the whole thing. NYI("No support for synchronized methods"); #endif // !FEATURE_EH // Create a scratch first BB where we can put the new variable initialization. // Don't put the scratch BB in the protected region. fgEnsureFirstBBisScratch(); // Create a block for the start of the try region, where the monitor enter call // will go. assert(fgFirstBB->bbFallsThrough()); BasicBlock* tryBegBB = fgNewBBafter(BBJ_NONE, fgFirstBB, false); BasicBlock* tryNextBB = tryBegBB->bbNext; BasicBlock* tryLastBB = fgLastBB; // If we have profile data the new block will inherit the next block's weight if (tryNextBB->hasProfileWeight()) { tryBegBB->inheritWeight(tryNextBB); } // Create a block for the fault. assert(!tryLastBB->bbFallsThrough()); BasicBlock* faultBB = fgNewBBafter(BBJ_EHFINALLYRET, tryLastBB, false); assert(tryLastBB->bbNext == faultBB); assert(faultBB->bbNext == nullptr); assert(faultBB == fgLastBB); { // Scope the EH region creation // Add the new EH region at the end, since it is the least nested, // and thus should be last. EHblkDsc* newEntry; unsigned XTnew = compHndBBtabCount; newEntry = fgAddEHTableEntry(XTnew); // Initialize the new entry newEntry->ebdHandlerType = EH_HANDLER_FAULT; newEntry->ebdTryBeg = tryBegBB; newEntry->ebdTryLast = tryLastBB; newEntry->ebdHndBeg = faultBB; newEntry->ebdHndLast = faultBB; newEntry->ebdTyp = 0; // unused for fault newEntry->ebdEnclosingTryIndex = EHblkDsc::NO_ENCLOSING_INDEX; newEntry->ebdEnclosingHndIndex = EHblkDsc::NO_ENCLOSING_INDEX; newEntry->ebdTryBegOffset = tryBegBB->bbCodeOffs; newEntry->ebdTryEndOffset = tryLastBB->bbCodeOffsEnd; newEntry->ebdFilterBegOffset = 0; newEntry->ebdHndBegOffset = 0; // handler doesn't correspond to any IL newEntry->ebdHndEndOffset = 0; // handler doesn't correspond to any IL // Set some flags on the new region. This is the same as when we set up // EH regions in fgFindBasicBlocks(). Note that the try has no enclosing // handler, and the fault has no enclosing try. tryBegBB->bbFlags |= BBF_HAS_LABEL | BBF_DONT_REMOVE | BBF_TRY_BEG | BBF_IMPORTED; faultBB->bbFlags |= BBF_HAS_LABEL | BBF_DONT_REMOVE | BBF_IMPORTED; faultBB->bbCatchTyp = BBCT_FAULT; tryBegBB->setTryIndex(XTnew); tryBegBB->clearHndIndex(); faultBB->clearTryIndex(); faultBB->setHndIndex(XTnew); // Walk the user code blocks and set all blocks that don't already have a try handler // to point to the new try handler. BasicBlock* tmpBB; for (tmpBB = tryBegBB->bbNext; tmpBB != faultBB; tmpBB = tmpBB->bbNext) { if (!tmpBB->hasTryIndex()) { tmpBB->setTryIndex(XTnew); } } // Walk the EH table. Make every EH entry that doesn't already have an enclosing // try index mark this new entry as their enclosing try index. unsigned XTnum; EHblkDsc* HBtab; for (XTnum = 0, HBtab = compHndBBtab; XTnum < XTnew; XTnum++, HBtab++) { if (HBtab->ebdEnclosingTryIndex == EHblkDsc::NO_ENCLOSING_INDEX) { HBtab->ebdEnclosingTryIndex = (unsigned short)XTnew; // This EH region wasn't previously nested, but now it is. } } #ifdef DEBUG if (verbose) { JITDUMP("Synchronized method - created additional EH descriptor EH#%u for try/fault wrapping monitor " "enter/exit\n", XTnew); fgDispBasicBlocks(); fgDispHandlerTab(); } fgVerifyHandlerTab(); #endif // DEBUG } // Create a 'monitor acquired' boolean (actually, an unsigned byte: 1 = acquired, 0 = not acquired). var_types typeMonAcquired = TYP_UBYTE; this->lvaMonAcquired = lvaGrabTemp(true DEBUGARG("Synchronized method monitor acquired boolean")); lvaTable[lvaMonAcquired].lvType = typeMonAcquired; { // Scope the variables of the variable initialization // Initialize the 'acquired' boolean. GenTree* zero = gtNewZeroConNode(genActualType(typeMonAcquired)); GenTree* varNode = gtNewLclvNode(lvaMonAcquired, typeMonAcquired); GenTree* initNode = gtNewAssignNode(varNode, zero); fgInsertStmtAtEnd(fgFirstBB, initNode); #ifdef DEBUG if (verbose) { printf("\nSynchronized method - Add 'acquired' initialization in first block %s\n", fgFirstBB->dspToString()); gtDispTree(initNode); printf("\n"); } #endif } // Make a copy of the 'this' pointer to be used in the handler so it does not inhibit enregistration // of all uses of the variable. unsigned lvaCopyThis = 0; if (!info.compIsStatic) { lvaCopyThis = lvaGrabTemp(true DEBUGARG("Synchronized method monitor acquired boolean")); lvaTable[lvaCopyThis].lvType = TYP_REF; GenTree* thisNode = gtNewLclvNode(info.compThisArg, TYP_REF); GenTree* copyNode = gtNewLclvNode(lvaCopyThis, TYP_REF); GenTree* initNode = gtNewAssignNode(copyNode, thisNode); fgInsertStmtAtEnd(tryBegBB, initNode); } fgCreateMonitorTree(lvaMonAcquired, info.compThisArg, tryBegBB, true /*enter*/); // exceptional case fgCreateMonitorTree(lvaMonAcquired, lvaCopyThis, faultBB, false /*exit*/); // non-exceptional cases for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext) { if (block->bbJumpKind == BBJ_RETURN) { fgCreateMonitorTree(lvaMonAcquired, info.compThisArg, block, false /*exit*/); } } } // fgCreateMonitorTree: Create tree to execute a monitor enter or exit operation for synchronized methods // lvaMonAcquired: lvaNum of boolean variable that tracks if monitor has been acquired. // lvaThisVar: lvaNum of variable being used as 'this' pointer, may not be the original one. Is only used for // nonstatic methods // block: block to insert the tree in. It is inserted at the end or in the case of a return, immediately before the // GT_RETURN // enter: whether to create a monitor enter or exit GenTree* Compiler::fgCreateMonitorTree(unsigned lvaMonAcquired, unsigned lvaThisVar, BasicBlock* block, bool enter) { // Insert the expression "enter/exitCrit(this, &acquired)" or "enter/exitCrit(handle, &acquired)" var_types typeMonAcquired = TYP_UBYTE; GenTree* varNode = gtNewLclvNode(lvaMonAcquired, typeMonAcquired); GenTree* varAddrNode = gtNewOperNode(GT_ADDR, TYP_BYREF, varNode); GenTree* tree; if (info.compIsStatic) { tree = fgGetCritSectOfStaticMethod(); tree = gtNewHelperCallNode(enter ? CORINFO_HELP_MON_ENTER_STATIC : CORINFO_HELP_MON_EXIT_STATIC, TYP_VOID, gtNewArgList(tree, varAddrNode)); } else { tree = gtNewLclvNode(lvaThisVar, TYP_REF); tree = gtNewHelperCallNode(enter ? CORINFO_HELP_MON_ENTER : CORINFO_HELP_MON_EXIT, TYP_VOID, gtNewArgList(tree, varAddrNode)); } #ifdef DEBUG if (verbose) { printf("\nSynchronized method - Add monitor %s call to block %s\n", enter ? "enter" : "exit", block->dspToString()); gtDispTree(tree); printf("\n"); } #endif if (block->bbJumpKind == BBJ_RETURN && block->lastStmt()->gtStmtExpr->gtOper == GT_RETURN) { GenTree* retNode = block->lastStmt()->gtStmtExpr; GenTree* retExpr = retNode->gtOp.gtOp1; if (retExpr != nullptr) { // have to insert this immediately before the GT_RETURN so we transform: // ret(...) -> // ret(comma(comma(tmp=...,call mon_exit), tmp) // // // Before morph stage, it is possible to have a case of GT_RETURN(TYP_LONG, op1) where op1's type is // TYP_STRUCT (of 8-bytes) and op1 is call node. See the big comment block in impReturnInstruction() // for details for the case where info.compRetType is not the same as info.compRetNativeType. For // this reason pass compMethodInfo->args.retTypeClass which is guaranteed to be a valid class handle // if the return type is a value class. Note that fgInsertCommFormTemp() in turn uses this class handle // if the type of op1 is TYP_STRUCT to perform lvaSetStruct() on the new temp that is created, which // in turn passes it to VM to know the size of value type. GenTree* temp = fgInsertCommaFormTemp(&retNode->gtOp.gtOp1, info.compMethodInfo->args.retTypeClass); GenTree* lclVar = retNode->gtOp.gtOp1->gtOp.gtOp2; // The return can't handle all of the trees that could be on the right-hand-side of an assignment, // especially in the case of a struct. Therefore, we need to propagate GTF_DONT_CSE. // If we don't, assertion propagation may, e.g., change a return of a local to a return of "CNS_INT struct // 0", // which downstream phases can't handle. lclVar->gtFlags |= (retExpr->gtFlags & GTF_DONT_CSE); retNode->gtOp.gtOp1->gtOp.gtOp2 = gtNewOperNode(GT_COMMA, retExpr->TypeGet(), tree, lclVar); } else { // Insert this immediately before the GT_RETURN fgInsertStmtNearEnd(block, tree); } } else { fgInsertStmtAtEnd(block, tree); } return tree; } // Convert a BBJ_RETURN block in a synchronized method to a BBJ_ALWAYS. // We've previously added a 'try' block around the original program code using fgAddSyncMethodEnterExit(). // Thus, we put BBJ_RETURN blocks inside a 'try'. In IL this is illegal. Instead, we would // see a 'leave' inside a 'try' that would get transformed into BBJ_CALLFINALLY/BBJ_ALWAYS blocks // during importing, and the BBJ_ALWAYS would point at an outer block with the BBJ_RETURN. // Here, we mimic some of the logic of importing a LEAVE to get the same effect for synchronized methods. void Compiler::fgConvertSyncReturnToLeave(BasicBlock* block) { assert(!fgFuncletsCreated); assert(info.compFlags & CORINFO_FLG_SYNCH); assert(genReturnBB != nullptr); assert(genReturnBB != block); assert(fgReturnCount <= 1); // We have a single return for synchronized methods assert(block->bbJumpKind == BBJ_RETURN); assert((block->bbFlags & BBF_HAS_JMP) == 0); assert(block->hasTryIndex()); assert(!block->hasHndIndex()); assert(compHndBBtabCount >= 1); unsigned tryIndex = block->getTryIndex(); assert(tryIndex == compHndBBtabCount - 1); // The BBJ_RETURN must be at the top-level before we inserted the // try/finally, which must be the last EH region. EHblkDsc* ehDsc = ehGetDsc(tryIndex); assert(ehDsc->ebdEnclosingTryIndex == EHblkDsc::NO_ENCLOSING_INDEX); // There are no enclosing regions of the BBJ_RETURN block assert(ehDsc->ebdEnclosingHndIndex == EHblkDsc::NO_ENCLOSING_INDEX); // Convert the BBJ_RETURN to BBJ_ALWAYS, jumping to genReturnBB. block->bbJumpKind = BBJ_ALWAYS; block->bbJumpDest = genReturnBB; block->bbJumpDest->bbRefs++; #ifdef DEBUG if (verbose) { printf("Synchronized method - convert block " FMT_BB " to BBJ_ALWAYS [targets " FMT_BB "]\n", block->bbNum, block->bbJumpDest->bbNum); } #endif } #endif // FEATURE_EH_FUNCLETS //------------------------------------------------------------------------ // fgAddReversePInvokeEnterExit: Add enter/exit calls for reverse PInvoke methods // // Arguments: // None. // // Return Value: // None. void Compiler::fgAddReversePInvokeEnterExit() { assert(opts.IsReversePInvoke()); lvaReversePInvokeFrameVar = lvaGrabTempWithImplicitUse(false DEBUGARG("Reverse Pinvoke FrameVar")); LclVarDsc* varDsc = &lvaTable[lvaReversePInvokeFrameVar]; varDsc->lvType = TYP_BLK; varDsc->lvExactSize = eeGetEEInfo()->sizeOfReversePInvokeFrame; GenTree* tree; // Add enter pinvoke exit callout at the start of prolog tree = gtNewOperNode(GT_ADDR, TYP_I_IMPL, gtNewLclvNode(lvaReversePInvokeFrameVar, TYP_BLK)); tree = gtNewHelperCallNode(CORINFO_HELP_JIT_REVERSE_PINVOKE_ENTER, TYP_VOID, gtNewArgList(tree)); fgEnsureFirstBBisScratch(); fgInsertStmtAtBeg(fgFirstBB, tree); #ifdef DEBUG if (verbose) { printf("\nReverse PInvoke method - Add reverse pinvoke enter in first basic block %s\n", fgFirstBB->dspToString()); gtDispTree(tree); printf("\n"); } #endif // Add reverse pinvoke exit callout at the end of epilog tree = gtNewOperNode(GT_ADDR, TYP_I_IMPL, gtNewLclvNode(lvaReversePInvokeFrameVar, TYP_BLK)); tree = gtNewHelperCallNode(CORINFO_HELP_JIT_REVERSE_PINVOKE_EXIT, TYP_VOID, gtNewArgList(tree)); assert(genReturnBB != nullptr); fgInsertStmtNearEnd(genReturnBB, tree); #ifdef DEBUG if (verbose) { printf("\nReverse PInvoke method - Add reverse pinvoke exit in return basic block %s\n", genReturnBB->dspToString()); gtDispTree(tree); printf("\n"); } #endif } /***************************************************************************** * * Return 'true' if there is more than one BBJ_RETURN block. */ bool Compiler::fgMoreThanOneReturnBlock() { unsigned retCnt = 0; for (BasicBlock* block = fgFirstBB; block; block = block->bbNext) { if (block->bbJumpKind == BBJ_RETURN) { retCnt++; if (retCnt > 1) { return true; } } } return false; } namespace { // Define a helper class for merging return blocks (which we do when the input has // more than the limit for this configuration). // // Notes: sets fgReturnCount, genReturnBB, and genReturnLocal. class MergedReturns { public: #ifdef JIT32_GCENCODER // X86 GC encoding has a hard limit of SET_EPILOGCNT_MAX epilogs. const static unsigned ReturnCountHardLimit = SET_EPILOGCNT_MAX; #else // JIT32_GCENCODER // We currently apply a hard limit of '4' to all other targets (see // the other uses of SET_EPILOGCNT_MAX), though it would be good // to revisit that decision based on CQ analysis. const static unsigned ReturnCountHardLimit = 4; #endif // JIT32_GCENCODER private: Compiler* comp; // As we discover returns, we'll record them in `returnBlocks`, until // the limit is reached, at which point we'll keep track of the merged // return blocks in `returnBlocks`. BasicBlock* returnBlocks[ReturnCountHardLimit]; // Each constant value returned gets its own merged return block that // returns that constant (up to the limit on number of returns); in // `returnConstants` we track the constant values returned by these // merged constant return blocks. INT64 returnConstants[ReturnCountHardLimit]; // Indicators of where in the lexical block list we'd like to place // each constant return block. BasicBlock* insertionPoints[ReturnCountHardLimit]; // Number of return blocks allowed PhasedVar<unsigned> maxReturns; // Flag to keep track of when we've hit the limit of returns and are // actively merging returns together. bool mergingReturns = false; public: MergedReturns(Compiler* comp) : comp(comp) { comp->fgReturnCount = 0; } void SetMaxReturns(unsigned value) { maxReturns = value; maxReturns.MarkAsReadOnly(); } //------------------------------------------------------------------------ // Record: Make note of a return block in the input program. // // Arguments: // returnBlock - Block in the input that has jump kind BBJ_RETURN // // Notes: // Updates fgReturnCount appropriately, and generates a merged return // block if necessary. If a constant merged return block is used, // `returnBlock` is rewritten to jump to it. If a non-constant return // block is used, `genReturnBB` is set to that block, and `genReturnLocal` // is set to the lclvar that it returns; morph will need to rewrite // `returnBlock` to set the local and jump to the return block in such // cases, which it will do after some key transformations like rewriting // tail calls and calls that return to hidden buffers. In either of these // cases, `fgReturnCount` and the merged return block's profile information // will be updated to reflect or anticipate the rewrite of `returnBlock`. // void Record(BasicBlock* returnBlock) { // Add this return to our tally unsigned oldReturnCount = comp->fgReturnCount++; if (!mergingReturns) { if (oldReturnCount < maxReturns) { // No need to merge just yet; simply record this return. returnBlocks[oldReturnCount] = returnBlock; return; } // We'e reached our threshold mergingReturns = true; // Merge any returns we've already identified for (unsigned i = 0, searchLimit = 0; i < oldReturnCount; ++i) { BasicBlock* mergedReturnBlock = Merge(returnBlocks[i], searchLimit); if (returnBlocks[searchLimit] == mergedReturnBlock) { // We've added a new block to the searchable set ++searchLimit; } } } // We have too many returns, so merge this one in. // Search limit is new return count minus one (to exclude this block). unsigned searchLimit = comp->fgReturnCount - 1; Merge(returnBlock, searchLimit); } //------------------------------------------------------------------------ // EagerCreate: Force creation of a non-constant merged return block `genReturnBB`. // // Return Value: // The newly-created block which returns `genReturnLocal`. // BasicBlock* EagerCreate() { mergingReturns = true; return Merge(nullptr, 0); } //------------------------------------------------------------------------ // PlaceReturns: Move any generated const return blocks to an appropriate // spot in the lexical block list. // // Notes: // The goal is to set things up favorably for a reasonable layout without // putting too much burden on fgReorderBlocks; in particular, since that // method doesn't (currently) shuffle non-profile, non-rare code to create // fall-through and reduce gotos, this method places each const return // block immediately after its last predecessor, so that the flow from // there to it can become fallthrough without requiring any motion to be // performed by fgReorderBlocks. // void PlaceReturns() { if (!mergingReturns) { // No returns generated => no returns to place. return; } for (unsigned index = 0; index < comp->fgReturnCount; ++index) { BasicBlock* returnBlock = returnBlocks[index]; BasicBlock* genReturnBlock = comp->genReturnBB; if (returnBlock == genReturnBlock) { continue; } BasicBlock* insertionPoint = insertionPoints[index]; assert(insertionPoint != nullptr); comp->fgUnlinkBlock(returnBlock); comp->fgMoveBlocksAfter(returnBlock, returnBlock, insertionPoint); // Treat the merged return block as belonging to the same EH region // as the insertion point block, to make sure we don't break up // EH regions; since returning a constant won't throw, this won't // affect program behavior. comp->fgExtendEHRegionAfter(insertionPoint); } } private: //------------------------------------------------------------------------ // CreateReturnBB: Create a basic block to serve as a merged return point, stored to // `returnBlocks` at the given index, and optionally returning the given constant. // // Arguments: // index - Index into `returnBlocks` to store the new block into. // returnConst - Constant that the new block should return; may be nullptr to // indicate that the new merged return is for the non-constant case, in which // case, if the method's return type is non-void, `comp->genReturnLocal` will // be initialized to a new local of the appropriate type, and the new block will // return it. // // Return Value: // The new merged return block. // BasicBlock* CreateReturnBB(unsigned index, GenTreeIntConCommon* returnConst = nullptr) { BasicBlock* newReturnBB = comp->fgNewBBinRegion(BBJ_RETURN); newReturnBB->bbRefs = 1; // bbRefs gets update later, for now it should be 1 comp->fgReturnCount++; newReturnBB->bbFlags |= BBF_INTERNAL; noway_assert(newReturnBB->bbNext == nullptr); #ifdef DEBUG if (comp->verbose) { printf("\n newReturnBB [" FMT_BB "] created\n", newReturnBB->bbNum); } #endif // We have profile weight, the weight is zero, and the block is run rarely, // until we prove otherwise by merging other returns into this one. newReturnBB->bbFlags |= (BBF_PROF_WEIGHT | BBF_RUN_RARELY); newReturnBB->bbWeight = 0; GenTree* returnExpr; if (returnConst != nullptr) { returnExpr = comp->gtNewOperNode(GT_RETURN, returnConst->gtType, returnConst); returnConstants[index] = returnConst->IntegralValue(); } else if (comp->compMethodHasRetVal()) { // There is a return value, so create a temp for it. Real returns will store the value in there and // it'll be reloaded by the single return. unsigned returnLocalNum = comp->lvaGrabTemp(true DEBUGARG("Single return block return value")); comp->genReturnLocal = returnLocalNum; LclVarDsc& returnLocalDsc = comp->lvaTable[returnLocalNum]; if (comp->compMethodReturnsNativeScalarType()) { returnLocalDsc.lvType = genActualType(comp->info.compRetNativeType); } else if (comp->compMethodReturnsRetBufAddr()) { returnLocalDsc.lvType = TYP_BYREF; } else if (comp->compMethodReturnsMultiRegRetType()) { returnLocalDsc.lvType = TYP_STRUCT; comp->lvaSetStruct(returnLocalNum, comp->info.compMethodInfo->args.retTypeClass, true); returnLocalDsc.lvIsMultiRegRet = true; } else { assert(!"unreached"); } if (varTypeIsFloating(returnLocalDsc.lvType)) { comp->compFloatingPointUsed = true; } #ifdef DEBUG // This temporary should not be converted to a double in stress mode, // because we introduce assigns to it after the stress conversion returnLocalDsc.lvKeepType = 1; #endif GenTree* retTemp = comp->gtNewLclvNode(returnLocalNum, returnLocalDsc.TypeGet()); // make sure copy prop ignores this node (make sure it always does a reload from the temp). retTemp->gtFlags |= GTF_DONT_CSE; returnExpr = comp->gtNewOperNode(GT_RETURN, retTemp->gtType, retTemp); } else { // return void noway_assert(comp->info.compRetType == TYP_VOID || varTypeIsStruct(comp->info.compRetType)); comp->genReturnLocal = BAD_VAR_NUM; returnExpr = new (comp, GT_RETURN) GenTreeOp(GT_RETURN, TYP_VOID); } // Add 'return' expression to the return block comp->fgInsertStmtAtEnd(newReturnBB, returnExpr); // Flag that this 'return' was generated by return merging so that subsequent // return block morhping will know to leave it alone. returnExpr->gtFlags |= GTF_RET_MERGED; #ifdef DEBUG if (comp->verbose) { printf("\nmergeReturns statement tree "); Compiler::printTreeID(returnExpr); printf(" added to genReturnBB %s\n", newReturnBB->dspToString()); comp->gtDispTree(returnExpr); printf("\n"); } #endif assert(index < maxReturns); returnBlocks[index] = newReturnBB; return newReturnBB; } //------------------------------------------------------------------------ // Merge: Find or create an appropriate merged return block for the given input block. // // Arguments: // returnBlock - Return block from the input program to find a merged return for. // May be nullptr to indicate that new block suitable for non-constant // returns should be generated but no existing block modified. // searchLimit - Blocks in `returnBlocks` up to but not including index `searchLimit` // will be checked to see if we already have an appropriate merged return // block for this case. If a new block must be created, it will be stored // to `returnBlocks` at index `searchLimit`. // // Return Value: // Merged return block suitable for handling this return value. May be newly-created // or pre-existing. // // Notes: // If a constant-valued merged return block is used, `returnBlock` will be rewritten to // jump to the merged return block and its `GT_RETURN` statement will be removed. If // a non-constant-valued merged return block is used, `genReturnBB` and `genReturnLocal` // will be set so that Morph can perform that rewrite, which it will do after some key // transformations like rewriting tail calls and calls that return to hidden buffers. // In either of these cases, `fgReturnCount` and the merged return block's profile // information will be updated to reflect or anticipate the rewrite of `returnBlock`. // BasicBlock* Merge(BasicBlock* returnBlock, unsigned searchLimit) { assert(mergingReturns); BasicBlock* mergedReturnBlock = nullptr; // Do not look for mergable constant returns in debug codegen as // we may lose track of sequence points. if ((returnBlock != nullptr) && (maxReturns > 1) && !comp->opts.compDbgCode) { // Check to see if this is a constant return so that we can search // for and/or create a constant return block for it. GenTreeIntConCommon* retConst = GetReturnConst(returnBlock); if (retConst != nullptr) { // We have a constant. Now find or create a corresponding return block. unsigned index; BasicBlock* constReturnBlock = FindConstReturnBlock(retConst, searchLimit, &index); if (constReturnBlock == nullptr) { // We didn't find a const return block. See if we have space left // to make one. // We have already allocated `searchLimit` slots. unsigned slotsReserved = searchLimit; if (comp->genReturnBB == nullptr) { // We haven't made a non-const return yet, so we have to reserve // a slot for one. ++slotsReserved; } if (slotsReserved < maxReturns) { // We have enough space to allocate a slot for this constant. constReturnBlock = CreateReturnBB(searchLimit, retConst); } } if (constReturnBlock != nullptr) { // Found a constant merged return block. mergedReturnBlock = constReturnBlock; // Change BBJ_RETURN to BBJ_ALWAYS targeting const return block. assert((comp->info.compFlags & CORINFO_FLG_SYNCH) == 0); returnBlock->bbJumpKind = BBJ_ALWAYS; returnBlock->bbJumpDest = constReturnBlock; // Remove GT_RETURN since constReturnBlock returns the constant. assert(returnBlock->lastStmt()->gtStmtExpr->OperIs(GT_RETURN)); assert(returnBlock->lastStmt()->gtStmtExpr->gtGetOp1()->IsIntegralConst()); comp->fgRemoveStmt(returnBlock, returnBlock->lastStmt()); // Using 'returnBlock' as the insertion point for 'mergedReturnBlock' // will give it a chance to use fallthrough rather than BBJ_ALWAYS. // Resetting this after each merge ensures that any branches to the // merged return block are lexically forward. insertionPoints[index] = returnBlock; } } } if (mergedReturnBlock == nullptr) { // No constant return block for this return; use the general one. mergedReturnBlock = comp->genReturnBB; if (mergedReturnBlock == nullptr) { // No general merged return for this function yet; create one. // There had better still be room left in the array. assert(searchLimit < maxReturns); mergedReturnBlock = CreateReturnBB(searchLimit); comp->genReturnBB = mergedReturnBlock; // Downstream code expects the `genReturnBB` to always remain // once created, so that it can redirect flow edges to it. mergedReturnBlock->bbFlags |= BBF_DONT_REMOVE; } } if (returnBlock != nullptr) { // Propagate profile weight and related annotations to the merged block. // Return weight should never exceed entry weight, so cap it to avoid nonsensical // hot returns in synthetic profile settings. mergedReturnBlock->bbWeight = min(mergedReturnBlock->bbWeight + returnBlock->bbWeight, comp->fgFirstBB->bbWeight); if (!returnBlock->hasProfileWeight()) { mergedReturnBlock->bbFlags &= ~BBF_PROF_WEIGHT; } if (mergedReturnBlock->bbWeight > 0) { mergedReturnBlock->bbFlags &= ~BBF_RUN_RARELY; } // Update fgReturnCount to reflect or anticipate that `returnBlock` will no longer // be a return point. comp->fgReturnCount--; } return mergedReturnBlock; } //------------------------------------------------------------------------ // GetReturnConst: If the given block returns an integral constant, return the // GenTreeIntConCommon that represents the constant. // // Arguments: // returnBlock - Block whose return value is to be inspected. // // Return Value: // GenTreeIntCommon that is the argument of `returnBlock`'s `GT_RETURN` if // such exists; nullptr otherwise. // static GenTreeIntConCommon* GetReturnConst(BasicBlock* returnBlock) { GenTreeStmt* lastStmt = returnBlock->lastStmt(); if (lastStmt == nullptr) { return nullptr; } GenTree* lastExpr = lastStmt->gtStmtExpr; if (!lastExpr->OperIs(GT_RETURN)) { return nullptr; } GenTree* retExpr = lastExpr->gtGetOp1(); if ((retExpr == nullptr) || !retExpr->IsIntegralConst()) { return nullptr; } return retExpr->AsIntConCommon(); } //------------------------------------------------------------------------ // FindConstReturnBlock: Scan the already-created merged return blocks, up to `searchLimit`, // and return the one corresponding to the given const expression if it exists. // // Arguments: // constExpr - GenTreeIntCommon representing the constant return value we're // searching for. // searchLimit - Check `returnBlocks`/`returnConstants` up to but not including // this index. // index - [out] Index of return block in the `returnBlocks` array, if found; // searchLimit otherwise. // // Return Value: // A block that returns the same constant, if one is found; otherwise nullptr. // BasicBlock* FindConstReturnBlock(GenTreeIntConCommon* constExpr, unsigned searchLimit, unsigned* index) { INT64 constVal = constExpr->IntegralValue(); for (unsigned i = 0; i < searchLimit; ++i) { // Need to check both for matching const val and for genReturnBB // because genReturnBB is used for non-constant returns and its // corresponding entry in the returnConstants array is garbage. if (returnConstants[i] == constVal) { BasicBlock* returnBlock = returnBlocks[i]; if (returnBlock == comp->genReturnBB) { // This is the block used for non-constant returns, so // its returnConstants entry is just garbage; don't be // fooled. continue; } *index = i; return returnBlock; } } *index = searchLimit; return nullptr; } }; } /***************************************************************************** * * Add any internal blocks/trees we may need */ void Compiler::fgAddInternal() { noway_assert(!compIsForInlining()); // The backend requires a scratch BB into which it can safely insert a P/Invoke method prolog if one is // required. Create it here. if (info.compCallUnmanaged != 0) { fgEnsureFirstBBisScratch(); fgFirstBB->bbFlags |= BBF_DONT_REMOVE; } /* <BUGNUM> VSW441487 </BUGNUM> The "this" pointer is implicitly used in the following cases: 1. Locking of synchronized methods 2. Dictionary access of shared generics code 3. If a method has "catch(FooException<T>)", the EH code accesses "this" to determine T. 4. Initializing the type from generic methods which require precise cctor semantics 5. Verifier does special handling of "this" in the .ctor However, we might overwrite it with a "starg 0". In this case, we will redirect all "ldarg(a)/starg(a) 0" to a temp lvaTable[lvaArg0Var] */ if (!info.compIsStatic) { if (lvaArg0Var != info.compThisArg) { // When we're using the general encoder, we mark compThisArg address-taken to ensure that it is not // enregistered (since the decoder always reports a stack location for "this" for generics // context vars). bool lva0CopiedForGenericsCtxt; #ifndef JIT32_GCENCODER lva0CopiedForGenericsCtxt = ((info.compMethodInfo->options & CORINFO_GENERICS_CTXT_FROM_THIS) != 0); #else // JIT32_GCENCODER lva0CopiedForGenericsCtxt = false; #endif // JIT32_GCENCODER noway_assert(lva0CopiedForGenericsCtxt || !lvaTable[info.compThisArg].lvAddrExposed); noway_assert(!lvaTable[info.compThisArg].lvHasILStoreOp); noway_assert(lvaTable[lvaArg0Var].lvAddrExposed || lvaTable[lvaArg0Var].lvHasILStoreOp || lva0CopiedForGenericsCtxt); var_types thisType = lvaTable[info.compThisArg].TypeGet(); // Now assign the original input "this" to the temp GenTree* tree; tree = gtNewLclvNode(lvaArg0Var, thisType); tree = gtNewAssignNode(tree, // dst gtNewLclvNode(info.compThisArg, thisType) // src ); /* Create a new basic block and stick the assignment in it */ fgEnsureFirstBBisScratch(); fgInsertStmtAtEnd(fgFirstBB, tree); #ifdef DEBUG if (verbose) { printf("\nCopy \"this\" to lvaArg0Var in first basic block %s\n", fgFirstBB->dspToString()); gtDispTree(tree); printf("\n"); } #endif } } // Grab a temp for the security object. // (Note: opts.compDbgEnC currently also causes the security object to be generated. See Compiler::compCompile) if (opts.compNeedSecurityCheck) { noway_assert(lvaSecurityObject == BAD_VAR_NUM); lvaSecurityObject = lvaGrabTempWithImplicitUse(false DEBUGARG("security check")); lvaTable[lvaSecurityObject].lvType = TYP_REF; } // Merge return points if required or beneficial MergedReturns merger(this); #if FEATURE_EH_FUNCLETS // Add the synchronized method enter/exit calls and try/finally protection. Note // that this must happen before the one BBJ_RETURN block is created below, so the // BBJ_RETURN block gets placed at the top-level, not within an EH region. (Otherwise, // we'd have to be really careful when creating the synchronized method try/finally // not to include the BBJ_RETURN block.) if ((info.compFlags & CORINFO_FLG_SYNCH) != 0) { fgAddSyncMethodEnterExit(); } #endif // FEATURE_EH_FUNCLETS // // We will generate just one epilog (return block) // when we are asked to generate enter/leave callbacks // or for methods with PInvoke // or for methods calling into unmanaged code // or for synchronized methods. // BasicBlock* lastBlockBeforeGenReturns = fgLastBB; if (compIsProfilerHookNeeded() || (info.compCallUnmanaged != 0) || opts.IsReversePInvoke() || ((info.compFlags & CORINFO_FLG_SYNCH) != 0)) { // We will generate only one return block // We will transform the BBJ_RETURN blocks // into jumps to the one return block // merger.SetMaxReturns(1); // Eagerly create the genReturnBB since the lowering of these constructs // will expect to find it. BasicBlock* mergedReturn = merger.EagerCreate(); assert(mergedReturn == genReturnBB); // Assume weight equal to entry weight for this BB. mergedReturn->bbFlags &= ~BBF_PROF_WEIGHT; mergedReturn->bbWeight = fgFirstBB->bbWeight; if (mergedReturn->bbWeight > 0) { mergedReturn->bbFlags &= ~BBF_RUN_RARELY; } } else { // // We are allowed to have multiple individual exits // However we can still decide to have a single return // if (compCodeOpt() == SMALL_CODE) { // For the Small_Code case we always generate a // single return block when we have multiple // return points // merger.SetMaxReturns(1); } else { merger.SetMaxReturns(MergedReturns::ReturnCountHardLimit); } } // Visit the BBJ_RETURN blocks and merge as necessary. for (BasicBlock* block = fgFirstBB; block != lastBlockBeforeGenReturns->bbNext; block = block->bbNext) { if ((block->bbJumpKind == BBJ_RETURN) && ((block->bbFlags & BBF_HAS_JMP) == 0)) { merger.Record(block); } } merger.PlaceReturns(); if (info.compCallUnmanaged != 0) { // The P/Invoke helpers only require a frame variable, so only allocate the // TCB variable if we're not using them. if (!opts.ShouldUsePInvokeHelpers()) { info.compLvFrameListRoot = lvaGrabTemp(false DEBUGARG("Pinvoke FrameListRoot")); LclVarDsc* rootVarDsc = &lvaTable[info.compLvFrameListRoot]; rootVarDsc->lvType = TYP_I_IMPL; rootVarDsc->lvImplicitlyReferenced = 1; } lvaInlinedPInvokeFrameVar = lvaGrabTempWithImplicitUse(false DEBUGARG("Pinvoke FrameVar")); LclVarDsc* varDsc = &lvaTable[lvaInlinedPInvokeFrameVar]; varDsc->lvType = TYP_BLK; // Make room for the inlined frame. varDsc->lvExactSize = eeGetEEInfo()->inlinedCallFrameInfo.size; #if FEATURE_FIXED_OUT_ARGS // Grab and reserve space for TCB, Frame regs used in PInvoke epilog to pop the inlined frame. // See genPInvokeMethodEpilog() for use of the grabbed var. This is only necessary if we are // not using the P/Invoke helpers. if (!opts.ShouldUsePInvokeHelpers() && compJmpOpUsed) { lvaPInvokeFrameRegSaveVar = lvaGrabTempWithImplicitUse(false DEBUGARG("PInvokeFrameRegSave Var")); varDsc = &lvaTable[lvaPInvokeFrameRegSaveVar]; varDsc->lvType = TYP_BLK; varDsc->lvExactSize = 2 * REGSIZE_BYTES; } #endif } // Do we need to insert a "JustMyCode" callback? CORINFO_JUST_MY_CODE_HANDLE* pDbgHandle = nullptr; CORINFO_JUST_MY_CODE_HANDLE dbgHandle = nullptr; if (opts.compDbgCode && !opts.jitFlags->IsSet(JitFlags::JIT_FLAG_IL_STUB)) { dbgHandle = info.compCompHnd->getJustMyCodeHandle(info.compMethodHnd, &pDbgHandle); } noway_assert(!dbgHandle || !pDbgHandle); if (dbgHandle || pDbgHandle) { GenTree* embNode = gtNewIconEmbHndNode(dbgHandle, pDbgHandle, GTF_ICON_TOKEN_HDL, info.compMethodHnd); GenTree* guardCheckVal = gtNewOperNode(GT_IND, TYP_INT, embNode); GenTree* guardCheckCond = gtNewOperNode(GT_EQ, TYP_INT, guardCheckVal, gtNewZeroConNode(TYP_INT)); // Create the callback which will yield the final answer GenTree* callback = gtNewHelperCallNode(CORINFO_HELP_DBG_IS_JUST_MY_CODE, TYP_VOID); callback = new (this, GT_COLON) GenTreeColon(TYP_VOID, gtNewNothingNode(), callback); // Stick the conditional call at the start of the method fgEnsureFirstBBisScratch(); fgInsertStmtAtEnd(fgFirstBB, gtNewQmarkNode(TYP_VOID, guardCheckCond, callback)); } /* Do we need to call out for security ? */ if (tiSecurityCalloutNeeded) { // We must have grabbed this local. noway_assert(opts.compNeedSecurityCheck); noway_assert(lvaSecurityObject != BAD_VAR_NUM); GenTree* tree; /* Insert the expression "call JIT_Security_Prolog(MethodHnd, &SecurityObject)" */ tree = gtNewIconEmbMethHndNode(info.compMethodHnd); tree = gtNewHelperCallNode(info.compCompHnd->getSecurityPrologHelper(info.compMethodHnd), TYP_VOID, gtNewArgList(tree, gtNewOperNode(GT_ADDR, TYP_BYREF, gtNewLclvNode(lvaSecurityObject, TYP_REF)))); /* Create a new basic block and stick the call in it */ fgEnsureFirstBBisScratch(); fgInsertStmtAtEnd(fgFirstBB, tree); #ifdef DEBUG if (verbose) { printf("\ntiSecurityCalloutNeeded - Add call JIT_Security_Prolog(%08p) statement ", dspPtr(info.compMethodHnd)); printTreeID(tree); printf(" in first basic block %s\n", fgFirstBB->dspToString()); gtDispTree(tree); printf("\n"); } #endif } #if !FEATURE_EH_FUNCLETS /* Is this a 'synchronized' method? */ if (info.compFlags & CORINFO_FLG_SYNCH) { GenTree* tree = NULL; /* Insert the expression "enterCrit(this)" or "enterCrit(handle)" */ if (info.compIsStatic) { tree = fgGetCritSectOfStaticMethod(); tree = gtNewHelperCallNode(CORINFO_HELP_MON_ENTER_STATIC, TYP_VOID, gtNewArgList(tree)); } else { noway_assert(lvaTable[info.compThisArg].lvType == TYP_REF); tree = gtNewLclvNode(info.compThisArg, TYP_REF); tree = gtNewHelperCallNode(CORINFO_HELP_MON_ENTER, TYP_VOID, gtNewArgList(tree)); } /* Create a new basic block and stick the call in it */ fgEnsureFirstBBisScratch(); fgInsertStmtAtEnd(fgFirstBB, tree); #ifdef DEBUG if (verbose) { printf("\nSynchronized method - Add enterCrit statement in first basic block %s\n", fgFirstBB->dspToString()); gtDispTree(tree); printf("\n"); } #endif /* We must be generating a single exit point for this to work */ noway_assert(genReturnBB != nullptr); /* Create the expression "exitCrit(this)" or "exitCrit(handle)" */ if (info.compIsStatic) { tree = fgGetCritSectOfStaticMethod(); tree = gtNewHelperCallNode(CORINFO_HELP_MON_EXIT_STATIC, TYP_VOID, gtNewArgList(tree)); } else { tree = gtNewLclvNode(info.compThisArg, TYP_REF); tree = gtNewHelperCallNode(CORINFO_HELP_MON_EXIT, TYP_VOID, gtNewArgList(tree)); } fgInsertStmtNearEnd(genReturnBB, tree); #ifdef DEBUG if (verbose) { printf("\nSynchronized method - Add exit expression "); printTreeID(tree); printf("\n"); } #endif // Reset cookies used to track start and end of the protected region in synchronized methods syncStartEmitCookie = NULL; syncEndEmitCookie = NULL; } #endif // !FEATURE_EH_FUNCLETS /* Do we need to do runtime call out to check the security? */ if (tiRuntimeCalloutNeeded) { GenTree* tree; /* Insert the expression "call verificationRuntimeCheck(MethodHnd)" */ tree = gtNewIconEmbMethHndNode(info.compMethodHnd); tree = gtNewHelperCallNode(CORINFO_HELP_VERIFICATION_RUNTIME_CHECK, TYP_VOID, gtNewArgList(tree)); /* Create a new basic block and stick the call in it */ fgEnsureFirstBBisScratch(); fgInsertStmtAtEnd(fgFirstBB, tree); #ifdef DEBUG if (verbose) { printf("\ntiRuntimeCalloutNeeded - Call verificationRuntimeCheck(%08p) statement in first basic block %s\n", dspPtr(info.compMethodHnd), fgFirstBB->dspToString()); gtDispTree(tree); printf("\n"); } #endif } if (opts.IsReversePInvoke()) { fgAddReversePInvokeEnterExit(); } #ifdef DEBUG if (verbose) { printf("\n*************** After fgAddInternal()\n"); fgDispBasicBlocks(); fgDispHandlerTab(); } #endif } /***************************************************************************** * * Create a new statement from tree and wire the links up. */ GenTreeStmt* Compiler::fgNewStmtFromTree(GenTree* tree, BasicBlock* block, IL_OFFSETX offs) { GenTreeStmt* stmt = gtNewStmt(tree, offs); if (fgStmtListThreaded) { gtSetStmtInfo(stmt); fgSetStmtSeq(stmt); } #if DEBUG if (block != nullptr) { fgDebugCheckNodeLinks(block, stmt); } #endif return stmt; } GenTreeStmt* Compiler::fgNewStmtFromTree(GenTree* tree) { return fgNewStmtFromTree(tree, nullptr, BAD_IL_OFFSET); } GenTreeStmt* Compiler::fgNewStmtFromTree(GenTree* tree, BasicBlock* block) { return fgNewStmtFromTree(tree, block, BAD_IL_OFFSET); } GenTreeStmt* Compiler::fgNewStmtFromTree(GenTree* tree, IL_OFFSETX offs) { return fgNewStmtFromTree(tree, nullptr, offs); } //------------------------------------------------------------------------ // fgFindBlockILOffset: Given a block, find the IL offset corresponding to the first statement // in the block with a legal IL offset. Skip any leading statements that have BAD_IL_OFFSET. // If no statement has an initialized statement offset (including the case where there are // no statements in the block), then return BAD_IL_OFFSET. This function is used when // blocks are split or modified, and we want to maintain the IL offset as much as possible // to preserve good debugging behavior. // // Arguments: // block - The block to check. // // Return Value: // The first good IL offset of a statement in the block, or BAD_IL_OFFSET if such an IL offset // cannot be found. // IL_OFFSET Compiler::fgFindBlockILOffset(BasicBlock* block) { // This function searches for IL offsets in statement nodes, so it can't be used in LIR. We // could have a similar function for LIR that searches for GT_IL_OFFSET nodes. assert(!block->IsLIR()); for (GenTreeStmt* stmt = block->firstStmt(); stmt != nullptr; stmt = stmt->getNextStmt()) { if (stmt->gtStmtILoffsx != BAD_IL_OFFSET) { return jitGetILoffs(stmt->gtStmtILoffsx); } } return BAD_IL_OFFSET; } //------------------------------------------------------------------------------ // fgSplitBlockAtEnd - split the given block into two blocks. // All code in the block stays in the original block. // Control falls through from original to new block, and // the new block is returned. //------------------------------------------------------------------------------ BasicBlock* Compiler::fgSplitBlockAtEnd(BasicBlock* curr) { // We'd like to use fgNewBBafter(), but we need to update the preds list before linking in the new block. // (We need the successors of 'curr' to be correct when we do this.) BasicBlock* newBlock = bbNewBasicBlock(curr->bbJumpKind); // Start the new block with no refs. When we set the preds below, this will get updated correctly. newBlock->bbRefs = 0; // For each successor of the original block, set the new block as their predecessor. // Note we are using the "rational" version of the successor iterator that does not hide the finallyret arcs. // Without these arcs, a block 'b' may not be a member of succs(preds(b)) if (curr->bbJumpKind != BBJ_SWITCH) { unsigned numSuccs = curr->NumSucc(this); for (unsigned i = 0; i < numSuccs; i++) { BasicBlock* succ = curr->GetSucc(i, this); if (succ != newBlock) { JITDUMP(FMT_BB " previous predecessor was " FMT_BB ", now is " FMT_BB "\n", succ->bbNum, curr->bbNum, newBlock->bbNum); fgReplacePred(succ, curr, newBlock); } } newBlock->bbJumpDest = curr->bbJumpDest; curr->bbJumpDest = nullptr; } else { // In the case of a switch statement there's more complicated logic in order to wire up the predecessor lists // but fortunately there's an existing method that implements this functionality. newBlock->bbJumpSwt = curr->bbJumpSwt; fgChangeSwitchBlock(curr, newBlock); curr->bbJumpSwt = nullptr; } newBlock->inheritWeight(curr); // Set the new block's flags. Note that the new block isn't BBF_INTERNAL unless the old block is. newBlock->bbFlags = curr->bbFlags; // Remove flags that the new block can't have. newBlock->bbFlags &= ~(BBF_TRY_BEG | BBF_LOOP_HEAD | BBF_LOOP_CALL0 | BBF_LOOP_CALL1 | BBF_HAS_LABEL | BBF_JMP_TARGET | BBF_FUNCLET_BEG | BBF_LOOP_PREHEADER | BBF_KEEP_BBJ_ALWAYS); // Remove the GC safe bit on the new block. It seems clear that if we split 'curr' at the end, // such that all the code is left in 'curr', and 'newBlock' just gets the control flow, then // both 'curr' and 'newBlock' could accurately retain an existing GC safe bit. However, callers // use this function to split blocks in the middle, or at the beginning, and they don't seem to // be careful about updating this flag appropriately. So, removing the GC safe bit is simply // conservative: some functions might end up being fully interruptible that could be partially // interruptible if we exercised more care here. newBlock->bbFlags &= ~BBF_GC_SAFE_POINT; #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) newBlock->bbFlags &= ~(BBF_FINALLY_TARGET); #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) // The new block has no code, so we leave bbCodeOffs/bbCodeOffsEnd set to BAD_IL_OFFSET. If a caller // puts code in the block, then it needs to update these. // Insert the new block in the block list after the 'curr' block. fgInsertBBafter(curr, newBlock); fgExtendEHRegionAfter(curr); // The new block is in the same EH region as the old block. // Remove flags from the old block that are no longer possible. curr->bbFlags &= ~(BBF_HAS_JMP | BBF_RETLESS_CALL); // Default to fallthru, and add the arc for that. curr->bbJumpKind = BBJ_NONE; fgAddRefPred(newBlock, curr); return newBlock; } //------------------------------------------------------------------------------ // fgSplitBlockAfterStatement - Split the given block, with all code after // the given statement going into the second block. //------------------------------------------------------------------------------ BasicBlock* Compiler::fgSplitBlockAfterStatement(BasicBlock* curr, GenTreeStmt* stmt) { assert(!curr->IsLIR()); // No statements in LIR, so you can't use this function. BasicBlock* newBlock = fgSplitBlockAtEnd(curr); if (stmt != nullptr) { newBlock->bbTreeList = stmt->gtNext; if (newBlock->bbTreeList) { newBlock->bbTreeList->gtPrev = curr->bbTreeList->gtPrev; } curr->bbTreeList->gtPrev = stmt; stmt->gtNext = nullptr; // Update the IL offsets of the blocks to match the split. assert(newBlock->bbCodeOffs == BAD_IL_OFFSET); assert(newBlock->bbCodeOffsEnd == BAD_IL_OFFSET); // curr->bbCodeOffs remains the same newBlock->bbCodeOffsEnd = curr->bbCodeOffsEnd; IL_OFFSET splitPointILOffset = fgFindBlockILOffset(newBlock); curr->bbCodeOffsEnd = splitPointILOffset; newBlock->bbCodeOffs = splitPointILOffset; } else { assert(curr->bbTreeList == nullptr); // if no tree was given then it better be an empty block } return newBlock; } //------------------------------------------------------------------------------ // fgSplitBlockAfterNode - Split the given block, with all code after // the given node going into the second block. // This function is only used in LIR. //------------------------------------------------------------------------------ BasicBlock* Compiler::fgSplitBlockAfterNode(BasicBlock* curr, GenTree* node) { assert(curr->IsLIR()); BasicBlock* newBlock = fgSplitBlockAtEnd(curr); if (node != nullptr) { LIR::Range& currBBRange = LIR::AsRange(curr); if (node != currBBRange.LastNode()) { LIR::Range nodesToMove = currBBRange.Remove(node->gtNext, currBBRange.LastNode()); LIR::AsRange(newBlock).InsertAtBeginning(std::move(nodesToMove)); } // Update the IL offsets of the blocks to match the split. assert(newBlock->bbCodeOffs == BAD_IL_OFFSET); assert(newBlock->bbCodeOffsEnd == BAD_IL_OFFSET); // curr->bbCodeOffs remains the same newBlock->bbCodeOffsEnd = curr->bbCodeOffsEnd; // Search backwards from the end of the current block looking for the IL offset to use // for the end IL offset for the original block. IL_OFFSET splitPointILOffset = BAD_IL_OFFSET; LIR::Range::ReverseIterator riter; LIR::Range::ReverseIterator riterEnd; for (riter = currBBRange.rbegin(), riterEnd = currBBRange.rend(); riter != riterEnd; ++riter) { if ((*riter)->gtOper == GT_IL_OFFSET) { GenTreeStmt* stmt = (*riter)->AsStmt(); if (stmt->gtStmtILoffsx != BAD_IL_OFFSET) { splitPointILOffset = jitGetILoffs(stmt->gtStmtILoffsx); break; } } } curr->bbCodeOffsEnd = splitPointILOffset; // Also use this as the beginning offset of the next block. Presumably we could/should // look to see if the first node is a GT_IL_OFFSET node, and use that instead. newBlock->bbCodeOffs = splitPointILOffset; } else { assert(curr->bbTreeList == nullptr); // if no node was given then it better be an empty block } return newBlock; } //------------------------------------------------------------------------------ // fgSplitBlockAtBeginning - Split the given block into two blocks. // Control falls through from original to new block, // and the new block is returned. // All code in the original block goes into the new block //------------------------------------------------------------------------------ BasicBlock* Compiler::fgSplitBlockAtBeginning(BasicBlock* curr) { BasicBlock* newBlock = fgSplitBlockAtEnd(curr); newBlock->bbTreeList = curr->bbTreeList; curr->bbTreeList = nullptr; // The new block now has all the code, and the old block has none. Update the // IL offsets for the block to reflect this. newBlock->bbCodeOffs = curr->bbCodeOffs; newBlock->bbCodeOffsEnd = curr->bbCodeOffsEnd; curr->bbCodeOffs = BAD_IL_OFFSET; curr->bbCodeOffsEnd = BAD_IL_OFFSET; return newBlock; } //------------------------------------------------------------------------ // fgSplitEdge: Splits the edge between a block 'curr' and its successor 'succ' by creating a new block // that replaces 'succ' as a successor of 'curr', and which branches unconditionally // to (or falls through to) 'succ'. Note that for a BBJ_COND block 'curr', // 'succ' might be the fall-through path or the branch path from 'curr'. // // Arguments: // curr - A block which branches conditionally to 'succ' // succ - The target block // // Return Value: // Returns a new block, that is a successor of 'curr' and which branches unconditionally to 'succ' // // Assumptions: // 'curr' must have a bbJumpKind of BBJ_COND or BBJ_SWITCH // // Notes: // The returned block is empty. BasicBlock* Compiler::fgSplitEdge(BasicBlock* curr, BasicBlock* succ) { assert(curr->bbJumpKind == BBJ_COND || curr->bbJumpKind == BBJ_SWITCH); assert(fgGetPredForBlock(succ, curr) != nullptr); BasicBlock* newBlock; if (succ == curr->bbNext) { // The successor is the fall-through path of a BBJ_COND, or // an immediately following block of a BBJ_SWITCH (which has // no fall-through path). For this case, simply insert a new // fall-through block after 'curr'. newBlock = fgNewBBafter(BBJ_NONE, curr, true /*extendRegion*/); } else { newBlock = fgNewBBinRegion(BBJ_ALWAYS, curr, curr->isRunRarely()); // The new block always jumps to 'succ' newBlock->bbJumpDest = succ; } newBlock->bbFlags |= (curr->bbFlags & succ->bbFlags & (BBF_BACKWARD_JUMP)); JITDUMP("Splitting edge from " FMT_BB " to " FMT_BB "; adding " FMT_BB "\n", curr->bbNum, succ->bbNum, newBlock->bbNum); if (curr->bbJumpKind == BBJ_COND) { fgReplacePred(succ, curr, newBlock); if (curr->bbJumpDest == succ) { // Now 'curr' jumps to newBlock curr->bbJumpDest = newBlock; newBlock->bbFlags |= BBF_JMP_TARGET; } fgAddRefPred(newBlock, curr); } else { assert(curr->bbJumpKind == BBJ_SWITCH); // newBlock replaces 'succ' in the switch. fgReplaceSwitchJumpTarget(curr, newBlock, succ); // And 'succ' has 'newBlock' as a new predecessor. fgAddRefPred(succ, newBlock); } // This isn't accurate, but it is complex to compute a reasonable number so just assume that we take the // branch 50% of the time. newBlock->inheritWeightPercentage(curr, 50); // The bbLiveIn and bbLiveOut are both equal to the bbLiveIn of 'succ' if (fgLocalVarLivenessDone) { VarSetOps::Assign(this, newBlock->bbLiveIn, succ->bbLiveIn); VarSetOps::Assign(this, newBlock->bbLiveOut, succ->bbLiveIn); } return newBlock; } /*****************************************************************************/ /*****************************************************************************/ void Compiler::fgFindOperOrder() { #ifdef DEBUG if (verbose) { printf("*************** In fgFindOperOrder()\n"); } #endif BasicBlock* block; GenTreeStmt* stmt; /* Walk the basic blocks and for each statement determine * the evaluation order, cost, FP levels, etc... */ for (block = fgFirstBB; block; block = block->bbNext) { compCurBB = block; for (stmt = block->firstStmt(); stmt; stmt = stmt->gtNextStmt) { /* Recursively process the statement */ compCurStmt = stmt; gtSetStmtInfo(stmt); } } } //------------------------------------------------------------------------ // fgSimpleLowering: do full walk of all IR, lowering selected operations // and computing lvaOutgoingArgumentAreaSize. // // Notes: // Lowers GT_ARR_LENGTH, GT_ARR_BOUNDS_CHECK, and GT_SIMD_CHK. // // For target ABIs with fixed out args area, computes upper bound on // the size of this area from the calls in the IR. // // Outgoing arg area size is computed here because we want to run it // after optimization (in case calls are removed) and need to look at // all possible calls in the method. void Compiler::fgSimpleLowering() { #if FEATURE_FIXED_OUT_ARGS unsigned outgoingArgSpaceSize = 0; #endif // FEATURE_FIXED_OUT_ARGS for (BasicBlock* block = fgFirstBB; block; block = block->bbNext) { // Walk the statement trees in this basic block. compCurBB = block; // Used in fgRngChkTarget. LIR::Range& range = LIR::AsRange(block); for (GenTree* tree : range) { switch (tree->OperGet()) { case GT_ARR_LENGTH: { GenTreeArrLen* arrLen = tree->AsArrLen(); GenTree* arr = arrLen->gtArrLen.ArrRef(); GenTree* add; GenTree* con; /* Create the expression "*(array_addr + ArrLenOffs)" */ noway_assert(arr->gtNext == tree); noway_assert(arrLen->ArrLenOffset() == OFFSETOF__CORINFO_Array__length || arrLen->ArrLenOffset() == OFFSETOF__CORINFO_String__stringLen); if ((arr->gtOper == GT_CNS_INT) && (arr->gtIntCon.gtIconVal == 0)) { // If the array is NULL, then we should get a NULL reference // exception when computing its length. We need to maintain // an invariant where there is no sum of two constants node, so // let's simply return an indirection of NULL. add = arr; } else { con = gtNewIconNode(arrLen->ArrLenOffset(), TYP_I_IMPL); add = gtNewOperNode(GT_ADD, TYP_REF, arr, con); range.InsertAfter(arr, con, add); } // Change to a GT_IND. tree->ChangeOperUnchecked(GT_IND); tree->gtOp.gtOp1 = add; break; } case GT_ARR_BOUNDS_CHECK: #ifdef FEATURE_SIMD case GT_SIMD_CHK: #endif // FEATURE_SIMD #ifdef FEATURE_HW_INTRINSICS case GT_HW_INTRINSIC_CHK: #endif // FEATURE_HW_INTRINSICS { // Add in a call to an error routine. fgSetRngChkTarget(tree, false); break; } #if FEATURE_FIXED_OUT_ARGS case GT_CALL: { GenTreeCall* call = tree->AsCall(); // Fast tail calls use the caller-supplied scratch // space so have no impact on this method's outgoing arg size. if (!call->IsFastTailCall()) { // Update outgoing arg size to handle this call const unsigned thisCallOutAreaSize = call->fgArgInfo->GetOutArgSize(); assert(thisCallOutAreaSize >= MIN_ARG_AREA_FOR_CALL); if (thisCallOutAreaSize > outgoingArgSpaceSize) { outgoingArgSpaceSize = thisCallOutAreaSize; JITDUMP("Bumping outgoingArgSpaceSize to %u for call [%06d]\n", outgoingArgSpaceSize, dspTreeID(tree)); } else { JITDUMP("outgoingArgSpaceSize %u sufficient for call [%06d], which needs %u\n", outgoingArgSpaceSize, dspTreeID(tree), thisCallOutAreaSize); } } else { JITDUMP("outgoingArgSpaceSize not impacted by fast tail call [%06d]\n", dspTreeID(tree)); } break; } #endif // FEATURE_FIXED_OUT_ARGS default: { // No other operators need processing. break; } } // switch on oper } // foreach tree } // foreach BB #if FEATURE_FIXED_OUT_ARGS // Finish computing the outgoing args area size // // Need to make sure the MIN_ARG_AREA_FOR_CALL space is added to the frame if: // 1. there are calls to THROW_HEPLPER methods. // 2. we are generating profiling Enter/Leave/TailCall hooks. This will ensure // that even methods without any calls will have outgoing arg area space allocated. // // An example for these two cases is Windows Amd64, where the ABI requires to have 4 slots for // the outgoing arg space if the method makes any calls. if (outgoingArgSpaceSize < MIN_ARG_AREA_FOR_CALL) { if (compUsesThrowHelper || compIsProfilerHookNeeded()) { outgoingArgSpaceSize = MIN_ARG_AREA_FOR_CALL; JITDUMP("Bumping outgoingArgSpaceSize to %u for throw helper or profile hook", outgoingArgSpaceSize); } } // If a function has localloc, we will need to move the outgoing arg space when the // localloc happens. When we do this, we need to maintain stack alignment. To avoid // leaving alignment-related holes when doing this move, make sure the outgoing // argument space size is a multiple of the stack alignment by aligning up to the next // stack alignment boundary. if (compLocallocUsed) { outgoingArgSpaceSize = roundUp(outgoingArgSpaceSize, STACK_ALIGN); JITDUMP("Bumping outgoingArgSpaceSize to %u for localloc", outgoingArgSpaceSize); } // Publish the final value and mark it as read only so any update // attempt later will cause an assert. lvaOutgoingArgSpaceSize = outgoingArgSpaceSize; lvaOutgoingArgSpaceSize.MarkAsReadOnly(); #endif // FEATURE_FIXED_OUT_ARGS #ifdef DEBUG if (verbose && fgRngChkThrowAdded) { printf("\nAfter fgSimpleLowering() added some RngChk throw blocks"); fgDispBasicBlocks(); fgDispHandlerTab(); printf("\n"); } #endif } VARSET_VALRET_TP Compiler::fgGetVarBits(GenTree* tree) { VARSET_TP varBits(VarSetOps::MakeEmpty(this)); assert(tree->gtOper == GT_LCL_VAR || tree->gtOper == GT_LCL_FLD); unsigned int lclNum = tree->gtLclVarCommon.gtLclNum; LclVarDsc* varDsc = lvaTable + lclNum; if (varDsc->lvTracked) { VarSetOps::AddElemD(this, varBits, varDsc->lvVarIndex); } // We have to check type of root tree, not Local Var descriptor because // for legacy backend we promote TYP_STRUCT to TYP_INT if it is an unused or // independently promoted non-argument struct local. // For more details see Compiler::raAssignVars() method. else if (tree->gtType == TYP_STRUCT && varDsc->lvPromoted) { assert(varDsc->lvType == TYP_STRUCT); for (unsigned i = varDsc->lvFieldLclStart; i < varDsc->lvFieldLclStart + varDsc->lvFieldCnt; ++i) { noway_assert(lvaTable[i].lvIsStructField); if (lvaTable[i].lvTracked) { unsigned varIndex = lvaTable[i].lvVarIndex; noway_assert(varIndex < lvaTrackedCount); VarSetOps::AddElemD(this, varBits, varIndex); } } } return varBits; } /***************************************************************************** * * Find and remove any basic blocks that are useless (e.g. they have not been * imported because they are not reachable, or they have been optimized away). */ void Compiler::fgRemoveEmptyBlocks() { BasicBlock* cur; BasicBlock* nxt; /* If we remove any blocks, we'll have to do additional work */ unsigned removedBlks = 0; for (cur = fgFirstBB; cur != nullptr; cur = nxt) { /* Get hold of the next block (in case we delete 'cur') */ nxt = cur->bbNext; /* Should this block be removed? */ if (!(cur->bbFlags & BBF_IMPORTED)) { noway_assert(cur->isEmpty()); if (ehCanDeleteEmptyBlock(cur)) { /* Mark the block as removed */ cur->bbFlags |= BBF_REMOVED; /* Remember that we've removed a block from the list */ removedBlks++; #ifdef DEBUG if (verbose) { printf(FMT_BB " was not imported, marked as removed (%d)\n", cur->bbNum, removedBlks); } #endif // DEBUG /* Drop the block from the list */ fgUnlinkBlock(cur); } else { // We were prevented from deleting this block by EH normalization. Mark the block as imported. cur->bbFlags |= BBF_IMPORTED; } } } /* If no blocks were removed, we're done */ if (removedBlks == 0) { return; } /* Update all references in the exception handler table. * Mark the new blocks as non-removable. * * We may have made the entire try block unreachable. * Check for this case and remove the entry from the EH table. */ unsigned XTnum; EHblkDsc* HBtab; INDEBUG(unsigned delCnt = 0;) for (XTnum = 0, HBtab = compHndBBtab; XTnum < compHndBBtabCount; XTnum++, HBtab++) { AGAIN: /* If the beginning of the try block was not imported, we * need to remove the entry from the EH table. */ if (HBtab->ebdTryBeg->bbFlags & BBF_REMOVED) { noway_assert(!(HBtab->ebdTryBeg->bbFlags & BBF_IMPORTED)); #ifdef DEBUG if (verbose) { printf("Beginning of try block (" FMT_BB ") not imported " "- remove index #%u from the EH table\n", HBtab->ebdTryBeg->bbNum, XTnum + delCnt); } delCnt++; #endif // DEBUG fgRemoveEHTableEntry(XTnum); if (XTnum < compHndBBtabCount) { // There are more entries left to process, so do more. Note that // HBtab now points to the next entry, that we copied down to the // current slot. XTnum also stays the same. goto AGAIN; } break; // no more entries (we deleted the last one), so exit the loop } /* At this point we know we have a valid try block */ #ifdef DEBUG assert(HBtab->ebdTryBeg->bbFlags & BBF_IMPORTED); assert(HBtab->ebdTryBeg->bbFlags & BBF_DONT_REMOVE); assert(HBtab->ebdHndBeg->bbFlags & BBF_IMPORTED); assert(HBtab->ebdHndBeg->bbFlags & BBF_DONT_REMOVE); if (HBtab->HasFilter()) { assert(HBtab->ebdFilter->bbFlags & BBF_IMPORTED); assert(HBtab->ebdFilter->bbFlags & BBF_DONT_REMOVE); } #endif // DEBUG fgSkipRmvdBlocks(HBtab); } /* end of the for loop over XTnum */ // Renumber the basic blocks JITDUMP("\nRenumbering the basic blocks for fgRemoveEmptyBlocks\n"); fgRenumberBlocks(); #ifdef DEBUG fgVerifyHandlerTab(); #endif // DEBUG } /***************************************************************************** * * Remove a useless statement from a basic block. * */ void Compiler::fgRemoveStmt(BasicBlock* block, GenTreeStmt* stmt) { assert(fgOrder == FGOrderTree); GenTreeStmt* tree = block->firstStmt(); #ifdef DEBUG if (verbose && stmt->gtStmtExpr->gtOper != GT_NOP) // Don't print if it is a GT_NOP. Too much noise from the inliner. { printf("\nRemoving statement "); printTreeID(stmt); printf(" in " FMT_BB " as useless:\n", block->bbNum); gtDispTree(stmt); } #endif // DEBUG if (opts.compDbgCode && stmt->gtPrev != stmt && stmt->gtStmtILoffsx != BAD_IL_OFFSET) { /* TODO: For debuggable code, should we remove significant statement boundaries. Or should we leave a GT_NO_OP in its place? */ } GenTreeStmt* firstStmt = block->firstStmt(); if (firstStmt == stmt) // Is it the first statement in the list? { if (firstStmt->gtNext == nullptr) { assert(firstStmt == block->lastStmt()); /* this is the only statement - basic block becomes empty */ block->bbTreeList = nullptr; } else { block->bbTreeList = tree->gtNext; block->bbTreeList->gtPrev = tree->gtPrev; } } else if (stmt == block->lastStmt()) // Is it the last statement in the list? { stmt->gtPrev->gtNext = nullptr; block->bbTreeList->gtPrev = stmt->gtPrev; } else // The statement is in the middle. { assert(stmt->gtPrevStmt != nullptr && stmt->gtNext != nullptr); tree = stmt->gtPrevStmt; tree->gtNext = stmt->gtNext; stmt->gtNext->gtPrev = tree; } noway_assert(!optValnumCSE_phase); fgStmtRemoved = true; #ifdef DEBUG if (verbose) { if (block->bbTreeList == nullptr) { printf("\n" FMT_BB " becomes empty", block->bbNum); } printf("\n"); } #endif // DEBUG } /******************************************************************************/ // Returns true if the operator is involved in control-flow // TODO-Cleanup: Move this into genTreeKinds in genTree.h inline bool OperIsControlFlow(genTreeOps oper) { switch (oper) { case GT_JTRUE: case GT_JCMP: case GT_JCC: case GT_SWITCH: case GT_LABEL: case GT_CALL: case GT_JMP: case GT_RETURN: case GT_RETFILT: #if !FEATURE_EH_FUNCLETS case GT_END_LFIN: #endif // !FEATURE_EH_FUNCLETS return true; default: return false; } } /****************************************************************************** * Tries to throw away a stmt. The statement can be anywhere in block->bbTreeList. * Returns true if it did remove the statement. */ bool Compiler::fgCheckRemoveStmt(BasicBlock* block, GenTreeStmt* stmt) { if (opts.compDbgCode) { return false; } GenTree* tree = stmt->gtStmtExpr; genTreeOps oper = tree->OperGet(); if (OperIsControlFlow(oper) || GenTree::OperIsHWIntrinsic(oper) || oper == GT_NO_OP) { return false; } // TODO: Use a recursive version of gtNodeHasSideEffects() if (tree->gtFlags & GTF_SIDE_EFFECT) { return false; } fgRemoveStmt(block, stmt); return true; } /**************************************************************************************************** * * */ bool Compiler::fgCanCompactBlocks(BasicBlock* block, BasicBlock* bNext) { if ((block == nullptr) || (bNext == nullptr)) { return false; } noway_assert(block->bbNext == bNext); if (block->bbJumpKind != BBJ_NONE) { return false; } // If the next block has multiple incoming edges, we can still compact if the first block is empty. // However, not if it is the beginning of a handler. if (bNext->countOfInEdges() != 1 && (!block->isEmpty() || (block->bbFlags & BBF_FUNCLET_BEG) || (block->bbCatchTyp != BBCT_NONE))) { return false; } if (bNext->bbFlags & BBF_DONT_REMOVE) { return false; } // Don't compact the first block if it was specially created as a scratch block. if (fgBBisScratch(block)) { return false; } #if defined(_TARGET_ARM_) // We can't compact a finally target block, as we need to generate special code for such blocks during code // generation if ((bNext->bbFlags & BBF_FINALLY_TARGET) != 0) return false; #endif // We don't want to compact blocks that are in different Hot/Cold regions // if (fgInDifferentRegions(block, bNext)) { return false; } // We cannot compact two blocks in different EH regions. // if (fgCanRelocateEHRegions) { if (!BasicBlock::sameEHRegion(block, bNext)) { return false; } } // if there is a switch predecessor don't bother because we'd have to update the uniquesuccs as well // (if they are valid) for (flowList* pred = bNext->bbPreds; pred; pred = pred->flNext) { if (pred->flBlock->bbJumpKind == BBJ_SWITCH) { return false; } } return true; } /***************************************************************************************************** * * Function called to compact two given blocks in the flowgraph * Assumes that all necessary checks have been performed, * i.e. fgCanCompactBlocks returns true. * * Uses for this function - whenever we change links, insert blocks,... * It will keep the flowgraph data in synch - bbNum, bbRefs, bbPreds */ void Compiler::fgCompactBlocks(BasicBlock* block, BasicBlock* bNext) { noway_assert(block != nullptr); noway_assert((block->bbFlags & BBF_REMOVED) == 0); noway_assert(block->bbJumpKind == BBJ_NONE); noway_assert(bNext == block->bbNext); noway_assert(bNext != nullptr); noway_assert((bNext->bbFlags & BBF_REMOVED) == 0); noway_assert(bNext->countOfInEdges() == 1 || block->isEmpty()); noway_assert(bNext->bbPreds); #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) noway_assert((bNext->bbFlags & BBF_FINALLY_TARGET) == 0); #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) // Make sure the second block is not the start of a TRY block or an exception handler noway_assert(bNext->bbCatchTyp == BBCT_NONE); noway_assert((bNext->bbFlags & BBF_TRY_BEG) == 0); noway_assert((bNext->bbFlags & BBF_DONT_REMOVE) == 0); /* both or none must have an exception handler */ noway_assert(block->hasTryIndex() == bNext->hasTryIndex()); #ifdef DEBUG if (verbose) { printf("\nCompacting blocks " FMT_BB " and " FMT_BB ":\n", block->bbNum, bNext->bbNum); } #endif if (bNext->countOfInEdges() > 1) { JITDUMP("Second block has multiple incoming edges\n"); assert(block->isEmpty()); block->bbFlags |= BBF_JMP_TARGET; for (flowList* pred = bNext->bbPreds; pred; pred = pred->flNext) { fgReplaceJumpTarget(pred->flBlock, block, bNext); if (pred->flBlock != block) { fgAddRefPred(block, pred->flBlock); } } bNext->bbPreds = nullptr; } else { noway_assert(bNext->bbPreds->flNext == nullptr); noway_assert(bNext->bbPreds->flBlock == block); } /* Start compacting - move all the statements in the second block to the first block */ // First move any phi definitions of the second block after the phi defs of the first. // TODO-CQ: This may be the wrong thing to do. If we're compacting blocks, it's because a // control-flow choice was constant-folded away. So probably phi's need to go away, // as well, in favor of one of the incoming branches. Or at least be modified. assert(block->IsLIR() == bNext->IsLIR()); if (block->IsLIR()) { LIR::Range& blockRange = LIR::AsRange(block); LIR::Range& nextRange = LIR::AsRange(bNext); // Does the next block have any phis? GenTree* nextFirstNonPhi = nullptr; LIR::ReadOnlyRange nextPhis = nextRange.PhiNodes(); if (!nextPhis.IsEmpty()) { GenTree* blockLastPhi = blockRange.LastPhiNode(); nextFirstNonPhi = nextPhis.LastNode()->gtNext; LIR::Range phisToMove = nextRange.Remove(std::move(nextPhis)); blockRange.InsertAfter(blockLastPhi, std::move(phisToMove)); } else { nextFirstNonPhi = nextRange.FirstNode(); } // Does the block have any other code? if (nextFirstNonPhi != nullptr) { LIR::Range nextNodes = nextRange.Remove(nextFirstNonPhi, nextRange.LastNode()); blockRange.InsertAtEnd(std::move(nextNodes)); } } else { GenTree* blkNonPhi1 = block->FirstNonPhiDef(); GenTree* bNextNonPhi1 = bNext->FirstNonPhiDef(); GenTree* blkFirst = block->firstStmt(); GenTree* bNextFirst = bNext->firstStmt(); // Does the second have any phis? if (bNextFirst != nullptr && bNextFirst != bNextNonPhi1) { GenTree* bNextLast = bNextFirst->gtPrev; assert(bNextLast->gtNext == nullptr); // Does "blk" have phis? if (blkNonPhi1 != blkFirst) { // Yes, has phis. // Insert after the last phi of "block." // First, bNextPhis after last phi of block. GenTree* blkLastPhi; if (blkNonPhi1 != nullptr) { blkLastPhi = blkNonPhi1->gtPrev; } else { blkLastPhi = blkFirst->gtPrev; } blkLastPhi->gtNext = bNextFirst; bNextFirst->gtPrev = blkLastPhi; // Now, rest of "block" after last phi of "bNext". GenTree* bNextLastPhi = nullptr; if (bNextNonPhi1 != nullptr) { bNextLastPhi = bNextNonPhi1->gtPrev; } else { bNextLastPhi = bNextFirst->gtPrev; } bNextLastPhi->gtNext = blkNonPhi1; if (blkNonPhi1 != nullptr) { blkNonPhi1->gtPrev = bNextLastPhi; } else { // block has no non phis, so make the last statement be the last added phi. blkFirst->gtPrev = bNextLastPhi; } // Now update the bbTreeList of "bNext". bNext->bbTreeList = bNextNonPhi1; if (bNextNonPhi1 != nullptr) { bNextNonPhi1->gtPrev = bNextLast; } } else { if (blkFirst != nullptr) // If "block" has no statements, fusion will work fine... { // First, bNextPhis at start of block. GenTree* blkLast = blkFirst->gtPrev; block->bbTreeList = bNextFirst; // Now, rest of "block" (if it exists) after last phi of "bNext". GenTree* bNextLastPhi = nullptr; if (bNextNonPhi1 != nullptr) { // There is a first non phi, so the last phi is before it. bNextLastPhi = bNextNonPhi1->gtPrev; } else { // All the statements are phi defns, so the last one is the prev of the first. bNextLastPhi = bNextFirst->gtPrev; } bNextFirst->gtPrev = blkLast; bNextLastPhi->gtNext = blkFirst; blkFirst->gtPrev = bNextLastPhi; // Now update the bbTreeList of "bNext" bNext->bbTreeList = bNextNonPhi1; if (bNextNonPhi1 != nullptr) { bNextNonPhi1->gtPrev = bNextLast; } } } } // Now proceed with the updated bbTreeLists. GenTreeStmt* stmtList1 = block->firstStmt(); GenTreeStmt* stmtList2 = bNext->firstStmt(); /* the block may have an empty list */ if (stmtList1 != nullptr) { GenTreeStmt* stmtLast1 = block->lastStmt(); /* The second block may be a GOTO statement or something with an empty bbTreeList */ if (stmtList2 != nullptr) { GenTreeStmt* stmtLast2 = bNext->lastStmt(); /* append list2 to list 1 */ stmtLast1->gtNext = stmtList2; stmtList2->gtPrev = stmtLast1; stmtList1->gtPrev = stmtLast2; } } else { /* block was formerly empty and now has bNext's statements */ block->bbTreeList = stmtList2; } } // Note we could update the local variable weights here by // calling lvaMarkLocalVars, with the block and weight adjustment. // If either block or bNext has a profile weight // or if both block and bNext have non-zero weights // then we select the highest weight block. if (block->hasProfileWeight() || bNext->hasProfileWeight() || (block->bbWeight && bNext->bbWeight)) { // We are keeping block so update its fields // when bNext has a greater weight if (block->bbWeight < bNext->bbWeight) { block->bbWeight = bNext->bbWeight; block->bbFlags |= (bNext->bbFlags & BBF_PROF_WEIGHT); // Set the profile weight flag (if necessary) if (block->bbWeight != 0) { block->bbFlags &= ~BBF_RUN_RARELY; // Clear any RarelyRun flag } } } // otherwise if either block has a zero weight we select the zero weight else { noway_assert((block->bbWeight == BB_ZERO_WEIGHT) || (bNext->bbWeight == BB_ZERO_WEIGHT)); block->bbWeight = BB_ZERO_WEIGHT; block->bbFlags |= BBF_RUN_RARELY; // Set the RarelyRun flag } /* set the right links */ block->bbJumpKind = bNext->bbJumpKind; VarSetOps::AssignAllowUninitRhs(this, block->bbLiveOut, bNext->bbLiveOut); // Update the beginning and ending IL offsets (bbCodeOffs and bbCodeOffsEnd). // Set the beginning IL offset to the minimum, and the ending offset to the maximum, of the respective blocks. // If one block has an unknown offset, we take the other block. // We are merging into 'block', so if its values are correct, just leave them alone. // TODO: we should probably base this on the statements within. if (block->bbCodeOffs == BAD_IL_OFFSET) { block->bbCodeOffs = bNext->bbCodeOffs; // If they are both BAD_IL_OFFSET, this doesn't change anything. } else if (bNext->bbCodeOffs != BAD_IL_OFFSET) { // The are both valid offsets; compare them. if (block->bbCodeOffs > bNext->bbCodeOffs) { block->bbCodeOffs = bNext->bbCodeOffs; } } if (block->bbCodeOffsEnd == BAD_IL_OFFSET) { block->bbCodeOffsEnd = bNext->bbCodeOffsEnd; // If they are both BAD_IL_OFFSET, this doesn't change anything. } else if (bNext->bbCodeOffsEnd != BAD_IL_OFFSET) { // The are both valid offsets; compare them. if (block->bbCodeOffsEnd < bNext->bbCodeOffsEnd) { block->bbCodeOffsEnd = bNext->bbCodeOffsEnd; } } if (((block->bbFlags & BBF_INTERNAL) != 0) && ((bNext->bbFlags & BBF_INTERNAL) == 0)) { // If 'block' is an internal block and 'bNext' isn't, then adjust the flags set on 'block'. block->bbFlags &= ~BBF_INTERNAL; // Clear the BBF_INTERNAL flag block->bbFlags |= BBF_IMPORTED; // Set the BBF_IMPORTED flag } /* Update the flags for block with those found in bNext */ block->bbFlags |= (bNext->bbFlags & BBF_COMPACT_UPD); /* mark bNext as removed */ bNext->bbFlags |= BBF_REMOVED; /* Unlink bNext and update all the marker pointers if necessary */ fgUnlinkRange(block->bbNext, bNext); // If bNext was the last block of a try or handler, update the EH table. ehUpdateForDeletedBlock(bNext); /* If we're collapsing a block created after the dominators are computed, rename the block and reuse dominator information from the other block */ if (fgDomsComputed && block->bbNum > fgDomBBcount) { BlockSetOps::Assign(this, block->bbReach, bNext->bbReach); BlockSetOps::ClearD(this, bNext->bbReach); block->bbIDom = bNext->bbIDom; bNext->bbIDom = nullptr; // In this case, there's no need to update the preorder and postorder numbering // since we're changing the bbNum, this makes the basic block all set. block->bbNum = bNext->bbNum; } /* Set the jump targets */ switch (bNext->bbJumpKind) { case BBJ_CALLFINALLY: // Propagate RETLESS property block->bbFlags |= (bNext->bbFlags & BBF_RETLESS_CALL); __fallthrough; case BBJ_COND: case BBJ_ALWAYS: case BBJ_EHCATCHRET: block->bbJumpDest = bNext->bbJumpDest; /* Update the predecessor list for 'bNext->bbJumpDest' */ fgReplacePred(bNext->bbJumpDest, bNext, block); /* Update the predecessor list for 'bNext->bbNext' if it is different than 'bNext->bbJumpDest' */ if (bNext->bbJumpKind == BBJ_COND && bNext->bbJumpDest != bNext->bbNext) { fgReplacePred(bNext->bbNext, bNext, block); } break; case BBJ_NONE: /* Update the predecessor list for 'bNext->bbNext' */ fgReplacePred(bNext->bbNext, bNext, block); break; case BBJ_EHFILTERRET: fgReplacePred(bNext->bbJumpDest, bNext, block); break; case BBJ_EHFINALLYRET: { unsigned hndIndex = block->getHndIndex(); EHblkDsc* ehDsc = ehGetDsc(hndIndex); if (ehDsc->HasFinallyHandler()) // No need to do this for fault handlers { BasicBlock* begBlk; BasicBlock* endBlk; ehGetCallFinallyBlockRange(hndIndex, &begBlk, &endBlk); BasicBlock* finBeg = ehDsc->ebdHndBeg; for (BasicBlock* bcall = begBlk; bcall != endBlk; bcall = bcall->bbNext) { if (bcall->bbJumpKind != BBJ_CALLFINALLY || bcall->bbJumpDest != finBeg) { continue; } noway_assert(bcall->isBBCallAlwaysPair()); fgReplacePred(bcall->bbNext, bNext, block); } } } break; case BBJ_THROW: case BBJ_RETURN: /* no jumps or fall through blocks to set here */ break; case BBJ_SWITCH: block->bbJumpSwt = bNext->bbJumpSwt; // We are moving the switch jump from bNext to block. Examine the jump targets // of the BBJ_SWITCH at bNext and replace the predecessor to 'bNext' with ones to 'block' fgChangeSwitchBlock(bNext, block); break; default: noway_assert(!"Unexpected bbJumpKind"); break; } fgUpdateLoopsAfterCompacting(block, bNext); #if DEBUG if (verbose && 0) { printf("\nAfter compacting:\n"); fgDispBasicBlocks(false); } #endif #if DEBUG if (JitConfig.JitSlowDebugChecksEnabled() != 0) { // Make sure that the predecessor lists are accurate fgDebugCheckBBlist(); } #endif // DEBUG } void Compiler::fgUpdateLoopsAfterCompacting(BasicBlock* block, BasicBlock* bNext) { /* Check if the removed block is not part the loop table */ noway_assert(bNext); for (unsigned loopNum = 0; loopNum < optLoopCount; loopNum++) { /* Some loops may have been already removed by * loop unrolling or conditional folding */ if (optLoopTable[loopNum].lpFlags & LPFLG_REMOVED) { continue; } /* Check the loop head (i.e. the block preceding the loop) */ if (optLoopTable[loopNum].lpHead == bNext) { optLoopTable[loopNum].lpHead = block; } /* Check the loop bottom */ if (optLoopTable[loopNum].lpBottom == bNext) { optLoopTable[loopNum].lpBottom = block; } /* Check the loop exit */ if (optLoopTable[loopNum].lpExit == bNext) { noway_assert(optLoopTable[loopNum].lpExitCnt == 1); optLoopTable[loopNum].lpExit = block; } /* Check the loop entry */ if (optLoopTable[loopNum].lpEntry == bNext) { optLoopTable[loopNum].lpEntry = block; } } } /***************************************************************************************************** * * Function called to remove a block when it is unreachable. * * This function cannot remove the first block. */ void Compiler::fgUnreachableBlock(BasicBlock* block) { // genReturnBB should never be removed, as we might have special hookups there. // Therefore, we should never come here to remove the statements in the genReturnBB block. // For example, <BUGNUM> in VSW 364383, </BUGNUM> // the profiler hookup needs to have the "void GT_RETURN" statement // to properly set the info.compProfilerCallback flag. noway_assert(block != genReturnBB); if (block->bbFlags & BBF_REMOVED) { return; } /* Removing an unreachable block */ #ifdef DEBUG if (verbose) { printf("\nRemoving unreachable " FMT_BB "\n", block->bbNum); } #endif // DEBUG noway_assert(block->bbPrev != nullptr); // Can use this function to remove the first block #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) assert(!block->bbPrev->isBBCallAlwaysPair()); // can't remove the BBJ_ALWAYS of a BBJ_CALLFINALLY / BBJ_ALWAYS pair #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) /* First walk the statement trees in this basic block and delete each stmt */ /* Make the block publicly available */ compCurBB = block; if (block->IsLIR()) { LIR::Range& blockRange = LIR::AsRange(block); if (!blockRange.IsEmpty()) { blockRange.Delete(this, block, blockRange.FirstNode(), blockRange.LastNode()); } } else { // TODO-Cleanup: I'm not sure why this happens -- if the block is unreachable, why does it have phis? // Anyway, remove any phis. GenTree* firstNonPhi = block->FirstNonPhiDef(); if (block->bbTreeList != firstNonPhi) { if (firstNonPhi != nullptr) { firstNonPhi->gtPrev = block->lastStmt(); } block->bbTreeList = firstNonPhi; } for (GenTreeStmt* stmt = block->firstStmt(); stmt; stmt = stmt->gtNextStmt) { fgRemoveStmt(block, stmt); } noway_assert(block->bbTreeList == nullptr); } /* Next update the loop table and bbWeights */ optUpdateLoopsBeforeRemoveBlock(block); /* Mark the block as removed */ block->bbFlags |= BBF_REMOVED; /* update bbRefs and bbPreds for the blocks reached by this block */ fgRemoveBlockAsPred(block); } /***************************************************************************************************** * * Function called to remove or morph a jump when we jump to the same * block when both the condition is true or false. */ void Compiler::fgRemoveConditionalJump(BasicBlock* block) { noway_assert(block->bbJumpKind == BBJ_COND && block->bbJumpDest == block->bbNext); assert(compRationalIRForm == block->IsLIR()); flowList* flow = fgGetPredForBlock(block->bbNext, block); noway_assert(flow->flDupCount == 2); // Change the BBJ_COND to BBJ_NONE, and adjust the refCount and dupCount. block->bbJumpKind = BBJ_NONE; block->bbFlags &= ~BBF_NEEDS_GCPOLL; --block->bbNext->bbRefs; --flow->flDupCount; #ifdef DEBUG block->bbJumpDest = nullptr; if (verbose) { printf("Block " FMT_BB " becoming a BBJ_NONE to " FMT_BB " (jump target is the same whether the condition is true or " "false)\n", block->bbNum, block->bbNext->bbNum); } #endif /* Remove the block jump condition */ if (block->IsLIR()) { LIR::Range& blockRange = LIR::AsRange(block); GenTree* test = blockRange.LastNode(); assert(test->OperIsConditionalJump()); bool isClosed; unsigned sideEffects; LIR::ReadOnlyRange testRange = blockRange.GetTreeRange(test, &isClosed, &sideEffects); // TODO-LIR: this should really be checking GTF_ALL_EFFECT, but that produces unacceptable // diffs compared to the existing backend. if (isClosed && ((sideEffects & GTF_SIDE_EFFECT) == 0)) { // If the jump and its operands form a contiguous, side-effect-free range, // remove them. blockRange.Delete(this, block, std::move(testRange)); } else { // Otherwise, just remove the jump node itself. blockRange.Remove(test, true); } } else { GenTreeStmt* test = block->lastStmt(); GenTree* tree = test->gtStmtExpr; noway_assert(tree->gtOper == GT_JTRUE); GenTree* sideEffList = nullptr; if (tree->gtFlags & GTF_SIDE_EFFECT) { gtExtractSideEffList(tree, &sideEffList); if (sideEffList) { noway_assert(sideEffList->gtFlags & GTF_SIDE_EFFECT); #ifdef DEBUG if (verbose) { printf("Extracted side effects list from condition...\n"); gtDispTree(sideEffList); printf("\n"); } #endif } } // Delete the cond test or replace it with the side effect tree if (sideEffList == nullptr) { fgRemoveStmt(block, test); } else { test->gtStmtExpr = sideEffList; fgMorphBlockStmt(block, test DEBUGARG("fgRemoveConditionalJump")); } } } /***************************************************************************************************** * * Function to return the last basic block in the main part of the function. With funclets, it is * the block immediately before the first funclet. * An inclusive end of the main method. */ BasicBlock* Compiler::fgLastBBInMainFunction() { #if FEATURE_EH_FUNCLETS if (fgFirstFuncletBB != nullptr) { return fgFirstFuncletBB->bbPrev; } #endif // FEATURE_EH_FUNCLETS assert(fgLastBB->bbNext == nullptr); return fgLastBB; } /***************************************************************************************************** * * Function to return the first basic block after the main part of the function. With funclets, it is * the block of the first funclet. Otherwise it is NULL if there are no funclets (fgLastBB->bbNext). * This is equivalent to fgLastBBInMainFunction()->bbNext * An exclusive end of the main method. */ BasicBlock* Compiler::fgEndBBAfterMainFunction() { #if FEATURE_EH_FUNCLETS if (fgFirstFuncletBB != nullptr) { return fgFirstFuncletBB; } #endif // FEATURE_EH_FUNCLETS assert(fgLastBB->bbNext == nullptr); return nullptr; } // Removes the block from the bbPrev/bbNext chain // Updates fgFirstBB and fgLastBB if necessary // Does not update fgFirstFuncletBB or fgFirstColdBlock (fgUnlinkRange does) void Compiler::fgUnlinkBlock(BasicBlock* block) { if (block->bbPrev) { block->bbPrev->bbNext = block->bbNext; if (block->bbNext) { block->bbNext->bbPrev = block->bbPrev; } else { fgLastBB = block->bbPrev; } } else { assert(block == fgFirstBB); assert(block != fgLastBB); assert((fgFirstBBScratch == nullptr) || (fgFirstBBScratch == fgFirstBB)); fgFirstBB = block->bbNext; fgFirstBB->bbPrev = nullptr; if (fgFirstBBScratch != nullptr) { #ifdef DEBUG // We had created an initial scratch BB, but now we're deleting it. if (verbose) { printf("Unlinking scratch " FMT_BB "\n", block->bbNum); } #endif // DEBUG fgFirstBBScratch = nullptr; } } } /***************************************************************************************************** * * Function called to unlink basic block range [bBeg .. bEnd] from the basic block list. * * 'bBeg' can't be the first block. */ void Compiler::fgUnlinkRange(BasicBlock* bBeg, BasicBlock* bEnd) { assert(bBeg != nullptr); assert(bEnd != nullptr); BasicBlock* bPrev = bBeg->bbPrev; assert(bPrev != nullptr); // Can't unlink a range starting with the first block bPrev->setNext(bEnd->bbNext); /* If we removed the last block in the method then update fgLastBB */ if (fgLastBB == bEnd) { fgLastBB = bPrev; noway_assert(fgLastBB->bbNext == nullptr); } // If bEnd was the first Cold basic block update fgFirstColdBlock if (fgFirstColdBlock == bEnd) { fgFirstColdBlock = bPrev->bbNext; } #if FEATURE_EH_FUNCLETS #ifdef DEBUG // You can't unlink a range that includes the first funclet block. A range certainly // can't cross the non-funclet/funclet region. And you can't unlink the first block // of the first funclet with this, either. (If that's necessary, it could be allowed // by updating fgFirstFuncletBB to bEnd->bbNext.) for (BasicBlock* tempBB = bBeg; tempBB != bEnd->bbNext; tempBB = tempBB->bbNext) { assert(tempBB != fgFirstFuncletBB); } #endif // DEBUG #endif // FEATURE_EH_FUNCLETS } /***************************************************************************************************** * * Function called to remove a basic block */ void Compiler::fgRemoveBlock(BasicBlock* block, bool unreachable) { BasicBlock* bPrev = block->bbPrev; /* The block has to be either unreachable or empty */ PREFIX_ASSUME(block != nullptr); JITDUMP("fgRemoveBlock " FMT_BB "\n", block->bbNum); // If we've cached any mappings from switch blocks to SwitchDesc's (which contain only the // *unique* successors of the switch block), invalidate that cache, since an entry in one of // the SwitchDescs might be removed. InvalidateUniqueSwitchSuccMap(); noway_assert((block == fgFirstBB) || (bPrev && (bPrev->bbNext == block))); noway_assert(!(block->bbFlags & BBF_DONT_REMOVE)); // Should never remove a genReturnBB, as we might have special hookups there. noway_assert(block != genReturnBB); #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) // Don't remove a finally target assert(!(block->bbFlags & BBF_FINALLY_TARGET)); #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) if (unreachable) { PREFIX_ASSUME(bPrev != nullptr); fgUnreachableBlock(block); /* If this is the last basic block update fgLastBB */ if (block == fgLastBB) { fgLastBB = bPrev; } #if FEATURE_EH_FUNCLETS // If block was the fgFirstFuncletBB then set fgFirstFuncletBB to block->bbNext if (block == fgFirstFuncletBB) { fgFirstFuncletBB = block->bbNext; } #endif // FEATURE_EH_FUNCLETS if (bPrev->bbJumpKind == BBJ_CALLFINALLY) { // bPrev CALL becomes RETLESS as the BBJ_ALWAYS block is unreachable bPrev->bbFlags |= BBF_RETLESS_CALL; #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) NO_WAY("No retless call finally blocks; need unwind target instead"); #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) } else if (bPrev->bbJumpKind == BBJ_ALWAYS && bPrev->bbJumpDest == block->bbNext && !(bPrev->bbFlags & BBF_KEEP_BBJ_ALWAYS) && (block != fgFirstColdBlock) && (block->bbNext != fgFirstColdBlock)) { // previous block is a BBJ_ALWAYS to the next block: change to BBJ_NONE. // Note that we don't do it if bPrev follows a BBJ_CALLFINALLY block (BBF_KEEP_BBJ_ALWAYS), // because that would violate our invariant that BBJ_CALLFINALLY blocks are followed by // BBJ_ALWAYS blocks. bPrev->bbJumpKind = BBJ_NONE; bPrev->bbFlags &= ~BBF_NEEDS_GCPOLL; } // If this is the first Cold basic block update fgFirstColdBlock if (block == fgFirstColdBlock) { fgFirstColdBlock = block->bbNext; } /* Unlink this block from the bbNext chain */ fgUnlinkBlock(block); /* At this point the bbPreds and bbRefs had better be zero */ noway_assert((block->bbRefs == 0) && (block->bbPreds == nullptr)); /* A BBJ_CALLFINALLY is usually paired with a BBJ_ALWAYS. * If we delete such a BBJ_CALLFINALLY we also delete the BBJ_ALWAYS */ if (block->isBBCallAlwaysPair()) { BasicBlock* leaveBlk = block->bbNext; noway_assert(leaveBlk->bbJumpKind == BBJ_ALWAYS); leaveBlk->bbFlags &= ~BBF_DONT_REMOVE; leaveBlk->bbRefs = 0; leaveBlk->bbPreds = nullptr; fgRemoveBlock(leaveBlk, true); #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) fgClearFinallyTargetBit(leaveBlk->bbJumpDest); #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) } else if (block->bbJumpKind == BBJ_RETURN) { fgRemoveReturnBlock(block); } } else // block is empty { noway_assert(block->isEmpty()); /* The block cannot follow a non-retless BBJ_CALLFINALLY (because we don't know who may jump to it) */ noway_assert((bPrev == nullptr) || !bPrev->isBBCallAlwaysPair()); /* This cannot be the last basic block */ noway_assert(block != fgLastBB); #ifdef DEBUG if (verbose) { printf("Removing empty " FMT_BB "\n", block->bbNum); } #endif // DEBUG #ifdef DEBUG /* Some extra checks for the empty case */ switch (block->bbJumpKind) { case BBJ_NONE: break; case BBJ_ALWAYS: /* Do not remove a block that jumps to itself - used for while (true){} */ noway_assert(block->bbJumpDest != block); /* Empty GOTO can be removed iff bPrev is BBJ_NONE */ noway_assert(bPrev && bPrev->bbJumpKind == BBJ_NONE); break; default: noway_assert(!"Empty block of this type cannot be removed!"); break; } #endif // DEBUG noway_assert(block->bbJumpKind == BBJ_NONE || block->bbJumpKind == BBJ_ALWAYS); /* Who is the "real" successor of this block? */ BasicBlock* succBlock; if (block->bbJumpKind == BBJ_ALWAYS) { succBlock = block->bbJumpDest; } else { succBlock = block->bbNext; } bool skipUnmarkLoop = false; // If block is the backedge for a loop and succBlock precedes block // then the succBlock becomes the new LOOP HEAD // NOTE: there's an assumption here that the blocks are numbered in increasing bbNext order. // NOTE 2: if fgDomsComputed is false, then we can't check reachability. However, if this is // the case, then the loop structures probably are also invalid, and shouldn't be used. This // can be the case late in compilation (such as Lower), where remnants of earlier created // structures exist, but haven't been maintained. if (block->isLoopHead() && (succBlock->bbNum <= block->bbNum)) { succBlock->bbFlags |= BBF_LOOP_HEAD; if (fgDomsComputed && fgReachable(succBlock, block)) { /* Mark all the reachable blocks between 'succBlock' and 'block', excluding 'block' */ optMarkLoopBlocks(succBlock, block, true); } } else if (succBlock->isLoopHead() && bPrev && (succBlock->bbNum <= bPrev->bbNum)) { skipUnmarkLoop = true; } noway_assert(succBlock); // If this is the first Cold basic block update fgFirstColdBlock if (block == fgFirstColdBlock) { fgFirstColdBlock = block->bbNext; } #if FEATURE_EH_FUNCLETS // Update fgFirstFuncletBB if necessary if (block == fgFirstFuncletBB) { fgFirstFuncletBB = block->bbNext; } #endif // FEATURE_EH_FUNCLETS /* First update the loop table and bbWeights */ optUpdateLoopsBeforeRemoveBlock(block, skipUnmarkLoop); // Update successor block start IL offset, if empty predecessor // covers the immediately preceding range. if ((block->bbCodeOffsEnd == succBlock->bbCodeOffs) && (block->bbCodeOffs != BAD_IL_OFFSET)) { assert(block->bbCodeOffs <= succBlock->bbCodeOffs); succBlock->bbCodeOffs = block->bbCodeOffs; } /* Remove the block */ if (bPrev == nullptr) { /* special case if this is the first BB */ noway_assert(block == fgFirstBB); /* Must be a fall through to next block */ noway_assert(block->bbJumpKind == BBJ_NONE); /* old block no longer gets the extra ref count for being the first block */ block->bbRefs--; succBlock->bbRefs++; /* Set the new firstBB */ fgUnlinkBlock(block); /* Always treat the initial block as a jump target */ fgFirstBB->bbFlags |= BBF_JMP_TARGET | BBF_HAS_LABEL; } else { fgUnlinkBlock(block); } /* mark the block as removed and set the change flag */ block->bbFlags |= BBF_REMOVED; /* Update bbRefs and bbPreds. * All blocks jumping to 'block' now jump to 'succBlock'. * First, remove 'block' from the predecessor list of succBlock. */ fgRemoveRefPred(succBlock, block); for (flowList* pred = block->bbPreds; pred; pred = pred->flNext) { BasicBlock* predBlock = pred->flBlock; /* Are we changing a loop backedge into a forward jump? */ if (block->isLoopHead() && (predBlock->bbNum >= block->bbNum) && (predBlock->bbNum <= succBlock->bbNum)) { /* First update the loop table and bbWeights */ optUpdateLoopsBeforeRemoveBlock(predBlock); } /* If predBlock is a new predecessor, then add it to succBlock's predecessor's list. */ if (predBlock->bbJumpKind != BBJ_SWITCH) { // Even if the pred is not a switch, we could have a conditional branch // to the fallthrough, so duplicate there could be preds for (unsigned i = 0; i < pred->flDupCount; i++) { fgAddRefPred(succBlock, predBlock); } } /* change all jumps to the removed block */ switch (predBlock->bbJumpKind) { default: noway_assert(!"Unexpected bbJumpKind in fgRemoveBlock()"); break; case BBJ_NONE: noway_assert(predBlock == bPrev); PREFIX_ASSUME(bPrev != nullptr); /* In the case of BBJ_ALWAYS we have to change the type of its predecessor */ if (block->bbJumpKind == BBJ_ALWAYS) { /* bPrev now becomes a BBJ_ALWAYS */ bPrev->bbJumpKind = BBJ_ALWAYS; bPrev->bbJumpDest = succBlock; } break; case BBJ_COND: /* The links for the direct predecessor case have already been updated above */ if (predBlock->bbJumpDest != block) { succBlock->bbFlags |= BBF_HAS_LABEL | BBF_JMP_TARGET; break; } /* Check if both side of the BBJ_COND now jump to the same block */ if (predBlock->bbNext == succBlock) { // Make sure we are replacing "block" with "succBlock" in predBlock->bbJumpDest. noway_assert(predBlock->bbJumpDest == block); predBlock->bbJumpDest = succBlock; fgRemoveConditionalJump(predBlock); break; } /* Fall through for the jump case */ __fallthrough; case BBJ_CALLFINALLY: case BBJ_ALWAYS: case BBJ_EHCATCHRET: noway_assert(predBlock->bbJumpDest == block); predBlock->bbJumpDest = succBlock; succBlock->bbFlags |= BBF_HAS_LABEL | BBF_JMP_TARGET; break; case BBJ_SWITCH: // Change any jumps from 'predBlock' (a BBJ_SWITCH) to 'block' to jump to 'succBlock' // // For the jump targets of 'predBlock' (a BBJ_SWITCH) that jump to 'block' // remove the old predecessor at 'block' from 'predBlock' and // add the new predecessor at 'succBlock' from 'predBlock' // fgReplaceSwitchJumpTarget(predBlock, succBlock, block); break; } } } if (bPrev != nullptr) { switch (bPrev->bbJumpKind) { case BBJ_CALLFINALLY: // If prev is a BBJ_CALLFINALLY it better be marked as RETLESS noway_assert(bPrev->bbFlags & BBF_RETLESS_CALL); break; case BBJ_ALWAYS: // Check for branch to next block. Just make sure the BBJ_ALWAYS block is not // part of a BBJ_CALLFINALLY/BBJ_ALWAYS pair. We do this here and don't rely on fgUpdateFlowGraph // because we can be called by ComputeDominators and it expects it to remove this jump to // the next block. This is the safest fix. We should remove all this BBJ_CALLFINALLY/BBJ_ALWAYS // pairing. if ((bPrev->bbJumpDest == bPrev->bbNext) && !fgInDifferentRegions(bPrev, bPrev->bbJumpDest)) // We don't remove a branch from Hot -> Cold { if ((bPrev == fgFirstBB) || !bPrev->bbPrev->isBBCallAlwaysPair()) { // It's safe to change the jump type bPrev->bbJumpKind = BBJ_NONE; bPrev->bbFlags &= ~BBF_NEEDS_GCPOLL; } } break; case BBJ_COND: /* Check for branch to next block */ if (bPrev->bbJumpDest == bPrev->bbNext) { fgRemoveConditionalJump(bPrev); } break; default: break; } ehUpdateForDeletedBlock(block); } } /***************************************************************************** * * Function called to connect to block that previously had a fall through */ BasicBlock* Compiler::fgConnectFallThrough(BasicBlock* bSrc, BasicBlock* bDst) { BasicBlock* jmpBlk = nullptr; /* If bSrc is non-NULL */ if (bSrc != nullptr) { /* If bSrc falls through to a block that is not bDst, we will insert a jump to bDst */ if (bSrc->bbFallsThrough() && (bSrc->bbNext != bDst)) { switch (bSrc->bbJumpKind) { case BBJ_NONE: bSrc->bbJumpKind = BBJ_ALWAYS; bSrc->bbJumpDest = bDst; bSrc->bbJumpDest->bbFlags |= (BBF_JMP_TARGET | BBF_HAS_LABEL); #ifdef DEBUG if (verbose) { printf("Block " FMT_BB " ended with a BBJ_NONE, Changed to an unconditional jump to " FMT_BB "\n", bSrc->bbNum, bSrc->bbJumpDest->bbNum); } #endif break; case BBJ_CALLFINALLY: case BBJ_COND: // Add a new block after bSrc which jumps to 'bDst' jmpBlk = fgNewBBafter(BBJ_ALWAYS, bSrc, true); if (fgComputePredsDone) { fgAddRefPred(jmpBlk, bSrc, fgGetPredForBlock(bDst, bSrc)); } // When adding a new jmpBlk we will set the bbWeight and bbFlags // if (fgHaveValidEdgeWeights) { noway_assert(fgComputePredsDone); flowList* newEdge = fgGetPredForBlock(jmpBlk, bSrc); jmpBlk->bbWeight = (newEdge->flEdgeWeightMin + newEdge->flEdgeWeightMax) / 2; if (bSrc->bbWeight == 0) { jmpBlk->bbWeight = 0; } if (jmpBlk->bbWeight == 0) { jmpBlk->bbFlags |= BBF_RUN_RARELY; } BasicBlock::weight_t weightDiff = (newEdge->flEdgeWeightMax - newEdge->flEdgeWeightMin); BasicBlock::weight_t slop = BasicBlock::GetSlopFraction(bSrc, bDst); // // If the [min/max] values for our edge weight is within the slop factor // then we will set the BBF_PROF_WEIGHT flag for the block // if (weightDiff <= slop) { jmpBlk->bbFlags |= BBF_PROF_WEIGHT; } } else { // We set the bbWeight to the smaller of bSrc->bbWeight or bDst->bbWeight if (bSrc->bbWeight < bDst->bbWeight) { jmpBlk->bbWeight = bSrc->bbWeight; jmpBlk->bbFlags |= (bSrc->bbFlags & BBF_RUN_RARELY); } else { jmpBlk->bbWeight = bDst->bbWeight; jmpBlk->bbFlags |= (bDst->bbFlags & BBF_RUN_RARELY); } } jmpBlk->bbJumpDest = bDst; jmpBlk->bbJumpDest->bbFlags |= (BBF_JMP_TARGET | BBF_HAS_LABEL); if (fgComputePredsDone) { fgReplacePred(bDst, bSrc, jmpBlk); } else { jmpBlk->bbFlags |= BBF_IMPORTED; } #ifdef DEBUG if (verbose) { printf("Added an unconditional jump to " FMT_BB " after block " FMT_BB "\n", jmpBlk->bbJumpDest->bbNum, bSrc->bbNum); } #endif // DEBUG break; default: noway_assert(!"Unexpected bbJumpKind"); break; } } else { // If bSrc is an unconditional branch to the next block // then change it to a BBJ_NONE block // if ((bSrc->bbJumpKind == BBJ_ALWAYS) && !(bSrc->bbFlags & BBF_KEEP_BBJ_ALWAYS) && (bSrc->bbJumpDest == bSrc->bbNext)) { bSrc->bbJumpKind = BBJ_NONE; bSrc->bbFlags &= ~BBF_NEEDS_GCPOLL; #ifdef DEBUG if (verbose) { printf("Changed an unconditional jump from " FMT_BB " to the next block " FMT_BB " into a BBJ_NONE block\n", bSrc->bbNum, bSrc->bbNext->bbNum); } #endif // DEBUG } } } return jmpBlk; } /***************************************************************************** Walk the flow graph, reassign block numbers to keep them in ascending order. Returns 'true' if any renumbering was actually done, OR if we change the maximum number of assigned basic blocks (this can happen if we do inlining, create a new, high-numbered block, then that block goes away. We go to renumber the blocks, none of them actually change number, but we shrink the maximum assigned block number. This affects the block set epoch). */ bool Compiler::fgRenumberBlocks() { // If we renumber the blocks the dominator information will be out-of-date if (fgDomsComputed) { noway_assert(!"Can't call Compiler::fgRenumberBlocks() when fgDomsComputed==true"); } #ifdef DEBUG if (verbose) { printf("\n*************** Before renumbering the basic blocks\n"); fgDispBasicBlocks(); fgDispHandlerTab(); } #endif // DEBUG bool renumbered = false; bool newMaxBBNum = false; BasicBlock* block; unsigned numStart = 1 + (compIsForInlining() ? impInlineInfo->InlinerCompiler->fgBBNumMax : 0); unsigned num; for (block = fgFirstBB, num = numStart; block != nullptr; block = block->bbNext, num++) { noway_assert((block->bbFlags & BBF_REMOVED) == 0); if (block->bbNum != num) { renumbered = true; #ifdef DEBUG if (verbose) { printf("Renumber " FMT_BB " to " FMT_BB "\n", block->bbNum, num); } #endif // DEBUG block->bbNum = num; } if (block->bbNext == nullptr) { fgLastBB = block; fgBBcount = num - numStart + 1; if (compIsForInlining()) { if (impInlineInfo->InlinerCompiler->fgBBNumMax != num) { impInlineInfo->InlinerCompiler->fgBBNumMax = num; newMaxBBNum = true; } } else { if (fgBBNumMax != num) { fgBBNumMax = num; newMaxBBNum = true; } } } } #ifdef DEBUG if (verbose) { printf("\n*************** After renumbering the basic blocks\n"); if (renumbered) { fgDispBasicBlocks(); fgDispHandlerTab(); } else { printf("=============== No blocks renumbered!\n"); } } #endif // DEBUG // Now update the BlockSet epoch, which depends on the block numbers. // If any blocks have been renumbered then create a new BlockSet epoch. // Even if we have not renumbered any blocks, we might still need to force // a new BlockSet epoch, for one of several reasons. If there are any new // blocks with higher numbers than the former maximum numbered block, then we // need a new epoch with a new size matching the new largest numbered block. // Also, if the number of blocks is different from the last time we set the // BlockSet epoch, then we need a new epoch. This wouldn't happen if we // renumbered blocks after every block addition/deletion, but it might be // the case that we can change the number of blocks, then set the BlockSet // epoch without renumbering, then change the number of blocks again, then // renumber. if (renumbered || newMaxBBNum) { NewBasicBlockEpoch(); // The key in the unique switch successor map is dependent on the block number, so invalidate that cache. InvalidateUniqueSwitchSuccMap(); } else { EnsureBasicBlockEpoch(); } // Tell our caller if any blocks actually were renumbered. return renumbered || newMaxBBNum; } /***************************************************************************** * * Is the BasicBlock bJump a forward branch? * Optionally bSrc can be supplied to indicate that * bJump must be forward with respect to bSrc */ bool Compiler::fgIsForwardBranch(BasicBlock* bJump, BasicBlock* bSrc /* = NULL */) { bool result = false; if ((bJump->bbJumpKind == BBJ_COND) || (bJump->bbJumpKind == BBJ_ALWAYS)) { BasicBlock* bDest = bJump->bbJumpDest; BasicBlock* bTemp = (bSrc == nullptr) ? bJump : bSrc; while (true) { bTemp = bTemp->bbNext; if (bTemp == nullptr) { break; } if (bTemp == bDest) { result = true; break; } } } return result; } /***************************************************************************** * * Function called to expand the set of rarely run blocks */ bool Compiler::fgExpandRarelyRunBlocks() { bool result = false; #ifdef DEBUG if (verbose) { printf("\n*************** In fgExpandRarelyRunBlocks()\n"); } const char* reason = nullptr; #endif // We expand the number of rarely run blocks by observing // that a block that falls into or jumps to a rarely run block, // must itself be rarely run and when we have a conditional // jump in which both branches go to rarely run blocks then // the block must itself be rarely run BasicBlock* block; BasicBlock* bPrev; for (bPrev = fgFirstBB, block = bPrev->bbNext; block != nullptr; bPrev = block, block = block->bbNext) { if (bPrev->isRunRarely()) { continue; } /* bPrev is known to be a normal block here */ switch (bPrev->bbJumpKind) { case BBJ_ALWAYS: /* Is the jump target rarely run? */ if (bPrev->bbJumpDest->isRunRarely()) { INDEBUG(reason = "Unconditional jump to a rarely run block";) goto NEW_RARELY_RUN; } break; case BBJ_CALLFINALLY: // Check for a BBJ_CALLFINALLY followed by a rarely run paired BBJ_ALWAYS // if (bPrev->isBBCallAlwaysPair()) { /* Is the next block rarely run? */ if (block->isRunRarely()) { INDEBUG(reason = "Call of finally followed by a rarely run block";) goto NEW_RARELY_RUN; } } break; case BBJ_NONE: /* is fall through target rarely run? */ if (block->isRunRarely()) { INDEBUG(reason = "Falling into a rarely run block";) goto NEW_RARELY_RUN; } break; case BBJ_COND: if (!block->isRunRarely()) { continue; } /* If both targets of the BBJ_COND are run rarely then don't reorder */ if (bPrev->bbJumpDest->isRunRarely()) { /* bPrev should also be marked as run rarely */ if (!bPrev->isRunRarely()) { INDEBUG(reason = "Both sides of a conditional jump are rarely run";) NEW_RARELY_RUN: /* If the weight of the block was obtained from a profile run, than it's more accurate than our static analysis */ if (bPrev->hasProfileWeight()) { continue; } result = true; #ifdef DEBUG assert(reason != nullptr); if (verbose) { printf("%s, marking " FMT_BB " as rarely run\n", reason, bPrev->bbNum); } #endif // DEBUG /* Must not have previously been marked */ noway_assert(!bPrev->isRunRarely()); /* Mark bPrev as a new rarely run block */ bPrev->bbSetRunRarely(); BasicBlock* bPrevPrev = nullptr; BasicBlock* tmpbb; if ((bPrev->bbFlags & BBF_KEEP_BBJ_ALWAYS) != 0) { // If we've got a BBJ_CALLFINALLY/BBJ_ALWAYS pair, treat the BBJ_CALLFINALLY as an // additional predecessor for the BBJ_ALWAYS block tmpbb = bPrev->bbPrev; noway_assert(tmpbb != nullptr); #if FEATURE_EH_FUNCLETS noway_assert(tmpbb->isBBCallAlwaysPair()); bPrevPrev = tmpbb; #else if (tmpbb->bbJumpKind == BBJ_CALLFINALLY) { bPrevPrev = tmpbb; } #endif } /* Now go back to it's earliest predecessor to see */ /* if it too should now be marked as rarely run */ flowList* pred = bPrev->bbPreds; if ((pred != nullptr) || (bPrevPrev != nullptr)) { // bPrevPrev will be set to the lexically // earliest predecessor of bPrev. while (pred != nullptr) { if (bPrevPrev == nullptr) { // Initially we select the first block in the bbPreds list bPrevPrev = pred->flBlock; continue; } // Walk the flow graph lexically forward from pred->flBlock // if we find (block == bPrevPrev) then // pred->flBlock is an earlier predecessor. for (tmpbb = pred->flBlock; tmpbb != nullptr; tmpbb = tmpbb->bbNext) { if (tmpbb == bPrevPrev) { /* We found an ealier predecessor */ bPrevPrev = pred->flBlock; break; } else if (tmpbb == bPrev) { // We have reached bPrev so stop walking // as this cannot be an earlier predecessor break; } } // Onto the next predecessor pred = pred->flNext; } // Walk the flow graph forward from bPrevPrev // if we don't find (tmpbb == bPrev) then our candidate // bPrevPrev is lexically after bPrev and we do not // want to select it as our new block for (tmpbb = bPrevPrev; tmpbb != nullptr; tmpbb = tmpbb->bbNext) { if (tmpbb == bPrev) { // Set up block back to the lexically // earliest predecessor of pPrev block = bPrevPrev; } } } } break; default: break; } } } // Now iterate over every block to see if we can prove that a block is rarely run // (i.e. when all predecessors to the block are rarely run) // for (bPrev = fgFirstBB, block = bPrev->bbNext; block != nullptr; bPrev = block, block = block->bbNext) { // If block is not run rarely, then check to make sure that it has // at least one non-rarely run block. if (!block->isRunRarely()) { bool rare = true; /* Make sure that block has at least one normal predecessor */ for (flowList* pred = block->bbPreds; pred != nullptr; pred = pred->flNext) { /* Find the fall through predecessor, if any */ if (!pred->flBlock->isRunRarely()) { rare = false; break; } } if (rare) { // If 'block' is the start of a handler or filter then we cannot make it // rarely run because we may have an exceptional edge that // branches here. // if (bbIsHandlerBeg(block)) { rare = false; } } if (rare) { block->bbSetRunRarely(); result = true; #ifdef DEBUG if (verbose) { printf("All branches to " FMT_BB " are from rarely run blocks, marking as rarely run\n", block->bbNum); } #endif // DEBUG // When marking a BBJ_CALLFINALLY as rarely run we also mark // the BBJ_ALWAYS that comes after it as rarely run // if (block->isBBCallAlwaysPair()) { BasicBlock* bNext = block->bbNext; PREFIX_ASSUME(bNext != nullptr); bNext->bbSetRunRarely(); #ifdef DEBUG if (verbose) { printf("Also marking the BBJ_ALWAYS at " FMT_BB " as rarely run\n", bNext->bbNum); } #endif // DEBUG } } } /* COMPACT blocks if possible */ if (bPrev->bbJumpKind == BBJ_NONE) { if (fgCanCompactBlocks(bPrev, block)) { fgCompactBlocks(bPrev, block); block = bPrev; continue; } } // // if bPrev->bbWeight is not based upon profile data we can adjust // the weights of bPrev and block // else if (bPrev->isBBCallAlwaysPair() && // we must have a BBJ_CALLFINALLY and BBK_ALWAYS pair (bPrev->bbWeight != block->bbWeight) && // the weights are currently different !bPrev->hasProfileWeight()) // and the BBJ_CALLFINALLY block is not using profiled // weights { if (block->isRunRarely()) { bPrev->bbWeight = block->bbWeight; // the BBJ_CALLFINALLY block now has the same weight as the BBJ_ALWAYS block bPrev->bbFlags |= BBF_RUN_RARELY; // and is now rarely run #ifdef DEBUG if (verbose) { printf("Marking the BBJ_CALLFINALLY block at " FMT_BB " as rarely run because " FMT_BB " is rarely run\n", bPrev->bbNum, block->bbNum); } #endif // DEBUG } else if (bPrev->isRunRarely()) { block->bbWeight = bPrev->bbWeight; // the BBJ_ALWAYS block now has the same weight as the BBJ_CALLFINALLY block block->bbFlags |= BBF_RUN_RARELY; // and is now rarely run #ifdef DEBUG if (verbose) { printf("Marking the BBJ_ALWAYS block at " FMT_BB " as rarely run because " FMT_BB " is rarely run\n", block->bbNum, bPrev->bbNum); } #endif // DEBUG } else // Both blocks are hot, bPrev is known not to be using profiled weight { bPrev->bbWeight = block->bbWeight; // the BBJ_CALLFINALLY block now has the same weight as the BBJ_ALWAYS block } noway_assert(block->bbWeight == bPrev->bbWeight); } } return result; } /***************************************************************************** * * Returns true if it is allowable (based upon the EH regions) * to place block bAfter immediately after bBefore. It is allowable * if the 'bBefore' and 'bAfter' blocks are in the exact same EH region. */ bool Compiler::fgEhAllowsMoveBlock(BasicBlock* bBefore, BasicBlock* bAfter) { return BasicBlock::sameEHRegion(bBefore, bAfter); } /***************************************************************************** * * Function called to move the range of blocks [bStart .. bEnd]. * The blocks are placed immediately after the insertAfterBlk. * fgFirstFuncletBB is not updated; that is the responsibility of the caller, if necessary. */ void Compiler::fgMoveBlocksAfter(BasicBlock* bStart, BasicBlock* bEnd, BasicBlock* insertAfterBlk) { /* We have decided to insert the block(s) after 'insertAfterBlk' */ CLANG_FORMAT_COMMENT_ANCHOR; #ifdef DEBUG if (verbose) { printf("Relocated block%s [" FMT_BB ".." FMT_BB "] inserted after " FMT_BB "%s\n", (bStart == bEnd) ? "" : "s", bStart->bbNum, bEnd->bbNum, insertAfterBlk->bbNum, (insertAfterBlk->bbNext == nullptr) ? " at the end of method" : ""); } #endif // DEBUG /* relink [bStart .. bEnd] into the flow graph */ bEnd->bbNext = insertAfterBlk->bbNext; if (insertAfterBlk->bbNext) { insertAfterBlk->bbNext->bbPrev = bEnd; } insertAfterBlk->setNext(bStart); /* If insertAfterBlk was fgLastBB then update fgLastBB */ if (insertAfterBlk == fgLastBB) { fgLastBB = bEnd; noway_assert(fgLastBB->bbNext == nullptr); } } /***************************************************************************** * * Function called to relocate a single range to the end of the method. * Only an entire consecutive region can be moved and it will be kept together. * Except for the first block, the range cannot have any blocks that jump into or out of the region. * When successful we return the bLast block which is the last block that we relocated. * When unsuccessful we return NULL. ============================================================= NOTE: This function can invalidate all pointers into the EH table, as well as change the size of the EH table! ============================================================= */ BasicBlock* Compiler::fgRelocateEHRange(unsigned regionIndex, FG_RELOCATE_TYPE relocateType) { INDEBUG(const char* reason = "None";) // Figure out the range of blocks we're going to move unsigned XTnum; EHblkDsc* HBtab; BasicBlock* bStart = nullptr; BasicBlock* bMiddle = nullptr; BasicBlock* bLast = nullptr; BasicBlock* bPrev = nullptr; #if FEATURE_EH_FUNCLETS // We don't support moving try regions... yet? noway_assert(relocateType == FG_RELOCATE_HANDLER); #endif // FEATURE_EH_FUNCLETS HBtab = ehGetDsc(regionIndex); if (relocateType == FG_RELOCATE_TRY) { bStart = HBtab->ebdTryBeg; bLast = HBtab->ebdTryLast; } else if (relocateType == FG_RELOCATE_HANDLER) { if (HBtab->HasFilter()) { // The filter and handler funclets must be moved together, and remain contiguous. bStart = HBtab->ebdFilter; bMiddle = HBtab->ebdHndBeg; bLast = HBtab->ebdHndLast; } else { bStart = HBtab->ebdHndBeg; bLast = HBtab->ebdHndLast; } } // Our range must contain either all rarely run blocks or all non-rarely run blocks bool inTheRange = false; bool validRange = false; BasicBlock* block; noway_assert(bStart != nullptr && bLast != nullptr); if (bStart == fgFirstBB) { INDEBUG(reason = "can not relocate first block";) goto FAILURE; } #if !FEATURE_EH_FUNCLETS // In the funclets case, we still need to set some information on the handler blocks if (bLast->bbNext == NULL) { INDEBUG(reason = "region is already at the end of the method";) goto FAILURE; } #endif // !FEATURE_EH_FUNCLETS // Walk the block list for this purpose: // 1. Verify that all the blocks in the range are either all rarely run or not rarely run. // When creating funclets, we ignore the run rarely flag, as we need to be able to move any blocks // in the range. CLANG_FORMAT_COMMENT_ANCHOR; #if !FEATURE_EH_FUNCLETS bool isRare; isRare = bStart->isRunRarely(); #endif // !FEATURE_EH_FUNCLETS block = fgFirstBB; while (true) { if (block == bStart) { noway_assert(inTheRange == false); inTheRange = true; } else if (block == bLast->bbNext) { noway_assert(inTheRange == true); inTheRange = false; break; // we found the end, so we're done } if (inTheRange) { #if !FEATURE_EH_FUNCLETS // Unless all blocks are (not) run rarely we must return false. if (isRare != block->isRunRarely()) { INDEBUG(reason = "this region contains both rarely run and non-rarely run blocks";) goto FAILURE; } #endif // !FEATURE_EH_FUNCLETS validRange = true; } if (block == nullptr) { break; } block = block->bbNext; } // Ensure that bStart .. bLast defined a valid range noway_assert((validRange == true) && (inTheRange == false)); bPrev = bStart->bbPrev; noway_assert(bPrev != nullptr); // Can't move a range that includes the first block of the function. JITDUMP("Relocating %s range " FMT_BB ".." FMT_BB " (EH#%u) to end of BBlist\n", (relocateType == FG_RELOCATE_TRY) ? "try" : "handler", bStart->bbNum, bLast->bbNum, regionIndex); #ifdef DEBUG if (verbose) { fgDispBasicBlocks(); fgDispHandlerTab(); } if (!FEATURE_EH_FUNCLETS) { // This is really expensive, and quickly becomes O(n^n) with funclets // so only do it once after we've created them (see fgCreateFunclets) if (expensiveDebugCheckLevel >= 2) { fgDebugCheckBBlist(); } } #endif // DEBUG #if FEATURE_EH_FUNCLETS bStart->bbFlags |= BBF_FUNCLET_BEG; // Mark the start block of the funclet if (bMiddle != nullptr) { bMiddle->bbFlags |= BBF_FUNCLET_BEG; // Also mark the start block of a filter handler as a funclet } #endif // FEATURE_EH_FUNCLETS BasicBlock* bNext; bNext = bLast->bbNext; /* Temporarily unlink [bStart .. bLast] from the flow graph */ fgUnlinkRange(bStart, bLast); BasicBlock* insertAfterBlk; insertAfterBlk = fgLastBB; #if FEATURE_EH_FUNCLETS // There are several cases we need to consider when moving an EH range. // If moving a range X, we must consider its relationship to every other EH // range A in the table. Note that each entry in the table represents both // a protected region and a handler region (possibly including a filter region // that must live before and adjacent to the handler region), so we must // consider try and handler regions independently. These are the cases: // 1. A is completely contained within X (where "completely contained" means // that the 'begin' and 'last' parts of A are strictly between the 'begin' // and 'end' parts of X, and aren't equal to either, for example, they don't // share 'last' blocks). In this case, when we move X, A moves with it, and // the EH table doesn't need to change. // 2. X is completely contained within A. In this case, X gets extracted from A, // and the range of A shrinks, but because A is strictly within X, the EH // table doesn't need to change. // 3. A and X have exactly the same range. In this case, A is moving with X and // the EH table doesn't need to change. // 4. A and X share the 'last' block. There are two sub-cases: // (a) A is a larger range than X (such that the beginning of A precedes the // beginning of X): in this case, we are moving the tail of A. We set the // 'last' block of A to the the block preceding the beginning block of X. // (b) A is a smaller range than X. Thus, we are moving the entirety of A along // with X. In this case, nothing in the EH record for A needs to change. // 5. A and X share the 'beginning' block (but aren't the same range, as in #3). // This can never happen here, because we are only moving handler ranges (we don't // move try ranges), and handler regions cannot start at the beginning of a try // range or handler range and be a subset. // // Note that A and X must properly nest for the table to be well-formed. For example, // the beginning of A can't be strictly within the range of X (that is, the beginning // of A isn't shared with the beginning of X) and the end of A outside the range. for (XTnum = 0, HBtab = compHndBBtab; XTnum < compHndBBtabCount; XTnum++, HBtab++) { if (XTnum != regionIndex) // we don't need to update our 'last' pointer { if (HBtab->ebdTryLast == bLast) { // If we moved a set of blocks that were at the end of // a different try region then we may need to update ebdTryLast for (block = HBtab->ebdTryBeg; block != nullptr; block = block->bbNext) { if (block == bPrev) { // We were contained within it, so shrink its region by // setting its 'last' fgSetTryEnd(HBtab, bPrev); break; } else if (block == HBtab->ebdTryLast->bbNext) { // bPrev does not come after the TryBeg, thus we are larger, and // it is moving with us. break; } } } if (HBtab->ebdHndLast == bLast) { // If we moved a set of blocks that were at the end of // a different handler region then we must update ebdHndLast for (block = HBtab->ebdHndBeg; block != nullptr; block = block->bbNext) { if (block == bPrev) { fgSetHndEnd(HBtab, bPrev); break; } else if (block == HBtab->ebdHndLast->bbNext) { // bPrev does not come after the HndBeg break; } } } } } // end exception table iteration // Insert the block(s) we are moving after fgLastBlock fgMoveBlocksAfter(bStart, bLast, insertAfterBlk); if (fgFirstFuncletBB == nullptr) // The funclet region isn't set yet { fgFirstFuncletBB = bStart; } else { assert(fgFirstFuncletBB != insertAfterBlk->bbNext); // We insert at the end, not at the beginning, of the funclet region. } // These asserts assume we aren't moving try regions (which we might need to do). Only // try regions can have fall through into or out of the region. noway_assert(!bPrev->bbFallsThrough()); // There can be no fall through into a filter or handler region noway_assert(!bLast->bbFallsThrough()); // There can be no fall through out of a handler region #ifdef DEBUG if (verbose) { printf("Create funclets: moved region\n"); fgDispHandlerTab(); } // We have to wait to do this until we've created all the additional regions // Because this relies on ebdEnclosingTryIndex and ebdEnclosingHndIndex if (!FEATURE_EH_FUNCLETS) { // This is really expensive, and quickly becomes O(n^n) with funclets // so only do it once after we've created them (see fgCreateFunclets) if (expensiveDebugCheckLevel >= 2) { fgDebugCheckBBlist(); } } #endif // DEBUG #else // FEATURE_EH_FUNCLETS for (XTnum = 0, HBtab = compHndBBtab; XTnum < compHndBBtabCount; XTnum++, HBtab++) { if (XTnum == regionIndex) { // Don't update our handler's Last info continue; } if (HBtab->ebdTryLast == bLast) { // If we moved a set of blocks that were at the end of // a different try region then we may need to update ebdTryLast for (block = HBtab->ebdTryBeg; block != NULL; block = block->bbNext) { if (block == bPrev) { fgSetTryEnd(HBtab, bPrev); break; } else if (block == HBtab->ebdTryLast->bbNext) { // bPrev does not come after the TryBeg break; } } } if (HBtab->ebdHndLast == bLast) { // If we moved a set of blocks that were at the end of // a different handler region then we must update ebdHndLast for (block = HBtab->ebdHndBeg; block != NULL; block = block->bbNext) { if (block == bPrev) { fgSetHndEnd(HBtab, bPrev); break; } else if (block == HBtab->ebdHndLast->bbNext) { // bPrev does not come after the HndBeg break; } } } } // end exception table iteration // We have decided to insert the block(s) after fgLastBlock fgMoveBlocksAfter(bStart, bLast, insertAfterBlk); // If bPrev falls through, we will insert a jump to block fgConnectFallThrough(bPrev, bStart); // If bLast falls through, we will insert a jump to bNext fgConnectFallThrough(bLast, bNext); #endif // FEATURE_EH_FUNCLETS goto DONE; FAILURE: #ifdef DEBUG if (verbose) { printf("*************** Failed fgRelocateEHRange(" FMT_BB ".." FMT_BB ") because %s\n", bStart->bbNum, bLast->bbNum, reason); } #endif // DEBUG bLast = nullptr; DONE: return bLast; } #if FEATURE_EH_FUNCLETS #if defined(_TARGET_ARM_) /***************************************************************************** * We just removed a BBJ_CALLFINALLY/BBJ_ALWAYS pair. If this was the only such pair * targeting the BBJ_ALWAYS target, then we need to clear the BBF_FINALLY_TARGET bit * so that target can also be removed. 'block' is the finally target. Since we just * removed the BBJ_ALWAYS, it better have the BBF_FINALLY_TARGET bit set. */ void Compiler::fgClearFinallyTargetBit(BasicBlock* block) { assert(fgComputePredsDone); assert((block->bbFlags & BBF_FINALLY_TARGET) != 0); for (flowList* pred = block->bbPreds; pred; pred = pred->flNext) { if (pred->flBlock->bbJumpKind == BBJ_ALWAYS && pred->flBlock->bbJumpDest == block) { BasicBlock* pPrev = pred->flBlock->bbPrev; if (pPrev != NULL) { if (pPrev->bbJumpKind == BBJ_CALLFINALLY) { // We found a BBJ_CALLFINALLY / BBJ_ALWAYS that still points to this finally target return; } } } } // Didn't find any BBJ_CALLFINALLY / BBJ_ALWAYS that still points here, so clear the bit block->bbFlags &= ~BBF_FINALLY_TARGET; } #endif // defined(_TARGET_ARM_) /***************************************************************************** * Is this an intra-handler control flow edge? * * 'block' is the head block of a funclet/handler region, or . * 'predBlock' is a predecessor block of 'block' in the predecessor list. * * 'predBlock' can legally only be one of three things: * 1. in the same handler region (e.g., the source of a back-edge of a loop from * 'predBlock' to 'block'), including in nested regions within the handler, * 2. if 'block' begins a handler that is a filter-handler, 'predBlock' must be in the 'filter' region, * 3. for other handlers, 'predBlock' must be in the 'try' region corresponding to handler (or any * region nested in the 'try' region). * * Note that on AMD64/ARM64, the BBJ_CALLFINALLY block that calls a finally handler is not * within the corresponding 'try' region: it is placed in the corresponding 'try' region's * parent (which might be the main function body). This is how it is represented to the VM * (with a special "cloned finally" EH table entry). * * Return 'true' for case #1, and 'false' otherwise. */ bool Compiler::fgIsIntraHandlerPred(BasicBlock* predBlock, BasicBlock* block) { // Some simple preconditions (as stated above) assert(!fgFuncletsCreated); assert(fgGetPredForBlock(block, predBlock) != nullptr); assert(block->hasHndIndex()); EHblkDsc* xtab = ehGetDsc(block->getHndIndex()); #if FEATURE_EH_CALLFINALLY_THUNKS if (xtab->HasFinallyHandler()) { assert((xtab->ebdHndBeg == block) || // The normal case ((xtab->ebdHndBeg->bbNext == block) && (xtab->ebdHndBeg->bbFlags & BBF_INTERNAL))); // After we've already inserted a header block, and we're // trying to decide how to split up the predecessor edges. if (predBlock->bbJumpKind == BBJ_CALLFINALLY) { assert(predBlock->bbJumpDest == block); // A BBJ_CALLFINALLY predecessor of the handler can only come from the corresponding try, // not from any EH clauses nested in this handler. However, we represent the BBJ_CALLFINALLY // as being in the 'try' region's parent EH region, which might be the main function body. unsigned tryIndex = xtab->ebdEnclosingTryIndex; if (tryIndex == EHblkDsc::NO_ENCLOSING_INDEX) { assert(!predBlock->hasTryIndex()); } else { assert(predBlock->hasTryIndex()); assert(tryIndex == predBlock->getTryIndex()); assert(ehGetDsc(tryIndex)->InTryRegionBBRange(predBlock)); } return false; } } #endif // FEATURE_EH_CALLFINALLY_THUNKS assert(predBlock->hasHndIndex() || predBlock->hasTryIndex()); // We could search the try region looking for predBlock by using bbInTryRegions // but that does a lexical search for the block, and then assumes funclets // have been created and does a lexical search of all funclets that were pulled // out of the parent try region. // First, funclets haven't been created yet, and even if they had been, we shouldn't // have any funclet directly branching to another funclet (they have to return first). // So we can safely use CheckIsTryRegion instead of bbInTryRegions. // Second, I believe the depth of any EH graph will on average be smaller than the // breadth of the blocks within a try body. Thus it is faster to get our answer by // looping outward over the region graph. However, I have added asserts, as a // precaution, to ensure both algorithms agree. The asserts also check that the only // way to reach the head of a funclet is from the corresponding try body or from // within the funclet (and *not* any nested funclets). if (predBlock->hasTryIndex()) { // Because the EH clauses are listed inside-out, any nested trys will be at a // lower index than the current try and if there's no enclosing try, tryIndex // will terminate at NO_ENCLOSING_INDEX unsigned tryIndex = predBlock->getTryIndex(); while (tryIndex < block->getHndIndex()) { tryIndex = ehGetEnclosingTryIndex(tryIndex); } // tryIndex should enclose predBlock assert((tryIndex == EHblkDsc::NO_ENCLOSING_INDEX) || ehGetDsc(tryIndex)->InTryRegionBBRange(predBlock)); // At this point tryIndex is either block's handler's corresponding try body // or some outer try region that contains both predBlock & block or // NO_ENCLOSING_REGION (because there was no try body that encloses both). if (tryIndex == block->getHndIndex()) { assert(xtab->InTryRegionBBRange(predBlock)); assert(!xtab->InHndRegionBBRange(predBlock)); return false; } // tryIndex should enclose block (and predBlock as previously asserted) assert((tryIndex == EHblkDsc::NO_ENCLOSING_INDEX) || ehGetDsc(tryIndex)->InTryRegionBBRange(block)); } if (xtab->HasFilter()) { // The block is a handler. Check if the pred block is from its filter. We only need to // check the end filter flag, as there is only a single filter for any handler, and we // already know predBlock is a predecessor of block. if (predBlock->bbJumpKind == BBJ_EHFILTERRET) { assert(!xtab->InHndRegionBBRange(predBlock)); return false; } } // It is not in our try region (or filter), so it must be within this handler (or try bodies // within this handler) assert(!xtab->InTryRegionBBRange(predBlock)); assert(xtab->InHndRegionBBRange(predBlock)); return true; } /***************************************************************************** * Does this block, first block of a handler region, have any predecessor edges * that are not from its corresponding try region? */ bool Compiler::fgAnyIntraHandlerPreds(BasicBlock* block) { assert(block->hasHndIndex()); assert(fgFirstBlockOfHandler(block) == block); // this block is the first block of a handler flowList* pred; for (pred = block->bbPreds; pred; pred = pred->flNext) { BasicBlock* predBlock = pred->flBlock; if (fgIsIntraHandlerPred(predBlock, block)) { // We have a predecessor that is not from our try region return true; } } return false; } /***************************************************************************** * Introduce a new head block of the handler for the prolog to be put in, ahead * of the current handler head 'block'. * Note that this code has some similarities to fgCreateLoopPreHeader(). */ void Compiler::fgInsertFuncletPrologBlock(BasicBlock* block) { #ifdef DEBUG if (verbose) { printf("\nCreating funclet prolog header for " FMT_BB "\n", block->bbNum); } #endif assert(block->hasHndIndex()); assert(fgFirstBlockOfHandler(block) == block); // this block is the first block of a handler /* Allocate a new basic block */ BasicBlock* newHead = bbNewBasicBlock(BBJ_NONE); // In fgComputePreds() we set the BBF_JMP_TARGET and BBF_HAS_LABEL for all of the handler entry points // newHead->bbFlags |= (BBF_INTERNAL | BBF_JMP_TARGET | BBF_HAS_LABEL); newHead->inheritWeight(block); newHead->bbRefs = 0; fgInsertBBbefore(block, newHead); // insert the new block in the block list fgExtendEHRegionBefore(block); // Update the EH table to make the prolog block the first block in the block's EH // block. // Distribute the pred list between newHead and block. Incoming edges coming from outside // the handler go to the prolog. Edges coming from with the handler are back-edges, and // go to the existing 'block'. for (flowList* pred = block->bbPreds; pred; pred = pred->flNext) { BasicBlock* predBlock = pred->flBlock; if (!fgIsIntraHandlerPred(predBlock, block)) { // It's a jump from outside the handler; add it to the newHead preds list and remove // it from the block preds list. switch (predBlock->bbJumpKind) { case BBJ_CALLFINALLY: noway_assert(predBlock->bbJumpDest == block); predBlock->bbJumpDest = newHead; fgRemoveRefPred(block, predBlock); fgAddRefPred(newHead, predBlock); break; default: // The only way into the handler is via a BBJ_CALLFINALLY (to a finally handler), or // via exception handling. noway_assert(false); break; } } } assert(nullptr == fgGetPredForBlock(block, newHead)); fgAddRefPred(block, newHead); assert((newHead->bbFlags & (BBF_INTERNAL | BBF_JMP_TARGET | BBF_HAS_LABEL)) == (BBF_INTERNAL | BBF_JMP_TARGET | BBF_HAS_LABEL)); } /***************************************************************************** * * Every funclet will have a prolog. That prolog will be inserted as the first instructions * in the first block of the funclet. If the prolog is also the head block of a loop, we * would end up with the prolog instructions being executed more than once. * Check for this by searching the predecessor list for loops, and create a new prolog header * block when needed. We detect a loop by looking for any predecessor that isn't in the * handler's try region, since the only way to get into a handler is via that try region. */ void Compiler::fgCreateFuncletPrologBlocks() { noway_assert(fgComputePredsDone); noway_assert(!fgDomsComputed); // this function doesn't maintain the dom sets assert(!fgFuncletsCreated); bool prologBlocksCreated = false; EHblkDsc* HBtabEnd; EHblkDsc* HBtab; for (HBtab = compHndBBtab, HBtabEnd = compHndBBtab + compHndBBtabCount; HBtab < HBtabEnd; HBtab++) { BasicBlock* head = HBtab->ebdHndBeg; if (fgAnyIntraHandlerPreds(head)) { // We need to create a new block in which to place the prolog, and split the existing // head block predecessor edges into those that should point to the prolog, and those // that shouldn't. // // It's arguable that we should just always do this, and not only when we "need to", // so there aren't two different code paths. However, it's unlikely to be necessary // for catch handlers because they have an incoming argument (the exception object) // that needs to get stored or saved, so back-arcs won't normally go to the head. It's // possible when writing in IL to generate a legal loop (e.g., push an Exception object // on the stack before jumping back to the catch head), but C# probably won't. This will // most commonly only be needed for finallys with a do/while loop at the top of the // finally. // // Note that we don't check filters. This might be a bug, but filters always have a filter // object live on entry, so it's at least unlikely (illegal?) that a loop edge targets the // filter head. fgInsertFuncletPrologBlock(head); prologBlocksCreated = true; } } if (prologBlocksCreated) { // If we've modified the graph, reset the 'modified' flag, since the dominators haven't // been computed. fgModified = false; #if DEBUG if (verbose) { JITDUMP("\nAfter fgCreateFuncletPrologBlocks()"); fgDispBasicBlocks(); fgDispHandlerTab(); } fgVerifyHandlerTab(); fgDebugCheckBBlist(); #endif // DEBUG } } /***************************************************************************** * * Function to create funclets out of all EH catch/finally/fault blocks. * We only move filter and handler blocks, not try blocks. */ void Compiler::fgCreateFunclets() { assert(!fgFuncletsCreated); #ifdef DEBUG if (verbose) { printf("*************** In fgCreateFunclets()\n"); } #endif fgCreateFuncletPrologBlocks(); unsigned XTnum; EHblkDsc* HBtab; const unsigned int funcCnt = ehFuncletCount() + 1; if (!FitsIn<unsigned short>(funcCnt)) { IMPL_LIMITATION("Too many funclets"); } FuncInfoDsc* funcInfo = new (this, CMK_BasicBlock) FuncInfoDsc[funcCnt]; unsigned short funcIdx; // Setup the root FuncInfoDsc and prepare to start associating // FuncInfoDsc's with their corresponding EH region memset((void*)funcInfo, 0, funcCnt * sizeof(FuncInfoDsc)); assert(funcInfo[0].funKind == FUNC_ROOT); funcIdx = 1; // Because we iterate from the top to the bottom of the compHndBBtab array, we are iterating // from most nested (innermost) to least nested (outermost) EH region. It would be reasonable // to iterate in the opposite order, but the order of funclets shouldn't matter. // // We move every handler region to the end of the function: each handler will become a funclet. // // Note that fgRelocateEHRange() can add new entries to the EH table. However, they will always // be added *after* the current index, so our iteration here is not invalidated. // It *can* invalidate the compHndBBtab pointer itself, though, if it gets reallocated! for (XTnum = 0; XTnum < compHndBBtabCount; XTnum++) { HBtab = ehGetDsc(XTnum); // must re-compute this every loop, since fgRelocateEHRange changes the table if (HBtab->HasFilter()) { assert(funcIdx < funcCnt); funcInfo[funcIdx].funKind = FUNC_FILTER; funcInfo[funcIdx].funEHIndex = (unsigned short)XTnum; funcIdx++; } assert(funcIdx < funcCnt); funcInfo[funcIdx].funKind = FUNC_HANDLER; funcInfo[funcIdx].funEHIndex = (unsigned short)XTnum; HBtab->ebdFuncIndex = funcIdx; funcIdx++; fgRelocateEHRange(XTnum, FG_RELOCATE_HANDLER); } // We better have populated all of them by now assert(funcIdx == funcCnt); // Publish compCurrFuncIdx = 0; compFuncInfos = funcInfo; compFuncInfoCount = (unsigned short)funcCnt; fgFuncletsCreated = true; #if DEBUG if (verbose) { JITDUMP("\nAfter fgCreateFunclets()"); fgDispBasicBlocks(); fgDispHandlerTab(); } fgVerifyHandlerTab(); fgDebugCheckBBlist(); #endif // DEBUG } #else // !FEATURE_EH_FUNCLETS /***************************************************************************** * * Function called to relocate any and all EH regions. * Only entire consecutive EH regions will be moved and they will be kept together. * Except for the first block, the range can not have any blocks that jump into or out of the region. */ bool Compiler::fgRelocateEHRegions() { bool result = false; // Our return value #ifdef DEBUG if (verbose) printf("*************** In fgRelocateEHRegions()\n"); #endif if (fgCanRelocateEHRegions) { unsigned XTnum; EHblkDsc* HBtab; for (XTnum = 0, HBtab = compHndBBtab; XTnum < compHndBBtabCount; XTnum++, HBtab++) { // Nested EH regions cannot be moved. // Also we don't want to relocate an EH region that has a filter if ((HBtab->ebdHandlerNestingLevel == 0) && !HBtab->HasFilter()) { bool movedTry = false; #if DEBUG bool movedHnd = false; #endif // DEBUG // Only try to move the outermost try region if (HBtab->ebdEnclosingTryIndex == EHblkDsc::NO_ENCLOSING_INDEX) { // Move the entire try region if it can be moved if (HBtab->ebdTryBeg->isRunRarely()) { BasicBlock* bTryLastBB = fgRelocateEHRange(XTnum, FG_RELOCATE_TRY); if (bTryLastBB != NULL) { result = true; movedTry = true; } } #if DEBUG if (verbose && movedTry) { printf("\nAfter relocating an EH try region"); fgDispBasicBlocks(); fgDispHandlerTab(); // Make sure that the predecessor lists are accurate if (expensiveDebugCheckLevel >= 2) { fgDebugCheckBBlist(); } } #endif // DEBUG } // Currently it is not good to move the rarely run handler regions to the end of the method // because fgDetermineFirstColdBlock() must put the start of any handler region in the hot // section. CLANG_FORMAT_COMMENT_ANCHOR; #if 0 // Now try to move the entire handler region if it can be moved. // Don't try to move a finally handler unless we already moved the try region. if (HBtab->ebdHndBeg->isRunRarely() && !HBtab->ebdHndBeg->hasTryIndex() && (movedTry || !HBtab->HasFinallyHandler())) { BasicBlock* bHndLastBB = fgRelocateEHRange(XTnum, FG_RELOCATE_HANDLER); if (bHndLastBB != NULL) { result = true; movedHnd = true; } } #endif // 0 #if DEBUG if (verbose && movedHnd) { printf("\nAfter relocating an EH handler region"); fgDispBasicBlocks(); fgDispHandlerTab(); // Make sure that the predecessor lists are accurate if (expensiveDebugCheckLevel >= 2) { fgDebugCheckBBlist(); } } #endif // DEBUG } } } #if DEBUG fgVerifyHandlerTab(); if (verbose && result) { printf("\nAfter fgRelocateEHRegions()"); fgDispBasicBlocks(); fgDispHandlerTab(); // Make sure that the predecessor lists are accurate fgDebugCheckBBlist(); } #endif // DEBUG return result; } #endif // !FEATURE_EH_FUNCLETS bool flowList::setEdgeWeightMinChecked(BasicBlock::weight_t newWeight, BasicBlock::weight_t slop, bool* wbUsedSlop) { bool result = false; if ((newWeight <= flEdgeWeightMax) && (newWeight >= flEdgeWeightMin)) { flEdgeWeightMin = newWeight; result = true; } else if (slop > 0) { // We allow for a small amount of inaccuracy in block weight counts. if (flEdgeWeightMax < newWeight) { // We have already determined that this edge's weight // is less than newWeight, so we just allow for the slop if (newWeight <= (flEdgeWeightMax + slop)) { result = true; if (flEdgeWeightMax != 0) { // We will raise flEdgeWeightMin and Max towards newWeight flEdgeWeightMin = flEdgeWeightMax; flEdgeWeightMax = newWeight; } if (wbUsedSlop != nullptr) { *wbUsedSlop = true; } } } else { assert(flEdgeWeightMin > newWeight); // We have already determined that this edge's weight // is more than newWeight, so we just allow for the slop if ((newWeight + slop) >= flEdgeWeightMin) { result = true; assert(flEdgeWeightMax != 0); // We will lower flEdgeWeightMin towards newWeight flEdgeWeightMin = newWeight; if (wbUsedSlop != nullptr) { *wbUsedSlop = true; } } } // If we are returning true then we should have adjusted the range so that // the newWeight is in new range [Min..Max] or fgEdjeWeightMax is zero. // Also we should have set wbUsedSlop to true. if (result == true) { assert((flEdgeWeightMax == 0) || ((newWeight <= flEdgeWeightMax) && (newWeight >= flEdgeWeightMin))); if (wbUsedSlop != nullptr) { assert(*wbUsedSlop == true); } } } #if DEBUG if (result == false) { result = false; // break here } #endif // DEBUG return result; } bool flowList::setEdgeWeightMaxChecked(BasicBlock::weight_t newWeight, BasicBlock::weight_t slop, bool* wbUsedSlop) { bool result = false; if ((newWeight >= flEdgeWeightMin) && (newWeight <= flEdgeWeightMax)) { flEdgeWeightMax = newWeight; result = true; } else if (slop > 0) { // We allow for a small amount of inaccuracy in block weight counts. if (flEdgeWeightMax < newWeight) { // We have already determined that this edge's weight // is less than newWeight, so we just allow for the slop if (newWeight <= (flEdgeWeightMax + slop)) { result = true; if (flEdgeWeightMax != 0) { // We will allow this to raise flEdgeWeightMax towards newWeight flEdgeWeightMax = newWeight; } if (wbUsedSlop != nullptr) { *wbUsedSlop = true; } } } else { assert(flEdgeWeightMin > newWeight); // We have already determined that this edge's weight // is more than newWeight, so we just allow for the slop if ((newWeight + slop) >= flEdgeWeightMin) { result = true; assert(flEdgeWeightMax != 0); // We will allow this to lower flEdgeWeightMin and Max towards newWeight flEdgeWeightMax = flEdgeWeightMin; flEdgeWeightMin = newWeight; if (wbUsedSlop != nullptr) { *wbUsedSlop = true; } } } // If we are returning true then we should have adjusted the range so that // the newWeight is in new range [Min..Max] or fgEdjeWeightMax is zero // Also we should have set wbUsedSlop to true, unless it is NULL if (result == true) { assert((flEdgeWeightMax == 0) || ((newWeight <= flEdgeWeightMax) && (newWeight >= flEdgeWeightMin))); assert((wbUsedSlop == nullptr) || (*wbUsedSlop == true)); } } #if DEBUG if (result == false) { result = false; // break here } #endif // DEBUG return result; } #ifdef DEBUG void Compiler::fgPrintEdgeWeights() { BasicBlock* bSrc; BasicBlock* bDst; flowList* edge; // Print out all of the edge weights for (bDst = fgFirstBB; bDst != nullptr; bDst = bDst->bbNext) { if (bDst->bbPreds != nullptr) { printf(" Edge weights into " FMT_BB " :", bDst->bbNum); for (edge = bDst->bbPreds; edge != nullptr; edge = edge->flNext) { bSrc = edge->flBlock; // This is the control flow edge (bSrc -> bDst) printf(FMT_BB " ", bSrc->bbNum); if (edge->flEdgeWeightMin < BB_MAX_WEIGHT) { printf("(%u", edge->flEdgeWeightMin); } else { printf("(MAX"); } if (edge->flEdgeWeightMin != edge->flEdgeWeightMax) { if (edge->flEdgeWeightMax < BB_MAX_WEIGHT) { printf("..%u", edge->flEdgeWeightMax); } else { printf("..MAX"); } } printf(")"); if (edge->flNext != nullptr) { printf(", "); } } printf("\n"); } } } #endif // DEBUG // return true if there is a possibility that the method has a loop (a backedge is present) bool Compiler::fgMightHaveLoop() { // Don't use a BlockSet for this temporary bitset of blocks: we don't want to have to call EnsureBasicBlockEpoch() // and potentially change the block epoch. BitVecTraits blockVecTraits(fgBBNumMax + 1, this); BitVec blocksSeen(BitVecOps::MakeEmpty(&blockVecTraits)); for (BasicBlock* block = fgFirstBB; block; block = block->bbNext) { BitVecOps::AddElemD(&blockVecTraits, blocksSeen, block->bbNum); for (BasicBlock* succ : block->GetAllSuccs(this)) { if (BitVecOps::IsMember(&blockVecTraits, blocksSeen, succ->bbNum)) { return true; } } } return false; } //------------------------------------------------------------- // fgComputeBlockAndEdgeWeights: determine weights for blocks // and optionally for edges // void Compiler::fgComputeBlockAndEdgeWeights() { JITDUMP("*************** In fgComputeBlockAndEdgeWeights()\n"); const bool usingProfileWeights = fgIsUsingProfileWeights(); const bool isOptimizing = opts.OptimizationEnabled(); fgHaveValidEdgeWeights = false; fgCalledCount = BB_UNITY_WEIGHT; #if DEBUG if (verbose) { fgDispBasicBlocks(); printf("\n"); } #endif // DEBUG const BasicBlock::weight_t returnWeight = fgComputeMissingBlockWeights(); if (usingProfileWeights) { fgComputeCalledCount(returnWeight); } else { JITDUMP(" -- no profile data, so using default called count\n"); } if (isOptimizing) { fgComputeEdgeWeights(); } else { JITDUMP(" -- not optimizing, so not computing edge weights\n"); } } //------------------------------------------------------------- // fgComputeMissingBlockWeights: determine weights for blocks // that were not profiled and do not yet have weights. // // Returns: // sum of weights for all return and throw blocks in the method BasicBlock::weight_t Compiler::fgComputeMissingBlockWeights() { BasicBlock* bSrc; BasicBlock* bDst; unsigned iterations = 0; bool changed; bool modified = false; BasicBlock::weight_t returnWeight; // If we have any blocks that did not have profile derived weight // we will try to fix their weight up here // modified = false; do // while (changed) { changed = false; returnWeight = 0; iterations++; for (bDst = fgFirstBB; bDst != nullptr; bDst = bDst->bbNext) { if (!bDst->hasProfileWeight() && (bDst->bbPreds != nullptr)) { BasicBlock* bOnlyNext; // This block does not have a profile derived weight // BasicBlock::weight_t newWeight = BB_MAX_WEIGHT; if (bDst->countOfInEdges() == 1) { // Only one block flows into bDst bSrc = bDst->bbPreds->flBlock; // Does this block flow into only one other block if (bSrc->bbJumpKind == BBJ_NONE) { bOnlyNext = bSrc->bbNext; } else if (bSrc->bbJumpKind == BBJ_ALWAYS) { bOnlyNext = bSrc->bbJumpDest; } else { bOnlyNext = nullptr; } if ((bOnlyNext == bDst) && bSrc->hasProfileWeight()) { // We know the exact weight of bDst newWeight = bSrc->bbWeight; } } // Does this block flow into only one other block if (bDst->bbJumpKind == BBJ_NONE) { bOnlyNext = bDst->bbNext; } else if (bDst->bbJumpKind == BBJ_ALWAYS) { bOnlyNext = bDst->bbJumpDest; } else { bOnlyNext = nullptr; } if ((bOnlyNext != nullptr) && (bOnlyNext->bbPreds != nullptr)) { // Does only one block flow into bOnlyNext if (bOnlyNext->countOfInEdges() == 1) { noway_assert(bOnlyNext->bbPreds->flBlock == bDst); // We know the exact weight of bDst newWeight = bOnlyNext->bbWeight; } } if ((newWeight != BB_MAX_WEIGHT) && (bDst->bbWeight != newWeight)) { changed = true; modified = true; bDst->bbWeight = newWeight; if (newWeight == 0) { bDst->bbFlags |= BBF_RUN_RARELY; } else { bDst->bbFlags &= ~BBF_RUN_RARELY; } } } // Sum up the weights of all of the return blocks and throw blocks // This is used when we have a back-edge into block 1 // if (bDst->hasProfileWeight() && ((bDst->bbJumpKind == BBJ_RETURN) || (bDst->bbJumpKind == BBJ_THROW))) { returnWeight += bDst->bbWeight; } } } // Generally when we synthesize profile estimates we do it in a way where this algorithm will converge // but downstream opts that remove conditional branches may create a situation where this is not the case. // For instance a loop that becomes unreachable creates a sort of 'ring oscillator' (See test b539509) while (changed && iterations < 10); #if DEBUG if (verbose && modified) { printf("fgComputeMissingBlockWeights() adjusted the weight of some blocks\n"); fgDispBasicBlocks(); printf("\n"); } #endif return returnWeight; } //------------------------------------------------------------- // fgComputeCalledCount: when profile information is in use, // compute fgCalledCount // // Argument: // returnWeight - sum of weights for all return and throw blocks void Compiler::fgComputeCalledCount(BasicBlock::weight_t returnWeight) { // When we are not using profile data we have already setup fgCalledCount // only set it here if we are using profile data assert(fgIsUsingProfileWeights()); BasicBlock* firstILBlock = fgFirstBB; // The first block for IL code (i.e. for the IL code at offset 0) // Do we have an internal block as our first Block? if (firstILBlock->bbFlags & BBF_INTERNAL) { // Skip past any/all BBF_INTERNAL blocks that may have been added before the first real IL block. // while (firstILBlock->bbFlags & BBF_INTERNAL) { firstILBlock = firstILBlock->bbNext; } // The 'firstILBlock' is now expected to have a profile-derived weight assert(firstILBlock->hasProfileWeight()); } // If the first block only has one ref then we use it's weight for fgCalledCount. // Otherwise we have backedge's into the first block, so instead we use the sum // of the return block weights for fgCalledCount. // // If the profile data has a 0 for the returnWeight // (i.e. the function never returns because it always throws) // then just use the first block weight rather than 0. // if ((firstILBlock->countOfInEdges() == 1) || (returnWeight == 0)) { assert(firstILBlock->hasProfileWeight()); // This should always be a profile-derived weight fgCalledCount = firstILBlock->bbWeight; } else { fgCalledCount = returnWeight; } // If we allocated a scratch block as the first BB then we need // to set its profile-derived weight to be fgCalledCount if (fgFirstBBisScratch()) { fgFirstBB->setBBProfileWeight(fgCalledCount); if (fgFirstBB->bbWeight == 0) { fgFirstBB->bbFlags |= BBF_RUN_RARELY; } } #if DEBUG if (verbose) { printf("We are using the Profile Weights and fgCalledCount is %d.\n", fgCalledCount); } #endif } //------------------------------------------------------------- // fgComputeEdgeWeights: compute edge weights from block weights void Compiler::fgComputeEdgeWeights() { BasicBlock* bSrc; BasicBlock* bDst; flowList* edge; BasicBlock::weight_t slop; unsigned goodEdgeCountCurrent = 0; unsigned goodEdgeCountPrevious = 0; bool inconsistentProfileData = false; bool hasIncompleteEdgeWeights = false; bool usedSlop = false; unsigned numEdges = 0; unsigned iterations = 0; // Now we will compute the initial flEdgeWeightMin and flEdgeWeightMax values for (bDst = fgFirstBB; bDst != nullptr; bDst = bDst->bbNext) { BasicBlock::weight_t bDstWeight = bDst->bbWeight; // We subtract out the called count so that bDstWeight is // the sum of all edges that go into this block from this method. // if (bDst == fgFirstBB) { bDstWeight -= fgCalledCount; } for (edge = bDst->bbPreds; edge != nullptr; edge = edge->flNext) { bool assignOK = true; bSrc = edge->flBlock; // We are processing the control flow edge (bSrc -> bDst) numEdges++; // // If the bSrc or bDst blocks do not have exact profile weights // then we must reset any values that they currently have // if (!bSrc->hasProfileWeight() || !bDst->hasProfileWeight()) { edge->flEdgeWeightMin = BB_ZERO_WEIGHT; edge->flEdgeWeightMax = BB_MAX_WEIGHT; } slop = BasicBlock::GetSlopFraction(bSrc, bDst) + 1; switch (bSrc->bbJumpKind) { case BBJ_ALWAYS: case BBJ_EHCATCHRET: case BBJ_NONE: case BBJ_CALLFINALLY: // We know the exact edge weight assignOK &= edge->setEdgeWeightMinChecked(bSrc->bbWeight, slop, &usedSlop); assignOK &= edge->setEdgeWeightMaxChecked(bSrc->bbWeight, slop, &usedSlop); break; case BBJ_COND: case BBJ_SWITCH: case BBJ_EHFINALLYRET: case BBJ_EHFILTERRET: if (edge->flEdgeWeightMax > bSrc->bbWeight) { // The maximum edge weight to block can't be greater than the weight of bSrc assignOK &= edge->setEdgeWeightMaxChecked(bSrc->bbWeight, slop, &usedSlop); } break; default: // We should never have an edge that starts from one of these jump kinds noway_assert(!"Unexpected bbJumpKind"); break; } // The maximum edge weight to block can't be greater than the weight of bDst if (edge->flEdgeWeightMax > bDstWeight) { assignOK &= edge->setEdgeWeightMaxChecked(bDstWeight, slop, &usedSlop); } if (!assignOK) { // Here we have inconsistent profile data inconsistentProfileData = true; // No point in continuing goto EARLY_EXIT; } } } fgEdgeCount = numEdges; iterations = 0; do { iterations++; goodEdgeCountPrevious = goodEdgeCountCurrent; goodEdgeCountCurrent = 0; hasIncompleteEdgeWeights = false; for (bDst = fgFirstBB; bDst != nullptr; bDst = bDst->bbNext) { for (edge = bDst->bbPreds; edge != nullptr; edge = edge->flNext) { bool assignOK = true; // We are processing the control flow edge (bSrc -> bDst) bSrc = edge->flBlock; slop = BasicBlock::GetSlopFraction(bSrc, bDst) + 1; if (bSrc->bbJumpKind == BBJ_COND) { int diff; flowList* otherEdge; if (bSrc->bbNext == bDst) { otherEdge = fgGetPredForBlock(bSrc->bbJumpDest, bSrc); } else { otherEdge = fgGetPredForBlock(bSrc->bbNext, bSrc); } noway_assert(edge->flEdgeWeightMin <= edge->flEdgeWeightMax); noway_assert(otherEdge->flEdgeWeightMin <= otherEdge->flEdgeWeightMax); // Adjust edge->flEdgeWeightMin up or adjust otherEdge->flEdgeWeightMax down diff = ((int)bSrc->bbWeight) - ((int)edge->flEdgeWeightMin + (int)otherEdge->flEdgeWeightMax); if (diff > 0) { assignOK &= edge->setEdgeWeightMinChecked(edge->flEdgeWeightMin + diff, slop, &usedSlop); } else if (diff < 0) { assignOK &= otherEdge->setEdgeWeightMaxChecked(otherEdge->flEdgeWeightMax + diff, slop, &usedSlop); } // Adjust otherEdge->flEdgeWeightMin up or adjust edge->flEdgeWeightMax down diff = ((int)bSrc->bbWeight) - ((int)otherEdge->flEdgeWeightMin + (int)edge->flEdgeWeightMax); if (diff > 0) { assignOK &= otherEdge->setEdgeWeightMinChecked(otherEdge->flEdgeWeightMin + diff, slop, &usedSlop); } else if (diff < 0) { assignOK &= edge->setEdgeWeightMaxChecked(edge->flEdgeWeightMax + diff, slop, &usedSlop); } if (!assignOK) { // Here we have inconsistent profile data inconsistentProfileData = true; // No point in continuing goto EARLY_EXIT; } #ifdef DEBUG // Now edge->flEdgeWeightMin and otherEdge->flEdgeWeightMax) should add up to bSrc->bbWeight diff = ((int)bSrc->bbWeight) - ((int)edge->flEdgeWeightMin + (int)otherEdge->flEdgeWeightMax); noway_assert((-((int)slop) <= diff) && (diff <= ((int)slop))); // Now otherEdge->flEdgeWeightMin and edge->flEdgeWeightMax) should add up to bSrc->bbWeight diff = ((int)bSrc->bbWeight) - ((int)otherEdge->flEdgeWeightMin + (int)edge->flEdgeWeightMax); noway_assert((-((int)slop) <= diff) && (diff <= ((int)slop))); #endif // DEBUG } } } for (bDst = fgFirstBB; bDst != nullptr; bDst = bDst->bbNext) { BasicBlock::weight_t bDstWeight = bDst->bbWeight; if (bDstWeight == BB_MAX_WEIGHT) { inconsistentProfileData = true; // No point in continuing goto EARLY_EXIT; } else { // We subtract out the called count so that bDstWeight is // the sum of all edges that go into this block from this method. // if (bDst == fgFirstBB) { bDstWeight -= fgCalledCount; } UINT64 minEdgeWeightSum = 0; UINT64 maxEdgeWeightSum = 0; // Calculate the sums of the minimum and maximum edge weights for (edge = bDst->bbPreds; edge != nullptr; edge = edge->flNext) { // We are processing the control flow edge (bSrc -> bDst) bSrc = edge->flBlock; maxEdgeWeightSum += edge->flEdgeWeightMax; minEdgeWeightSum += edge->flEdgeWeightMin; } // maxEdgeWeightSum is the sum of all flEdgeWeightMax values into bDst // minEdgeWeightSum is the sum of all flEdgeWeightMin values into bDst for (edge = bDst->bbPreds; edge != nullptr; edge = edge->flNext) { bool assignOK = true; // We are processing the control flow edge (bSrc -> bDst) bSrc = edge->flBlock; slop = BasicBlock::GetSlopFraction(bSrc, bDst) + 1; // otherMaxEdgesWeightSum is the sum of all of the other edges flEdgeWeightMax values // This can be used to compute a lower bound for our minimum edge weight noway_assert(maxEdgeWeightSum >= edge->flEdgeWeightMax); UINT64 otherMaxEdgesWeightSum = maxEdgeWeightSum - edge->flEdgeWeightMax; // otherMinEdgesWeightSum is the sum of all of the other edges flEdgeWeightMin values // This can be used to compute an upper bound for our maximum edge weight noway_assert(minEdgeWeightSum >= edge->flEdgeWeightMin); UINT64 otherMinEdgesWeightSum = minEdgeWeightSum - edge->flEdgeWeightMin; if (bDstWeight >= otherMaxEdgesWeightSum) { // minWeightCalc is our minWeight when every other path to bDst takes it's flEdgeWeightMax value BasicBlock::weight_t minWeightCalc = (BasicBlock::weight_t)(bDstWeight - otherMaxEdgesWeightSum); if (minWeightCalc > edge->flEdgeWeightMin) { assignOK &= edge->setEdgeWeightMinChecked(minWeightCalc, slop, &usedSlop); } } if (bDstWeight >= otherMinEdgesWeightSum) { // maxWeightCalc is our maxWeight when every other path to bDst takes it's flEdgeWeightMin value BasicBlock::weight_t maxWeightCalc = (BasicBlock::weight_t)(bDstWeight - otherMinEdgesWeightSum); if (maxWeightCalc < edge->flEdgeWeightMax) { assignOK &= edge->setEdgeWeightMaxChecked(maxWeightCalc, slop, &usedSlop); } } if (!assignOK) { // Here we have inconsistent profile data inconsistentProfileData = true; // No point in continuing goto EARLY_EXIT; } // When flEdgeWeightMin equals flEdgeWeightMax we have a "good" edge weight if (edge->flEdgeWeightMin == edge->flEdgeWeightMax) { // Count how many "good" edge weights we have // Each time through we should have more "good" weights // We exit the while loop when no longer find any new "good" edges goodEdgeCountCurrent++; } else { // Remember that we have seen at least one "Bad" edge weight // so that we will repeat the while loop again hasIncompleteEdgeWeights = true; } } } } if (inconsistentProfileData) { hasIncompleteEdgeWeights = true; break; } if (numEdges == goodEdgeCountCurrent) { noway_assert(hasIncompleteEdgeWeights == false); break; } } while (hasIncompleteEdgeWeights && (goodEdgeCountCurrent > goodEdgeCountPrevious) && (iterations < 8)); EARLY_EXIT:; #ifdef DEBUG if (verbose) { if (inconsistentProfileData) { printf("fgComputeEdgeWeights() found inconsistent profile data, not using the edge weights\n"); } else { if (hasIncompleteEdgeWeights) { printf("fgComputeEdgeWeights() was able to compute exact edge weights for %3d of the %3d edges, using " "%d passes.\n", goodEdgeCountCurrent, numEdges, iterations); } else { printf("fgComputeEdgeWeights() was able to compute exact edge weights for all of the %3d edges, using " "%d passes.\n", numEdges, iterations); } fgPrintEdgeWeights(); } } #endif // DEBUG fgSlopUsedInEdgeWeights = usedSlop; fgRangeUsedInEdgeWeights = false; // See if any edge weight are expressed in [min..max] form for (bDst = fgFirstBB; bDst != nullptr; bDst = bDst->bbNext) { if (bDst->bbPreds != nullptr) { for (edge = bDst->bbPreds; edge != nullptr; edge = edge->flNext) { bSrc = edge->flBlock; // This is the control flow edge (bSrc -> bDst) if (edge->flEdgeWeightMin != edge->flEdgeWeightMax) { fgRangeUsedInEdgeWeights = true; break; } } if (fgRangeUsedInEdgeWeights) { break; } } } fgHaveValidEdgeWeights = !inconsistentProfileData; fgEdgeWeightsComputed = true; } // fgOptimizeBranchToEmptyUnconditional: // optimize a jump to an empty block which ends in an unconditional branch. // Args: // block: source block // bDest: destination // Returns: true if we changed the code // bool Compiler::fgOptimizeBranchToEmptyUnconditional(BasicBlock* block, BasicBlock* bDest) { bool optimizeJump = true; assert(bDest->isEmpty()); assert(bDest->bbJumpKind == BBJ_ALWAYS); // We do not optimize jumps between two different try regions. // However jumping to a block that is not in any try region is OK // if (bDest->hasTryIndex() && !BasicBlock::sameTryRegion(block, bDest)) { optimizeJump = false; } // Don't optimize a jump to a removed block if (bDest->bbJumpDest->bbFlags & BBF_REMOVED) { optimizeJump = false; } // Don't optimize a jump to a cloned finally if (bDest->bbFlags & BBF_CLONED_FINALLY_BEGIN) { optimizeJump = false; } #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) // Don't optimize a jump to a finally target. For BB1->BB2->BB3, where // BB2 is a finally target, if we changed BB1 to jump directly to BB3, // it would skip the finally target. BB1 might be a BBJ_ALWAYS block part // of a BBJ_CALLFINALLY/BBJ_ALWAYS pair, so changing the finally target // would change the unwind behavior. if (bDest->bbFlags & BBF_FINALLY_TARGET) { optimizeJump = false; } #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) // Must optimize jump if bDest has been removed // if (bDest->bbFlags & BBF_REMOVED) { optimizeJump = true; } // If we are optimizing using real profile weights // then don't optimize a conditional jump to an unconditional jump // until after we have computed the edge weights // if (fgIsUsingProfileWeights() && !fgEdgeWeightsComputed) { fgNeedsUpdateFlowGraph = true; optimizeJump = false; } if (optimizeJump) { #ifdef DEBUG if (verbose) { printf("\nOptimizing a jump to an unconditional jump (" FMT_BB " -> " FMT_BB " -> " FMT_BB ")\n", block->bbNum, bDest->bbNum, bDest->bbJumpDest->bbNum); } #endif // DEBUG // // When we optimize a branch to branch we need to update the profile weight // of bDest by subtracting out the block/edge weight of the path that is being optimized. // if (fgHaveValidEdgeWeights && bDest->hasProfileWeight()) { flowList* edge1 = fgGetPredForBlock(bDest, block); noway_assert(edge1 != nullptr); BasicBlock::weight_t edgeWeight; if (edge1->flEdgeWeightMin != edge1->flEdgeWeightMax) { // // We only have an estimate for the edge weight // edgeWeight = (edge1->flEdgeWeightMin + edge1->flEdgeWeightMax) / 2; // // Clear the profile weight flag // bDest->bbFlags &= ~BBF_PROF_WEIGHT; } else { // // We only have the exact edge weight // edgeWeight = edge1->flEdgeWeightMin; } // // Update the bDest->bbWeight // if (bDest->bbWeight > edgeWeight) { bDest->bbWeight -= edgeWeight; } else { bDest->bbWeight = BB_ZERO_WEIGHT; bDest->bbFlags |= BBF_RUN_RARELY; // Set the RarelyRun flag } flowList* edge2 = fgGetPredForBlock(bDest->bbJumpDest, bDest); if (edge2 != nullptr) { // // Update the edge2 min/max weights // if (edge2->flEdgeWeightMin > edge1->flEdgeWeightMin) { edge2->flEdgeWeightMin -= edge1->flEdgeWeightMin; } else { edge2->flEdgeWeightMin = BB_ZERO_WEIGHT; } if (edge2->flEdgeWeightMax > edge1->flEdgeWeightMin) { edge2->flEdgeWeightMax -= edge1->flEdgeWeightMin; } else { edge2->flEdgeWeightMax = BB_ZERO_WEIGHT; } } } // Optimize the JUMP to empty unconditional JUMP to go to the new target block->bbJumpDest = bDest->bbJumpDest; fgAddRefPred(bDest->bbJumpDest, block, fgRemoveRefPred(bDest, block)); return true; } return false; } // fgOptimizeEmptyBlock: // Does flow optimization of an empty block (can remove it in some cases) // // Args: // block: an empty block // Returns: true if we changed the code bool Compiler::fgOptimizeEmptyBlock(BasicBlock* block) { assert(block->isEmpty()); BasicBlock* bPrev = block->bbPrev; switch (block->bbJumpKind) { case BBJ_COND: case BBJ_SWITCH: case BBJ_THROW: /* can never happen */ noway_assert(!"Conditional, switch, or throw block with empty body!"); break; case BBJ_CALLFINALLY: case BBJ_RETURN: case BBJ_EHCATCHRET: case BBJ_EHFINALLYRET: case BBJ_EHFILTERRET: /* leave them as is */ /* some compilers generate multiple returns and put all of them at the end - * to solve that we need the predecessor list */ break; case BBJ_ALWAYS: // A GOTO cannot be to the next block since that // should have been fixed by the optimization above // An exception is made for a jump from Hot to Cold noway_assert(block->bbJumpDest != block->bbNext || ((bPrev != nullptr) && bPrev->isBBCallAlwaysPair()) || fgInDifferentRegions(block, block->bbNext)); /* Cannot remove the first BB */ if (!bPrev) { break; } /* Do not remove a block that jumps to itself - used for while (true){} */ if (block->bbJumpDest == block) { break; } /* Empty GOTO can be removed iff bPrev is BBJ_NONE */ if (bPrev->bbJumpKind != BBJ_NONE) { break; } // can't allow fall through into cold code if (block->bbNext == fgFirstColdBlock) { break; } /* Can fall through since this is similar with removing * a BBJ_NONE block, only the successor is different */ __fallthrough; case BBJ_NONE: /* special case if this is the first BB */ if (!bPrev) { assert(block == fgFirstBB); } else { /* If this block follows a BBJ_CALLFINALLY do not remove it * (because we don't know who may jump to it) */ if (bPrev->bbJumpKind == BBJ_CALLFINALLY) { break; } } #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) /* Don't remove finally targets */ if (block->bbFlags & BBF_FINALLY_TARGET) break; #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) #if FEATURE_EH_FUNCLETS /* Don't remove an empty block that is in a different EH region * from its successor block, if the block is the target of a * catch return. It is required that the return address of a * catch be in the correct EH region, for re-raise of thread * abort exceptions to work. Insert a NOP in the empty block * to ensure we generate code for the block, if we keep it. */ { BasicBlock* succBlock; if (block->bbJumpKind == BBJ_ALWAYS) { succBlock = block->bbJumpDest; } else { succBlock = block->bbNext; } if ((succBlock != nullptr) && !BasicBlock::sameEHRegion(block, succBlock)) { // The empty block and the block that follows it are in different // EH regions. Is this a case where they can't be merged? bool okToMerge = true; // assume it's ok for (flowList* pred = block->bbPreds; pred; pred = pred->flNext) { if (pred->flBlock->bbJumpKind == BBJ_EHCATCHRET) { assert(pred->flBlock->bbJumpDest == block); okToMerge = false; // we can't get rid of the empty block break; } } if (!okToMerge) { // Insert a NOP in the empty block to ensure we generate code // for the catchret target in the right EH region. GenTree* nop = new (this, GT_NO_OP) GenTree(GT_NO_OP, TYP_VOID); if (block->IsLIR()) { LIR::AsRange(block).InsertAtEnd(nop); LIR::ReadOnlyRange range(nop, nop); m_pLowering->LowerRange(block, range); } else { GenTreeStmt* nopStmt = fgInsertStmtAtEnd(block, nop); fgSetStmtSeq(nopStmt); gtSetStmtInfo(nopStmt); } #ifdef DEBUG if (verbose) { printf("\nKeeping empty block " FMT_BB " - it is the target of a catch return\n", block->bbNum); } #endif // DEBUG break; // go to the next block } } } #endif // FEATURE_EH_FUNCLETS if (!ehCanDeleteEmptyBlock(block)) { // We're not allowed to remove this block due to reasons related to the EH table. break; } /* special case if this is the last BB */ if (block == fgLastBB) { if (!bPrev) { break; } fgLastBB = bPrev; } // When using profile weights, fgComputeEdgeWeights expects the first non-internal block to have profile // weight. // Make sure we don't break that invariant. if (fgIsUsingProfileWeights() && block->hasProfileWeight() && (block->bbFlags & BBF_INTERNAL) == 0) { BasicBlock* bNext = block->bbNext; // Check if the next block can't maintain the invariant. if ((bNext == nullptr) || ((bNext->bbFlags & BBF_INTERNAL) != 0) || !bNext->hasProfileWeight()) { // Check if the current block is the first non-internal block. BasicBlock* curBB = bPrev; while ((curBB != nullptr) && (curBB->bbFlags & BBF_INTERNAL) != 0) { curBB = curBB->bbPrev; } if (curBB == nullptr) { // This block is the first non-internal block and it has profile weight. // Don't delete it. break; } } } /* Remove the block */ compCurBB = block; fgRemoveBlock(block, false); return true; default: noway_assert(!"Unexpected bbJumpKind"); break; } return false; } // fgOptimizeSwitchBranches: // Does flow optimization for a switch - bypasses jumps to empty unconditional branches, // and transforms degenerate switch cases like those with 1 or 2 targets // // Args: // block: BasicBlock that contains the switch // Returns: true if we changed the code // bool Compiler::fgOptimizeSwitchBranches(BasicBlock* block) { assert(block->bbJumpKind == BBJ_SWITCH); unsigned jmpCnt = block->bbJumpSwt->bbsCount; BasicBlock** jmpTab = block->bbJumpSwt->bbsDstTab; BasicBlock* bNewDest; // the new jump target for the current switch case BasicBlock* bDest; bool returnvalue = false; do { REPEAT_SWITCH:; bDest = *jmpTab; bNewDest = bDest; // Do we have a JUMP to an empty unconditional JUMP block? if (bDest->isEmpty() && (bDest->bbJumpKind == BBJ_ALWAYS) && (bDest != bDest->bbJumpDest)) // special case for self jumps { bool optimizeJump = true; // We do not optimize jumps between two different try regions. // However jumping to a block that is not in any try region is OK // if (bDest->hasTryIndex() && !BasicBlock::sameTryRegion(block, bDest)) { optimizeJump = false; } // If we are optimize using real profile weights // then don't optimize a switch jump to an unconditional jump // until after we have computed the edge weights // if (fgIsUsingProfileWeights() && !fgEdgeWeightsComputed) { fgNeedsUpdateFlowGraph = true; optimizeJump = false; } if (optimizeJump) { bNewDest = bDest->bbJumpDest; #ifdef DEBUG if (verbose) { printf("\nOptimizing a switch jump to an empty block with an unconditional jump (" FMT_BB " -> " FMT_BB " " "-> " FMT_BB ")\n", block->bbNum, bDest->bbNum, bNewDest->bbNum); } #endif // DEBUG } } if (bNewDest != bDest) { // // When we optimize a branch to branch we need to update the profile weight // of bDest by subtracting out the block/edge weight of the path that is being optimized. // if (fgIsUsingProfileWeights() && bDest->hasProfileWeight()) { if (fgHaveValidEdgeWeights) { flowList* edge = fgGetPredForBlock(bDest, block); BasicBlock::weight_t branchThroughWeight = edge->flEdgeWeightMin; if (bDest->bbWeight > branchThroughWeight) { bDest->bbWeight -= branchThroughWeight; } else { bDest->bbWeight = BB_ZERO_WEIGHT; bDest->bbFlags |= BBF_RUN_RARELY; } } } // Update the switch jump table *jmpTab = bNewDest; // Maintain, if necessary, the set of unique targets of "block." UpdateSwitchTableTarget(block, bDest, bNewDest); fgAddRefPred(bNewDest, block, fgRemoveRefPred(bDest, block)); // we optimized a Switch label - goto REPEAT_SWITCH to follow this new jump returnvalue = true; goto REPEAT_SWITCH; } } while (++jmpTab, --jmpCnt); GenTreeStmt* switchStmt = nullptr; LIR::Range* blockRange = nullptr; GenTree* switchTree; if (block->IsLIR()) { blockRange = &LIR::AsRange(block); switchTree = blockRange->LastNode(); assert(switchTree->OperGet() == GT_SWITCH_TABLE); } else { switchStmt = block->lastStmt(); switchTree = switchStmt->gtStmtExpr; assert(switchTree->OperGet() == GT_SWITCH); } noway_assert(switchTree->gtType == TYP_VOID); // At this point all of the case jump targets have been updated such // that none of them go to block that is an empty unconditional block // jmpTab = block->bbJumpSwt->bbsDstTab; jmpCnt = block->bbJumpSwt->bbsCount; // Now check for two trivial switch jumps. // if (block->NumSucc(this) == 1) { // Use BBJ_ALWAYS for a switch with only a default clause, or with only one unique successor. BasicBlock* uniqueSucc = jmpTab[0]; #ifdef DEBUG if (verbose) { printf("\nRemoving a switch jump with a single target (" FMT_BB ")\n", block->bbNum); printf("BEFORE:\n"); } #endif // DEBUG if (block->IsLIR()) { bool isClosed; unsigned sideEffects; LIR::ReadOnlyRange switchTreeRange = blockRange->GetTreeRange(switchTree, &isClosed, &sideEffects); // The switch tree should form a contiguous, side-effect free range by construction. See // Lowering::LowerSwitch for details. assert(isClosed); assert((sideEffects & GTF_ALL_EFFECT) == 0); blockRange->Delete(this, block, std::move(switchTreeRange)); } else { /* check for SIDE_EFFECTS */ if (switchTree->gtFlags & GTF_SIDE_EFFECT) { /* Extract the side effects from the conditional */ GenTree* sideEffList = nullptr; gtExtractSideEffList(switchTree, &sideEffList); if (sideEffList == nullptr) { goto NO_SWITCH_SIDE_EFFECT; } noway_assert(sideEffList->gtFlags & GTF_SIDE_EFFECT); #ifdef DEBUG if (verbose) { printf("\nSwitch expression has side effects! Extracting side effects...\n"); gtDispTree(switchTree); printf("\n"); gtDispTree(sideEffList); printf("\n"); } #endif // DEBUG /* Replace the conditional statement with the list of side effects */ noway_assert(sideEffList->gtOper != GT_STMT); noway_assert(sideEffList->gtOper != GT_SWITCH); switchStmt->gtStmtExpr = sideEffList; if (fgStmtListThreaded) { compCurBB = block; /* Update ordering, costs, FP levels, etc. */ gtSetStmtInfo(switchStmt); /* Re-link the nodes for this statement */ fgSetStmtSeq(switchStmt); } } else { NO_SWITCH_SIDE_EFFECT: /* conditional has NO side effect - remove it */ fgRemoveStmt(block, switchStmt); } } // Change the switch jump into a BBJ_ALWAYS block->bbJumpDest = block->bbJumpSwt->bbsDstTab[0]; block->bbJumpKind = BBJ_ALWAYS; if (jmpCnt > 1) { for (unsigned i = 1; i < jmpCnt; ++i) { (void)fgRemoveRefPred(jmpTab[i], block); } } return true; } else if (block->bbJumpSwt->bbsCount == 2 && block->bbJumpSwt->bbsDstTab[1] == block->bbNext) { /* Use a BBJ_COND(switchVal==0) for a switch with only one significant clause besides the default clause, if the default clause is bbNext */ GenTree* switchVal = switchTree->gtOp.gtOp1; noway_assert(genActualTypeIsIntOrI(switchVal->TypeGet())); // If we are in LIR, remove the jump table from the block. if (block->IsLIR()) { GenTree* jumpTable = switchTree->gtOp.gtOp2; assert(jumpTable->OperGet() == GT_JMPTABLE); blockRange->Remove(jumpTable); } // Change the GT_SWITCH(switchVal) into GT_JTRUE(GT_EQ(switchVal==0)). // Also mark the node as GTF_DONT_CSE as further down JIT is not capable of handling it. // For example CSE could determine that the expression rooted at GT_EQ is a candidate cse and // replace it with a COMMA node. In such a case we will end up with GT_JTRUE node pointing to // a COMMA node which results in noway asserts in fgMorphSmpOp(), optAssertionGen() and rpPredictTreeRegUse(). // For the same reason fgMorphSmpOp() marks GT_JTRUE nodes with RELOP children as GTF_DONT_CSE. CLANG_FORMAT_COMMENT_ANCHOR; #ifdef DEBUG if (verbose) { printf("\nConverting a switch (" FMT_BB ") with only one significant clause besides a default target to a " "conditional branch\n", block->bbNum); } #endif // DEBUG switchTree->ChangeOper(GT_JTRUE); GenTree* zeroConstNode = gtNewZeroConNode(genActualType(switchVal->TypeGet())); GenTree* condNode = gtNewOperNode(GT_EQ, TYP_INT, switchVal, zeroConstNode); switchTree->gtOp.gtOp1 = condNode; switchTree->gtOp.gtOp1->gtFlags |= (GTF_RELOP_JMP_USED | GTF_DONT_CSE); if (block->IsLIR()) { blockRange->InsertAfter(switchVal, zeroConstNode, condNode); LIR::ReadOnlyRange range(zeroConstNode, switchTree); m_pLowering->LowerRange(block, range); } else { // Re-link the nodes for this statement. fgSetStmtSeq(switchStmt); } block->bbJumpDest = block->bbJumpSwt->bbsDstTab[0]; block->bbJumpKind = BBJ_COND; return true; } return returnvalue; } // fgBlockEndFavorsTailDuplication: // Heuristic function that returns true if this block ends in a statement that looks favorable // for tail-duplicating its successor (such as assigning a constant to a local). // Args: // block: BasicBlock we are considering duplicating the successor of // Returns: // true if it seems like a good idea // bool Compiler::fgBlockEndFavorsTailDuplication(BasicBlock* block) { if (block->isRunRarely()) { return false; } if (!block->lastStmt()) { return false; } else { // Tail duplication tends to pay off when the last statement // is an assignment of a constant, arraylength, or a relop. // This is because these statements produce information about values // that would otherwise be lost at the upcoming merge point. GenTreeStmt* lastStmt = block->lastStmt(); GenTree* tree = lastStmt->gtStmtExpr; if (tree->gtOper != GT_ASG) { return false; } if (tree->OperIsBlkOp()) { return false; } GenTree* op2 = tree->gtOp.gtOp2; if (op2->gtOper != GT_ARR_LENGTH && !op2->OperIsConst() && ((op2->OperKind() & GTK_RELOP) == 0)) { return false; } } return true; } // fgBlockIsGoodTailDuplicationCandidate: // Heuristic function that examines a block (presumably one that is a merge point) to determine // if it should be duplicated. // args: // target - the tail block (candidate for duplication) // returns: // true if this block seems like a good candidate for duplication // bool Compiler::fgBlockIsGoodTailDuplicationCandidate(BasicBlock* target) { GenTreeStmt* stmt = target->FirstNonPhiDef(); // Here we are looking for blocks with a single statement feeding a conditional branch. // These blocks are small, and when duplicated onto the tail of blocks that end in // assignments, there is a high probability of the branch completely going away. // This is by no means the only kind of tail that it is beneficial to duplicate, // just the only one we recognize for now. if (stmt != target->lastStmt()) { return false; } if (target->bbJumpKind != BBJ_COND) { return false; } GenTree* tree = stmt->gtStmtExpr; if (tree->gtOper != GT_JTRUE) { return false; } // must be some kind of relational operator GenTree* cond = tree->gtOp.gtOp1; if (!(cond->OperKind() & GTK_RELOP)) { return false; } // op1 must be some combinations of casts of local or constant GenTree* op1 = cond->gtOp.gtOp1; while (op1->gtOper == GT_CAST) { op1 = op1->gtOp.gtOp1; } if (!op1->IsLocal() && !op1->OperIsConst()) { return false; } // op2 must be some combinations of casts of local or constant GenTree* op2 = cond->gtOp.gtOp2; while (op2->gtOper == GT_CAST) { op2 = op2->gtOp.gtOp1; } if (!op2->IsLocal() && !op2->OperIsConst()) { return false; } return true; } // fgOptimizeUncondBranchToSimpleCond: // For a block which has an unconditional branch, look to see if its target block // is a good candidate for tail duplication, and if so do that duplication. // // Args: // block - block with uncond branch // target - block which is target of first block // // returns: true if changes were made bool Compiler::fgOptimizeUncondBranchToSimpleCond(BasicBlock* block, BasicBlock* target) { assert(block->bbJumpKind == BBJ_ALWAYS); assert(block->bbJumpDest == target); // TODO-Review: OK if they are in the same region? if (compHndBBtabCount > 0) { return false; } if (!fgBlockIsGoodTailDuplicationCandidate(target)) { return false; } if (!fgBlockEndFavorsTailDuplication(block)) { return false; } // NOTE: we do not currently hit this assert because this function is only called when // `fgUpdateFlowGraph` has been called with `doTailDuplication` set to true, and the // backend always calls `fgUpdateFlowGraph` with `doTailDuplication` set to false. assert(!block->IsLIR()); GenTreeStmt* stmt = target->FirstNonPhiDef(); assert(stmt == target->lastStmt()); // Duplicate the target block at the end of this block GenTree* cloned = gtCloneExpr(stmt->gtStmtExpr); noway_assert(cloned); GenTreeStmt* jmpStmt = gtNewStmt(cloned); block->bbJumpKind = BBJ_COND; block->bbJumpDest = target->bbJumpDest; fgAddRefPred(block->bbJumpDest, block); fgRemoveRefPred(target, block); // add an unconditional block after this block to jump to the target block's fallthrough block BasicBlock* next = fgNewBBafter(BBJ_ALWAYS, block, true); // The new block 'next' will inherit its weight from 'block' next->inheritWeight(block); next->bbJumpDest = target->bbNext; target->bbNext->bbFlags |= BBF_JMP_TARGET; fgAddRefPred(next, block); fgAddRefPred(next->bbJumpDest, next); #ifdef DEBUG if (verbose) { printf("fgOptimizeUncondBranchToSimpleCond(from " FMT_BB " to cond " FMT_BB "), created new uncond " FMT_BB "\n", block->bbNum, target->bbNum, next->bbNum); } #endif // DEBUG if (fgStmtListThreaded) { gtSetStmtInfo(jmpStmt); } fgInsertStmtAtEnd(block, jmpStmt); return true; } // fgOptimizeBranchToNext: // Optimize a block which has a branch to the following block // Args: // block - block with a branch // bNext - block which is both next and the target of the first block // bPrev - block which is prior to the first block // // returns: true if changes were made // bool Compiler::fgOptimizeBranchToNext(BasicBlock* block, BasicBlock* bNext, BasicBlock* bPrev) { assert(block->bbJumpKind == BBJ_COND || block->bbJumpKind == BBJ_ALWAYS); assert(block->bbJumpDest == bNext); assert(block->bbNext == bNext); assert(block->bbPrev == bPrev); if (block->bbJumpKind == BBJ_ALWAYS) { // We can't remove it if it is a branch from hot => cold if (!fgInDifferentRegions(block, bNext)) { // We can't remove if it is marked as BBF_KEEP_BBJ_ALWAYS if (!(block->bbFlags & BBF_KEEP_BBJ_ALWAYS)) { // We can't remove if the BBJ_ALWAYS is part of a BBJ_CALLFINALLY pair if ((bPrev == nullptr) || !bPrev->isBBCallAlwaysPair()) { /* the unconditional jump is to the next BB */ block->bbJumpKind = BBJ_NONE; block->bbFlags &= ~BBF_NEEDS_GCPOLL; #ifdef DEBUG if (verbose) { printf("\nRemoving unconditional jump to next block (" FMT_BB " -> " FMT_BB ") (converted " FMT_BB " to " "fall-through)\n", block->bbNum, bNext->bbNum, block->bbNum); } #endif // DEBUG return true; } } } } else { /* remove the conditional statement at the end of block */ noway_assert(block->bbJumpKind == BBJ_COND); noway_assert(block->bbTreeList); #ifdef DEBUG if (verbose) { printf("\nRemoving conditional jump to next block (" FMT_BB " -> " FMT_BB ")\n", block->bbNum, bNext->bbNum); } #endif // DEBUG if (block->IsLIR()) { LIR::Range& blockRange = LIR::AsRange(block); GenTree* jmp = blockRange.LastNode(); assert(jmp->OperIsConditionalJump()); if (jmp->OperGet() == GT_JTRUE) { jmp->gtOp.gtOp1->gtFlags &= ~GTF_SET_FLAGS; } bool isClosed; unsigned sideEffects; LIR::ReadOnlyRange jmpRange = blockRange.GetTreeRange(jmp, &isClosed, &sideEffects); // TODO-LIR: this should really be checking GTF_ALL_EFFECT, but that produces unacceptable // diffs compared to the existing backend. if (isClosed && ((sideEffects & GTF_SIDE_EFFECT) == 0)) { // If the jump and its operands form a contiguous, side-effect-free range, // remove them. blockRange.Delete(this, block, std::move(jmpRange)); } else { // Otherwise, just remove the jump node itself. blockRange.Remove(jmp, true); } } else { GenTreeStmt* cond = block->lastStmt(); noway_assert(cond->gtStmtExpr->gtOper == GT_JTRUE); /* check for SIDE_EFFECTS */ if (cond->gtStmtExpr->gtFlags & GTF_SIDE_EFFECT) { /* Extract the side effects from the conditional */ GenTree* sideEffList = nullptr; gtExtractSideEffList(cond->gtStmtExpr, &sideEffList); if (sideEffList == nullptr) { compCurBB = block; fgRemoveStmt(block, cond); } else { noway_assert(sideEffList->gtFlags & GTF_SIDE_EFFECT); #ifdef DEBUG if (verbose) { printf("\nConditional has side effects! Extracting side effects...\n"); gtDispTree(cond); printf("\n"); gtDispTree(sideEffList); printf("\n"); } #endif // DEBUG /* Replace the conditional statement with the list of side effects */ noway_assert(sideEffList->gtOper != GT_STMT); noway_assert(sideEffList->gtOper != GT_JTRUE); cond->gtStmtExpr = sideEffList; if (fgStmtListThreaded) { compCurBB = block; /* Update ordering, costs, FP levels, etc. */ gtSetStmtInfo(cond); /* Re-link the nodes for this statement */ fgSetStmtSeq(cond); } } } else { compCurBB = block; /* conditional has NO side effect - remove it */ fgRemoveStmt(block, cond); } } /* Conditional is gone - simply fall into the next block */ block->bbJumpKind = BBJ_NONE; block->bbFlags &= ~BBF_NEEDS_GCPOLL; /* Update bbRefs and bbNum - Conditional predecessors to the same * block are counted twice so we have to remove one of them */ noway_assert(bNext->countOfInEdges() > 1); fgRemoveRefPred(bNext, block); return true; } return false; } /***************************************************************************** * * Function called to optimize an unconditional branch that branches * to a conditional branch. * Currently we require that the conditional branch jump back to the * block that follows the unconditional branch. * * We can improve the code execution and layout by concatenating a copy * of the conditional branch block at the end of the conditional branch * and reversing the sense of the branch. * * This is only done when the amount of code to be copied is smaller than * our calculated threshold in maxDupCostSz. * */ bool Compiler::fgOptimizeBranch(BasicBlock* bJump) { if (opts.MinOpts()) { return false; } if (bJump->bbJumpKind != BBJ_ALWAYS) { return false; } if (bJump->bbFlags & BBF_KEEP_BBJ_ALWAYS) { return false; } // Don't hoist a conditional branch into the scratch block; we'd prefer it stay // either BBJ_NONE or BBJ_ALWAYS. if (fgBBisScratch(bJump)) { return false; } BasicBlock* bDest = bJump->bbJumpDest; if (bDest->bbJumpKind != BBJ_COND) { return false; } if (bDest->bbJumpDest != bJump->bbNext) { return false; } // 'bJump' must be in the same try region as the condition, since we're going to insert // a duplicated condition in 'bJump', and the condition might include exception throwing code. if (!BasicBlock::sameTryRegion(bJump, bDest)) { return false; } // do not jump into another try region BasicBlock* bDestNext = bDest->bbNext; if (bDestNext->hasTryIndex() && !BasicBlock::sameTryRegion(bJump, bDestNext)) { return false; } // This function is only called by fgReorderBlocks, which we do not run in the backend. // If we wanted to run block reordering in the backend, we would need to be able to // calculate cost information for LIR on a per-node basis in order for this function // to work. assert(!bJump->IsLIR()); assert(!bDest->IsLIR()); unsigned estDupCostSz = 0; for (GenTreeStmt* stmt = bDest->firstStmt(); stmt != nullptr; stmt = stmt->gtNextStmt) { GenTree* expr = stmt->gtStmtExpr; /* We call gtPrepareCost to measure the cost of duplicating this tree */ gtPrepareCost(expr); estDupCostSz += expr->gtCostSz; } bool allProfileWeightsAreValid = false; BasicBlock::weight_t weightJump = bJump->bbWeight; BasicBlock::weight_t weightDest = bDest->bbWeight; BasicBlock::weight_t weightNext = bJump->bbNext->bbWeight; bool rareJump = bJump->isRunRarely(); bool rareDest = bDest->isRunRarely(); bool rareNext = bJump->bbNext->isRunRarely(); // If we have profile data then we calculate the number of time // the loop will iterate into loopIterations if (fgIsUsingProfileWeights()) { // Only rely upon the profile weight when all three of these blocks // have either good profile weights or are rarelyRun // if ((bJump->bbFlags & (BBF_PROF_WEIGHT | BBF_RUN_RARELY)) && (bDest->bbFlags & (BBF_PROF_WEIGHT | BBF_RUN_RARELY)) && (bJump->bbNext->bbFlags & (BBF_PROF_WEIGHT | BBF_RUN_RARELY))) { allProfileWeightsAreValid = true; if ((weightJump * 100) < weightDest) { rareJump = true; } if ((weightNext * 100) < weightDest) { rareNext = true; } if (((weightDest * 100) < weightJump) && ((weightDest * 100) < weightNext)) { rareDest = true; } } } unsigned maxDupCostSz = 6; // // Branches between the hot and rarely run regions // should be minimized. So we allow a larger size // if (rareDest != rareJump) { maxDupCostSz += 6; } if (rareDest != rareNext) { maxDupCostSz += 6; } // // We we are ngen-ing: // If the uncondional branch is a rarely run block then // we are willing to have more code expansion since we // won't be running code from this page // if (opts.jitFlags->IsSet(JitFlags::JIT_FLAG_PREJIT)) { if (rareJump) { maxDupCostSz *= 2; } } // If the compare has too high cost then we don't want to dup bool costIsTooHigh = (estDupCostSz > maxDupCostSz); #ifdef DEBUG if (verbose) { printf("\nDuplication of the conditional block " FMT_BB " (always branch from " FMT_BB ") %s, because the cost of " "duplication (%i) is %s than %i," " validProfileWeights = %s\n", bDest->bbNum, bJump->bbNum, costIsTooHigh ? "not done" : "performed", estDupCostSz, costIsTooHigh ? "greater" : "less or equal", maxDupCostSz, allProfileWeightsAreValid ? "true" : "false"); } #endif // DEBUG if (costIsTooHigh) { return false; } /* Looks good - duplicate the conditional block */ GenTreeStmt* newStmtList = nullptr; // new stmt list to be added to bJump GenTreeStmt* newLastStmt = nullptr; /* Visit all the statements in bDest */ for (GenTreeStmt* curStmt = bDest->firstStmt(); curStmt != nullptr; curStmt = curStmt->getNextStmt()) { // Clone/substitute the expression. GenTreeStmt* stmt = gtCloneExpr(curStmt)->AsStmt(); // cloneExpr doesn't handle everything. if (stmt == nullptr) { return false; } /* Append the expression to our list */ if (newStmtList != nullptr) { newLastStmt->gtNext = stmt; } else { newStmtList = stmt; } stmt->gtPrev = newLastStmt; newLastStmt = stmt; } // Get to the condition node from the statement tree. GenTree* condTree = newLastStmt->gtStmtExpr; noway_assert(condTree->gtOper == GT_JTRUE); // Set condTree to the operand to the GT_JTRUE. condTree = condTree->gtOp.gtOp1; // This condTree has to be a RelOp comparison. if (condTree->OperIsCompare() == false) { return false; } // Join the two linked lists. GenTreeStmt* lastStmt = bJump->lastStmt(); if (lastStmt != nullptr) { GenTreeStmt* stmt = bJump->firstStmt(); stmt->gtPrev = newLastStmt; lastStmt->gtNext = newStmtList; newStmtList->gtPrev = lastStmt; } else { bJump->bbTreeList = newStmtList; newStmtList->gtPrev = newLastStmt; } // // Reverse the sense of the compare // gtReverseCond(condTree); // We need to update the following flags of the bJump block if they were set in the bDest block bJump->bbFlags |= (bDest->bbFlags & (BBF_HAS_NEWOBJ | BBF_HAS_NEWARRAY | BBF_HAS_NULLCHECK | BBF_HAS_IDX_LEN | BBF_HAS_VTABREF)); bJump->bbJumpKind = BBJ_COND; bJump->bbJumpDest = bDest->bbNext; /* Mark the jump dest block as being a jump target */ bJump->bbJumpDest->bbFlags |= BBF_JMP_TARGET | BBF_HAS_LABEL; /* Update bbRefs and bbPreds */ // bJump now falls through into the next block // fgAddRefPred(bJump->bbNext, bJump); // bJump no longer jumps to bDest // fgRemoveRefPred(bDest, bJump); // bJump now jumps to bDest->bbNext // fgAddRefPred(bDest->bbNext, bJump); if (weightJump > 0) { if (allProfileWeightsAreValid) { if (weightDest > weightJump) { bDest->bbWeight = (weightDest - weightJump); } else if (!bDest->isRunRarely()) { bDest->bbWeight = BB_UNITY_WEIGHT; } } else { BasicBlock::weight_t newWeightDest = 0; BasicBlock::weight_t unloopWeightDest = 0; if (weightDest > weightJump) { newWeightDest = (weightDest - weightJump); } if (weightDest >= (BB_LOOP_WEIGHT * BB_UNITY_WEIGHT) / 2) { newWeightDest = (weightDest * 2) / (BB_LOOP_WEIGHT * BB_UNITY_WEIGHT); } if ((newWeightDest > 0) || (unloopWeightDest > 0)) { bDest->bbWeight = Max(newWeightDest, unloopWeightDest); } } } #if DEBUG if (verbose) { // Dump out the newStmtList that we created printf("\nfgOptimizeBranch added these statements(s) at the end of " FMT_BB ":\n", bJump->bbNum); for (GenTreeStmt* stmt = newStmtList; stmt != nullptr; stmt = stmt->getNextStmt()) { gtDispTree(stmt); } printf("\nfgOptimizeBranch changed block " FMT_BB " from BBJ_ALWAYS to BBJ_COND.\n", bJump->bbNum); printf("\nAfter this change in fgOptimizeBranch the BB graph is:"); fgDispBasicBlocks(verboseTrees); printf("\n"); } #endif // DEBUG return true; } /***************************************************************************** * * Function called to optimize switch statements */ bool Compiler::fgOptimizeSwitchJumps() { bool result = false; // Our return value #if 0 // TODO-CQ: Add switch jump optimizations? if (!fgHasSwitch) return false; if (!fgHaveValidEdgeWeights) return false; for (BasicBlock* bSrc = fgFirstBB; bSrc != NULL; bSrc = bSrc->bbNext) { if (bSrc->bbJumpKind == BBJ_SWITCH) { unsigned jumpCnt; jumpCnt = bSrc->bbJumpSwt->bbsCount; BasicBlock** jumpTab; jumpTab = bSrc->bbJumpSwt->bbsDstTab; do { BasicBlock* bDst = *jumpTab; flowList* edgeToDst = fgGetPredForBlock(bDst, bSrc); double outRatio = (double) edgeToDst->flEdgeWeightMin / (double) bSrc->bbWeight; if (outRatio >= 0.60) { // straighten switch here... } } while (++jumpTab, --jumpCnt); } } #endif return result; } #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable : 21000) // Suppress PREFast warning about overly large function #endif /***************************************************************************** * * Function called to reorder the flowgraph of BasicBlocks such that any * rarely run blocks are placed at the end of the block list. * If we have profile information we also use that information to reverse * all conditional jumps that would benefit. */ void Compiler::fgReorderBlocks() { noway_assert(opts.compDbgCode == false); #if FEATURE_EH_FUNCLETS assert(fgFuncletsCreated); #endif // FEATURE_EH_FUNCLETS // We can't relocate anything if we only have one block if (fgFirstBB->bbNext == nullptr) { return; } bool newRarelyRun = false; bool movedBlocks = false; bool optimizedSwitches = false; // First let us expand the set of run rarely blocks newRarelyRun |= fgExpandRarelyRunBlocks(); #if !FEATURE_EH_FUNCLETS movedBlocks |= fgRelocateEHRegions(); #endif // !FEATURE_EH_FUNCLETS // // If we are using profile weights we can change some // switch jumps into conditional test and jump // if (fgIsUsingProfileWeights()) { // // Note that this is currently not yet implemented // optimizedSwitches = fgOptimizeSwitchJumps(); if (optimizedSwitches) { fgUpdateFlowGraph(); } } #ifdef DEBUG if (verbose) { printf("*************** In fgReorderBlocks()\n"); printf("\nInitial BasicBlocks"); fgDispBasicBlocks(verboseTrees); printf("\n"); } #endif // DEBUG BasicBlock* bNext; BasicBlock* bPrev; BasicBlock* block; unsigned XTnum; EHblkDsc* HBtab; // Iterate over every block, remembering our previous block in bPrev for (bPrev = fgFirstBB, block = bPrev->bbNext; block != nullptr; bPrev = block, block = block->bbNext) { // // Consider relocating the rarely run blocks such that they are at the end of the method. // We also consider reversing conditional branches so that they become a not taken forwards branch. // // If block is marked with a BBF_KEEP_BBJ_ALWAYS flag then we don't move the block if ((block->bbFlags & BBF_KEEP_BBJ_ALWAYS) != 0) { continue; } // Finally and handlers blocks are to be kept contiguous. // TODO-CQ: Allow reordering within the handler region if (block->hasHndIndex() == true) { continue; } bool reorderBlock = true; // This is set to false if we decide not to reorder 'block' bool isRare = block->isRunRarely(); BasicBlock* bDest = nullptr; bool forwardBranch = false; bool backwardBranch = false; // Setup bDest if ((bPrev->bbJumpKind == BBJ_COND) || (bPrev->bbJumpKind == BBJ_ALWAYS)) { bDest = bPrev->bbJumpDest; forwardBranch = fgIsForwardBranch(bPrev); backwardBranch = !forwardBranch; } // We will look for bPrev as a non rarely run block followed by block as a rarely run block // if (bPrev->isRunRarely()) { reorderBlock = false; } // If the weights of the bPrev, block and bDest were all obtained from a profile run // then we can use them to decide if it is useful to reverse this conditional branch BasicBlock::weight_t profHotWeight = -1; if (bPrev->hasProfileWeight() && block->hasProfileWeight() && ((bDest == nullptr) || bDest->hasProfileWeight())) { // // All blocks have profile information // if (forwardBranch) { if (bPrev->bbJumpKind == BBJ_ALWAYS) { // We can pull up the blocks that the unconditional jump branches to // if the weight of bDest is greater or equal to the weight of block // also the weight of bDest can't be zero. // if ((bDest->bbWeight < block->bbWeight) || (bDest->bbWeight == 0)) { reorderBlock = false; } else { // // If this remains true then we will try to pull up bDest to succeed bPrev // bool moveDestUp = true; if (fgHaveValidEdgeWeights) { // // The edge bPrev -> bDest must have a higher minimum weight // than every other edge into bDest // flowList* edgeFromPrev = fgGetPredForBlock(bDest, bPrev); noway_assert(edgeFromPrev != nullptr); // Examine all of the other edges into bDest for (flowList* edge = bDest->bbPreds; edge != nullptr; edge = edge->flNext) { if (edge != edgeFromPrev) { if (edge->flEdgeWeightMax >= edgeFromPrev->flEdgeWeightMin) { moveDestUp = false; break; } } } } else { // // The block bPrev must have a higher weight // than every other block that goes into bDest // // Examine all of the other edges into bDest for (flowList* edge = bDest->bbPreds; edge != nullptr; edge = edge->flNext) { BasicBlock* bTemp = edge->flBlock; if ((bTemp != bPrev) && (bTemp->bbWeight >= bPrev->bbWeight)) { moveDestUp = false; break; } } } // Are we still good to move bDest up to bPrev? if (moveDestUp) { // // We will consider all blocks that have less weight than profHotWeight to be // uncommonly run blocks as compared with the hot path of bPrev taken-jump to bDest // profHotWeight = bDest->bbWeight - 1; } else { if (block->isRunRarely()) { // We will move any rarely run blocks blocks profHotWeight = 0; } else { // We will move all blocks that have a weight less or equal to our fall through block profHotWeight = block->bbWeight + 1; } // But we won't try to connect with bDest bDest = nullptr; } } } else // (bPrev->bbJumpKind == BBJ_COND) { noway_assert(bPrev->bbJumpKind == BBJ_COND); // // We will reverse branch if the taken-jump to bDest ratio (i.e. 'takenRatio') // is more than 51% // // We will setup profHotWeight to be maximum bbWeight that a block // could have for us not to want to reverse the conditional branch // // We will consider all blocks that have less weight than profHotWeight to be // uncommonly run blocks as compared with the hot path of bPrev taken-jump to bDest // if (fgHaveValidEdgeWeights) { // We have valid edge weights, however even with valid edge weights // we may have a minimum and maximum range for each edges value // // We will check that the min weight of the bPrev to bDest edge // is more than twice the max weight of the bPrev to block edge. // // bPrev --> [BB04, weight 31] // | \. // edgeToBlock -------------> O \. // [min=8,max=10] V \. // block --> [BB05, weight 10] \. // \. // edgeToDest ----------------------------> O // [min=21,max=23] | // V // bDest ---------------> [BB08, weight 21] // flowList* edgeToDest = fgGetPredForBlock(bDest, bPrev); flowList* edgeToBlock = fgGetPredForBlock(block, bPrev); noway_assert(edgeToDest != nullptr); noway_assert(edgeToBlock != nullptr); // // Calculate the taken ratio // A takenRation of 0.10 means taken 10% of the time, not taken 90% of the time // A takenRation of 0.50 means taken 50% of the time, not taken 50% of the time // A takenRation of 0.90 means taken 90% of the time, not taken 10% of the time // double takenCount = ((double)edgeToDest->flEdgeWeightMin + (double)edgeToDest->flEdgeWeightMax) / 2.0; double notTakenCount = ((double)edgeToBlock->flEdgeWeightMin + (double)edgeToBlock->flEdgeWeightMax) / 2.0; double totalCount = takenCount + notTakenCount; double takenRatio = takenCount / totalCount; // If the takenRatio is greater or equal to 51% then we will reverse the branch if (takenRatio < 0.51) { reorderBlock = false; } else { // set profHotWeight profHotWeight = (edgeToBlock->flEdgeWeightMin + edgeToBlock->flEdgeWeightMax) / 2 - 1; } } else { // We don't have valid edge weight so we will be more conservative // We could have bPrev, block or bDest as part of a loop and thus have extra weight // // We will do two checks: // 1. Check that the weight of bDest is at least two times more than block // 2. Check that the weight of bPrev is at least three times more than block // // bPrev --> [BB04, weight 31] // | \. // V \. // block --> [BB05, weight 10] \. // \. // | // V // bDest ---------------> [BB08, weight 21] // // For this case weightDest is calculated as (21+1)/2 or 11 // and weightPrev is calculated as (31+2)/3 also 11 // // Generally both weightDest and weightPrev should calculate // the same value unless bPrev or bDest are part of a loop // BasicBlock::weight_t weightDest = bDest->isMaxBBWeight() ? bDest->bbWeight : (bDest->bbWeight + 1) / 2; BasicBlock::weight_t weightPrev = bPrev->isMaxBBWeight() ? bPrev->bbWeight : (bPrev->bbWeight + 2) / 3; // select the lower of weightDest and weightPrev profHotWeight = (weightDest < weightPrev) ? weightDest : weightPrev; // if the weight of block is greater (or equal) to profHotWeight then we don't reverse the cond if (block->bbWeight >= profHotWeight) { reorderBlock = false; } } } } else // not a forwardBranch { if (bPrev->bbFallsThrough()) { goto CHECK_FOR_RARE; } // Here we should pull up the highest weight block remaining // and place it here since bPrev does not fall through. BasicBlock::weight_t highestWeight = 0; BasicBlock* candidateBlock = nullptr; BasicBlock* lastNonFallThroughBlock = bPrev; BasicBlock* bTmp = bPrev->bbNext; while (bTmp != nullptr) { // Don't try to split a Call/Always pair // if (bTmp->isBBCallAlwaysPair()) { // Move bTmp forward bTmp = bTmp->bbNext; } // // Check for loop exit condition // if (bTmp == nullptr) { break; } // // if its weight is the highest one we've seen and // the EH regions allow for us to place bTmp after bPrev // if ((bTmp->bbWeight > highestWeight) && fgEhAllowsMoveBlock(bPrev, bTmp)) { // When we have a current candidateBlock that is a conditional (or unconditional) jump // to bTmp (which is a higher weighted block) then it is better to keep out current // candidateBlock and have it fall into bTmp // if ((candidateBlock == nullptr) || ((candidateBlock->bbJumpKind != BBJ_COND) && (candidateBlock->bbJumpKind != BBJ_ALWAYS)) || (candidateBlock->bbJumpDest != bTmp)) { // otherwise we have a new candidateBlock // highestWeight = bTmp->bbWeight; candidateBlock = lastNonFallThroughBlock->bbNext; } } if ((bTmp->bbFallsThrough() == false) || (bTmp->bbWeight == 0)) { lastNonFallThroughBlock = bTmp; } bTmp = bTmp->bbNext; } // If we didn't find a suitable block then skip this if (highestWeight == 0) { reorderBlock = false; } else { noway_assert(candidateBlock != nullptr); // If the candidateBlock is the same a block then skip this if (candidateBlock == block) { reorderBlock = false; } else { // Set bDest to the block that we want to come after bPrev bDest = candidateBlock; // set profHotWeight profHotWeight = highestWeight - 1; } } } } else // we don't have good profile info (or we are falling through) { CHECK_FOR_RARE:; /* We only want to reorder when we have a rarely run */ /* block right after a normal block, */ /* (bPrev is known to be a normal block at this point) */ if (!isRare) { if ((bDest == block->bbNext) && (block->bbJumpKind == BBJ_RETURN) && (bPrev->bbJumpKind == BBJ_ALWAYS)) { // This is a common case with expressions like "return Expr1 && Expr2" -- move the return // to establish fall-through. } else { reorderBlock = false; } } else { /* If the jump target bDest is also a rarely run block then we don't want to do the reversal */ if (bDest && bDest->isRunRarely()) { reorderBlock = false; /* Both block and bDest are rarely run */ } else { // We will move any rarely run blocks blocks profHotWeight = 0; } } } if (reorderBlock == false) { // // Check for an unconditional branch to a conditional branch // which also branches back to our next block // if (fgOptimizeBranch(bPrev)) { noway_assert(bPrev->bbJumpKind == BBJ_COND); } continue; } // Now we need to determine which blocks should be moved // // We consider one of two choices: // // 1. Moving the fall-through blocks (or rarely run blocks) down to // later in the method and hopefully connecting the jump dest block // so that it becomes the fall through block // // And when bDest in not NULL, we also consider: // // 2. Moving the bDest block (or blocks) up to bPrev // so that it could be used as a fall through block // // We will prefer option #1 if we are able to connect the jump dest // block as the fall though block otherwise will we try to use option #2 // // // Consider option #1: relocating blocks starting at 'block' // to later in flowgraph // // We set bStart to the first block that will be relocated // and bEnd to the last block that will be relocated BasicBlock* bStart = block; BasicBlock* bEnd = bStart; bNext = bEnd->bbNext; bool connected_bDest = false; if ((backwardBranch && !isRare) || ((block->bbFlags & BBF_DONT_REMOVE) != 0)) // Don't choose option #1 when block is the start of a try region { bStart = nullptr; bEnd = nullptr; } else { while (true) { // Don't try to split a Call/Always pair // if (bEnd->isBBCallAlwaysPair()) { // Move bEnd and bNext forward bEnd = bNext; bNext = bNext->bbNext; } // // Check for loop exit condition // if (bNext == nullptr) { break; } #if FEATURE_EH_FUNCLETS // Check if we've reached the funclets region, at the end of the function if (fgFirstFuncletBB == bEnd->bbNext) { break; } #endif // FEATURE_EH_FUNCLETS if (bNext == bDest) { connected_bDest = true; break; } // All the blocks must have the same try index // and must not have the BBF_DONT_REMOVE flag set if (!BasicBlock::sameTryRegion(bStart, bNext) || ((bNext->bbFlags & BBF_DONT_REMOVE) != 0)) { // exit the loop, bEnd is now set to the // last block that we want to relocate break; } // If we are relocating rarely run blocks.. if (isRare) { // ... then all blocks must be rarely run if (!bNext->isRunRarely()) { // exit the loop, bEnd is now set to the // last block that we want to relocate break; } } else { // If we are moving blocks that are hot then all // of the blocks moved must be less than profHotWeight */ if (bNext->bbWeight >= profHotWeight) { // exit the loop, bEnd is now set to the // last block that we would relocate break; } } // Move bEnd and bNext forward bEnd = bNext; bNext = bNext->bbNext; } // Set connected_bDest to true if moving blocks [bStart .. bEnd] // connects with the the jump dest of bPrev (i.e bDest) and // thus allows bPrev fall through instead of jump. if (bNext == bDest) { connected_bDest = true; } } // Now consider option #2: Moving the jump dest block (or blocks) // up to bPrev // // The variables bStart2, bEnd2 and bPrev2 are used for option #2 // // We will setup bStart2 to the first block that will be relocated // and bEnd2 to the last block that will be relocated // and bPrev2 to be the lexical pred of bDest // // If after this calculation bStart2 is NULL we cannot use option #2, // otherwise bStart2, bEnd2 and bPrev2 are all non-NULL and we will use option #2 BasicBlock* bStart2 = nullptr; BasicBlock* bEnd2 = nullptr; BasicBlock* bPrev2 = nullptr; // If option #1 didn't connect bDest and bDest isn't NULL if ((connected_bDest == false) && (bDest != nullptr) && // The jump target cannot be moved if it has the BBF_DONT_REMOVE flag set ((bDest->bbFlags & BBF_DONT_REMOVE) == 0)) { // We will consider option #2: relocating blocks starting at 'bDest' to succeed bPrev // // setup bPrev2 to be the lexical pred of bDest bPrev2 = block; while (bPrev2 != nullptr) { if (bPrev2->bbNext == bDest) { break; } bPrev2 = bPrev2->bbNext; } if ((bPrev2 != nullptr) && fgEhAllowsMoveBlock(bPrev, bDest)) { // We have decided that relocating bDest to be after bPrev is best // Set bStart2 to the first block that will be relocated // and bEnd2 to the last block that will be relocated // // Assigning to bStart2 selects option #2 // bStart2 = bDest; bEnd2 = bStart2; bNext = bEnd2->bbNext; while (true) { // Don't try to split a Call/Always pair // if (bEnd2->isBBCallAlwaysPair()) { noway_assert(bNext->bbJumpKind == BBJ_ALWAYS); // Move bEnd2 and bNext forward bEnd2 = bNext; bNext = bNext->bbNext; } // Check for the Loop exit conditions if (bNext == nullptr) { break; } if (bEnd2->bbFallsThrough() == false) { break; } // If we are relocating rarely run blocks.. // All the blocks must have the same try index, // and must not have the BBF_DONT_REMOVE flag set if (!BasicBlock::sameTryRegion(bStart2, bNext) || ((bNext->bbFlags & BBF_DONT_REMOVE) != 0)) { // exit the loop, bEnd2 is now set to the // last block that we want to relocate break; } if (isRare) { /* ... then all blocks must not be rarely run */ if (bNext->isRunRarely()) { // exit the loop, bEnd2 is now set to the // last block that we want to relocate break; } } else { // If we are relocating hot blocks // all blocks moved must be greater than profHotWeight if (bNext->bbWeight <= profHotWeight) { // exit the loop, bEnd2 is now set to the // last block that we want to relocate break; } } // Move bEnd2 and bNext forward bEnd2 = bNext; bNext = bNext->bbNext; } } } // If we are using option #1 then ... if (bStart2 == nullptr) { // Don't use option #1 for a backwards branch if (bStart == nullptr) { continue; } // .... Don't move a set of blocks that are already at the end of the main method if (bEnd == fgLastBBInMainFunction()) { continue; } } #ifdef DEBUG if (verbose) { if (bDest != nullptr) { if (bPrev->bbJumpKind == BBJ_COND) { printf("Decided to reverse conditional branch at block " FMT_BB " branch to " FMT_BB " ", bPrev->bbNum, bDest->bbNum); } else if (bPrev->bbJumpKind == BBJ_ALWAYS) { printf("Decided to straighten unconditional branch at block " FMT_BB " branch to " FMT_BB " ", bPrev->bbNum, bDest->bbNum); } else { printf("Decided to place hot code after " FMT_BB ", placed " FMT_BB " after this block ", bPrev->bbNum, bDest->bbNum); } if (profHotWeight > 0) { printf("because of IBC profile data\n"); } else { if (bPrev->bbFallsThrough()) { printf("since it falls into a rarely run block\n"); } else { printf("since it is succeeded by a rarely run block\n"); } } } else { printf("Decided to relocate block(s) after block " FMT_BB " since they are %s block(s)\n", bPrev->bbNum, block->isRunRarely() ? "rarely run" : "uncommonly run"); } } #endif // DEBUG // We will set insertAfterBlk to the block the precedes our insertion range // We will set bStartPrev to be the block that precedes the set of blocks that we are moving BasicBlock* insertAfterBlk; BasicBlock* bStartPrev; if (bStart2 != nullptr) { // Option #2: relocating blocks starting at 'bDest' to follow bPrev // Update bStart and bEnd so that we can use these two for all later operations bStart = bStart2; bEnd = bEnd2; // Set bStartPrev to be the block that comes before bStart bStartPrev = bPrev2; // We will move [bStart..bEnd] to immediately after bPrev insertAfterBlk = bPrev; } else { // option #1: Moving the fall-through blocks (or rarely run blocks) down to later in the method // Set bStartPrev to be the block that come before bStart bStartPrev = bPrev; // We will move [bStart..bEnd] but we will pick the insert location later insertAfterBlk = nullptr; } // We are going to move [bStart..bEnd] so they can't be NULL noway_assert(bStart != nullptr); noway_assert(bEnd != nullptr); // bEnd can't be a BBJ_CALLFINALLY unless it is a RETLESS call noway_assert((bEnd->bbJumpKind != BBJ_CALLFINALLY) || (bEnd->bbFlags & BBF_RETLESS_CALL)); // bStartPrev must be set to the block that precedes bStart noway_assert(bStartPrev->bbNext == bStart); // Since we will be unlinking [bStart..bEnd], // we need to compute and remember if bStart is in each of // the try and handler regions // bool* fStartIsInTry = nullptr; bool* fStartIsInHnd = nullptr; if (compHndBBtabCount > 0) { fStartIsInTry = new (this, CMK_Unknown) bool[compHndBBtabCount]; fStartIsInHnd = new (this, CMK_Unknown) bool[compHndBBtabCount]; for (XTnum = 0, HBtab = compHndBBtab; XTnum < compHndBBtabCount; XTnum++, HBtab++) { fStartIsInTry[XTnum] = HBtab->InTryRegionBBRange(bStart); fStartIsInHnd[XTnum] = HBtab->InHndRegionBBRange(bStart); } } /* Temporarily unlink [bStart..bEnd] from the flow graph */ fgUnlinkRange(bStart, bEnd); if (insertAfterBlk == nullptr) { // Find new location for the unlinked block(s) // Set insertAfterBlk to the block which will precede the insertion point if (!bStart->hasTryIndex() && isRare) { // We'll just insert the blocks at the end of the method. If the method // has funclets, we will insert at the end of the main method but before // any of the funclets. Note that we create funclets before we call // fgReorderBlocks(). insertAfterBlk = fgLastBBInMainFunction(); noway_assert(insertAfterBlk != bPrev); } else { BasicBlock* startBlk; BasicBlock* lastBlk; EHblkDsc* ehDsc = ehInitTryBlockRange(bStart, &startBlk, &lastBlk); BasicBlock* endBlk; /* Setup startBlk and endBlk as the range to search */ if (ehDsc != nullptr) { endBlk = lastBlk->bbNext; /* Multiple (nested) try regions might start from the same BB. For example, try3 try2 try1 |--- |--- |--- BB01 | | | BB02 | | |--- BB03 | | BB04 | |------------ BB05 | BB06 |------------------- BB07 Now if we want to insert in try2 region, we will start with startBlk=BB01. The following loop will allow us to start from startBlk==BB04. */ while (!BasicBlock::sameTryRegion(startBlk, bStart) && (startBlk != endBlk)) { startBlk = startBlk->bbNext; } // startBlk cannot equal endBlk as it must come before endBlk if (startBlk == endBlk) { goto CANNOT_MOVE; } // we also can't start searching the try region at bStart if (startBlk == bStart) { // if bEnd is the last block in the method or // or if bEnd->bbNext is in a different try region // then we cannot move the blocks // if ((bEnd->bbNext == nullptr) || !BasicBlock::sameTryRegion(startBlk, bEnd->bbNext)) { goto CANNOT_MOVE; } startBlk = bEnd->bbNext; // Check that the new startBlk still comes before endBlk // startBlk cannot equal endBlk as it must come before endBlk if (startBlk == endBlk) { goto CANNOT_MOVE; } BasicBlock* tmpBlk = startBlk; while ((tmpBlk != endBlk) && (tmpBlk != nullptr)) { tmpBlk = tmpBlk->bbNext; } // when tmpBlk is NULL that means startBlk is after endBlk // so there is no way to move bStart..bEnd within the try region if (tmpBlk == nullptr) { goto CANNOT_MOVE; } } } else { noway_assert(isRare == false); /* We'll search through the entire main method */ startBlk = fgFirstBB; endBlk = fgEndBBAfterMainFunction(); } // Calculate nearBlk and jumpBlk and then call fgFindInsertPoint() // to find our insertion block // { // If the set of blocks that we are moving ends with a BBJ_ALWAYS to // another [rarely run] block that comes after bPrev (forward branch) // then we can set up nearBlk to eliminate this jump sometimes // BasicBlock* nearBlk = nullptr; BasicBlock* jumpBlk = nullptr; if ((bEnd->bbJumpKind == BBJ_ALWAYS) && (!isRare || bEnd->bbJumpDest->isRunRarely()) && fgIsForwardBranch(bEnd, bPrev)) { // Set nearBlk to be the block in [startBlk..endBlk] // such that nearBlk->bbNext == bEnd->JumpDest // if no such block exists then set nearBlk to NULL nearBlk = startBlk; jumpBlk = bEnd; do { // We do not want to set nearBlk to bPrev // since then we will not move [bStart..bEnd] // if (nearBlk != bPrev) { // Check if nearBlk satisfies our requirement if (nearBlk->bbNext == bEnd->bbJumpDest) { break; } } // Did we reach the endBlk? if (nearBlk == endBlk) { nearBlk = nullptr; break; } // advance nearBlk to the next block nearBlk = nearBlk->bbNext; } while (nearBlk != nullptr); } // if nearBlk is NULL then we set nearBlk to be the // first block that we want to insert after. if (nearBlk == nullptr) { if (bDest != nullptr) { // we want to insert after bDest nearBlk = bDest; } else { // we want to insert after bPrev nearBlk = bPrev; } } /* Set insertAfterBlk to the block which we will insert after. */ insertAfterBlk = fgFindInsertPoint(bStart->bbTryIndex, true, // Insert in the try region. startBlk, endBlk, nearBlk, jumpBlk, bStart->bbWeight == BB_ZERO_WEIGHT); } /* See if insertAfterBlk is the same as where we started, */ /* or if we could not find any insertion point */ if ((insertAfterBlk == bPrev) || (insertAfterBlk == nullptr)) { CANNOT_MOVE:; /* We couldn't move the blocks, so put everything back */ /* relink [bStart .. bEnd] into the flow graph */ bPrev->setNext(bStart); if (bEnd->bbNext) { bEnd->bbNext->bbPrev = bEnd; } #ifdef DEBUG if (verbose) { if (bStart != bEnd) { printf("Could not relocate blocks (" FMT_BB " .. " FMT_BB ")\n", bStart->bbNum, bEnd->bbNum); } else { printf("Could not relocate block " FMT_BB "\n", bStart->bbNum); } } #endif // DEBUG continue; } } } noway_assert(insertAfterBlk != nullptr); noway_assert(bStartPrev != nullptr); noway_assert(bStartPrev != insertAfterBlk); #ifdef DEBUG movedBlocks = true; if (verbose) { const char* msg; if (bStart2 != nullptr) { msg = "hot"; } else { if (isRare) { msg = "rarely run"; } else { msg = "uncommon"; } } printf("Relocated %s ", msg); if (bStart != bEnd) { printf("blocks (" FMT_BB " .. " FMT_BB ")", bStart->bbNum, bEnd->bbNum); } else { printf("block " FMT_BB, bStart->bbNum); } if (bPrev->bbJumpKind == BBJ_COND) { printf(" by reversing conditional jump at " FMT_BB "\n", bPrev->bbNum); } else { printf("\n", bPrev->bbNum); } } #endif // DEBUG if (bPrev->bbJumpKind == BBJ_COND) { /* Reverse the bPrev jump condition */ GenTreeStmt* condTestStmt = bPrev->lastStmt(); GenTree* condTest = condTestStmt->gtStmtExpr; noway_assert(condTest->gtOper == GT_JTRUE); condTest->gtOp.gtOp1 = gtReverseCond(condTest->gtOp.gtOp1); if (bStart2 == nullptr) { /* Set the new jump dest for bPrev to the rarely run or uncommon block(s) */ bPrev->bbJumpDest = bStart; bStart->bbFlags |= (BBF_JMP_TARGET | BBF_HAS_LABEL); } else { noway_assert(insertAfterBlk == bPrev); noway_assert(insertAfterBlk->bbNext == block); /* Set the new jump dest for bPrev to the rarely run or uncommon block(s) */ bPrev->bbJumpDest = block; block->bbFlags |= (BBF_JMP_TARGET | BBF_HAS_LABEL); } } // If we are moving blocks that are at the end of a try or handler // we will need to shorten ebdTryLast or ebdHndLast // ehUpdateLastBlocks(bEnd, bStartPrev); // If we are moving blocks into the end of a try region or handler region // we will need to extend ebdTryLast or ebdHndLast so the blocks that we // are moving are part of this try or handler region. // for (XTnum = 0, HBtab = compHndBBtab; XTnum < compHndBBtabCount; XTnum++, HBtab++) { // Are we moving blocks to the end of a try region? if (HBtab->ebdTryLast == insertAfterBlk) { if (fStartIsInTry[XTnum]) { // bStart..bEnd is in the try, so extend the try region fgSetTryEnd(HBtab, bEnd); } } // Are we moving blocks to the end of a handler region? if (HBtab->ebdHndLast == insertAfterBlk) { if (fStartIsInHnd[XTnum]) { // bStart..bEnd is in the handler, so extend the handler region fgSetHndEnd(HBtab, bEnd); } } } /* We have decided to insert the block(s) after 'insertAfterBlk' */ fgMoveBlocksAfter(bStart, bEnd, insertAfterBlk); if (bDest) { /* We may need to insert an unconditional branch after bPrev to bDest */ fgConnectFallThrough(bPrev, bDest); } else { /* If bPrev falls through, we must insert a jump to block */ fgConnectFallThrough(bPrev, block); } BasicBlock* bSkip = bEnd->bbNext; /* If bEnd falls through, we must insert a jump to bNext */ fgConnectFallThrough(bEnd, bNext); if (bStart2 == nullptr) { /* If insertAfterBlk falls through, we are forced to */ /* add a jump around the block(s) we just inserted */ fgConnectFallThrough(insertAfterBlk, bSkip); } else { /* We may need to insert an unconditional branch after bPrev2 to bStart */ fgConnectFallThrough(bPrev2, bStart); } #if DEBUG if (verbose) { printf("\nAfter this change in fgReorderBlocks the BB graph is:"); fgDispBasicBlocks(verboseTrees); printf("\n"); } fgVerifyHandlerTab(); // Make sure that the predecessor lists are accurate if (expensiveDebugCheckLevel >= 2) { fgDebugCheckBBlist(); } #endif // DEBUG // Set our iteration point 'block' to be the new bPrev->bbNext // It will be used as the next bPrev block = bPrev->bbNext; } // end of for loop(bPrev,block) bool changed = movedBlocks || newRarelyRun || optimizedSwitches; if (changed) { fgNeedsUpdateFlowGraph = true; #if DEBUG // Make sure that the predecessor lists are accurate if (expensiveDebugCheckLevel >= 2) { fgDebugCheckBBlist(); } #endif // DEBUG } } #ifdef _PREFAST_ #pragma warning(pop) #endif /*------------------------------------------------------------------------- * * Walk the basic blocks list to determine the first block to place in the * cold section. This would be the first of a series of rarely executed blocks * such that no succeeding blocks are in a try region or an exception handler * or are rarely executed. */ void Compiler::fgDetermineFirstColdBlock() { #ifdef DEBUG if (verbose) { printf("\n*************** In fgDetermineFirstColdBlock()\n"); } #endif // DEBUG // Since we may need to create a new transistion block // we assert that it is OK to create new blocks. // assert(fgSafeBasicBlockCreation); fgFirstColdBlock = nullptr; if (!opts.compProcedureSplitting) { JITDUMP("No procedure splitting will be done for this method\n"); return; } #ifdef DEBUG if ((compHndBBtabCount > 0) && !opts.compProcedureSplittingEH) { JITDUMP("No procedure splitting will be done for this method with EH (by request)\n"); return; } #endif // DEBUG #if FEATURE_EH_FUNCLETS // TODO-CQ: handle hot/cold splitting in functions with EH (including synchronized methods // that create EH in methods without explicit EH clauses). if (compHndBBtabCount > 0) { JITDUMP("No procedure splitting will be done for this method with EH (implementation limitation)\n"); return; } #endif // FEATURE_EH_FUNCLETS BasicBlock* firstColdBlock = nullptr; BasicBlock* prevToFirstColdBlock = nullptr; BasicBlock* block; BasicBlock* lblk; for (lblk = nullptr, block = fgFirstBB; block != nullptr; lblk = block, block = block->bbNext) { bool blockMustBeInHotSection = false; #if HANDLER_ENTRY_MUST_BE_IN_HOT_SECTION if (bbIsHandlerBeg(block)) { blockMustBeInHotSection = true; } #endif // HANDLER_ENTRY_MUST_BE_IN_HOT_SECTION // Do we have a candidate for the first cold block? if (firstColdBlock != nullptr) { // We have a candidate for first cold block // Is this a hot block? if (blockMustBeInHotSection || (block->isRunRarely() == false)) { // We have to restart the search for the first cold block firstColdBlock = nullptr; prevToFirstColdBlock = nullptr; } } else // (firstColdBlock == NULL) { // We don't have a candidate for first cold block // Is this a cold block? if (!blockMustBeInHotSection && (block->isRunRarely() == true)) { // // If the last block that was hot was a BBJ_COND // then we will have to add an unconditional jump // so the code size for block needs be large // enough to make it worth our while // if ((lblk == nullptr) || (lblk->bbJumpKind != BBJ_COND) || (fgGetCodeEstimate(block) >= 8)) { // This block is now a candidate for first cold block // Also remember the predecessor to this block firstColdBlock = block; prevToFirstColdBlock = lblk; } } } } if (firstColdBlock == fgFirstBB) { // If the first block is Cold then we can't move any blocks // into the cold section firstColdBlock = nullptr; } if (firstColdBlock != nullptr) { noway_assert(prevToFirstColdBlock != nullptr); if (prevToFirstColdBlock == nullptr) { return; // To keep Prefast happy } // If we only have one cold block // then it may not be worth it to move it // into the Cold section as a jump to the // Cold section is 5 bytes in size. // if (firstColdBlock->bbNext == nullptr) { // If the size of the cold block is 7 or less // then we will keep it in the Hot section. // if (fgGetCodeEstimate(firstColdBlock) < 8) { firstColdBlock = nullptr; goto EXIT; } } // When the last Hot block fall through into the Cold section // we may need to add a jump // if (prevToFirstColdBlock->bbFallsThrough()) { switch (prevToFirstColdBlock->bbJumpKind) { default: noway_assert(!"Unhandled jumpkind in fgDetermineFirstColdBlock()"); case BBJ_CALLFINALLY: // A BBJ_CALLFINALLY that falls through is always followed // by an empty BBJ_ALWAYS. // assert(prevToFirstColdBlock->isBBCallAlwaysPair()); firstColdBlock = firstColdBlock->bbNext; // Note that this assignment could make firstColdBlock == nullptr break; case BBJ_COND: // // This is a slightly more complicated case, because we will // probably need to insert a block to jump to the cold section. // if (firstColdBlock->isEmpty() && (firstColdBlock->bbJumpKind == BBJ_ALWAYS)) { // We can just use this block as the transitionBlock firstColdBlock = firstColdBlock->bbNext; // Note that this assignment could make firstColdBlock == NULL } else { BasicBlock* transitionBlock = fgNewBBafter(BBJ_ALWAYS, prevToFirstColdBlock, true); transitionBlock->bbJumpDest = firstColdBlock; transitionBlock->inheritWeight(firstColdBlock); noway_assert(fgComputePredsDone); // Update the predecessor list for firstColdBlock fgReplacePred(firstColdBlock, prevToFirstColdBlock, transitionBlock); // Add prevToFirstColdBlock as a predecessor for transitionBlock fgAddRefPred(transitionBlock, prevToFirstColdBlock); } break; case BBJ_NONE: // If the block preceding the first cold block is BBJ_NONE, // convert it to BBJ_ALWAYS to force an explicit jump. prevToFirstColdBlock->bbJumpDest = firstColdBlock; prevToFirstColdBlock->bbJumpKind = BBJ_ALWAYS; break; } } } if (firstColdBlock != nullptr) { firstColdBlock->bbFlags |= BBF_JMP_TARGET; for (block = firstColdBlock; block; block = block->bbNext) { block->bbFlags |= BBF_COLD; } } EXIT:; #ifdef DEBUG if (verbose) { if (firstColdBlock) { printf("fgFirstColdBlock is " FMT_BB ".\n", firstColdBlock->bbNum); } else { printf("fgFirstColdBlock is NULL.\n"); } fgDispBasicBlocks(); } fgVerifyHandlerTab(); #endif // DEBUG fgFirstColdBlock = firstColdBlock; } #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable : 21000) // Suppress PREFast warning about overly large function #endif /***************************************************************************** * * Function called to "comb" the basic block list. * Removes any empty blocks, unreachable blocks and redundant jumps. * Most of those appear after dead store removal and folding of conditionals. * * Returns: true if the flowgraph has been modified * * It also compacts basic blocks * (consecutive basic blocks that should in fact be one). * * NOTE: * Debuggable code and Min Optimization JIT also introduces basic blocks * but we do not optimize those! */ bool Compiler::fgUpdateFlowGraph(bool doTailDuplication) { #ifdef DEBUG if (verbose) { printf("\n*************** In fgUpdateFlowGraph()"); } #endif // DEBUG /* This should never be called for debuggable code */ noway_assert(opts.OptimizationEnabled()); #ifdef DEBUG if (verbose) { printf("\nBefore updating the flow graph:\n"); fgDispBasicBlocks(verboseTrees); printf("\n"); } #endif // DEBUG /* Walk all the basic blocks - look for unconditional jumps, empty blocks, blocks to compact, etc... * * OBSERVATION: * Once a block is removed the predecessors are not accurate (assuming they were at the beginning) * For now we will only use the information in bbRefs because it is easier to be updated */ bool modified = false; bool change; do { change = false; BasicBlock* block; // the current block BasicBlock* bPrev = nullptr; // the previous non-worthless block BasicBlock* bNext; // the successor of the current block BasicBlock* bDest; // the jump target of the current block for (block = fgFirstBB; block != nullptr; block = block->bbNext) { /* Some blocks may be already marked removed by other optimizations * (e.g worthless loop removal), without being explicitly removed * from the list. */ if (block->bbFlags & BBF_REMOVED) { if (bPrev) { bPrev->setNext(block->bbNext); } else { /* WEIRD first basic block is removed - should have an assert here */ noway_assert(!"First basic block marked as BBF_REMOVED???"); fgFirstBB = block->bbNext; } continue; } /* We jump to the REPEAT label if we performed a change involving the current block * This is in case there are other optimizations that can show up * (e.g. - compact 3 blocks in a row) * If nothing happens, we then finish the iteration and move to the next block */ REPEAT:; bNext = block->bbNext; bDest = nullptr; if (block->bbJumpKind == BBJ_ALWAYS) { bDest = block->bbJumpDest; if (doTailDuplication && fgOptimizeUncondBranchToSimpleCond(block, bDest)) { change = true; modified = true; bDest = block->bbJumpDest; bNext = block->bbNext; } } // Remove JUMPS to the following block // and optimize any JUMPS to JUMPS if (block->bbJumpKind == BBJ_COND || block->bbJumpKind == BBJ_ALWAYS) { bDest = block->bbJumpDest; if (bDest == bNext) { if (fgOptimizeBranchToNext(block, bNext, bPrev)) { change = true; modified = true; bDest = nullptr; } } } if (bDest != nullptr) { // Do we have a JUMP to an empty unconditional JUMP block? if (bDest->isEmpty() && (bDest->bbJumpKind == BBJ_ALWAYS) && (bDest != bDest->bbJumpDest)) // special case for self jumps { if (fgOptimizeBranchToEmptyUnconditional(block, bDest)) { change = true; modified = true; goto REPEAT; } } // Check for a conditional branch that just skips over an empty BBJ_ALWAYS block if ((block->bbJumpKind == BBJ_COND) && // block is a BBJ_COND block (bNext != nullptr) && // block is not the last block (bNext->bbRefs == 1) && // No other block jumps to bNext (bNext->bbNext == bDest) && // The block after bNext is the BBJ_COND jump dest (bNext->bbJumpKind == BBJ_ALWAYS) && // The next block is a BBJ_ALWAYS block bNext->isEmpty() && // and it is an an empty block (bNext != bNext->bbJumpDest) && // special case for self jumps (bDest != fgFirstColdBlock)) { bool optimizeJump = true; // We do not optimize jumps between two different try regions. // However jumping to a block that is not in any try region is OK // if (bDest->hasTryIndex() && !BasicBlock::sameTryRegion(block, bDest)) { optimizeJump = false; } // Also consider bNext's try region // if (bNext->hasTryIndex() && !BasicBlock::sameTryRegion(block, bNext)) { optimizeJump = false; } // If we are optimizing using real profile weights // then don't optimize a conditional jump to an unconditional jump // until after we have computed the edge weights // if (fgIsUsingProfileWeights()) { // if block and bdest are in different hot/cold regions we can't do this this optimization // because we can't allow fall-through into the cold region. if (!fgEdgeWeightsComputed || fgInDifferentRegions(block, bDest)) { fgNeedsUpdateFlowGraph = true; optimizeJump = false; } } if (optimizeJump) { #ifdef DEBUG if (verbose) { printf("\nReversing a conditional jump around an unconditional jump (" FMT_BB " -> " FMT_BB " -> " FMT_BB ")\n", block->bbNum, bDest->bbNum, bNext->bbJumpDest->bbNum); } #endif // DEBUG /* Reverse the jump condition */ GenTree* test = block->lastNode(); noway_assert(test->OperIsConditionalJump()); if (test->OperGet() == GT_JTRUE) { GenTree* cond = gtReverseCond(test->gtOp.gtOp1); assert(cond == test->gtOp.gtOp1); // Ensure `gtReverseCond` did not create a new node. test->gtOp.gtOp1 = cond; } else { gtReverseCond(test); } // Optimize the Conditional JUMP to go to the new target block->bbJumpDest = bNext->bbJumpDest; fgAddRefPred(bNext->bbJumpDest, block, fgRemoveRefPred(bNext->bbJumpDest, bNext)); /* Unlink bNext from the BasicBlock list; note that we can do this even though other blocks could jump to it - the reason is that elsewhere in this function we always redirect jumps to jumps to jump to the final label, so even if another block jumps to bNext it won't matter once we're done since any such jump will be redirected to the final target by the time we're done here. */ fgRemoveRefPred(bNext, block); fgUnlinkBlock(bNext); /* Mark the block as removed */ bNext->bbFlags |= BBF_REMOVED; // If this is the first Cold basic block update fgFirstColdBlock if (bNext == fgFirstColdBlock) { fgFirstColdBlock = bNext->bbNext; } // // If we removed the end of a try region or handler region // we will need to update ebdTryLast or ebdHndLast. // EHblkDsc* HBtab; EHblkDsc* HBtabEnd; for (HBtab = compHndBBtab, HBtabEnd = compHndBBtab + compHndBBtabCount; HBtab < HBtabEnd; HBtab++) { if ((HBtab->ebdTryLast == bNext) || (HBtab->ebdHndLast == bNext)) { fgSkipRmvdBlocks(HBtab); } } // we optimized this JUMP - goto REPEAT to catch similar cases change = true; modified = true; #ifdef DEBUG if (verbose) { printf("\nAfter reversing the jump:\n"); fgDispBasicBlocks(verboseTrees); } #endif // DEBUG /* For a rare special case we cannot jump to REPEAT as jumping to REPEAT will cause us to delete 'block' because it currently appears to be unreachable. As it is a self loop that only has a single bbRef (itself) However since the unlinked bNext has additional bbRefs (that we will later connect to 'block'), it is not really unreachable. */ if ((bNext->bbRefs > 0) && (bNext->bbJumpDest == block) && (block->bbRefs == 1)) { continue; } goto REPEAT; } } } // // Update the switch jump table such that it follows jumps to jumps: // if (block->bbJumpKind == BBJ_SWITCH) { if (fgOptimizeSwitchBranches(block)) { change = true; modified = true; goto REPEAT; } } noway_assert(!(block->bbFlags & BBF_REMOVED)); /* COMPACT blocks if possible */ if (fgCanCompactBlocks(block, bNext)) { fgCompactBlocks(block, bNext); /* we compacted two blocks - goto REPEAT to catch similar cases */ change = true; modified = true; goto REPEAT; } /* Remove unreachable or empty blocks - do not consider blocks marked BBF_DONT_REMOVE or genReturnBB block * These include first and last block of a TRY, exception handlers and RANGE_CHECK_FAIL THROW blocks */ if ((block->bbFlags & BBF_DONT_REMOVE) == BBF_DONT_REMOVE || block == genReturnBB) { bPrev = block; continue; } #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) // Don't remove the BBJ_ALWAYS block of a BBJ_CALLFINALLY/BBJ_ALWAYS pair. if (block->countOfInEdges() == 0 && bPrev->bbJumpKind == BBJ_CALLFINALLY) { assert(bPrev->isBBCallAlwaysPair()); noway_assert(!(bPrev->bbFlags & BBF_RETLESS_CALL)); noway_assert(block->bbJumpKind == BBJ_ALWAYS); bPrev = block; continue; } #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) noway_assert(!block->bbCatchTyp); noway_assert(!(block->bbFlags & BBF_TRY_BEG)); /* Remove unreachable blocks * * We'll look for blocks that have countOfInEdges() = 0 (blocks may become * unreachable due to a BBJ_ALWAYS introduced by conditional folding for example) */ if (block->countOfInEdges() == 0) { /* no references -> unreachable - remove it */ /* For now do not update the bbNum, do it at the end */ fgRemoveBlock(block, true); change = true; modified = true; /* we removed the current block - the rest of the optimizations won't have a target * continue with the next one */ continue; } else if (block->countOfInEdges() == 1) { switch (block->bbJumpKind) { case BBJ_COND: case BBJ_ALWAYS: if (block->bbJumpDest == block) { fgRemoveBlock(block, true); change = true; modified = true; /* we removed the current block - the rest of the optimizations * won't have a target so continue with the next block */ continue; } break; default: break; } } noway_assert(!(block->bbFlags & BBF_REMOVED)); /* Remove EMPTY blocks */ if (block->isEmpty()) { assert(bPrev == block->bbPrev); if (fgOptimizeEmptyBlock(block)) { change = true; modified = true; } /* Have we removed the block? */ if (block->bbFlags & BBF_REMOVED) { /* block was removed - no change to bPrev */ continue; } } /* Set the predecessor of the last reachable block * If we removed the current block, the predecessor remains unchanged * otherwise, since the current block is ok, it becomes the predecessor */ noway_assert(!(block->bbFlags & BBF_REMOVED)); bPrev = block; } } while (change); fgNeedsUpdateFlowGraph = false; #ifdef DEBUG if (verbose && modified) { printf("\nAfter updating the flow graph:\n"); fgDispBasicBlocks(verboseTrees); fgDispHandlerTab(); } if (compRationalIRForm) { for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext) { LIR::AsRange(block).CheckLIR(this); } } fgVerifyHandlerTab(); // Make sure that the predecessor lists are accurate fgDebugCheckBBlist(); fgDebugCheckUpdate(); #endif // DEBUG return modified; } #ifdef _PREFAST_ #pragma warning(pop) #endif /***************************************************************************** * Check that the flow graph is really updated */ #ifdef DEBUG void Compiler::fgDebugCheckUpdate() { if (!compStressCompile(STRESS_CHK_FLOW_UPDATE, 30)) { return; } /* We check for these conditions: * no unreachable blocks -> no blocks have countOfInEdges() = 0 * no empty blocks -> no blocks have bbTreeList = 0 * no un-imported blocks -> no blocks have BBF_IMPORTED not set (this is * kind of redundand with the above, but to make sure) * no un-compacted blocks -> BBJ_NONE followed by block with no jumps to it (countOfInEdges() = 1) */ BasicBlock* prev; BasicBlock* block; for (prev = nullptr, block = fgFirstBB; block != nullptr; prev = block, block = block->bbNext) { /* no unreachable blocks */ if ((block->countOfInEdges() == 0) && !(block->bbFlags & BBF_DONT_REMOVE) #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) // With funclets, we never get rid of the BBJ_ALWAYS part of a BBJ_CALLFINALLY/BBJ_ALWAYS pair, // even if we can prove that the finally block never returns. && (prev == NULL || block->bbJumpKind != BBJ_ALWAYS || !prev->isBBCallAlwaysPair()) #endif // FEATURE_EH_FUNCLETS ) { noway_assert(!"Unreachable block not removed!"); } /* no empty blocks */ if (block->isEmpty() && !(block->bbFlags & BBF_DONT_REMOVE)) { switch (block->bbJumpKind) { case BBJ_CALLFINALLY: case BBJ_EHFINALLYRET: case BBJ_EHFILTERRET: case BBJ_RETURN: /* for BBJ_ALWAYS is probably just a GOTO, but will have to be treated */ case BBJ_ALWAYS: case BBJ_EHCATCHRET: /* These jump kinds are allowed to have empty tree lists */ break; default: /* it may be the case that the block had more than one reference to it * so we couldn't remove it */ if (block->countOfInEdges() == 0) { noway_assert(!"Empty block not removed!"); } break; } } /* no un-imported blocks */ if (!(block->bbFlags & BBF_IMPORTED)) { /* internal blocks do not count */ if (!(block->bbFlags & BBF_INTERNAL)) { noway_assert(!"Non IMPORTED block not removed!"); } } bool prevIsCallAlwaysPair = ((prev != nullptr) && prev->isBBCallAlwaysPair()); // Check for an unnecessary jumps to the next block bool doAssertOnJumpToNextBlock = false; // unless we have a BBJ_COND or BBJ_ALWAYS we can not assert if (block->bbJumpKind == BBJ_COND) { // A conditional branch should never jump to the next block // as it can be folded into a BBJ_NONE; doAssertOnJumpToNextBlock = true; } else if (block->bbJumpKind == BBJ_ALWAYS) { // Generally we will want to assert if a BBJ_ALWAYS branches to the next block doAssertOnJumpToNextBlock = true; // If the BBF_KEEP_BBJ_ALWAYS flag is set we allow it to jump to the next block if (block->bbFlags & BBF_KEEP_BBJ_ALWAYS) { doAssertOnJumpToNextBlock = false; } // A call/always pair is also allowed to jump to the next block if (prevIsCallAlwaysPair) { doAssertOnJumpToNextBlock = false; } // We are allowed to have a branch from a hot 'block' to a cold 'bbNext' // if ((block->bbNext != nullptr) && fgInDifferentRegions(block, block->bbNext)) { doAssertOnJumpToNextBlock = false; } } if (doAssertOnJumpToNextBlock) { if (block->bbJumpDest == block->bbNext) { noway_assert(!"Unnecessary jump to the next block!"); } } /* Make sure BBF_KEEP_BBJ_ALWAYS is set correctly */ if ((block->bbJumpKind == BBJ_ALWAYS) && prevIsCallAlwaysPair) { noway_assert(block->bbFlags & BBF_KEEP_BBJ_ALWAYS); } /* For a BBJ_CALLFINALLY block we make sure that we are followed by */ /* an BBJ_ALWAYS block with BBF_INTERNAL set */ /* or that it's a BBF_RETLESS_CALL */ if (block->bbJumpKind == BBJ_CALLFINALLY) { assert((block->bbFlags & BBF_RETLESS_CALL) || block->isBBCallAlwaysPair()); } /* no un-compacted blocks */ if (fgCanCompactBlocks(block, block->bbNext)) { noway_assert(!"Found un-compacted blocks!"); } } } #endif // DEBUG /***************************************************************************** * We've inserted a new block before 'block' that should be part of the same EH region as 'block'. * Update the EH table to make this so. Also, set the new block to have the right EH region data * (copy the bbTryIndex, bbHndIndex, and bbCatchTyp from 'block' to the new predecessor, and clear * 'bbCatchTyp' from 'block'). */ void Compiler::fgExtendEHRegionBefore(BasicBlock* block) { assert(block->bbPrev != nullptr); BasicBlock* bPrev = block->bbPrev; bPrev->copyEHRegion(block); // The first block (and only the first block) of a handler has bbCatchTyp set bPrev->bbCatchTyp = block->bbCatchTyp; block->bbCatchTyp = BBCT_NONE; EHblkDsc* HBtab; EHblkDsc* HBtabEnd; for (HBtab = compHndBBtab, HBtabEnd = compHndBBtab + compHndBBtabCount; HBtab < HBtabEnd; HBtab++) { /* Multiple pointers in EHblkDsc can point to same block. We can not early out after the first match. */ if (HBtab->ebdTryBeg == block) { #ifdef DEBUG if (verbose) { printf("EH#%u: New first block of try: " FMT_BB "\n", ehGetIndex(HBtab), bPrev->bbNum); } #endif // DEBUG HBtab->ebdTryBeg = bPrev; bPrev->bbFlags |= BBF_TRY_BEG | BBF_DONT_REMOVE | BBF_HAS_LABEL; // clear the TryBeg flag unless it begins another try region if (!bbIsTryBeg(block)) { block->bbFlags &= ~BBF_TRY_BEG; } } if (HBtab->ebdHndBeg == block) { #ifdef DEBUG if (verbose) { printf("EH#%u: New first block of handler: " FMT_BB "\n", ehGetIndex(HBtab), bPrev->bbNum); } #endif // DEBUG // The first block of a handler has an artificial extra refcount. Transfer that to the new block. assert(block->bbRefs > 0); block->bbRefs--; HBtab->ebdHndBeg = bPrev; bPrev->bbFlags |= BBF_DONT_REMOVE | BBF_HAS_LABEL; #if FEATURE_EH_FUNCLETS if (fgFuncletsCreated) { assert((block->bbFlags & BBF_FUNCLET_BEG) != 0); bPrev->bbFlags |= BBF_FUNCLET_BEG; block->bbFlags &= ~BBF_FUNCLET_BEG; } #endif // FEATURE_EH_FUNCLETS bPrev->bbRefs++; // If this is a handler for a filter, the last block of the filter will end with // a BBJ_EJFILTERRET block that has a bbJumpDest that jumps to the first block of // it's handler. So we need to update it to keep things in sync. // if (HBtab->HasFilter()) { BasicBlock* bFilterLast = HBtab->BBFilterLast(); assert(bFilterLast != nullptr); assert(bFilterLast->bbJumpKind == BBJ_EHFILTERRET); assert(bFilterLast->bbJumpDest == block); #ifdef DEBUG if (verbose) { printf("EH#%u: Updating bbJumpDest for filter ret block: " FMT_BB " => " FMT_BB "\n", ehGetIndex(HBtab), bFilterLast->bbNum, bPrev->bbNum); } #endif // DEBUG // Change the bbJumpDest for bFilterLast from the old first 'block' to the new first 'bPrev' bFilterLast->bbJumpDest = bPrev; } } if (HBtab->HasFilter() && (HBtab->ebdFilter == block)) { #ifdef DEBUG if (verbose) { printf("EH#%u: New first block of filter: " FMT_BB "\n", ehGetIndex(HBtab), bPrev->bbNum); } #endif // DEBUG // The first block of a filter has an artificial extra refcount. Transfer that to the new block. assert(block->bbRefs > 0); block->bbRefs--; HBtab->ebdFilter = bPrev; bPrev->bbFlags |= BBF_DONT_REMOVE | BBF_HAS_LABEL; #if FEATURE_EH_FUNCLETS if (fgFuncletsCreated) { assert((block->bbFlags & BBF_FUNCLET_BEG) != 0); bPrev->bbFlags |= BBF_FUNCLET_BEG; block->bbFlags &= ~BBF_FUNCLET_BEG; } #endif // FEATURE_EH_FUNCLETS bPrev->bbRefs++; } } } /***************************************************************************** * We've inserted a new block after 'block' that should be part of the same EH region as 'block'. * Update the EH table to make this so. Also, set the new block to have the right EH region data. */ void Compiler::fgExtendEHRegionAfter(BasicBlock* block) { BasicBlock* newBlk = block->bbNext; assert(newBlk != nullptr); newBlk->copyEHRegion(block); newBlk->bbCatchTyp = BBCT_NONE; // Only the first block of a catch has this set, and 'newBlk' can't be the first block of a catch. // TODO-Throughput: if the block is not in an EH region, then we don't need to walk the EH table looking for 'last' // block pointers to update. ehUpdateLastBlocks(block, newBlk); } /***************************************************************************** * * Insert a BasicBlock before the given block. */ BasicBlock* Compiler::fgNewBBbefore(BBjumpKinds jumpKind, BasicBlock* block, bool extendRegion) { // Create a new BasicBlock and chain it in BasicBlock* newBlk = bbNewBasicBlock(jumpKind); newBlk->bbFlags |= BBF_INTERNAL; fgInsertBBbefore(block, newBlk); newBlk->bbRefs = 0; if (newBlk->bbFallsThrough() && block->isRunRarely()) { newBlk->bbSetRunRarely(); } if (extendRegion) { fgExtendEHRegionBefore(block); } else { // When extendRegion is false the caller is responsible for setting these two values newBlk->setTryIndex(MAX_XCPTN_INDEX); // Note: this is still a legal index, just unlikely newBlk->setHndIndex(MAX_XCPTN_INDEX); // Note: this is still a legal index, just unlikely } // We assume that if the block we are inserting before is in the cold region, then this new // block will also be in the cold region. newBlk->bbFlags |= (block->bbFlags & BBF_COLD); return newBlk; } /***************************************************************************** * * Insert a BasicBlock after the given block. */ BasicBlock* Compiler::fgNewBBafter(BBjumpKinds jumpKind, BasicBlock* block, bool extendRegion) { // Create a new BasicBlock and chain it in BasicBlock* newBlk = bbNewBasicBlock(jumpKind); newBlk->bbFlags |= BBF_INTERNAL; fgInsertBBafter(block, newBlk); newBlk->bbRefs = 0; if (block->bbFallsThrough() && block->isRunRarely()) { newBlk->bbSetRunRarely(); } if (extendRegion) { fgExtendEHRegionAfter(block); } else { // When extendRegion is false the caller is responsible for setting these two values newBlk->setTryIndex(MAX_XCPTN_INDEX); // Note: this is still a legal index, just unlikely newBlk->setHndIndex(MAX_XCPTN_INDEX); // Note: this is still a legal index, just unlikely } // If the new block is in the cold region (because the block we are inserting after // is in the cold region), mark it as such. newBlk->bbFlags |= (block->bbFlags & BBF_COLD); return newBlk; } /***************************************************************************** * Inserts basic block before existing basic block. * * If insertBeforeBlk is in the funclet region, then newBlk will be in the funclet region. * (If insertBeforeBlk is the first block of the funclet region, then 'newBlk' will be the * new first block of the funclet region.) */ void Compiler::fgInsertBBbefore(BasicBlock* insertBeforeBlk, BasicBlock* newBlk) { if (insertBeforeBlk->bbPrev) { fgInsertBBafter(insertBeforeBlk->bbPrev, newBlk); } else { newBlk->setNext(fgFirstBB); fgFirstBB = newBlk; newBlk->bbPrev = nullptr; } #if FEATURE_EH_FUNCLETS /* Update fgFirstFuncletBB if insertBeforeBlk is the first block of the funclet region. */ if (fgFirstFuncletBB == insertBeforeBlk) { fgFirstFuncletBB = newBlk; } #endif // FEATURE_EH_FUNCLETS } /***************************************************************************** * Inserts basic block after existing basic block. * * If insertBeforeBlk is in the funclet region, then newBlk will be in the funclet region. * (It can't be used to insert a block as the first block of the funclet region). */ void Compiler::fgInsertBBafter(BasicBlock* insertAfterBlk, BasicBlock* newBlk) { newBlk->bbNext = insertAfterBlk->bbNext; if (insertAfterBlk->bbNext) { insertAfterBlk->bbNext->bbPrev = newBlk; } insertAfterBlk->bbNext = newBlk; newBlk->bbPrev = insertAfterBlk; if (fgLastBB == insertAfterBlk) { fgLastBB = newBlk; assert(fgLastBB->bbNext == nullptr); } } // We have two edges (bAlt => bCur) and (bCur => bNext). // // Returns true if the weight of (bAlt => bCur) // is greater than the weight of (bCur => bNext). // We compare the edge weights if we have valid edge weights // otherwise we compare blocks weights. // bool Compiler::fgIsBetterFallThrough(BasicBlock* bCur, BasicBlock* bAlt) { // bCur can't be NULL and must be a fall through bbJumpKind noway_assert(bCur != nullptr); noway_assert(bCur->bbFallsThrough()); noway_assert(bAlt != nullptr); // We only handle the cases when bAlt is a BBJ_ALWAYS or a BBJ_COND if ((bAlt->bbJumpKind != BBJ_ALWAYS) && (bAlt->bbJumpKind != BBJ_COND)) { return false; } // if bAlt doesn't jump to bCur it can't be a better fall through than bCur if (bAlt->bbJumpDest != bCur) { return false; } // Currently bNext is the fall through for bCur BasicBlock* bNext = bCur->bbNext; noway_assert(bNext != nullptr); // We will set result to true if bAlt is a better fall through than bCur bool result; if (fgHaveValidEdgeWeights) { // We will compare the edge weight for our two choices flowList* edgeFromAlt = fgGetPredForBlock(bCur, bAlt); flowList* edgeFromCur = fgGetPredForBlock(bNext, bCur); noway_assert(edgeFromCur != nullptr); noway_assert(edgeFromAlt != nullptr); result = (edgeFromAlt->flEdgeWeightMin > edgeFromCur->flEdgeWeightMax); } else { if (bAlt->bbJumpKind == BBJ_ALWAYS) { // Our result is true if bAlt's weight is more than bCur's weight result = (bAlt->bbWeight > bCur->bbWeight); } else { noway_assert(bAlt->bbJumpKind == BBJ_COND); // Our result is true if bAlt's weight is more than twice bCur's weight result = (bAlt->bbWeight > (2 * bCur->bbWeight)); } } return result; } //------------------------------------------------------------------------ // fgCheckEHCanInsertAfterBlock: Determine if a block can be inserted after // 'blk' and legally be put in the EH region specified by 'regionIndex'. This // can be true if the most nested region the block is in is already 'regionIndex', // as we'll just extend the most nested region (and any region ending at the same block). // It can also be true if it is the end of (a set of) EH regions, such that // inserting the block and properly extending some EH regions (if necessary) // puts the block in the correct region. We only consider the case of extending // an EH region after 'blk' (that is, to include 'blk' and the newly insert block); // we don't consider inserting a block as the the first block of an EH region following 'blk'. // // Consider this example: // // try3 try2 try1 // |--- | | BB01 // | |--- | BB02 // | | |--- BB03 // | | | BB04 // | |--- |--- BB05 // | BB06 // |----------------- BB07 // // Passing BB05 and try1/try2/try3 as the region to insert into (as well as putInTryRegion==true) // will all return 'true'. Here are the cases: // 1. Insert into try1: the most nested EH region BB05 is in is already try1, so we can insert after // it and extend try1 (and try2). // 2. Insert into try2: we can extend try2, but leave try1 alone. // 3. Insert into try3: we can leave try1 and try2 alone, and put the new block just in try3. Note that // in this case, after we "loop outwards" in the EH nesting, we get to a place where we're in the middle // of the try3 region, not at the end of it. // In all cases, it is possible to put a block after BB05 and put it in any of these three 'try' regions legally. // // Filters are ignored; if 'blk' is in a filter, the answer will be false. // // Arguments: // blk - the BasicBlock we are checking to see if we can insert after. // regionIndex - the EH region we want to insert a block into. regionIndex is // in the range [0..compHndBBtabCount]; 0 means "main method". // putInTryRegion - 'true' if the new block should be inserted in the 'try' region of 'regionIndex'. // For regionIndex 0 (the "main method"), this should be 'true'. // // Return Value: // 'true' if a block can be inserted after 'blk' and put in EH region 'regionIndex', else 'false'. // bool Compiler::fgCheckEHCanInsertAfterBlock(BasicBlock* blk, unsigned regionIndex, bool putInTryRegion) { assert(blk != nullptr); assert(regionIndex <= compHndBBtabCount); if (regionIndex == 0) { assert(putInTryRegion); } bool inTryRegion; unsigned nestedRegionIndex = ehGetMostNestedRegionIndex(blk, &inTryRegion); bool insertOK = true; for (;;) { if (nestedRegionIndex == regionIndex) { // This block is in the region we want to be in. We can insert here if it's the right type of region. // (If we want to be in the 'try' region, but the block is in the handler region, then inserting a // new block after 'blk' can't put it in the 'try' region, and vice-versa, since we only consider // extending regions after, not prepending to regions.) // This check will be 'true' if we are trying to put something in the main function (as putInTryRegion // must be 'true' if regionIndex is zero, and inTryRegion will also be 'true' if nestedRegionIndex is zero). insertOK = (putInTryRegion == inTryRegion); break; } else if (nestedRegionIndex == 0) { // The block is in the main function, but we want to put something in a nested region. We can't do that. insertOK = false; break; } assert(nestedRegionIndex > 0); EHblkDsc* ehDsc = ehGetDsc(nestedRegionIndex - 1); // ehGetDsc uses [0..compHndBBtabCount) form. if (inTryRegion) { if (blk != ehDsc->ebdTryLast) { // Not the last block? Then it must be somewhere else within the try region, so we can't insert here. insertOK = false; break; // exit the 'for' loop } } else { // We ignore filters. if (blk != ehDsc->ebdHndLast) { // Not the last block? Then it must be somewhere else within the handler region, so we can't insert // here. insertOK = false; break; // exit the 'for' loop } } // Things look good for this region; check the enclosing regions, if any. nestedRegionIndex = ehGetEnclosingRegionIndex(nestedRegionIndex - 1, &inTryRegion); // ehGetEnclosingRegionIndex uses [0..compHndBBtabCount) form. // Convert to [0..compHndBBtabCount] form. nestedRegionIndex = (nestedRegionIndex == EHblkDsc::NO_ENCLOSING_INDEX) ? 0 : nestedRegionIndex + 1; } // end of for(;;) return insertOK; } //------------------------------------------------------------------------ // Finds the block closest to endBlk in the range [startBlk..endBlk) after which a block can be // inserted easily. Note that endBlk cannot be returned; its predecessor is the last block that can // be returned. The new block will be put in an EH region described by the arguments regionIndex, // putInTryRegion, startBlk, and endBlk (explained below), so it must be legal to place to put the // new block after the insertion location block, give it the specified EH region index, and not break // EH nesting rules. This function is careful to choose a block in the correct EH region. However, // it assumes that the new block can ALWAYS be placed at the end (just before endBlk). That means // that the caller must ensure that is true. // // Below are the possible cases for the arguments to this method: // 1. putInTryRegion == true and regionIndex > 0: // Search in the try region indicated by regionIndex. // 2. putInTryRegion == false and regionIndex > 0: // a. If startBlk is the first block of a filter and endBlk is the block after the end of the // filter (that is, the startBlk and endBlk match a filter bounds exactly), then choose a // location within this filter region. (Note that, due to IL rules, filters do not have any // EH nested within them.) Otherwise, filters are skipped. // b. Else, search in the handler region indicated by regionIndex. // 3. regionIndex = 0: // Search in the entire main method, excluding all EH regions. In this case, putInTryRegion must be true. // // This method makes sure to find an insertion point which would not cause the inserted block to // be put inside any inner try/filter/handler regions. // // The actual insertion occurs after the returned block. Note that the returned insertion point might // be the last block of a more nested EH region, because the new block will be inserted after the insertion // point, and will not extend the more nested EH region. For example: // // try3 try2 try1 // |--- | | BB01 // | |--- | BB02 // | | |--- BB03 // | | | BB04 // | |--- |--- BB05 // | BB06 // |----------------- BB07 // // for regionIndex==try3, putInTryRegion==true, we might return BB05, even though BB05 will have a try index // for try1 (the most nested 'try' region the block is in). That's because when we insert after BB05, the new // block will be in the correct, desired EH region, since try1 and try2 regions will not be extended to include // the inserted block. Furthermore, for regionIndex==try2, putInTryRegion==true, we can also return BB05. In this // case, when the new block is inserted, the try1 region remains the same, but we need extend region 'try2' to // include the inserted block. (We also need to check all parent regions as well, just in case any parent regions // also end on the same block, in which case we would also need to extend the parent regions. This is standard // procedure when inserting a block at the end of an EH region.) // // If nearBlk is non-nullptr then we return the closest block after nearBlk that will work best. // // We try to find a block in the appropriate region that is not a fallthrough block, so we can insert after it // without the need to insert a jump around the inserted block. // // Note that regionIndex is numbered the same as BasicBlock::bbTryIndex and BasicBlock::bbHndIndex, that is, "0" is // "main method" and otherwise is +1 from normal, so we can call, e.g., ehGetDsc(tryIndex - 1). // // Arguments: // regionIndex - the region index where the new block will be inserted. Zero means entire method; // non-zero means either a "try" or a "handler" region, depending on what putInTryRegion says. // putInTryRegion - 'true' to put the block in the 'try' region corresponding to 'regionIndex', 'false' // to put the block in the handler region. Should be 'true' if regionIndex==0. // startBlk - start block of range to search. // endBlk - end block of range to search (don't include this block in the range). Can be nullptr to indicate // the end of the function. // nearBlk - If non-nullptr, try to find an insertion location closely after this block. If nullptr, we insert // at the best location found towards the end of the acceptable block range. // jumpBlk - When nearBlk is set, this can be set to the block which jumps to bNext->bbNext (TODO: need to review // this?) // runRarely - true if the block being inserted is expected to be rarely run. This helps determine // the best place to put the new block, by putting in a place that has the same 'rarely run' characteristic. // // Return Value: // A block with the desired characteristics, so the new block will be inserted after this one. // If there is no suitable location, return nullptr. This should basically never happen. // BasicBlock* Compiler::fgFindInsertPoint(unsigned regionIndex, bool putInTryRegion, BasicBlock* startBlk, BasicBlock* endBlk, BasicBlock* nearBlk, BasicBlock* jumpBlk, bool runRarely) { noway_assert(startBlk != nullptr); noway_assert(startBlk != endBlk); noway_assert((regionIndex == 0 && putInTryRegion) || // Search in the main method (putInTryRegion && regionIndex > 0 && startBlk->bbTryIndex == regionIndex) || // Search in the specified try region (!putInTryRegion && regionIndex > 0 && startBlk->bbHndIndex == regionIndex)); // Search in the specified handler region #ifdef DEBUG // Assert that startBlk precedes endBlk in the block list. // We don't want to use bbNum to assert this condition, as we cannot depend on the block numbers being // sequential at all times. for (BasicBlock* b = startBlk; b != endBlk; b = b->bbNext) { assert(b != nullptr); // We reached the end of the block list, but never found endBlk. } #endif // DEBUG JITDUMP("fgFindInsertPoint(regionIndex=%u, putInTryRegion=%s, startBlk=" FMT_BB ", endBlk=" FMT_BB ", nearBlk=" FMT_BB ", " "jumpBlk=" FMT_BB ", runRarely=%s)\n", regionIndex, dspBool(putInTryRegion), startBlk->bbNum, (endBlk == nullptr) ? 0 : endBlk->bbNum, (nearBlk == nullptr) ? 0 : nearBlk->bbNum, (jumpBlk == nullptr) ? 0 : jumpBlk->bbNum, dspBool(runRarely)); bool insertingIntoFilter = false; if (!putInTryRegion) { EHblkDsc* const dsc = ehGetDsc(regionIndex - 1); insertingIntoFilter = dsc->HasFilter() && (startBlk == dsc->ebdFilter) && (endBlk == dsc->ebdHndBeg); } bool reachedNear = false; // Have we reached 'nearBlk' in our search? If not, we'll keep searching. bool inFilter = false; // Are we in a filter region that we need to skip? BasicBlock* bestBlk = nullptr; // Set to the best insertion point we've found so far that meets all the EH requirements. BasicBlock* goodBlk = nullptr; // Set to an acceptable insertion point that we'll use if we don't find a 'best' option. BasicBlock* blk; if (nearBlk != nullptr) { // Does the nearBlk precede the startBlk? for (blk = nearBlk; blk != nullptr; blk = blk->bbNext) { if (blk == startBlk) { reachedNear = true; break; } else if (blk == endBlk) { break; } } } for (blk = startBlk; blk != endBlk; blk = blk->bbNext) { // The only way (blk == nullptr) could be true is if the caller passed an endBlk that preceded startBlk in the // block list, or if endBlk isn't in the block list at all. In DEBUG, we'll instead hit the similar // well-formedness assert earlier in this function. noway_assert(blk != nullptr); if (blk == nearBlk) { reachedNear = true; } if (blk->bbCatchTyp == BBCT_FILTER) { // Record the fact that we entered a filter region, so we don't insert into filters... // Unless the caller actually wanted the block inserted in this exact filter region. if (!insertingIntoFilter || (blk != startBlk)) { inFilter = true; } } else if (blk->bbCatchTyp == BBCT_FILTER_HANDLER) { // Record the fact that we exited a filter region. inFilter = false; } // Don't insert a block inside this filter region. if (inFilter) { continue; } // Note that the new block will be inserted AFTER "blk". We check to make sure that doing so // would put the block in the correct EH region. We make an assumption here that you can // ALWAYS insert the new block before "endBlk" (that is, at the end of the search range) // and be in the correct EH region. This is must be guaranteed by the caller (as it is by // fgNewBBinRegion(), which passes the search range as an exact EH region block range). // Because of this assumption, we only check the EH information for blocks before the last block. if (blk->bbNext != endBlk) { // We are in the middle of the search range. We can't insert the new block in // an inner try or handler region. We can, however, set the insertion // point to the last block of an EH try/handler region, if the enclosing // region is the region we wish to insert in. (Since multiple regions can // end at the same block, we need to search outwards, checking that the // block is the last block of every EH region out to the region we want // to insert in.) This is especially useful for putting a call-to-finally // block on AMD64 immediately after its corresponding 'try' block, so in the // common case, we'll just fall through to it. For example: // // BB01 // BB02 -- first block of try // BB03 // BB04 -- last block of try // BB05 -- first block of finally // BB06 // BB07 -- last block of handler // BB08 // // Assume there is only one try/finally, so BB01 and BB08 are in the "main function". // For AMD64 call-to-finally, we'll want to insert the BBJ_CALLFINALLY in // the main function, immediately after BB04. This allows us to do that. if (!fgCheckEHCanInsertAfterBlock(blk, regionIndex, putInTryRegion)) { // Can't insert here. continue; } } // Look for an insert location: // 1. We want blocks that don't end with a fall through, // 2. Also, when blk equals nearBlk we may want to insert here. if (!blk->bbFallsThrough() || (blk == nearBlk)) { bool updateBestBlk = true; // We will probably update the bestBlk // If blk falls through then we must decide whether to use the nearBlk // hint if (blk->bbFallsThrough()) { noway_assert(blk == nearBlk); if (jumpBlk != nullptr) { updateBestBlk = fgIsBetterFallThrough(blk, jumpBlk); } else { updateBestBlk = false; } } // If we already have a best block, see if the 'runRarely' flags influences // our choice. If we want a runRarely insertion point, and the existing best // block is run rarely but the current block isn't run rarely, then don't // update the best block. // TODO-CQ: We should also handle the reverse case, where runRarely is false (we // want a non-rarely-run block), but bestBlock->isRunRarely() is true. In that // case, we should update the block, also. Probably what we want is: // (bestBlk->isRunRarely() != runRarely) && (blk->isRunRarely() == runRarely) if (updateBestBlk && (bestBlk != nullptr) && runRarely && bestBlk->isRunRarely() && !blk->isRunRarely()) { updateBestBlk = false; } if (updateBestBlk) { // We found a 'best' insertion location, so save it away. bestBlk = blk; // If we've reached nearBlk, we've satisfied all the criteria, // so we're done. if (reachedNear) { goto DONE; } // If we haven't reached nearBlk, keep looking for a 'best' location, just // in case we'll find one at or after nearBlk. If no nearBlk was specified, // we prefer inserting towards the end of the given range, so keep looking // for more acceptable insertion locations. } } // No need to update goodBlk after we have set bestBlk, but we could still find a better // bestBlk, so keep looking. if (bestBlk != nullptr) { continue; } // Set the current block as a "good enough" insertion point, if it meets certain criteria. // We'll return this block if we don't find a "best" block in the search range. The block // can't be a BBJ_CALLFINALLY of a BBJ_CALLFINALLY/BBJ_ALWAYS pair (since we don't want // to insert anything between these two blocks). Otherwise, we can use it. However, // if we'd previously chosen a BBJ_COND block, then we'd prefer the "good" block to be // something else. We keep updating it until we've reached the 'nearBlk', to push it as // close to endBlk as possible. if (!blk->isBBCallAlwaysPair()) { if (goodBlk == nullptr) { goodBlk = blk; } else if ((goodBlk->bbJumpKind == BBJ_COND) || (blk->bbJumpKind != BBJ_COND)) { if ((blk == nearBlk) || !reachedNear) { goodBlk = blk; } } } } // If we didn't find a non-fall_through block, then insert at the last good block. if (bestBlk == nullptr) { bestBlk = goodBlk; } DONE: #if defined(JIT32_GCENCODER) // If we are inserting into a filter and the best block is the end of the filter region, we need to // insert after its predecessor instead: the JIT32 GC encoding used by the x86 CLR ABI states that the // terminal block of a filter region is its exit block. If the filter region consists of a single block, // a new block cannot be inserted without either splitting the single block before inserting a new block // or inserting the new block before the single block and updating the filter description such that the // inserted block is marked as the entry block for the filter. Becuase this sort of split can be complex // (especially given that it must ensure that the liveness of the exception object is properly tracked), // we avoid this situation by never generating single-block filters on x86 (see impPushCatchArgOnStack). if (insertingIntoFilter && (bestBlk == endBlk->bbPrev)) { assert(bestBlk != startBlk); bestBlk = bestBlk->bbPrev; } #endif // defined(JIT32_GCENCODER) return bestBlk; } //------------------------------------------------------------------------ // Creates a new BasicBlock and inserts it in a specific EH region, given by 'tryIndex', 'hndIndex', and 'putInFilter'. // // If 'putInFilter' it true, then the block is inserted in the filter region given by 'hndIndex'. In this case, tryIndex // must be a less nested EH region (that is, tryIndex > hndIndex). // // Otherwise, the block is inserted in either the try region or the handler region, depending on which one is the inner // region. In other words, if the try region indicated by tryIndex is nested in the handler region indicated by // hndIndex, // then the new BB will be created in the try region. Vice versa. // // Note that tryIndex and hndIndex are numbered the same as BasicBlock::bbTryIndex and BasicBlock::bbHndIndex, that is, // "0" is "main method" and otherwise is +1 from normal, so we can call, e.g., ehGetDsc(tryIndex - 1). // // To be more specific, this function will create a new BB in one of the following 5 regions (if putInFilter is false): // 1. When tryIndex = 0 and hndIndex = 0: // The new BB will be created in the method region. // 2. When tryIndex != 0 and hndIndex = 0: // The new BB will be created in the try region indicated by tryIndex. // 3. When tryIndex == 0 and hndIndex != 0: // The new BB will be created in the handler region indicated by hndIndex. // 4. When tryIndex != 0 and hndIndex != 0 and tryIndex < hndIndex: // In this case, the try region is nested inside the handler region. Therefore, the new BB will be created // in the try region indicated by tryIndex. // 5. When tryIndex != 0 and hndIndex != 0 and tryIndex > hndIndex: // In this case, the handler region is nested inside the try region. Therefore, the new BB will be created // in the handler region indicated by hndIndex. // // Note that if tryIndex != 0 and hndIndex != 0 then tryIndex must not be equal to hndIndex (this makes sense because // if they are equal, you are asking to put the new block in both the try and handler, which is impossible). // // The BasicBlock will not be inserted inside an EH region that is more nested than the requested tryIndex/hndIndex // region (so the function is careful to skip more nested EH regions when searching for a place to put the new block). // // This function cannot be used to insert a block as the first block of any region. It always inserts a block after // an existing block in the given region. // // If nearBlk is nullptr, or the block is run rarely, then the new block is assumed to be run rarely. // // Arguments: // jumpKind - the jump kind of the new block to create. // tryIndex - the try region to insert the new block in, described above. This must be a number in the range // [0..compHndBBtabCount]. // hndIndex - the handler region to insert the new block in, described above. This must be a number in the range // [0..compHndBBtabCount]. // nearBlk - insert the new block closely after this block, if possible. If nullptr, put the new block anywhere // in the requested region. // putInFilter - put the new block in the filter region given by hndIndex, as described above. // runRarely - 'true' if the new block is run rarely. // insertAtEnd - 'true' if the block should be inserted at the end of the region. Note: this is currently only // implemented when inserting into the main function (not into any EH region). // // Return Value: // The new block. BasicBlock* Compiler::fgNewBBinRegion(BBjumpKinds jumpKind, unsigned tryIndex, unsigned hndIndex, BasicBlock* nearBlk, bool putInFilter /* = false */, bool runRarely /* = false */, bool insertAtEnd /* = false */) { assert(tryIndex <= compHndBBtabCount); assert(hndIndex <= compHndBBtabCount); /* afterBlk is the block which will precede the newBB */ BasicBlock* afterBlk; // start and end limit for inserting the block BasicBlock* startBlk = nullptr; BasicBlock* endBlk = nullptr; bool putInTryRegion = true; unsigned regionIndex = 0; // First, figure out which region (the "try" region or the "handler" region) to put the newBB in. if ((tryIndex == 0) && (hndIndex == 0)) { assert(!putInFilter); endBlk = fgEndBBAfterMainFunction(); // don't put new BB in funclet region if (insertAtEnd || (nearBlk == nullptr)) { /* We'll just insert the block at the end of the method, before the funclets */ afterBlk = fgLastBBInMainFunction(); goto _FoundAfterBlk; } else { // We'll search through the entire method startBlk = fgFirstBB; } noway_assert(regionIndex == 0); } else { noway_assert(tryIndex > 0 || hndIndex > 0); PREFIX_ASSUME(tryIndex <= compHndBBtabCount); PREFIX_ASSUME(hndIndex <= compHndBBtabCount); // Decide which region to put in, the "try" region or the "handler" region. if (tryIndex == 0) { noway_assert(hndIndex > 0); putInTryRegion = false; } else if (hndIndex == 0) { noway_assert(tryIndex > 0); noway_assert(putInTryRegion); assert(!putInFilter); } else { noway_assert(tryIndex > 0 && hndIndex > 0 && tryIndex != hndIndex); putInTryRegion = (tryIndex < hndIndex); } if (putInTryRegion) { // Try region is the inner region. // In other words, try region must be nested inside the handler region. noway_assert(hndIndex == 0 || bbInHandlerRegions(hndIndex - 1, ehGetDsc(tryIndex - 1)->ebdTryBeg)); assert(!putInFilter); } else { // Handler region is the inner region. // In other words, handler region must be nested inside the try region. noway_assert(tryIndex == 0 || bbInTryRegions(tryIndex - 1, ehGetDsc(hndIndex - 1)->ebdHndBeg)); } // Figure out the start and end block range to search for an insertion location. Pick the beginning and // ending blocks of the target EH region (the 'endBlk' is one past the last block of the EH region, to make // loop iteration easier). Note that, after funclets have been created (for FEATURE_EH_FUNCLETS), // this linear block range will not include blocks of handlers for try/handler clauses nested within // this EH region, as those blocks have been extracted as funclets. That is ok, though, because we don't // want to insert a block in any nested EH region. if (putInTryRegion) { // We will put the newBB in the try region. EHblkDsc* ehDsc = ehGetDsc(tryIndex - 1); startBlk = ehDsc->ebdTryBeg; endBlk = ehDsc->ebdTryLast->bbNext; regionIndex = tryIndex; } else if (putInFilter) { // We will put the newBB in the filter region. EHblkDsc* ehDsc = ehGetDsc(hndIndex - 1); startBlk = ehDsc->ebdFilter; endBlk = ehDsc->ebdHndBeg; regionIndex = hndIndex; } else { // We will put the newBB in the handler region. EHblkDsc* ehDsc = ehGetDsc(hndIndex - 1); startBlk = ehDsc->ebdHndBeg; endBlk = ehDsc->ebdHndLast->bbNext; regionIndex = hndIndex; } noway_assert(regionIndex > 0); } // Now find the insertion point. afterBlk = fgFindInsertPoint(regionIndex, putInTryRegion, startBlk, endBlk, nearBlk, nullptr, runRarely); _FoundAfterBlk:; /* We have decided to insert the block after 'afterBlk'. */ noway_assert(afterBlk != nullptr); JITDUMP("fgNewBBinRegion(jumpKind=%u, tryIndex=%u, hndIndex=%u, putInFilter=%s, runRarely=%s, insertAtEnd=%s): " "inserting after " FMT_BB "\n", jumpKind, tryIndex, hndIndex, dspBool(putInFilter), dspBool(runRarely), dspBool(insertAtEnd), afterBlk->bbNum); return fgNewBBinRegionWorker(jumpKind, afterBlk, regionIndex, putInTryRegion); } //------------------------------------------------------------------------ // Creates a new BasicBlock and inserts it in the same EH region as 'srcBlk'. // // See the implementation of fgNewBBinRegion() used by this one for more notes. // // Arguments: // jumpKind - the jump kind of the new block to create. // srcBlk - insert the new block in the same EH region as this block, and closely after it if possible. // // Return Value: // The new block. BasicBlock* Compiler::fgNewBBinRegion(BBjumpKinds jumpKind, BasicBlock* srcBlk, bool runRarely /* = false */, bool insertAtEnd /* = false */) { assert(srcBlk != nullptr); const unsigned tryIndex = srcBlk->bbTryIndex; const unsigned hndIndex = srcBlk->bbHndIndex; bool putInFilter = false; // Check to see if we need to put the new block in a filter. We do if srcBlk is in a filter. // This can only be true if there is a handler index, and the handler region is more nested than the // try region (if any). This is because no EH regions can be nested within a filter. if (BasicBlock::ehIndexMaybeMoreNested(hndIndex, tryIndex)) { assert(hndIndex != 0); // If hndIndex is more nested, we must be in some handler! putInFilter = ehGetDsc(hndIndex - 1)->InFilterRegionBBRange(srcBlk); } return fgNewBBinRegion(jumpKind, tryIndex, hndIndex, srcBlk, putInFilter, runRarely, insertAtEnd); } //------------------------------------------------------------------------ // Creates a new BasicBlock and inserts it at the end of the function. // // See the implementation of fgNewBBinRegion() used by this one for more notes. // // Arguments: // jumpKind - the jump kind of the new block to create. // // Return Value: // The new block. BasicBlock* Compiler::fgNewBBinRegion(BBjumpKinds jumpKind) { return fgNewBBinRegion(jumpKind, 0, 0, nullptr, /* putInFilter */ false, /* runRarely */ false, /* insertAtEnd */ true); } //------------------------------------------------------------------------ // Creates a new BasicBlock, and inserts it after 'afterBlk'. // // The block cannot be inserted into a more nested try/handler region than that specified by 'regionIndex'. // (It is given exactly 'regionIndex'.) Thus, the parameters must be passed to ensure proper EH nesting // rules are followed. // // Arguments: // jumpKind - the jump kind of the new block to create. // afterBlk - insert the new block after this one. // regionIndex - the block will be put in this EH region. // putInTryRegion - If true, put the new block in the 'try' region corresponding to 'regionIndex', and // set its handler index to the most nested handler region enclosing that 'try' region. // Otherwise, put the block in the handler region specified by 'regionIndex', and set its 'try' // index to the most nested 'try' region enclosing that handler region. // // Return Value: // The new block. BasicBlock* Compiler::fgNewBBinRegionWorker(BBjumpKinds jumpKind, BasicBlock* afterBlk, unsigned regionIndex, bool putInTryRegion) { /* Insert the new block */ BasicBlock* afterBlkNext = afterBlk->bbNext; (void)afterBlkNext; // prevent "unused variable" error from GCC BasicBlock* newBlk = fgNewBBafter(jumpKind, afterBlk, false); if (putInTryRegion) { noway_assert(regionIndex <= MAX_XCPTN_INDEX); newBlk->bbTryIndex = (unsigned short)regionIndex; newBlk->bbHndIndex = bbFindInnermostHandlerRegionContainingTryRegion(regionIndex); } else { newBlk->bbTryIndex = bbFindInnermostTryRegionContainingHandlerRegion(regionIndex); noway_assert(regionIndex <= MAX_XCPTN_INDEX); newBlk->bbHndIndex = (unsigned short)regionIndex; } // We're going to compare for equal try regions (to handle the case of 'mutually protect' // regions). We need to save off the current try region, otherwise we might change it // before it gets compared later, thereby making future comparisons fail. BasicBlock* newTryBeg; BasicBlock* newTryLast; (void)ehInitTryBlockRange(newBlk, &newTryBeg, &newTryLast); unsigned XTnum; EHblkDsc* HBtab; for (XTnum = 0, HBtab = compHndBBtab; XTnum < compHndBBtabCount; XTnum++, HBtab++) { // Is afterBlk at the end of a try region? if (HBtab->ebdTryLast == afterBlk) { noway_assert(afterBlkNext == newBlk->bbNext); bool extendTryRegion = false; if (newBlk->hasTryIndex()) { // We're adding a block after the last block of some try region. Do // we extend the try region to include the block, or not? // If the try region is exactly the same as the try region // associated with the new block (based on the block's try index, // which represents the innermost try the block is a part of), then // we extend it. // If the try region is a "parent" try region -- an enclosing try region // that has the same last block as the new block's try region -- then // we also extend. For example: // try { // 1 // ... // try { // 2 // ... // } /* 2 */ } /* 1 */ // This example is meant to indicate that both try regions 1 and 2 end at // the same block, and we're extending 2. Thus, we must also extend 1. If we // only extended 2, we would break proper nesting. (Dev11 bug 137967) extendTryRegion = HBtab->ebdIsSameTry(newTryBeg, newTryLast) || bbInTryRegions(XTnum, newBlk); } // Does newBlk extend this try region? if (extendTryRegion) { // Yes, newBlk extends this try region // newBlk is the now the new try last block fgSetTryEnd(HBtab, newBlk); } } // Is afterBlk at the end of a handler region? if (HBtab->ebdHndLast == afterBlk) { noway_assert(afterBlkNext == newBlk->bbNext); // Does newBlk extend this handler region? bool extendHndRegion = false; if (newBlk->hasHndIndex()) { // We're adding a block after the last block of some handler region. Do // we extend the handler region to include the block, or not? // If the handler region is exactly the same as the handler region // associated with the new block (based on the block's handler index, // which represents the innermost handler the block is a part of), then // we extend it. // If the handler region is a "parent" handler region -- an enclosing // handler region that has the same last block as the new block's handler // region -- then we also extend. For example: // catch { // 1 // ... // catch { // 2 // ... // } /* 2 */ } /* 1 */ // This example is meant to indicate that both handler regions 1 and 2 end at // the same block, and we're extending 2. Thus, we must also extend 1. If we // only extended 2, we would break proper nesting. (Dev11 bug 372051) extendHndRegion = bbInHandlerRegions(XTnum, newBlk); } if (extendHndRegion) { // Yes, newBlk extends this handler region // newBlk is now the last block of the handler. fgSetHndEnd(HBtab, newBlk); } } } /* If afterBlk falls through, we insert a jump around newBlk */ fgConnectFallThrough(afterBlk, newBlk->bbNext); #ifdef DEBUG fgVerifyHandlerTab(); #endif return newBlk; } /***************************************************************************** */ /* static */ unsigned Compiler::acdHelper(SpecialCodeKind codeKind) { switch (codeKind) { case SCK_RNGCHK_FAIL: return CORINFO_HELP_RNGCHKFAIL; case SCK_ARG_EXCPN: return CORINFO_HELP_THROW_ARGUMENTEXCEPTION; case SCK_ARG_RNG_EXCPN: return CORINFO_HELP_THROW_ARGUMENTOUTOFRANGEEXCEPTION; case SCK_DIV_BY_ZERO: return CORINFO_HELP_THROWDIVZERO; case SCK_ARITH_EXCPN: return CORINFO_HELP_OVERFLOW; default: assert(!"Bad codeKind"); return 0; } } //------------------------------------------------------------------------ // fgAddCodeRef: Find/create an added code entry associated with the given block and with the given kind. // // Arguments: // srcBlk - the block that needs an entry; // refData - the index to use as the cache key for sharing throw blocks; // kind - the kind of exception; // // Return Value: // The target throw helper block or nullptr if throw helper blocks are disabled. // BasicBlock* Compiler::fgAddCodeRef(BasicBlock* srcBlk, unsigned refData, SpecialCodeKind kind) { // Record that the code will call a THROW_HELPER // so on Windows Amd64 we can allocate the 4 outgoing // arg slots on the stack frame if there are no other calls. compUsesThrowHelper = true; if (!fgUseThrowHelperBlocks()) { return nullptr; } const static BBjumpKinds jumpKinds[] = { BBJ_NONE, // SCK_NONE BBJ_THROW, // SCK_RNGCHK_FAIL BBJ_ALWAYS, // SCK_PAUSE_EXEC BBJ_THROW, // SCK_DIV_BY_ZERO BBJ_THROW, // SCK_ARITH_EXCP, SCK_OVERFLOW BBJ_THROW, // SCK_ARG_EXCPN BBJ_THROW, // SCK_ARG_RNG_EXCPN }; noway_assert(sizeof(jumpKinds) == SCK_COUNT); // sanity check /* First look for an existing entry that matches what we're looking for */ AddCodeDsc* add = fgFindExcptnTarget(kind, refData); if (add) // found it { return add->acdDstBlk; } /* We have to allocate a new entry and prepend it to the list */ add = new (this, CMK_Unknown) AddCodeDsc; add->acdData = refData; add->acdKind = kind; add->acdNext = fgAddCodeList; #if !FEATURE_FIXED_OUT_ARGS add->acdStkLvl = 0; add->acdStkLvlInit = false; #endif // !FEATURE_FIXED_OUT_ARGS fgAddCodeList = add; /* Create the target basic block */ BasicBlock* newBlk; newBlk = add->acdDstBlk = fgNewBBinRegion(jumpKinds[kind], srcBlk, /* runRarely */ true, /* insertAtEnd */ true); add->acdDstBlk->bbFlags |= BBF_JMP_TARGET | BBF_HAS_LABEL; #ifdef DEBUG if (verbose) { const char* msgWhere = ""; if (!srcBlk->hasTryIndex() && !srcBlk->hasHndIndex()) { msgWhere = "non-EH region"; } else if (!srcBlk->hasTryIndex()) { msgWhere = "handler"; } else if (!srcBlk->hasHndIndex()) { msgWhere = "try"; } else if (srcBlk->getTryIndex() < srcBlk->getHndIndex()) { msgWhere = "try"; } else { msgWhere = "handler"; } const char* msg; switch (kind) { case SCK_RNGCHK_FAIL: msg = " for RNGCHK_FAIL"; break; case SCK_PAUSE_EXEC: msg = " for PAUSE_EXEC"; break; case SCK_DIV_BY_ZERO: msg = " for DIV_BY_ZERO"; break; case SCK_OVERFLOW: msg = " for OVERFLOW"; break; case SCK_ARG_EXCPN: msg = " for ARG_EXCPN"; break; case SCK_ARG_RNG_EXCPN: msg = " for ARG_RNG_EXCPN"; break; default: msg = " for ??"; break; } printf("\nfgAddCodeRef - Add BB in %s%s, new block %s\n", msgWhere, msg, add->acdDstBlk->dspToString()); } #endif // DEBUG /* Mark the block as added by the compiler and not removable by future flow graph optimizations. Note that no bbJumpDest points to these blocks. */ newBlk->bbFlags |= BBF_IMPORTED; newBlk->bbFlags |= BBF_DONT_REMOVE; /* Remember that we're adding a new basic block */ fgAddCodeModf = true; fgRngChkThrowAdded = true; /* Now figure out what code to insert */ GenTreeCall* tree; int helper = CORINFO_HELP_UNDEF; switch (kind) { case SCK_RNGCHK_FAIL: helper = CORINFO_HELP_RNGCHKFAIL; break; case SCK_DIV_BY_ZERO: helper = CORINFO_HELP_THROWDIVZERO; break; case SCK_ARITH_EXCPN: helper = CORINFO_HELP_OVERFLOW; noway_assert(SCK_OVERFLOW == SCK_ARITH_EXCPN); break; case SCK_ARG_EXCPN: helper = CORINFO_HELP_THROW_ARGUMENTEXCEPTION; break; case SCK_ARG_RNG_EXCPN: helper = CORINFO_HELP_THROW_ARGUMENTOUTOFRANGEEXCEPTION; break; // case SCK_PAUSE_EXEC: // noway_assert(!"add code to pause exec"); default: noway_assert(!"unexpected code addition kind"); return nullptr; } noway_assert(helper != CORINFO_HELP_UNDEF); // Add the appropriate helper call. tree = gtNewHelperCallNode(helper, TYP_VOID); // There are no args here but fgMorphArgs has side effects // such as setting the outgoing arg area (which is necessary // on AMD if there are any calls). tree = fgMorphArgs(tree); // Store the tree in the new basic block. assert(!srcBlk->isEmpty()); if (!srcBlk->IsLIR()) { fgInsertStmtAtEnd(newBlk, fgNewStmtFromTree(tree)); } else { LIR::AsRange(newBlk).InsertAtEnd(LIR::SeqTree(this, tree)); } return add->acdDstBlk; } /***************************************************************************** * Finds the block to jump to, to throw a given kind of exception * We maintain a cache of one AddCodeDsc for each kind, to make searching fast. * Note : Each block uses the same (maybe shared) block as the jump target for * a given type of exception */ Compiler::AddCodeDsc* Compiler::fgFindExcptnTarget(SpecialCodeKind kind, unsigned refData) { assert(fgUseThrowHelperBlocks()); if (!(fgExcptnTargetCache[kind] && // Try the cached value first fgExcptnTargetCache[kind]->acdData == refData)) { // Too bad, have to search for the jump target for the exception AddCodeDsc* add = nullptr; for (add = fgAddCodeList; add != nullptr; add = add->acdNext) { if (add->acdData == refData && add->acdKind == kind) { break; } } fgExcptnTargetCache[kind] = add; // Cache it } return fgExcptnTargetCache[kind]; } /***************************************************************************** * * The given basic block contains an array range check; return the label this * range check is to jump to upon failure. */ //------------------------------------------------------------------------ // fgRngChkTarget: Create/find the appropriate "range-fail" label for the block. // // Arguments: // srcBlk - the block that needs an entry; // kind - the kind of exception; // // Return Value: // The target throw helper block this check jumps to upon failure. // BasicBlock* Compiler::fgRngChkTarget(BasicBlock* block, SpecialCodeKind kind) { #ifdef DEBUG if (verbose) { printf("*** Computing fgRngChkTarget for block " FMT_BB "\n", block->bbNum); if (!block->IsLIR()) { gtDispTree(compCurStmt); } } #endif // DEBUG /* We attach the target label to the containing try block (if any) */ noway_assert(!compIsForInlining()); return fgAddCodeRef(block, bbThrowIndex(block), kind); } // Sequences the tree. // prevTree is what gtPrev of the first node in execution order gets set to. // Returns the first node (execution order) in the sequenced tree. GenTree* Compiler::fgSetTreeSeq(GenTree* tree, GenTree* prevTree, bool isLIR) { GenTree list; if (prevTree == nullptr) { prevTree = &list; } fgTreeSeqLst = prevTree; fgTreeSeqNum = 0; fgTreeSeqBeg = nullptr; fgSetTreeSeqHelper(tree, isLIR); GenTree* result = prevTree->gtNext; if (prevTree == &list) { list.gtNext->gtPrev = nullptr; } return result; } /***************************************************************************** * * Assigns sequence numbers to the given tree and its sub-operands, and * threads all the nodes together via the 'gtNext' and 'gtPrev' fields. * Uses 'global' - fgTreeSeqLst */ void Compiler::fgSetTreeSeqHelper(GenTree* tree, bool isLIR) { genTreeOps oper; unsigned kind; noway_assert(tree); assert(!IsUninitialized(tree)); noway_assert(tree->gtOper != GT_STMT); /* Figure out what kind of a node we have */ oper = tree->OperGet(); kind = tree->OperKind(); /* Is this a leaf/constant node? */ if (kind & (GTK_CONST | GTK_LEAF)) { fgSetTreeSeqFinish(tree, isLIR); return; } // Special handling for dynamic block ops. if (tree->OperIs(GT_DYN_BLK, GT_STORE_DYN_BLK)) { GenTreeDynBlk* dynBlk = tree->AsDynBlk(); GenTree* sizeNode = dynBlk->gtDynamicSize; GenTree* dstAddr = dynBlk->Addr(); GenTree* src = dynBlk->Data(); bool isReverse = ((dynBlk->gtFlags & GTF_REVERSE_OPS) != 0); if (dynBlk->gtEvalSizeFirst) { fgSetTreeSeqHelper(sizeNode, isLIR); } // We either have a DYN_BLK or a STORE_DYN_BLK. If the latter, we have a // src (the Data to be stored), and isReverse tells us whether to evaluate // that before dstAddr. if (isReverse && (src != nullptr)) { fgSetTreeSeqHelper(src, isLIR); } fgSetTreeSeqHelper(dstAddr, isLIR); if (!isReverse && (src != nullptr)) { fgSetTreeSeqHelper(src, isLIR); } if (!dynBlk->gtEvalSizeFirst) { fgSetTreeSeqHelper(sizeNode, isLIR); } fgSetTreeSeqFinish(dynBlk, isLIR); return; } /* Is it a 'simple' unary/binary operator? */ if (kind & GTK_SMPOP) { GenTree* op1 = tree->gtOp.gtOp1; GenTree* op2 = tree->gtGetOp2IfPresent(); // Special handling for GT_LIST if (tree->OperGet() == GT_LIST) { // First, handle the list items, which will be linked in forward order. // As we go, we will link the GT_LIST nodes in reverse order - we will number // them and update fgTreeSeqList in a subsequent traversal. GenTree* nextList = tree; GenTree* list = nullptr; while (nextList != nullptr && nextList->OperGet() == GT_LIST) { list = nextList; GenTree* listItem = list->gtOp.gtOp1; fgSetTreeSeqHelper(listItem, isLIR); nextList = list->gtOp.gtOp2; if (nextList != nullptr) { nextList->gtNext = list; } list->gtPrev = nextList; } // Next, handle the GT_LIST nodes. // Note that fgSetTreeSeqFinish() sets the gtNext to null, so we need to capture the nextList // before we call that method. nextList = list; do { assert(list != nullptr); list = nextList; nextList = list->gtNext; fgSetTreeSeqFinish(list, isLIR); } while (list != tree); return; } /* Special handling for AddrMode */ if (tree->OperIsAddrMode()) { bool reverse = ((tree->gtFlags & GTF_REVERSE_OPS) != 0); if (reverse) { assert(op1 != nullptr && op2 != nullptr); fgSetTreeSeqHelper(op2, isLIR); } if (op1 != nullptr) { fgSetTreeSeqHelper(op1, isLIR); } if (!reverse && op2 != nullptr) { fgSetTreeSeqHelper(op2, isLIR); } fgSetTreeSeqFinish(tree, isLIR); return; } /* Check for a nilary operator */ if (op1 == nullptr) { noway_assert(op2 == nullptr); fgSetTreeSeqFinish(tree, isLIR); return; } /* Is this a unary operator? * Although UNARY GT_IND has a special structure */ if (oper == GT_IND) { /* Visit the indirection first - op2 may point to the * jump Label for array-index-out-of-range */ fgSetTreeSeqHelper(op1, isLIR); fgSetTreeSeqFinish(tree, isLIR); return; } /* Now this is REALLY a unary operator */ if (!op2) { /* Visit the (only) operand and we're done */ fgSetTreeSeqHelper(op1, isLIR); fgSetTreeSeqFinish(tree, isLIR); return; } /* For "real" ?: operators, we make sure the order is as follows: condition 1st operand GT_COLON 2nd operand GT_QMARK */ if (oper == GT_QMARK) { noway_assert((tree->gtFlags & GTF_REVERSE_OPS) == 0); fgSetTreeSeqHelper(op1, isLIR); // Here, for the colon, the sequence does not actually represent "order of evaluation": // one or the other of the branches is executed, not both. Still, to make debugging checks // work, we want the sequence to match the order in which we'll generate code, which means // "else" clause then "then" clause. fgSetTreeSeqHelper(op2->AsColon()->ElseNode(), isLIR); fgSetTreeSeqHelper(op2, isLIR); fgSetTreeSeqHelper(op2->AsColon()->ThenNode(), isLIR); fgSetTreeSeqFinish(tree, isLIR); return; } if (oper == GT_COLON) { fgSetTreeSeqFinish(tree, isLIR); return; } /* This is a binary operator */ if (tree->gtFlags & GTF_REVERSE_OPS) { fgSetTreeSeqHelper(op2, isLIR); fgSetTreeSeqHelper(op1, isLIR); } else { fgSetTreeSeqHelper(op1, isLIR); fgSetTreeSeqHelper(op2, isLIR); } fgSetTreeSeqFinish(tree, isLIR); return; } /* See what kind of a special operator we have here */ switch (oper) { case GT_FIELD: noway_assert(tree->gtField.gtFldObj == nullptr); break; case GT_CALL: /* We'll evaluate the 'this' argument value first */ if (tree->gtCall.gtCallObjp) { fgSetTreeSeqHelper(tree->gtCall.gtCallObjp, isLIR); } /* We'll evaluate the arguments next, left to right * NOTE: setListOrder needs cleanup - eliminate the #ifdef afterwards */ if (tree->gtCall.gtCallArgs) { fgSetTreeSeqHelper(tree->gtCall.gtCallArgs, isLIR); } /* Evaluate the temp register arguments list * This is a "hidden" list and its only purpose is to * extend the life of temps until we make the call */ if (tree->gtCall.gtCallLateArgs) { fgSetTreeSeqHelper(tree->gtCall.gtCallLateArgs, isLIR); } if ((tree->gtCall.gtCallType == CT_INDIRECT) && (tree->gtCall.gtCallCookie != nullptr)) { fgSetTreeSeqHelper(tree->gtCall.gtCallCookie, isLIR); } if (tree->gtCall.gtCallType == CT_INDIRECT) { fgSetTreeSeqHelper(tree->gtCall.gtCallAddr, isLIR); } if (tree->gtCall.gtControlExpr) { fgSetTreeSeqHelper(tree->gtCall.gtControlExpr, isLIR); } break; case GT_ARR_ELEM: fgSetTreeSeqHelper(tree->gtArrElem.gtArrObj, isLIR); unsigned dim; for (dim = 0; dim < tree->gtArrElem.gtArrRank; dim++) { fgSetTreeSeqHelper(tree->gtArrElem.gtArrInds[dim], isLIR); } break; case GT_ARR_OFFSET: fgSetTreeSeqHelper(tree->gtArrOffs.gtOffset, isLIR); fgSetTreeSeqHelper(tree->gtArrOffs.gtIndex, isLIR); fgSetTreeSeqHelper(tree->gtArrOffs.gtArrObj, isLIR); break; case GT_CMPXCHG: // Evaluate the trees left to right fgSetTreeSeqHelper(tree->gtCmpXchg.gtOpLocation, isLIR); fgSetTreeSeqHelper(tree->gtCmpXchg.gtOpValue, isLIR); fgSetTreeSeqHelper(tree->gtCmpXchg.gtOpComparand, isLIR); break; case GT_ARR_BOUNDS_CHECK: #ifdef FEATURE_SIMD case GT_SIMD_CHK: #endif // FEATURE_SIMD #ifdef FEATURE_HW_INTRINSICS case GT_HW_INTRINSIC_CHK: #endif // FEATURE_HW_INTRINSICS // Evaluate the trees left to right fgSetTreeSeqHelper(tree->gtBoundsChk.gtIndex, isLIR); fgSetTreeSeqHelper(tree->gtBoundsChk.gtArrLen, isLIR); break; case GT_STORE_DYN_BLK: case GT_DYN_BLK: noway_assert(!"DYN_BLK nodes should be sequenced as a special case"); break; case GT_INDEX_ADDR: // Evaluate the array first, then the index.... assert((tree->gtFlags & GTF_REVERSE_OPS) == 0); fgSetTreeSeqHelper(tree->AsIndexAddr()->Arr(), isLIR); fgSetTreeSeqHelper(tree->AsIndexAddr()->Index(), isLIR); break; default: #ifdef DEBUG gtDispTree(tree); noway_assert(!"unexpected operator"); #endif // DEBUG break; } fgSetTreeSeqFinish(tree, isLIR); } void Compiler::fgSetTreeSeqFinish(GenTree* tree, bool isLIR) { // If we are sequencing for LIR: // - Clear the reverse ops flag // - If we are processing a node that does not appear in LIR, do not add it to the list. if (isLIR) { tree->gtFlags &= ~GTF_REVERSE_OPS; if ((tree->OperGet() == GT_LIST) || (tree->OperGet() == GT_ARGPLACE) || (tree->OperGet() == GT_FIELD_LIST && !tree->AsFieldList()->IsFieldListHead())) { return; } } /* Append to the node list */ ++fgTreeSeqNum; #ifdef DEBUG tree->gtSeqNum = fgTreeSeqNum; if (verbose & 0) { printf("SetTreeOrder: "); printTreeID(fgTreeSeqLst); printf(" followed by "); printTreeID(tree); printf("\n"); } #endif // DEBUG fgTreeSeqLst->gtNext = tree; tree->gtNext = nullptr; tree->gtPrev = fgTreeSeqLst; fgTreeSeqLst = tree; /* Remember the very first node */ if (!fgTreeSeqBeg) { fgTreeSeqBeg = tree; assert(tree->gtSeqNum == 1); } } /***************************************************************************** * * Figure out the order in which operators should be evaluated, along with * other information (such as the register sets trashed by each subtree). * Also finds blocks that need GC polls and inserts them as needed. */ void Compiler::fgSetBlockOrder() { #ifdef DEBUG if (verbose) { printf("*************** In fgSetBlockOrder()\n"); } #endif // DEBUG #ifdef DEBUG BasicBlock::s_nMaxTrees = 0; #endif /* Walk the basic blocks to assign sequence numbers */ /* If we don't compute the doms, then we never mark blocks as loops. */ if (fgDomsComputed) { for (BasicBlock* block = fgFirstBB; block; block = block->bbNext) { /* If this block is a loop header, mark it appropriately */ if (block->isLoopHead()) { fgMarkLoopHead(block); } } } // only enable fully interruptible code for if we're hijacking. else if (GCPOLL_NONE == opts.compGCPollType) { /* If we don't have the dominators, use an abbreviated test for fully interruptible. If there are * any back edges, check the source and destination blocks to see if they're GC Safe. If not, then * go fully interruptible. */ /* XXX Mon 1/21/2008 * Wouldn't it be nice to have a block iterator that can do this loop? */ for (BasicBlock* block = fgFirstBB; block; block = block->bbNext) { // true if the edge is forward, or if it is a back edge and either the source and dest are GC safe. #define EDGE_IS_GC_SAFE(src, dst) \ (((src)->bbNum < (dst)->bbNum) || (((src)->bbFlags | (dst)->bbFlags) & BBF_GC_SAFE_POINT)) bool partiallyInterruptible = true; switch (block->bbJumpKind) { case BBJ_COND: case BBJ_ALWAYS: partiallyInterruptible = EDGE_IS_GC_SAFE(block, block->bbJumpDest); break; case BBJ_SWITCH: unsigned jumpCnt; jumpCnt = block->bbJumpSwt->bbsCount; BasicBlock** jumpPtr; jumpPtr = block->bbJumpSwt->bbsDstTab; do { partiallyInterruptible &= EDGE_IS_GC_SAFE(block, *jumpPtr); } while (++jumpPtr, --jumpCnt); break; default: break; } if (!partiallyInterruptible) { // DDB 204533: // The GC encoding for fully interruptible methods does not // support more than 1023 pushed arguments, so we can't set // genInterruptible here when we have 1024 or more pushed args // if (compCanEncodePtrArgCntMax()) { genInterruptible = true; } break; } #undef EDGE_IS_GC_SAFE } } if (!fgGCPollsCreated) { fgCreateGCPolls(); } for (BasicBlock* block = fgFirstBB; block; block = block->bbNext) { #if FEATURE_FASTTAILCALL #ifndef JIT32_GCENCODER if (block->endsWithTailCallOrJmp(this, true) && optReachWithoutCall(fgFirstBB, block)) { // We have a tail call that is reachable without making any other // 'normal' call that would have counted as a GC Poll. If we were // using polls, all return blocks meeting this criteria would have // already added polls and then marked as being GC safe // (BBF_GC_SAFE_POINT). Thus we can only reach here when *NOT* // using GC polls, but instead relying on the JIT to generate // fully-interruptible code. noway_assert(GCPOLL_NONE == opts.compGCPollType); // This tail call might combine with other tail calls to form a // loop. Thus we need to either add a poll, or make the method // fully interruptible. I chose the later because that's what // JIT64 does. genInterruptible = true; } #endif // !JIT32_GCENCODER #endif // FEATURE_FASTTAILCALL fgSetBlockOrder(block); } /* Remember that now the tree list is threaded */ fgStmtListThreaded = true; #ifdef DEBUG if (verbose) { printf("The biggest BB has %4u tree nodes\n", BasicBlock::s_nMaxTrees); } fgDebugCheckLinks(); #endif // DEBUG } /*****************************************************************************/ void Compiler::fgSetStmtSeq(GenTreeStmt* stmt) { GenTree list; // helper node that we use to start the StmtList // It's located in front of the first node in the list /* Assign numbers and next/prev links for this tree */ fgTreeSeqNum = 0; fgTreeSeqLst = &list; fgTreeSeqBeg = nullptr; fgSetTreeSeqHelper(stmt->gtStmtExpr, false); /* Record the address of the first node */ stmt->gtStmtList = fgTreeSeqBeg; #ifdef DEBUG if (list.gtNext->gtPrev != &list) { printf("&list "); printTreeID(&list); printf(" != list.next->prev "); printTreeID(list.gtNext->gtPrev); printf("\n"); goto BAD_LIST; } GenTree* temp; GenTree* last; for (temp = list.gtNext, last = &list; temp != nullptr; last = temp, temp = temp->gtNext) { if (temp->gtPrev != last) { printTreeID(temp); printf("->gtPrev = "); printTreeID(temp->gtPrev); printf(", but last = "); printTreeID(last); printf("\n"); BAD_LIST:; printf("\n"); gtDispTree(stmt->gtStmtExpr); printf("\n"); for (GenTree* bad = &list; bad != nullptr; bad = bad->gtNext) { printf(" entry at "); printTreeID(bad); printf(" (prev="); printTreeID(bad->gtPrev); printf(",next=)"); printTreeID(bad->gtNext); printf("\n"); } printf("\n"); noway_assert(!"Badly linked tree"); break; } } #endif // DEBUG /* Fix the first node's 'prev' link */ noway_assert(list.gtNext->gtPrev == &list); list.gtNext->gtPrev = nullptr; #ifdef DEBUG /* Keep track of the highest # of tree nodes */ if (BasicBlock::s_nMaxTrees < fgTreeSeqNum) { BasicBlock::s_nMaxTrees = fgTreeSeqNum; } #endif // DEBUG } /*****************************************************************************/ void Compiler::fgSetBlockOrder(BasicBlock* block) { for (GenTreeStmt* stmt = block->firstStmt(); stmt != nullptr; stmt = stmt->getNextStmt()) { fgSetStmtSeq(stmt); /* Are there any more trees in this basic block? */ if (stmt->gtNext == nullptr) { /* last statement in the tree list */ noway_assert(block->lastStmt() == stmt); break; } #ifdef DEBUG if (block->bbTreeList == stmt) { /* first statement in the list */ assert(stmt->gtPrev->gtNext == nullptr); } else { assert(stmt->gtPrev->gtNext == stmt); } assert(stmt->gtNext->gtPrev == stmt); #endif // DEBUG } } //------------------------------------------------------------------------ // fgGetFirstNode: Get the first node in the tree, in execution order // // Arguments: // tree - The top node of the tree of interest // // Return Value: // The first node in execution order, that belongs to tree. // // Assumptions: // 'tree' must either be a leaf, or all of its constituent nodes must be contiguous // in execution order. // TODO-Cleanup: Add a debug-only method that verifies this. /* static */ GenTree* Compiler::fgGetFirstNode(GenTree* tree) { GenTree* child = tree; while (child->NumChildren() > 0) { if (child->OperIsBinary() && child->IsReverseOp()) { child = child->GetChild(1); } else { child = child->GetChild(0); } } return child; } // Examine the bbTreeList and return the estimated code size for this block unsigned Compiler::fgGetCodeEstimate(BasicBlock* block) { unsigned costSz = 0; // estimate of blocks code size cost switch (block->bbJumpKind) { case BBJ_NONE: costSz = 0; break; case BBJ_ALWAYS: case BBJ_EHCATCHRET: case BBJ_LEAVE: case BBJ_COND: costSz = 2; break; case BBJ_CALLFINALLY: costSz = 5; break; case BBJ_SWITCH: costSz = 10; break; case BBJ_THROW: costSz = 1; // We place a int3 after the code for a throw block break; case BBJ_EHFINALLYRET: case BBJ_EHFILTERRET: costSz = 1; break; case BBJ_RETURN: // return from method costSz = 3; break; default: noway_assert(!"Bad bbJumpKind"); break; } for (GenTreeStmt* stmt = block->FirstNonPhiDef(); stmt != nullptr; stmt = stmt->getNextStmt()) { if (stmt->gtCostSz < MAX_COST) { costSz += stmt->gtCostSz; } else { // We could walk the tree to find out the real gtCostSz, // but just using MAX_COST for this trees code size works OK costSz += stmt->gtCostSz; } } return costSz; } #if DUMP_FLOWGRAPHS struct escapeMapping_t { char ch; const char* sub; }; // clang-format off static escapeMapping_t s_EscapeFileMapping[] = { {':', "="}, {'<', "["}, {'>', "]"}, {';', "~semi~"}, {'|', "~bar~"}, {'&', "~amp~"}, {'"', "~quot~"}, {'*', "~star~"}, {0, nullptr} }; static escapeMapping_t s_EscapeMapping[] = { {'<', "&lt;"}, {'>', "&gt;"}, {'&', "&amp;"}, {'"', "&quot;"}, {0, nullptr} }; // clang-format on const char* Compiler::fgProcessEscapes(const char* nameIn, escapeMapping_t* map) { const char* nameOut = nameIn; unsigned lengthOut; unsigned index; bool match; bool subsitutionRequired; const char* pChar; lengthOut = 1; subsitutionRequired = false; pChar = nameIn; while (*pChar != '\0') { match = false; index = 0; while (map[index].ch != 0) { if (*pChar == map[index].ch) { match = true; break; } index++; } if (match) { subsitutionRequired = true; lengthOut += (unsigned)strlen(map[index].sub); } else { lengthOut += 1; } pChar++; } if (subsitutionRequired) { char* newName = getAllocator(CMK_DebugOnly).allocate<char>(lengthOut); char* pDest; pDest = newName; pChar = nameIn; while (*pChar != '\0') { match = false; index = 0; while (map[index].ch != 0) { if (*pChar == map[index].ch) { match = true; break; } index++; } if (match) { strcpy(pDest, map[index].sub); pDest += strlen(map[index].sub); } else { *pDest++ = *pChar; } pChar++; } *pDest++ = '\0'; nameOut = (const char*)newName; } return nameOut; } static void fprintfDouble(FILE* fgxFile, double value) { assert(value >= 0.0); if ((value >= 0.010) || (value == 0.0)) { fprintf(fgxFile, "\"%7.3f\"", value); } else if (value >= 0.00010) { fprintf(fgxFile, "\"%7.5f\"", value); } else { fprintf(fgxFile, "\"%7E\"", value); } } //------------------------------------------------------------------------ // fgOpenFlowGraphFile: Open a file to dump either the xml or dot format flow graph // // Arguments: // wbDontClose - A boolean out argument that indicates whether the caller should close the file // phase - A phase identifier to indicate which phase is associated with the dump // type - A (wide) string indicating the type of dump, "dot" or "xml" // // Return Value: // Opens a file to which a flowgraph can be dumped, whose name is based on the current // config vales. FILE* Compiler::fgOpenFlowGraphFile(bool* wbDontClose, Phases phase, LPCWSTR type) { FILE* fgxFile; LPCWSTR pattern = nullptr; LPCWSTR filename = nullptr; LPCWSTR pathname = nullptr; const char* escapedString; bool createDuplicateFgxFiles = true; #ifdef DEBUG if (opts.jitFlags->IsSet(JitFlags::JIT_FLAG_PREJIT)) { pattern = JitConfig.NgenDumpFg(); filename = JitConfig.NgenDumpFgFile(); pathname = JitConfig.NgenDumpFgDir(); } else { pattern = JitConfig.JitDumpFg(); filename = JitConfig.JitDumpFgFile(); pathname = JitConfig.JitDumpFgDir(); } #endif // DEBUG if (fgBBcount <= 1) { return nullptr; } if (pattern == nullptr) { return nullptr; } if (wcslen(pattern) == 0) { return nullptr; } LPCWSTR phasePattern = JitConfig.JitDumpFgPhase(); LPCWSTR phaseName = PhaseShortNames[phase]; if (phasePattern == nullptr) { if (phase != PHASE_DETERMINE_FIRST_COLD_BLOCK) { return nullptr; } } else if (*phasePattern != W('*')) { if (wcsstr(phasePattern, phaseName) == nullptr) { return nullptr; } } if (*pattern != W('*')) { bool hasColon = (wcschr(pattern, W(':')) != nullptr); if (hasColon) { const char* className = info.compClassName; if (*pattern == W('*')) { pattern++; } else { while ((*pattern != W(':')) && (*pattern != W('*'))) { if (*pattern != *className) { return nullptr; } pattern++; className++; } if (*pattern == W('*')) { pattern++; } else { if (*className != 0) { return nullptr; } } } if (*pattern != W(':')) { return nullptr; } pattern++; } const char* methodName = info.compMethodName; if (*pattern == W('*')) { pattern++; } else { while ((*pattern != 0) && (*pattern != W('*'))) { if (*pattern != *methodName) { return nullptr; } pattern++; methodName++; } if (*pattern == W('*')) { pattern++; } else { if (*methodName != 0) { return nullptr; } } } if (*pattern != 0) { return nullptr; } } if (filename == nullptr) { filename = W("default"); } if (wcscmp(filename, W("profiled")) == 0) { if (fgFirstBB->hasProfileWeight()) { createDuplicateFgxFiles = true; goto ONE_FILE_PER_METHOD; } else { return nullptr; } } if (wcscmp(filename, W("hot")) == 0) { if (info.compMethodInfo->regionKind == CORINFO_REGION_HOT) { createDuplicateFgxFiles = true; goto ONE_FILE_PER_METHOD; } else { return nullptr; } } else if (wcscmp(filename, W("cold")) == 0) { if (info.compMethodInfo->regionKind == CORINFO_REGION_COLD) { createDuplicateFgxFiles = true; goto ONE_FILE_PER_METHOD; } else { return nullptr; } } else if (wcscmp(filename, W("jit")) == 0) { if (info.compMethodInfo->regionKind == CORINFO_REGION_JIT) { createDuplicateFgxFiles = true; goto ONE_FILE_PER_METHOD; } else { return nullptr; } } else if (wcscmp(filename, W("all")) == 0) { createDuplicateFgxFiles = true; ONE_FILE_PER_METHOD:; escapedString = fgProcessEscapes(info.compFullName, s_EscapeFileMapping); size_t wCharCount = strlen(escapedString) + wcslen(phaseName) + 1 + strlen("~999") + wcslen(type) + 1; if (pathname != nullptr) { wCharCount += wcslen(pathname) + 1; } filename = (LPCWSTR)alloca(wCharCount * sizeof(WCHAR)); if (pathname != nullptr) { swprintf_s((LPWSTR)filename, wCharCount, W("%s\\%S-%s.%s"), pathname, escapedString, phaseName, type); } else { swprintf_s((LPWSTR)filename, wCharCount, W("%S.%s"), escapedString, type); } fgxFile = _wfopen(filename, W("r")); // Check if this file already exists if (fgxFile != nullptr) { // For Generic methods we will have both hot and cold versions if (createDuplicateFgxFiles == false) { fclose(fgxFile); return nullptr; } // Yes, this filename already exists, so create a different one by appending ~2, ~3, etc... for (int i = 2; i < 1000; i++) { fclose(fgxFile); if (pathname != nullptr) { swprintf_s((LPWSTR)filename, wCharCount, W("%s\\%S~%d.%s"), pathname, escapedString, i, type); } else { swprintf_s((LPWSTR)filename, wCharCount, W("%S~%d.%s"), escapedString, i, type); } fgxFile = _wfopen(filename, W("r")); // Check if this file exists if (fgxFile == nullptr) { break; } } // If we have already created 1000 files with this name then just fail if (fgxFile != nullptr) { fclose(fgxFile); return nullptr; } } fgxFile = _wfopen(filename, W("a+")); *wbDontClose = false; } else if (wcscmp(filename, W("stdout")) == 0) { fgxFile = jitstdout; *wbDontClose = true; } else if (wcscmp(filename, W("stderr")) == 0) { fgxFile = stderr; *wbDontClose = true; } else { LPCWSTR origFilename = filename; size_t wCharCount = wcslen(origFilename) + wcslen(type) + 2; if (pathname != nullptr) { wCharCount += wcslen(pathname) + 1; } filename = (LPCWSTR)alloca(wCharCount * sizeof(WCHAR)); if (pathname != nullptr) { swprintf_s((LPWSTR)filename, wCharCount, W("%s\\%s.%s"), pathname, origFilename, type); } else { swprintf_s((LPWSTR)filename, wCharCount, W("%s.%s"), origFilename, type); } fgxFile = _wfopen(filename, W("a+")); *wbDontClose = false; } return fgxFile; } //------------------------------------------------------------------------ // fgDumpFlowGraph: Dump the xml or dot format flow graph, if enabled for this phase. // // Arguments: // phase - A phase identifier to indicate which phase is associated with the dump, // i.e. which phase has just completed. // // Return Value: // True iff a flowgraph has been dumped. // // Notes: // The xml dumps are the historical mechanism for dumping the flowgraph. // The dot format can be viewed by: // - Graphviz (http://www.graphviz.org/) // - The command "C:\Program Files (x86)\Graphviz2.38\bin\dot.exe" -Tsvg -oFoo.svg -Kdot Foo.dot // will produce a Foo.svg file that can be opened with any svg-capable browser (e.g. IE). // - http://rise4fun.com/Agl/ // - Cut and paste the graph from your .dot file, replacing the digraph on the page, and then click the play // button. // - It will show a rotating '/' and then render the graph in the browser. // MSAGL has also been open-sourced to https://github.com/Microsoft/automatic-graph-layout.git. // // Here are the config values that control it: // COMPlus_JitDumpFg A string (ala the COMPlus_JitDump string) indicating what methods to dump flowgraphs // for. // COMPlus_JitDumpFgDir A path to a directory into which the flowgraphs will be dumped. // COMPlus_JitDumpFgFile The filename to use. The default is "default.[xml|dot]". // Note that the new graphs will be appended to this file if it already exists. // COMPlus_JitDumpFgPhase Phase(s) after which to dump the flowgraph. // Set to the short name of a phase to see the flowgraph after that phase. // Leave unset to dump after COLD-BLK (determine first cold block) or set to * for all // phases. // COMPlus_JitDumpFgDot Set to non-zero to emit Dot instead of Xml Flowgraph dump. (Default is xml format.) bool Compiler::fgDumpFlowGraph(Phases phase) { bool result = false; bool dontClose = false; bool createDotFile = false; if (JitConfig.JitDumpFgDot()) { createDotFile = true; } FILE* fgxFile = fgOpenFlowGraphFile(&dontClose, phase, createDotFile ? W("dot") : W("fgx")); if (fgxFile == nullptr) { return false; } bool validWeights = fgHaveValidEdgeWeights; unsigned calledCount = max(fgCalledCount, BB_UNITY_WEIGHT) / BB_UNITY_WEIGHT; double weightDivisor = (double)(calledCount * BB_UNITY_WEIGHT); const char* escapedString; const char* regionString = "NONE"; if (info.compMethodInfo->regionKind == CORINFO_REGION_HOT) { regionString = "HOT"; } else if (info.compMethodInfo->regionKind == CORINFO_REGION_COLD) { regionString = "COLD"; } else if (info.compMethodInfo->regionKind == CORINFO_REGION_JIT) { regionString = "JIT"; } if (createDotFile) { fprintf(fgxFile, "digraph %s\n{\n", info.compMethodName); fprintf(fgxFile, "/* Method %d, after phase %s */", Compiler::jitTotalMethodCompiled, PhaseNames[phase]); } else { fprintf(fgxFile, "<method"); escapedString = fgProcessEscapes(info.compFullName, s_EscapeMapping); fprintf(fgxFile, "\n name=\"%s\"", escapedString); escapedString = fgProcessEscapes(info.compClassName, s_EscapeMapping); fprintf(fgxFile, "\n className=\"%s\"", escapedString); escapedString = fgProcessEscapes(info.compMethodName, s_EscapeMapping); fprintf(fgxFile, "\n methodName=\"%s\"", escapedString); fprintf(fgxFile, "\n ngenRegion=\"%s\"", regionString); fprintf(fgxFile, "\n bytesOfIL=\"%d\"", info.compILCodeSize); fprintf(fgxFile, "\n localVarCount=\"%d\"", lvaCount); if (fgHaveProfileData()) { fprintf(fgxFile, "\n calledCount=\"%d\"", calledCount); fprintf(fgxFile, "\n profileData=\"true\""); } if (compHndBBtabCount > 0) { fprintf(fgxFile, "\n hasEHRegions=\"true\""); } if (fgHasLoops) { fprintf(fgxFile, "\n hasLoops=\"true\""); } if (validWeights) { fprintf(fgxFile, "\n validEdgeWeights=\"true\""); if (!fgSlopUsedInEdgeWeights && !fgRangeUsedInEdgeWeights) { fprintf(fgxFile, "\n exactEdgeWeights=\"true\""); } } if (fgFirstColdBlock != nullptr) { fprintf(fgxFile, "\n firstColdBlock=\"%d\"", fgFirstColdBlock->bbNum); } fprintf(fgxFile, ">"); fprintf(fgxFile, "\n <blocks"); fprintf(fgxFile, "\n blockCount=\"%d\"", fgBBcount); fprintf(fgxFile, ">"); } static const char* kindImage[] = {"EHFINALLYRET", "EHFILTERRET", "EHCATCHRET", "THROW", "RETURN", "NONE", "ALWAYS", "LEAVE", "CALLFINALLY", "COND", "SWITCH"}; BasicBlock* block; unsigned blockOrdinal; for (block = fgFirstBB, blockOrdinal = 1; block != nullptr; block = block->bbNext, blockOrdinal++) { if (createDotFile) { // Add constraint edges to try to keep nodes ordered. // It seems to work best if these edges are all created first. switch (block->bbJumpKind) { case BBJ_COND: case BBJ_NONE: assert(block->bbNext != nullptr); fprintf(fgxFile, " " FMT_BB " -> " FMT_BB "\n", block->bbNum, block->bbNext->bbNum); break; default: // These may or may not have an edge to the next block. // Add a transparent edge to keep nodes ordered. if (block->bbNext != nullptr) { fprintf(fgxFile, " " FMT_BB " -> " FMT_BB " [arrowtail=none,color=transparent]\n", block->bbNum, block->bbNext->bbNum); } } } else { fprintf(fgxFile, "\n <block"); fprintf(fgxFile, "\n id=\"%d\"", block->bbNum); fprintf(fgxFile, "\n ordinal=\"%d\"", blockOrdinal); fprintf(fgxFile, "\n jumpKind=\"%s\"", kindImage[block->bbJumpKind]); if (block->hasTryIndex()) { fprintf(fgxFile, "\n inTry=\"%s\"", "true"); } if (block->hasHndIndex()) { fprintf(fgxFile, "\n inHandler=\"%s\"", "true"); } if ((fgFirstBB->hasProfileWeight()) && ((block->bbFlags & BBF_COLD) == 0)) { fprintf(fgxFile, "\n hot=\"true\""); } if (block->bbFlags & (BBF_HAS_NEWOBJ | BBF_HAS_NEWARRAY)) { fprintf(fgxFile, "\n callsNew=\"true\""); } if (block->bbFlags & BBF_LOOP_HEAD) { fprintf(fgxFile, "\n loopHead=\"true\""); } fprintf(fgxFile, "\n weight="); fprintfDouble(fgxFile, ((double)block->bbWeight) / weightDivisor); fprintf(fgxFile, "\n codeEstimate=\"%d\"", fgGetCodeEstimate(block)); fprintf(fgxFile, "\n startOffset=\"%d\"", block->bbCodeOffs); fprintf(fgxFile, "\n endOffset=\"%d\"", block->bbCodeOffsEnd); fprintf(fgxFile, ">"); fprintf(fgxFile, "\n </block>"); } } if (!createDotFile) { fprintf(fgxFile, "\n </blocks>"); fprintf(fgxFile, "\n <edges"); fprintf(fgxFile, "\n edgeCount=\"%d\"", fgEdgeCount); fprintf(fgxFile, ">"); } unsigned edgeNum = 1; BasicBlock* bTarget; for (bTarget = fgFirstBB; bTarget != nullptr; bTarget = bTarget->bbNext) { double targetWeightDivisor; if (bTarget->bbWeight == BB_ZERO_WEIGHT) { targetWeightDivisor = 1.0; } else { targetWeightDivisor = (double)bTarget->bbWeight; } flowList* edge; for (edge = bTarget->bbPreds; edge != nullptr; edge = edge->flNext, edgeNum++) { BasicBlock* bSource = edge->flBlock; double sourceWeightDivisor; if (bSource->bbWeight == BB_ZERO_WEIGHT) { sourceWeightDivisor = 1.0; } else { sourceWeightDivisor = (double)bSource->bbWeight; } if (createDotFile) { // Don't duplicate the edges we added above. if ((bSource->bbNum == (bTarget->bbNum - 1)) && ((bSource->bbJumpKind == BBJ_NONE) || (bSource->bbJumpKind == BBJ_COND))) { continue; } fprintf(fgxFile, " " FMT_BB " -> " FMT_BB, bSource->bbNum, bTarget->bbNum); if ((bSource->bbNum > bTarget->bbNum)) { fprintf(fgxFile, "[arrowhead=normal,arrowtail=none,color=green]\n"); } else { fprintf(fgxFile, "\n"); } } else { fprintf(fgxFile, "\n <edge"); fprintf(fgxFile, "\n id=\"%d\"", edgeNum); fprintf(fgxFile, "\n source=\"%d\"", bSource->bbNum); fprintf(fgxFile, "\n target=\"%d\"", bTarget->bbNum); if (bSource->bbJumpKind == BBJ_SWITCH) { if (edge->flDupCount >= 2) { fprintf(fgxFile, "\n switchCases=\"%d\"", edge->flDupCount); } if (bSource->bbJumpSwt->getDefault() == bTarget) { fprintf(fgxFile, "\n switchDefault=\"true\""); } } if (validWeights) { unsigned edgeWeight = (edge->flEdgeWeightMin + edge->flEdgeWeightMax) / 2; fprintf(fgxFile, "\n weight="); fprintfDouble(fgxFile, ((double)edgeWeight) / weightDivisor); if (edge->flEdgeWeightMin != edge->flEdgeWeightMax) { fprintf(fgxFile, "\n minWeight="); fprintfDouble(fgxFile, ((double)edge->flEdgeWeightMin) / weightDivisor); fprintf(fgxFile, "\n maxWeight="); fprintfDouble(fgxFile, ((double)edge->flEdgeWeightMax) / weightDivisor); } if (edgeWeight > 0) { if (edgeWeight < bSource->bbWeight) { fprintf(fgxFile, "\n out="); fprintfDouble(fgxFile, ((double)edgeWeight) / sourceWeightDivisor); } if (edgeWeight < bTarget->bbWeight) { fprintf(fgxFile, "\n in="); fprintfDouble(fgxFile, ((double)edgeWeight) / targetWeightDivisor); } } } } if (!createDotFile) { fprintf(fgxFile, ">"); fprintf(fgxFile, "\n </edge>"); } } } if (createDotFile) { fprintf(fgxFile, "}\n"); } else { fprintf(fgxFile, "\n </edges>"); fprintf(fgxFile, "\n</method>\n"); } if (dontClose) { // fgxFile is jitstdout or stderr fprintf(fgxFile, "\n"); } else { fclose(fgxFile); } return result; } #endif // DUMP_FLOWGRAPHS /*****************************************************************************/ #ifdef DEBUG void Compiler::fgDispReach() { printf("------------------------------------------------\n"); printf("BBnum Reachable by \n"); printf("------------------------------------------------\n"); for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext) { printf(FMT_BB " : ", block->bbNum); BlockSetOps::Iter iter(this, block->bbReach); unsigned bbNum = 0; while (iter.NextElem(&bbNum)) { printf(FMT_BB " ", bbNum); } printf("\n"); } } void Compiler::fgDispDoms() { // Don't bother printing this when we have a large number of BasicBlocks in the method if (fgBBcount > 256) { return; } printf("------------------------------------------------\n"); printf("BBnum Dominated by\n"); printf("------------------------------------------------\n"); for (unsigned i = 1; i <= fgBBNumMax; ++i) { BasicBlock* current = fgBBInvPostOrder[i]; printf(FMT_BB ": ", current->bbNum); while (current != current->bbIDom) { printf(FMT_BB " ", current->bbNum); current = current->bbIDom; } printf("\n"); } } /*****************************************************************************/ void Compiler::fgTableDispBasicBlock(BasicBlock* block, int ibcColWidth /* = 0 */) { const unsigned __int64 flags = block->bbFlags; unsigned bbNumMax = compIsForInlining() ? impInlineInfo->InlinerCompiler->fgBBNumMax : fgBBNumMax; int maxBlockNumWidth = CountDigits(bbNumMax); maxBlockNumWidth = max(maxBlockNumWidth, 2); int blockNumWidth = CountDigits(block->bbNum); blockNumWidth = max(blockNumWidth, 2); int blockNumPadding = maxBlockNumWidth - blockNumWidth; printf("%s %2u", block->dspToString(blockNumPadding), block->bbRefs); // // Display EH 'try' region index // if (block->hasTryIndex()) { printf(" %2u", block->getTryIndex()); } else { printf(" "); } // // Display EH handler region index // if (block->hasHndIndex()) { printf(" %2u", block->getHndIndex()); } else { printf(" "); } printf(" "); // // Display block predecessor list // unsigned charCnt; if (fgCheapPredsValid) { charCnt = block->dspCheapPreds(); } else { charCnt = block->dspPreds(); } if (charCnt < 19) { printf("%*s", 19 - charCnt, ""); } printf(" "); // // Display block weight // if (block->isMaxBBWeight()) { printf(" MAX "); } else { BasicBlock::weight_t weight = block->getBBWeight(this); if (weight > 99999) // Is it going to be more than 6 characters? { if (weight <= 99999 * BB_UNITY_WEIGHT) { // print weight in this format ddddd. printf("%5u.", (weight + (BB_UNITY_WEIGHT / 2)) / BB_UNITY_WEIGHT); } else // print weight in terms of k (i.e. 156k ) { // print weight in this format dddddk BasicBlock::weight_t weightK = weight / 1000; printf("%5uk", (weightK + (BB_UNITY_WEIGHT / 2)) / BB_UNITY_WEIGHT); } } else // print weight in this format ddd.dd { printf("%6s", refCntWtd2str(weight)); } } printf(" "); // // Display optional IBC weight column. // Note that iColWidth includes one character for a leading space, if there is an IBC column. // if (ibcColWidth > 0) { if (block->hasProfileWeight()) { printf("%*u", ibcColWidth, block->bbWeight); } else { // No IBC data. Just print spaces to align the column. printf("%*s", ibcColWidth, ""); } } printf(" "); // // Display natural loop number // if (block->bbNatLoopNum == BasicBlock::NOT_IN_LOOP) { printf(" "); } else { printf("%2d ", block->bbNatLoopNum); } // // Display block IL range // block->dspBlockILRange(); // // Display block branch target // if (flags & BBF_REMOVED) { printf("[removed] "); } else { switch (block->bbJumpKind) { case BBJ_COND: printf("-> " FMT_BB "%*s ( cond )", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), ""); break; case BBJ_CALLFINALLY: printf("-> " FMT_BB "%*s (callf )", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), ""); break; case BBJ_ALWAYS: if (flags & BBF_KEEP_BBJ_ALWAYS) { printf("-> " FMT_BB "%*s (ALWAYS)", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), ""); } else { printf("-> " FMT_BB "%*s (always)", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), ""); } break; case BBJ_LEAVE: printf("-> " FMT_BB "%*s (leave )", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), ""); break; case BBJ_EHFINALLYRET: printf("%*s (finret)", maxBlockNumWidth - 2, ""); break; case BBJ_EHFILTERRET: printf("%*s (fltret)", maxBlockNumWidth - 2, ""); break; case BBJ_EHCATCHRET: printf("-> " FMT_BB "%*s ( cret )", block->bbJumpDest->bbNum, maxBlockNumWidth - max(CountDigits(block->bbJumpDest->bbNum), 2), ""); break; case BBJ_THROW: printf("%*s (throw )", maxBlockNumWidth - 2, ""); break; case BBJ_RETURN: printf("%*s (return)", maxBlockNumWidth - 2, ""); break; default: printf("%*s ", maxBlockNumWidth - 2, ""); break; case BBJ_SWITCH: printf("->"); unsigned jumpCnt; jumpCnt = block->bbJumpSwt->bbsCount; BasicBlock** jumpTab; jumpTab = block->bbJumpSwt->bbsDstTab; int switchWidth; switchWidth = 0; do { printf("%c" FMT_BB, (jumpTab == block->bbJumpSwt->bbsDstTab) ? ' ' : ',', (*jumpTab)->bbNum); switchWidth += 1 /* space/comma */ + 2 /* BB */ + max(CountDigits((*jumpTab)->bbNum), 2); } while (++jumpTab, --jumpCnt); if (switchWidth < 7) { printf("%*s", 8 - switchWidth, ""); } printf(" (switch)"); break; } } printf(" "); // // Display block EH region and type, including nesting indicator // if (block->hasTryIndex()) { printf("T%d ", block->getTryIndex()); } else { printf(" "); } if (block->hasHndIndex()) { printf("H%d ", block->getHndIndex()); } else { printf(" "); } if (flags & BBF_FUNCLET_BEG) { printf("F "); } else { printf(" "); } int cnt = 0; switch (block->bbCatchTyp) { case BBCT_NONE: break; case BBCT_FAULT: printf("fault "); cnt += 6; break; case BBCT_FINALLY: printf("finally "); cnt += 8; break; case BBCT_FILTER: printf("filter "); cnt += 7; break; case BBCT_FILTER_HANDLER: printf("filtHnd "); cnt += 8; break; default: printf("catch "); cnt += 6; break; } if (block->bbCatchTyp != BBCT_NONE) { cnt += 2; printf("{ "); /* brace matching editor workaround to compensate for the preceding line: } */ } if (flags & BBF_TRY_BEG) { // Output a brace for every try region that this block opens EHblkDsc* HBtab; EHblkDsc* HBtabEnd; for (HBtab = compHndBBtab, HBtabEnd = compHndBBtab + compHndBBtabCount; HBtab < HBtabEnd; HBtab++) { if (HBtab->ebdTryBeg == block) { cnt += 6; printf("try { "); /* brace matching editor workaround to compensate for the preceding line: } */ } } } EHblkDsc* HBtab; EHblkDsc* HBtabEnd; for (HBtab = compHndBBtab, HBtabEnd = compHndBBtab + compHndBBtabCount; HBtab < HBtabEnd; HBtab++) { if (HBtab->ebdTryLast == block) { cnt += 2; /* brace matching editor workaround to compensate for the following line: { */ printf("} "); } if (HBtab->ebdHndLast == block) { cnt += 2; /* brace matching editor workaround to compensate for the following line: { */ printf("} "); } if (HBtab->HasFilter() && block->bbNext == HBtab->ebdHndBeg) { cnt += 2; /* brace matching editor workaround to compensate for the following line: { */ printf("} "); } } while (cnt < 12) { cnt++; printf(" "); } // // Display block flags // block->dspFlags(); printf("\n"); } /**************************************************************************** Dump blocks from firstBlock to lastBlock. */ void Compiler::fgDispBasicBlocks(BasicBlock* firstBlock, BasicBlock* lastBlock, bool dumpTrees) { BasicBlock* block; // If any block has IBC data, we add an "IBC weight" column just before the 'IL range' column. This column is as // wide as necessary to accommodate all the various IBC weights. It's at least 4 characters wide, to accommodate // the "IBC" title and leading space. int ibcColWidth = 0; for (block = firstBlock; block != nullptr; block = block->bbNext) { if (block->hasProfileWeight()) { int thisIbcWidth = CountDigits(block->bbWeight); ibcColWidth = max(ibcColWidth, thisIbcWidth); } if (block == lastBlock) { break; } } if (ibcColWidth > 0) { ibcColWidth = max(ibcColWidth, 3) + 1; // + 1 for the leading space } unsigned bbNumMax = compIsForInlining() ? impInlineInfo->InlinerCompiler->fgBBNumMax : fgBBNumMax; int maxBlockNumWidth = CountDigits(bbNumMax); maxBlockNumWidth = max(maxBlockNumWidth, 2); int padWidth = maxBlockNumWidth - 2; // Account for functions with a large number of blocks. // clang-format off printf("\n"); printf("------%*s-------------------------------------%*s--------------------------%*s----------------------------------------\n", padWidth, "------------", ibcColWidth, "------------", maxBlockNumWidth, "----"); printf("BBnum %*sBBid ref try hnd %s weight %*s%s lp [IL range] [jump]%*s [EH region] [flags]\n", padWidth, "", fgCheapPredsValid ? "cheap preds" : (fgComputePredsDone ? "preds " : " "), ((ibcColWidth > 0) ? ibcColWidth - 3 : 0), "", // Subtract 3 for the width of "IBC", printed next. ((ibcColWidth > 0) ? "IBC" : ""), maxBlockNumWidth, "" ); printf("------%*s-------------------------------------%*s--------------------------%*s----------------------------------------\n", padWidth, "------------", ibcColWidth, "------------", maxBlockNumWidth, "----"); // clang-format on for (block = firstBlock; block; block = block->bbNext) { // First, do some checking on the bbPrev links if (block->bbPrev) { if (block->bbPrev->bbNext != block) { printf("bad prev link\n"); } } else if (block != fgFirstBB) { printf("bad prev link!\n"); } if (block == fgFirstColdBlock) { printf( "~~~~~~%*s~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%*s~~~~~~~~~~~~~~~~~~~~~~~~~~%*s~~~~~~~~~~~~~~~~~~~~~~~~" "~~~~~~~~~~~~~~~~\n", padWidth, "~~~~~~~~~~~~", ibcColWidth, "~~~~~~~~~~~~", maxBlockNumWidth, "~~~~"); } #if FEATURE_EH_FUNCLETS if (block == fgFirstFuncletBB) { printf( "++++++%*s+++++++++++++++++++++++++++++++++++++%*s++++++++++++++++++++++++++%*s++++++++++++++++++++++++" "++++++++++++++++ funclets follow\n", padWidth, "++++++++++++", ibcColWidth, "++++++++++++", maxBlockNumWidth, "++++"); } #endif // FEATURE_EH_FUNCLETS fgTableDispBasicBlock(block, ibcColWidth); if (block == lastBlock) { break; } } printf( "------%*s-------------------------------------%*s--------------------------%*s--------------------------------" "--------\n", padWidth, "------------", ibcColWidth, "------------", maxBlockNumWidth, "----"); if (dumpTrees) { fgDumpTrees(firstBlock, lastBlock); } } /*****************************************************************************/ void Compiler::fgDispBasicBlocks(bool dumpTrees) { fgDispBasicBlocks(fgFirstBB, nullptr, dumpTrees); } /*****************************************************************************/ // Increment the stmtNum and dump the tree using gtDispTree // void Compiler::fgDumpStmtTree(GenTreeStmt* stmt, unsigned bbNum) { compCurStmtNum++; // Increment the current stmtNum printf("\n***** " FMT_BB ", stmt %d\n", bbNum, compCurStmtNum); if (fgOrder == FGOrderLinear || opts.compDbgInfo) { gtDispTree(stmt); } else { gtDispTree(stmt->gtStmtExpr); } } //------------------------------------------------------------------------ // Compiler::fgDumpBlock: dumps the contents of the given block to stdout. // // Arguments: // block - The block to dump. // void Compiler::fgDumpBlock(BasicBlock* block) { printf("\n------------ "); block->dspBlockHeader(this); if (!block->IsLIR()) { GenTreeStmt* firstStmt = block->firstStmt(); for (GenTreeStmt* stmt = firstStmt; stmt != nullptr; stmt = stmt->getNextStmt()) { fgDumpStmtTree(stmt, block->bbNum); if (stmt == firstStmt) { block->bbStmtNum = compCurStmtNum; // Set the block->bbStmtNum } } } else { gtDispRange(LIR::AsRange(block)); } } /*****************************************************************************/ // Walk the BasicBlock list calling fgDumpTree once per Stmt // void Compiler::fgDumpTrees(BasicBlock* firstBlock, BasicBlock* lastBlock) { compCurStmtNum = 0; // Reset the current stmtNum /* Walk the basic blocks */ // Note that typically we have already called fgDispBasicBlocks() // so we don't need to print the preds and succs again here // for (BasicBlock* block = firstBlock; block; block = block->bbNext) { fgDumpBlock(block); if (block == lastBlock) { break; } } printf("\n---------------------------------------------------------------------------------------------------------" "----------\n"); } /***************************************************************************** * Try to create as many candidates for GTF_MUL_64RSLT as possible. * We convert 'intOp1*intOp2' into 'int(long(nop(intOp1))*long(intOp2))'. */ /* static */ Compiler::fgWalkResult Compiler::fgStress64RsltMulCB(GenTree** pTree, fgWalkData* data) { GenTree* tree = *pTree; Compiler* pComp = data->compiler; if (tree->gtOper != GT_MUL || tree->gtType != TYP_INT || (tree->gtOverflow())) { return WALK_CONTINUE; } #ifdef DEBUG if (pComp->verbose) { printf("STRESS_64RSLT_MUL before:\n"); pComp->gtDispTree(tree); } #endif // DEBUG // To ensure optNarrowTree() doesn't fold back to the original tree. tree->gtOp.gtOp1 = pComp->gtNewCastNode(TYP_LONG, tree->gtOp.gtOp1, false, TYP_LONG); tree->gtOp.gtOp1 = pComp->gtNewOperNode(GT_NOP, TYP_LONG, tree->gtOp.gtOp1); tree->gtOp.gtOp1 = pComp->gtNewCastNode(TYP_LONG, tree->gtOp.gtOp1, false, TYP_LONG); tree->gtOp.gtOp2 = pComp->gtNewCastNode(TYP_LONG, tree->gtOp.gtOp2, false, TYP_LONG); tree->gtType = TYP_LONG; *pTree = pComp->gtNewCastNode(TYP_INT, tree, false, TYP_INT); #ifdef DEBUG if (pComp->verbose) { printf("STRESS_64RSLT_MUL after:\n"); pComp->gtDispTree(*pTree); } #endif // DEBUG return WALK_SKIP_SUBTREES; } void Compiler::fgStress64RsltMul() { if (!compStressCompile(STRESS_64RSLT_MUL, 20)) { return; } fgWalkAllTreesPre(fgStress64RsltMulCB, (void*)this); } // BBPredsChecker checks jumps from the block's predecessors to the block. class BBPredsChecker { public: BBPredsChecker(Compiler* compiler) : comp(compiler) { } unsigned CheckBBPreds(BasicBlock* block, unsigned curTraversalStamp); private: bool CheckEhTryDsc(BasicBlock* block, BasicBlock* blockPred, EHblkDsc* ehTryDsc); bool CheckEhHndDsc(BasicBlock* block, BasicBlock* blockPred, EHblkDsc* ehHndlDsc); bool CheckJump(BasicBlock* blockPred, BasicBlock* block); bool CheckEHFinalyRet(BasicBlock* blockPred, BasicBlock* block); private: Compiler* comp; }; //------------------------------------------------------------------------ // CheckBBPreds: Check basic block predecessors list. // // Notes: // This DEBUG routine checks that all predecessors have the correct traversal stamp // and have correct jumps to the block. // It calculates the number of incoming edges from the internal block, // i.e. it does not count the global incoming edge for the first block. // // Arguments: // block - the block to process; // curTraversalStamp - current traversal stamp to distinguish different iterations. // // Return value: // the number of incoming edges for the block. unsigned BBPredsChecker::CheckBBPreds(BasicBlock* block, unsigned curTraversalStamp) { if (comp->fgCheapPredsValid) { return 0; } if (!comp->fgComputePredsDone) { assert(block->bbPreds == nullptr); return 0; } unsigned blockRefs = 0; for (flowList* pred = block->bbPreds; pred != nullptr; pred = pred->flNext) { blockRefs += pred->flDupCount; BasicBlock* blockPred = pred->flBlock; // Make sure this pred is part of the BB list. assert(blockPred->bbTraversalStamp == curTraversalStamp); EHblkDsc* ehTryDsc = comp->ehGetBlockTryDsc(block); if (ehTryDsc != nullptr) { assert(CheckEhTryDsc(block, blockPred, ehTryDsc)); } EHblkDsc* ehHndDsc = comp->ehGetBlockHndDsc(block); if (ehHndDsc != nullptr) { assert(CheckEhHndDsc(block, blockPred, ehHndDsc)); } assert(CheckJump(blockPred, block)); } return blockRefs; } bool BBPredsChecker::CheckEhTryDsc(BasicBlock* block, BasicBlock* blockPred, EHblkDsc* ehTryDsc) { // You can jump to the start of a try if (ehTryDsc->ebdTryBeg == block) { return true; } // You can jump within the same try region if (comp->bbInTryRegions(block->getTryIndex(), blockPred)) { return true; } // The catch block can jump back into the middle of the try if (comp->bbInCatchHandlerRegions(block, blockPred)) { return true; } // The end of a finally region is a BBJ_EHFINALLYRET block (during importing, BBJ_LEAVE) which // is marked as "returning" to the BBJ_ALWAYS block following the BBJ_CALLFINALLY // block that does a local call to the finally. This BBJ_ALWAYS is within // the try region protected by the finally (for x86, ARM), but that's ok. BasicBlock* prevBlock = block->bbPrev; if (prevBlock->bbJumpKind == BBJ_CALLFINALLY && block->bbJumpKind == BBJ_ALWAYS && blockPred->bbJumpKind == BBJ_EHFINALLYRET) { return true; } printf("Jump into the middle of try region: " FMT_BB " branches to " FMT_BB "\n", blockPred->bbNum, block->bbNum); assert(!"Jump into middle of try region"); return false; } bool BBPredsChecker::CheckEhHndDsc(BasicBlock* block, BasicBlock* blockPred, EHblkDsc* ehHndlDsc) { // You can do a BBJ_EHFINALLYRET or BBJ_EHFILTERRET into a handler region if ((blockPred->bbJumpKind == BBJ_EHFINALLYRET) || (blockPred->bbJumpKind == BBJ_EHFILTERRET)) { return true; } // Our try block can call our finally block if ((block->bbCatchTyp == BBCT_FINALLY) && (blockPred->bbJumpKind == BBJ_CALLFINALLY) && comp->ehCallFinallyInCorrectRegion(blockPred, block->getHndIndex())) { return true; } // You can jump within the same handler region if (comp->bbInHandlerRegions(block->getHndIndex(), blockPred)) { return true; } // A filter can jump to the start of the filter handler if (ehHndlDsc->HasFilter()) { return true; } printf("Jump into the middle of handler region: " FMT_BB " branches to " FMT_BB "\n", blockPred->bbNum, block->bbNum); assert(!"Jump into the middle of handler region"); return false; } bool BBPredsChecker::CheckJump(BasicBlock* blockPred, BasicBlock* block) { switch (blockPred->bbJumpKind) { case BBJ_COND: assert(blockPred->bbNext == block || blockPred->bbJumpDest == block); return true; case BBJ_NONE: assert(blockPred->bbNext == block); return true; case BBJ_CALLFINALLY: case BBJ_ALWAYS: case BBJ_EHCATCHRET: case BBJ_EHFILTERRET: assert(blockPred->bbJumpDest == block); return true; case BBJ_EHFINALLYRET: assert(CheckEHFinalyRet(blockPred, block)); return true; case BBJ_THROW: case BBJ_RETURN: assert(!"THROW and RETURN block cannot be in the predecessor list!"); break; case BBJ_SWITCH: { unsigned jumpCnt = blockPred->bbJumpSwt->bbsCount; for (unsigned i = 0; i < jumpCnt; ++i) { BasicBlock* jumpTab = blockPred->bbJumpSwt->bbsDstTab[i]; assert(jumpTab != nullptr); if (block == jumpTab) { return true; } } assert(!"SWITCH in the predecessor list with no jump label to BLOCK!"); } break; default: assert(!"Unexpected bbJumpKind"); break; } return false; } bool BBPredsChecker::CheckEHFinalyRet(BasicBlock* blockPred, BasicBlock* block) { // If the current block is a successor to a BBJ_EHFINALLYRET (return from finally), // then the lexically previous block should be a call to the same finally. // Verify all of that. unsigned hndIndex = blockPred->getHndIndex(); EHblkDsc* ehDsc = comp->ehGetDsc(hndIndex); BasicBlock* finBeg = ehDsc->ebdHndBeg; // Because there is no bbPrev, we have to search for the lexically previous // block. We can shorten the search by only looking in places where it is legal // to have a call to the finally. BasicBlock* begBlk; BasicBlock* endBlk; comp->ehGetCallFinallyBlockRange(hndIndex, &begBlk, &endBlk); for (BasicBlock* bcall = begBlk; bcall != endBlk; bcall = bcall->bbNext) { if (bcall->bbJumpKind != BBJ_CALLFINALLY || bcall->bbJumpDest != finBeg) { continue; } if (block == bcall->bbNext) { return true; } } #if FEATURE_EH_FUNCLETS if (comp->fgFuncletsCreated) { // There is no easy way to search just the funclets that were pulled out of // the corresponding try body, so instead we search all the funclets, and if // we find a potential 'hit' we check if the funclet we're looking at is // from the correct try region. for (BasicBlock* bcall = comp->fgFirstFuncletBB; bcall != nullptr; bcall = bcall->bbNext) { if (bcall->bbJumpKind != BBJ_CALLFINALLY || bcall->bbJumpDest != finBeg) { continue; } if (block != bcall->bbNext) { continue; } if (comp->ehCallFinallyInCorrectRegion(bcall, hndIndex)) { return true; } } } #endif // FEATURE_EH_FUNCLETS assert(!"BBJ_EHFINALLYRET predecessor of block that doesn't follow a BBJ_CALLFINALLY!"); return false; } // This variable is used to generate "traversal labels": one-time constants with which // we label basic blocks that are members of the basic block list, in order to have a // fast, high-probability test for membership in that list. Type is "volatile" because // it's incremented with an atomic operation, which wants a volatile type; "long" so that // wrap-around to 0 (which I think has the highest probability of accidental collision) is // postponed a *long* time. static volatile int bbTraverseLabel = 1; /***************************************************************************** * * A DEBUG routine to check the consistency of the flowgraph, * i.e. bbNum, bbRefs, bbPreds have to be up to date. * *****************************************************************************/ void Compiler::fgDebugCheckBBlist(bool checkBBNum /* = false */, bool checkBBRefs /* = true */) { #ifdef DEBUG if (verbose) { printf("*************** In fgDebugCheckBBlist\n"); } #endif // DEBUG fgDebugCheckBlockLinks(); if (fgBBcount > 10000 && expensiveDebugCheckLevel < 1) { // The basic block checks are too expensive if there are too many blocks, // so give up unless we've been told to try hard. return; } DWORD startTickCount = GetTickCount(); #if FEATURE_EH_FUNCLETS bool reachedFirstFunclet = false; if (fgFuncletsCreated) { // // Make sure that fgFirstFuncletBB is accurate. // It should be the first basic block in a handler region. // if (fgFirstFuncletBB != nullptr) { assert(fgFirstFuncletBB->hasHndIndex() == true); assert(fgFirstFuncletBB->bbFlags & BBF_FUNCLET_BEG); } } #endif // FEATURE_EH_FUNCLETS /* Check bbNum, bbRefs and bbPreds */ // First, pick a traversal stamp, and label all the blocks with it. unsigned curTraversalStamp = unsigned(InterlockedIncrement((LONG*)&bbTraverseLabel)); for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext) { block->bbTraversalStamp = curTraversalStamp; } for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext) { if (checkBBNum) { // Check that bbNum is sequential assert(block->bbNext == nullptr || (block->bbNum + 1 == block->bbNext->bbNum)); } // If the block is a BBJ_COND, a BBJ_SWITCH or a // lowered GT_SWITCH_TABLE node then make sure it // ends with a conditional jump or a GT_SWITCH if (block->bbJumpKind == BBJ_COND) { assert(block->lastNode()->gtNext == nullptr && block->lastNode()->OperIsConditionalJump()); } else if (block->bbJumpKind == BBJ_SWITCH) { assert(block->lastNode()->gtNext == nullptr && (block->lastNode()->gtOper == GT_SWITCH || block->lastNode()->gtOper == GT_SWITCH_TABLE)); } else if (!(block->bbJumpKind == BBJ_ALWAYS || block->bbJumpKind == BBJ_RETURN)) { // this block cannot have a poll assert(!(block->bbFlags & BBF_NEEDS_GCPOLL)); } if (block->bbCatchTyp == BBCT_FILTER) { if (!fgCheapPredsValid) // Don't check cheap preds { // A filter has no predecessors assert(block->bbPreds == nullptr); } } #if FEATURE_EH_FUNCLETS if (fgFuncletsCreated) { // // There should be no handler blocks until // we get to the fgFirstFuncletBB block, // then every block should be a handler block // if (!reachedFirstFunclet) { if (block == fgFirstFuncletBB) { assert(block->hasHndIndex() == true); reachedFirstFunclet = true; } else { assert(block->hasHndIndex() == false); } } else // reachedFirstFunclet { assert(block->hasHndIndex() == true); } } #endif // FEATURE_EH_FUNCLETS if (checkBBRefs) { assert(fgComputePredsDone); } BBPredsChecker checker(this); unsigned blockRefs = checker.CheckBBPreds(block, curTraversalStamp); // First basic block has an additional global incoming edge. if (block == fgFirstBB) { blockRefs += 1; } /* Check the bbRefs */ if (checkBBRefs) { if (block->bbRefs != blockRefs) { // Check to see if this block is the beginning of a filter or a handler and adjust the ref count // appropriately. for (EHblkDsc *HBtab = compHndBBtab, *HBtabEnd = &compHndBBtab[compHndBBtabCount]; HBtab != HBtabEnd; HBtab++) { if (HBtab->ebdHndBeg == block) { blockRefs++; } if (HBtab->HasFilter() && (HBtab->ebdFilter == block)) { blockRefs++; } } } assert(block->bbRefs == blockRefs); } /* Check that BBF_HAS_HANDLER is valid bbTryIndex */ if (block->hasTryIndex()) { assert(block->getTryIndex() < compHndBBtabCount); } /* Check if BBF_RUN_RARELY is set that we have bbWeight of zero */ if (block->isRunRarely()) { assert(block->bbWeight == BB_ZERO_WEIGHT); } else { assert(block->bbWeight > BB_ZERO_WEIGHT); } } // Make sure the one return BB is not changed. if (genReturnBB != nullptr) { assert(genReturnBB->bbTreeList); assert(genReturnBB->IsLIR() || genReturnBB->bbTreeList->gtOper == GT_STMT); assert(genReturnBB->IsLIR() || genReturnBB->bbTreeList->gtType == TYP_VOID); } // The general encoder/decoder (currently) only reports "this" as a generics context as a stack location, // so we mark info.compThisArg as lvAddrTaken to ensure that it is not enregistered. Otherwise, it should // not be address-taken. This variable determines if the address-taken-ness of "thisArg" is "OK". bool copiedForGenericsCtxt; #ifndef JIT32_GCENCODER copiedForGenericsCtxt = ((info.compMethodInfo->options & CORINFO_GENERICS_CTXT_FROM_THIS) != 0); #else // JIT32_GCENCODER copiedForGenericsCtxt = FALSE; #endif // JIT32_GCENCODER // This if only in support of the noway_asserts it contains. if (info.compIsStatic) { // For static method, should have never grabbed the temp. assert(lvaArg0Var == BAD_VAR_NUM); } else { // For instance method: assert(info.compThisArg != BAD_VAR_NUM); bool compThisArgAddrExposedOK = !lvaTable[info.compThisArg].lvAddrExposed; #ifndef JIT32_GCENCODER compThisArgAddrExposedOK = compThisArgAddrExposedOK || copiedForGenericsCtxt; #endif // !JIT32_GCENCODER // Should never expose the address of arg 0 or write to arg 0. // In addition, lvArg0Var should remain 0 if arg0 is not // written to or address-exposed. assert(compThisArgAddrExposedOK && !lvaTable[info.compThisArg].lvHasILStoreOp && (lvaArg0Var == info.compThisArg || (lvaArg0Var != info.compThisArg && (lvaTable[lvaArg0Var].lvAddrExposed || lvaTable[lvaArg0Var].lvHasILStoreOp || copiedForGenericsCtxt)))); } } /***************************************************************************** * * A DEBUG routine to check the that the exception flags are correctly set. * ****************************************************************************/ void Compiler::fgDebugCheckFlags(GenTree* tree) { noway_assert(tree->gtOper != GT_STMT); const genTreeOps oper = tree->OperGet(); const unsigned kind = tree->OperKind(); unsigned treeFlags = tree->gtFlags & GTF_ALL_EFFECT; unsigned chkFlags = 0; if (tree->OperMayThrow(this)) { chkFlags |= GTF_EXCEPT; } if (tree->OperRequiresCallFlag(this)) { chkFlags |= GTF_CALL; } /* Is this a leaf node? */ if (kind & GTK_LEAF) { switch (oper) { case GT_CLS_VAR: chkFlags |= GTF_GLOB_REF; break; case GT_CATCH_ARG: chkFlags |= GTF_ORDER_SIDEEFF; break; case GT_MEMORYBARRIER: chkFlags |= GTF_GLOB_REF | GTF_ASG; break; default: break; } } /* Is it a 'simple' unary/binary operator? */ else if (kind & GTK_SMPOP) { GenTree* op1 = tree->gtOp.gtOp1; GenTree* op2 = tree->gtGetOp2IfPresent(); // During GS work, we make shadow copies for params. // In gsParamsToShadows(), we create a shadow var of TYP_INT for every small type param. // Then in gsReplaceShadowParams(), we change the gtLclNum to the shadow var. // We also change the types of the local var tree and the assignment tree to TYP_INT if necessary. // However, since we don't morph the tree at this late stage. Manually propagating // TYP_INT up to the GT_ASG tree is only correct if we don't need to propagate the TYP_INT back up. // The following checks will ensure this. // Is the left child of "tree" a GT_ASG? // // If parent is a TYP_VOID, we don't no need to propagate TYP_INT up. We are fine. // (or) If GT_ASG is the left child of a GT_COMMA, the type of the GT_COMMA node will // be determined by its right child. So we don't need to propagate TYP_INT up either. We are fine. if (op1 && op1->gtOper == GT_ASG) { assert(tree->gtType == TYP_VOID || tree->gtOper == GT_COMMA); } // Is the right child of "tree" a GT_ASG? // // If parent is a TYP_VOID, we don't no need to propagate TYP_INT up. We are fine. if (op2 && op2->gtOper == GT_ASG) { // We can have ASGs on the RHS of COMMAs in setup arguments to a call. assert(tree->gtType == TYP_VOID || tree->gtOper == GT_COMMA); } switch (oper) { case GT_QMARK: if (op1->OperIsCompare()) { noway_assert(op1->gtFlags & GTF_DONT_CSE); } else { noway_assert((op1->gtOper == GT_CNS_INT) && ((op1->gtIntCon.gtIconVal == 0) || (op1->gtIntCon.gtIconVal == 1))); } break; case GT_LIST: case GT_FIELD_LIST: if ((op2 != nullptr) && op2->OperIsAnyList()) { ArrayStack<GenTree*> stack(getAllocator(CMK_DebugOnly)); while ((tree->gtGetOp2() != nullptr) && tree->gtGetOp2()->OperIsAnyList()) { stack.Push(tree); tree = tree->gtGetOp2(); } fgDebugCheckFlags(tree); while (!stack.Empty()) { tree = stack.Pop(); assert((tree->gtFlags & GTF_REVERSE_OPS) == 0); fgDebugCheckFlags(tree->gtOp.gtOp1); chkFlags |= (tree->gtOp.gtOp1->gtFlags & GTF_ALL_EFFECT); chkFlags |= (tree->gtGetOp2()->gtFlags & GTF_ALL_EFFECT); fgDebugCheckFlagsHelper(tree, (tree->gtFlags & GTF_ALL_EFFECT), chkFlags); } return; } break; default: break; } /* Recursively check the subtrees */ if (op1) { fgDebugCheckFlags(op1); } if (op2) { fgDebugCheckFlags(op2); } if (op1) { chkFlags |= (op1->gtFlags & GTF_ALL_EFFECT); } if (op2) { chkFlags |= (op2->gtFlags & GTF_ALL_EFFECT); } // We reuse the value of GTF_REVERSE_OPS for a GT_IND-specific flag, // so exempt that (unary) operator. if (tree->OperGet() != GT_IND && tree->gtFlags & GTF_REVERSE_OPS) { /* Must have two operands if GTF_REVERSE is set */ noway_assert(op1 && op2); /* Make sure that the order of side effects has not been swapped. */ /* However CSE may introduce an assignment after the reverse flag was set and thus GTF_ASG cannot be considered here. */ /* For a GT_ASG(GT_IND(x), y) we are interested in the side effects of x */ GenTree* op1p; if ((oper == GT_ASG) && (op1->gtOper == GT_IND)) { op1p = op1->gtOp.gtOp1; } else { op1p = op1; } /* This isn't true any more with the sticky GTF_REVERSE */ /* // if op1p has side effects, then op2 cannot have side effects if (op1p->gtFlags & (GTF_SIDE_EFFECT & ~GTF_ASG)) { if (op2->gtFlags & (GTF_SIDE_EFFECT & ~GTF_ASG)) gtDispTree(tree); noway_assert(!(op2->gtFlags & (GTF_SIDE_EFFECT & ~GTF_ASG))); } */ } if (tree->OperRequiresAsgFlag()) { chkFlags |= GTF_ASG; } if (oper == GT_ADDR && (op1->OperIsLocal() || op1->gtOper == GT_CLS_VAR || (op1->gtOper == GT_IND && op1->gtOp.gtOp1->gtOper == GT_CLS_VAR_ADDR))) { /* &aliasedVar doesn't need GTF_GLOB_REF, though alisasedVar does. Similarly for clsVar */ treeFlags |= GTF_GLOB_REF; } } /* See what kind of a special operator we have here */ else { switch (tree->OperGet()) { case GT_CALL: GenTree* args; GenTree* argx; GenTreeCall* call; call = tree->AsCall(); if (call->gtCallObjp) { fgDebugCheckFlags(call->gtCallObjp); chkFlags |= (call->gtCallObjp->gtFlags & GTF_SIDE_EFFECT); if (call->gtCallObjp->gtFlags & GTF_ASG) { treeFlags |= GTF_ASG; } } for (args = call->gtCallArgs; args; args = args->gtOp.gtOp2) { argx = args->gtOp.gtOp1; fgDebugCheckFlags(argx); chkFlags |= (argx->gtFlags & GTF_SIDE_EFFECT); if (argx->gtFlags & GTF_ASG) { treeFlags |= GTF_ASG; } } for (args = call->gtCallLateArgs; args; args = args->gtOp.gtOp2) { argx = args->gtOp.gtOp1; fgDebugCheckFlags(argx); chkFlags |= (argx->gtFlags & GTF_SIDE_EFFECT); if (argx->gtFlags & GTF_ASG) { treeFlags |= GTF_ASG; } } if ((call->gtCallType == CT_INDIRECT) && (call->gtCallCookie != nullptr)) { fgDebugCheckFlags(call->gtCallCookie); chkFlags |= (call->gtCallCookie->gtFlags & GTF_SIDE_EFFECT); } if (call->gtCallType == CT_INDIRECT) { fgDebugCheckFlags(call->gtCallAddr); chkFlags |= (call->gtCallAddr->gtFlags & GTF_SIDE_EFFECT); } if (call->IsUnmanaged() && (call->gtCallMoreFlags & GTF_CALL_M_UNMGD_THISCALL)) { if (call->gtCallArgs->gtOp.gtOp1->OperGet() == GT_NOP) { noway_assert(call->gtCallLateArgs->gtOp.gtOp1->TypeGet() == TYP_I_IMPL || call->gtCallLateArgs->gtOp.gtOp1->TypeGet() == TYP_BYREF); } else { noway_assert(call->gtCallArgs->gtOp.gtOp1->TypeGet() == TYP_I_IMPL || call->gtCallArgs->gtOp.gtOp1->TypeGet() == TYP_BYREF); } } break; case GT_ARR_ELEM: GenTree* arrObj; unsigned dim; arrObj = tree->gtArrElem.gtArrObj; fgDebugCheckFlags(arrObj); chkFlags |= (arrObj->gtFlags & GTF_ALL_EFFECT); for (dim = 0; dim < tree->gtArrElem.gtArrRank; dim++) { fgDebugCheckFlags(tree->gtArrElem.gtArrInds[dim]); chkFlags |= tree->gtArrElem.gtArrInds[dim]->gtFlags & GTF_ALL_EFFECT; } break; case GT_ARR_OFFSET: fgDebugCheckFlags(tree->gtArrOffs.gtOffset); chkFlags |= (tree->gtArrOffs.gtOffset->gtFlags & GTF_ALL_EFFECT); fgDebugCheckFlags(tree->gtArrOffs.gtIndex); chkFlags |= (tree->gtArrOffs.gtIndex->gtFlags & GTF_ALL_EFFECT); fgDebugCheckFlags(tree->gtArrOffs.gtArrObj); chkFlags |= (tree->gtArrOffs.gtArrObj->gtFlags & GTF_ALL_EFFECT); break; case GT_ARR_BOUNDS_CHECK: #ifdef FEATURE_SIMD case GT_SIMD_CHK: #endif // FEATURE_SIMD #ifdef FEATURE_HW_INTRINSICS case GT_HW_INTRINSIC_CHK: #endif // FEATURE_HW_INTRINSICS GenTreeBoundsChk* bndsChk; bndsChk = tree->AsBoundsChk(); fgDebugCheckFlags(bndsChk->gtIndex); chkFlags |= (bndsChk->gtIndex->gtFlags & GTF_ALL_EFFECT); fgDebugCheckFlags(bndsChk->gtArrLen); chkFlags |= (bndsChk->gtArrLen->gtFlags & GTF_ALL_EFFECT); break; case GT_CMPXCHG: chkFlags |= (GTF_GLOB_REF | GTF_ASG); GenTreeCmpXchg* cmpXchg; cmpXchg = tree->AsCmpXchg(); fgDebugCheckFlags(cmpXchg->gtOpLocation); chkFlags |= (cmpXchg->gtOpLocation->gtFlags & GTF_ALL_EFFECT); fgDebugCheckFlags(cmpXchg->gtOpValue); chkFlags |= (cmpXchg->gtOpValue->gtFlags & GTF_ALL_EFFECT); fgDebugCheckFlags(cmpXchg->gtOpComparand); chkFlags |= (cmpXchg->gtOpComparand->gtFlags & GTF_ALL_EFFECT); break; case GT_STORE_DYN_BLK: case GT_DYN_BLK: GenTreeDynBlk* dynBlk; dynBlk = tree->AsDynBlk(); fgDebugCheckFlags(dynBlk->gtDynamicSize); chkFlags |= (dynBlk->gtDynamicSize->gtFlags & GTF_ALL_EFFECT); fgDebugCheckFlags(dynBlk->Addr()); chkFlags |= (dynBlk->Addr()->gtFlags & GTF_ALL_EFFECT); if (tree->OperGet() == GT_STORE_DYN_BLK) { fgDebugCheckFlags(dynBlk->Data()); chkFlags |= (dynBlk->Data()->gtFlags & GTF_ALL_EFFECT); } break; default: #ifdef DEBUG gtDispTree(tree); #endif assert(!"Unknown operator for fgDebugCheckFlags"); break; } } fgDebugCheckFlagsHelper(tree, treeFlags, chkFlags); } //------------------------------------------------------------------------------ // fgDebugCheckFlagsHelper : Check if all bits that are set in chkFlags are also set in treeFlags. // // // Arguments: // tree - Tree whose flags are being checked // treeFlags - Actual flags on the tree // chkFlags - Expected flags // // Note: // Checking that all bits that are set in treeFlags are also set in chkFlags is currently disabled. void Compiler::fgDebugCheckFlagsHelper(GenTree* tree, unsigned treeFlags, unsigned chkFlags) { if (chkFlags & ~treeFlags) { // Print the tree so we can see it in the log. printf("Missing flags on tree [%06d]: ", dspTreeID(tree)); GenTree::gtDispFlags(chkFlags & ~treeFlags, GTF_DEBUG_NONE); printf("\n"); gtDispTree(tree); noway_assert(!"Missing flags on tree"); // Print the tree again so we can see it right after we hook up the debugger. printf("Missing flags on tree [%06d]: ", dspTreeID(tree)); GenTree::gtDispFlags(chkFlags & ~treeFlags, GTF_DEBUG_NONE); printf("\n"); gtDispTree(tree); } else if (treeFlags & ~chkFlags) { // TODO: We are currently only checking extra GTF_EXCEPT, GTF_ASG, and GTF_CALL flags. if ((treeFlags & ~chkFlags & ~GTF_GLOB_REF & ~GTF_ORDER_SIDEEFF) != 0) { // Print the tree so we can see it in the log. printf("Extra flags on parent tree [%X]: ", tree); GenTree::gtDispFlags(treeFlags & ~chkFlags, GTF_DEBUG_NONE); printf("\n"); gtDispTree(tree); noway_assert(!"Extra flags on tree"); // Print the tree again so we can see it right after we hook up the debugger. printf("Extra flags on parent tree [%X]: ", tree); GenTree::gtDispFlags(treeFlags & ~chkFlags, GTF_DEBUG_NONE); printf("\n"); gtDispTree(tree); } } } // DEBUG routine to check correctness of the internal gtNext, gtPrev threading of a statement. // This threading is only valid when fgStmtListThreaded is true. // This calls an alternate method for FGOrderLinear. void Compiler::fgDebugCheckNodeLinks(BasicBlock* block, GenTreeStmt* stmt) { // LIR blocks are checked using BasicBlock::CheckLIR(). if (block->IsLIR()) { LIR::AsRange(block).CheckLIR(this); // TODO: return? } assert(fgStmtListThreaded); noway_assert(stmt->gtStmtList); // The first node's gtPrev must be nullptr (the gtPrev list is not circular). // The last node's gtNext must be nullptr (the gtNext list is not circular). This is tested if the loop below // terminates. assert(stmt->gtStmtList->gtPrev == nullptr); for (GenTree* tree = stmt->gtStmtList; tree != nullptr; tree = tree->gtNext) { if (tree->gtPrev) { noway_assert(tree->gtPrev->gtNext == tree); } else { noway_assert(tree == stmt->gtStmtList); } if (tree->gtNext) { noway_assert(tree->gtNext->gtPrev == tree); } else { noway_assert(tree == stmt->gtStmtExpr); } /* Cross-check gtPrev,gtNext with gtOp for simple trees */ GenTree* expectedPrevTree = nullptr; if (tree->OperIsLeaf()) { if (tree->gtOper == GT_CATCH_ARG) { // The GT_CATCH_ARG should always have GTF_ORDER_SIDEEFF set noway_assert(tree->gtFlags & GTF_ORDER_SIDEEFF); // The GT_CATCH_ARG has to be the first thing evaluated noway_assert(stmt == block->FirstNonPhiDef()); noway_assert(stmt->gtStmtList->gtOper == GT_CATCH_ARG); // The root of the tree should have GTF_ORDER_SIDEEFF set noway_assert(stmt->gtStmtExpr->gtFlags & GTF_ORDER_SIDEEFF); } } if (tree->OperIsUnary() && tree->gtOp.gtOp1) { expectedPrevTree = tree->gtOp.gtOp1; } else if (tree->OperIsBinary() && tree->gtOp.gtOp1) { switch (tree->gtOper) { case GT_QMARK: expectedPrevTree = tree->gtOp.gtOp2->AsColon()->ThenNode(); // "then" operand of the GT_COLON (generated second). break; case GT_COLON: expectedPrevTree = tree->AsColon()->ElseNode(); // "else" branch result (generated first). break; default: if (tree->gtOp.gtOp2) { if (tree->gtFlags & GTF_REVERSE_OPS) { expectedPrevTree = tree->gtOp.gtOp1; } else { expectedPrevTree = tree->gtOp.gtOp2; } } else { expectedPrevTree = tree->gtOp.gtOp1; } break; } } noway_assert(expectedPrevTree == nullptr || // No expectations about the prev node tree->gtPrev == expectedPrevTree); // The "normal" case } } /***************************************************************************** * * A DEBUG routine to check the correctness of the links between GT_STMT nodes * and ordinary nodes within a statement. * ****************************************************************************/ void Compiler::fgDebugCheckLinks(bool morphTrees) { // This used to be only on for stress, and there was a comment stating that // it was "quite an expensive operation" but I did not find that to be true. // Set DO_SANITY_DEBUG_CHECKS to false to revert to that behavior. const bool DO_SANITY_DEBUG_CHECKS = true; if (!DO_SANITY_DEBUG_CHECKS && !compStressCompile(STRESS_CHK_FLOW_UPDATE, 30)) { return; } fgDebugCheckBlockLinks(); /* For each basic block check the bbTreeList links */ for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext) { if (block->IsLIR()) { LIR::AsRange(block).CheckLIR(this); } else { fgDebugCheckStmtsList(block, morphTrees); } } fgDebugCheckNodesUniqueness(); } //------------------------------------------------------------------------------ // fgDebugCheckStmtsList : Perfoms the set of checks: // - all statements in the block are linked correctly // - check statements flags // - check nodes gtNext and gtPrev values, if the node list is threaded // // Arguments: // block - the block to check statements in // morphTrees - try to morph trees in the checker // // Note: // Checking that all bits that are set in treeFlags are also set in chkFlags is currently disabled. void Compiler::fgDebugCheckStmtsList(BasicBlock* block, bool morphTrees) { for (GenTreeStmt* stmt = block->firstStmt(); stmt != nullptr; stmt = stmt->gtNextStmt) { /* Verify that bbTreeList is threaded correctly */ /* Note that for the GT_STMT list, the gtPrev list is circular. The gtNext list is not: gtNext of the * last GT_STMT in a block is nullptr. */ noway_assert(stmt->gtPrev); if (stmt == block->bbTreeList) { noway_assert(stmt->gtPrev->gtNext == nullptr); } else { noway_assert(stmt->gtPrev->gtNext == stmt); } if (stmt->gtNext) { noway_assert(stmt->gtNext->gtPrev == stmt); } else { noway_assert(block->lastStmt() == stmt); } /* For each statement check that the exception flags are properly set */ noway_assert(stmt->gtStmtExpr); if (verbose && 0) { gtDispTree(stmt->gtStmtExpr); } fgDebugCheckFlags(stmt->gtStmtExpr); // Not only will this stress fgMorphBlockStmt(), but we also get all the checks // done by fgMorphTree() if (morphTrees) { // If 'stmt' is removed from the block, start a new check for the current block, // break the current check. if (fgMorphBlockStmt(block, stmt DEBUGARG("test morphing"))) { fgDebugCheckStmtsList(block, morphTrees); break; } } /* For each GT_STMT node check that the nodes are threaded correcly - gtStmtList */ if (fgStmtListThreaded) { fgDebugCheckNodeLinks(block, stmt); } } } // ensure that bbNext and bbPrev are consistent void Compiler::fgDebugCheckBlockLinks() { assert(fgFirstBB->bbPrev == nullptr); for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext) { if (block->bbNext) { assert(block->bbNext->bbPrev == block); } else { assert(block == fgLastBB); } if (block->bbPrev) { assert(block->bbPrev->bbNext == block); } else { assert(block == fgFirstBB); } // If this is a switch, check that the tables are consistent. // Note that we don't call GetSwitchDescMap(), because it has the side-effect // of allocating it if it is not present. if (block->bbJumpKind == BBJ_SWITCH && m_switchDescMap != nullptr) { SwitchUniqueSuccSet uniqueSuccSet; if (m_switchDescMap->Lookup(block, &uniqueSuccSet)) { // Create a set with all the successors. Don't use BlockSet, so we don't need to worry // about the BlockSet epoch. BitVecTraits bitVecTraits(fgBBNumMax + 1, this); BitVec succBlocks(BitVecOps::MakeEmpty(&bitVecTraits)); BasicBlock** jumpTable = block->bbJumpSwt->bbsDstTab; unsigned jumpCount = block->bbJumpSwt->bbsCount; for (unsigned i = 0; i < jumpCount; i++) { BitVecOps::AddElemD(&bitVecTraits, succBlocks, jumpTable[i]->bbNum); } // Now we should have a set of unique successors that matches what's in the switchMap. // First, check the number of entries, then make sure all the blocks in uniqueSuccSet // are in the BlockSet. unsigned count = BitVecOps::Count(&bitVecTraits, succBlocks); assert(uniqueSuccSet.numDistinctSuccs == count); for (unsigned i = 0; i < uniqueSuccSet.numDistinctSuccs; i++) { assert(BitVecOps::IsMember(&bitVecTraits, succBlocks, uniqueSuccSet.nonDuplicates[i]->bbNum)); } } } } } // UniquenessCheckWalker keeps data that is neccesary to check // that each tree has it is own unique id and they do not repeat. class UniquenessCheckWalker { public: UniquenessCheckWalker(Compiler* comp) : comp(comp), nodesVecTraits(comp->compGenTreeID, comp), uniqueNodes(BitVecOps::MakeEmpty(&nodesVecTraits)) { } //------------------------------------------------------------------------ // fgMarkTreeId: Visit all subtrees in the tree and check gtTreeIDs. // // Arguments: // pTree - Pointer to the tree to walk // fgWalkPre - the UniquenessCheckWalker instance // static Compiler::fgWalkResult MarkTreeId(GenTree** pTree, Compiler::fgWalkData* fgWalkPre) { UniquenessCheckWalker* walker = static_cast<UniquenessCheckWalker*>(fgWalkPre->pCallbackData); unsigned gtTreeID = (*pTree)->gtTreeID; walker->CheckTreeId(gtTreeID); return Compiler::WALK_CONTINUE; } //------------------------------------------------------------------------ // CheckTreeId: Check that this tree was not visit before and memorize it as visited. // // Arguments: // gtTreeID - identificator of GenTree. // void CheckTreeId(unsigned gtTreeID) { assert(!BitVecOps::IsMember(&nodesVecTraits, uniqueNodes, gtTreeID)); BitVecOps::AddElemD(&nodesVecTraits, uniqueNodes, gtTreeID); } private: Compiler* comp; BitVecTraits nodesVecTraits; BitVec uniqueNodes; }; //------------------------------------------------------------------------------ // fgDebugCheckNodesUniqueness: Check that each tree in the method has its own unique gtTreeId. // void Compiler::fgDebugCheckNodesUniqueness() { UniquenessCheckWalker walker(this); for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext) { if (block->IsLIR()) { for (GenTree* i : LIR::AsRange(block)) { walker.CheckTreeId(i->gtTreeID); } } else { for (GenTreeStmt* stmt = block->firstStmt(); stmt != nullptr; stmt = stmt->gtNextStmt) { GenTree* root = stmt->gtStmtExpr; fgWalkTreePre(&root, UniquenessCheckWalker::MarkTreeId, &walker); } } } } /*****************************************************************************/ #endif // DEBUG /*****************************************************************************/ //------------------------------------------------------------------------ // fgCheckForInlineDepthAndRecursion: compute depth of the candidate, and // check for recursion. // // Return Value: // The depth of the inline candidate. The root method is a depth 0, top-level // candidates at depth 1, etc. // // Notes: // We generally disallow recursive inlines by policy. However, they are // supported by the underlying machinery. // // Likewise the depth limit is a policy consideration, and serves mostly // as a safeguard to prevent runaway inlining of small methods. // unsigned Compiler::fgCheckInlineDepthAndRecursion(InlineInfo* inlineInfo) { BYTE* candidateCode = inlineInfo->inlineCandidateInfo->methInfo.ILCode; InlineContext* inlineContext = inlineInfo->iciStmt->gtInlineContext; InlineResult* inlineResult = inlineInfo->inlineResult; // There should be a context for all candidates. assert(inlineContext != nullptr); int depth = 0; for (; inlineContext != nullptr; inlineContext = inlineContext->GetParent()) { depth++; if (inlineContext->GetCode() == candidateCode) { // This inline candidate has the same IL code buffer as an already // inlined method does. inlineResult->NoteFatal(InlineObservation::CALLSITE_IS_RECURSIVE); break; } if (depth > InlineStrategy::IMPLEMENTATION_MAX_INLINE_DEPTH) { break; } } inlineResult->NoteInt(InlineObservation::CALLSITE_DEPTH, depth); return depth; } /***************************************************************************** * * Inlining phase */ void Compiler::fgInline() { if (!opts.OptEnabled(CLFLG_INLINING)) { return; } #ifdef DEBUG if (verbose) { printf("*************** In fgInline()\n"); } #endif // DEBUG BasicBlock* block = fgFirstBB; noway_assert(block != nullptr); // Set the root inline context on all statements InlineContext* rootContext = m_inlineStrategy->GetRootContext(); for (; block != nullptr; block = block->bbNext) { for (GenTreeStmt* stmt = block->firstStmt(); stmt; stmt = stmt->gtNextStmt) { stmt->gtInlineContext = rootContext; } } // Reset block back to start for inlining block = fgFirstBB; do { // Make the current basic block address available globally compCurBB = block; for (GenTreeStmt* stmt = block->firstStmt(); stmt != nullptr; stmt = stmt->gtNextStmt) { #ifdef DEBUG // In debug builds we want the inline tree to show all failed // inlines. Some inlines may fail very early and never make it to // candidate stage. So scan the tree looking for those early failures. fgWalkTreePre(&stmt->gtStmtExpr, fgFindNonInlineCandidate, stmt); #endif GenTree* expr = stmt->gtStmtExpr; // The importer ensures that all inline candidates are // statement expressions. So see if we have a call. if (expr->IsCall()) { GenTreeCall* call = expr->AsCall(); // We do. Is it an inline candidate? // // Note we also process GuardeDevirtualizationCandidates here as we've // split off GT_RET_EXPRs for them even when they are not inline candidates // as we need similar processing to ensure they get patched back to where // they belong. if (call->IsInlineCandidate() || call->IsGuardedDevirtualizationCandidate()) { InlineResult inlineResult(this, call, stmt, "fgInline"); fgMorphStmt = stmt; fgMorphCallInline(call, &inlineResult); // fgMorphCallInline may have updated the // statement expression to a GT_NOP if the // call returned a value, regardless of // whether the inline succeeded or failed. // // If so, remove the GT_NOP and continue // on with the next statement. if (stmt->gtStmtExpr->IsNothingNode()) { fgRemoveStmt(block, stmt); continue; } } } // See if we need to replace some return value place holders. // Also, see if this replacement enables further devirtualization. // // Note we have both preorder and postorder callbacks here. // // The preorder callback is responsible for replacing GT_RET_EXPRs // with the appropriate expansion (call or inline result). // Replacement may introduce subtrees with GT_RET_EXPR and so // we rely on the preorder to recursively process those as well. // // On the way back up, the postorder callback then re-examines nodes for // possible further optimization, as the (now complete) GT_RET_EXPR // replacement may have enabled optimizations by providing more // specific types for trees or variables. fgWalkTree(&stmt->gtStmtExpr, fgUpdateInlineReturnExpressionPlaceHolder, fgLateDevirtualization, (void*)this); // See if stmt is of the form GT_COMMA(call, nop) // If yes, we can get rid of GT_COMMA. if (expr->OperGet() == GT_COMMA && expr->gtOp.gtOp1->OperGet() == GT_CALL && expr->gtOp.gtOp2->OperGet() == GT_NOP) { stmt->gtStmtExpr = expr->gtOp.gtOp1; } } block = block->bbNext; } while (block); #ifdef DEBUG // Check that we should not have any inline candidate or return value place holder left. block = fgFirstBB; noway_assert(block); do { GenTreeStmt* stmt; for (stmt = block->firstStmt(); stmt; stmt = stmt->gtNextStmt) { // Call Compiler::fgDebugCheckInlineCandidates on each node fgWalkTreePre(&stmt->gtStmtExpr, fgDebugCheckInlineCandidates); } block = block->bbNext; } while (block); fgVerifyHandlerTab(); if (verbose) { printf("*************** After fgInline()\n"); fgDispBasicBlocks(true); fgDispHandlerTab(); } if (verbose || fgPrintInlinedMethods) { JITDUMP("**************** Inline Tree"); printf("\n"); m_inlineStrategy->Dump(verbose); } #endif // DEBUG } #ifdef DEBUG //------------------------------------------------------------------------ // fgFindNonInlineCandidate: tree walk helper to ensure that a tree node // that is not an inline candidate is noted as a failed inline. // // Arguments: // pTree - pointer to pointer tree node being walked // data - contextual data for the walk // // Return Value: // walk result // // Note: // Invokes fgNoteNonInlineCandidate on the nodes it finds. Compiler::fgWalkResult Compiler::fgFindNonInlineCandidate(GenTree** pTree, fgWalkData* data) { GenTree* tree = *pTree; if (tree->gtOper == GT_CALL) { Compiler* compiler = data->compiler; GenTreeStmt* stmt = (GenTreeStmt*)data->pCallbackData; GenTreeCall* call = tree->AsCall(); compiler->fgNoteNonInlineCandidate(stmt, call); } return WALK_CONTINUE; } //------------------------------------------------------------------------ // fgNoteNonInlineCandidate: account for inlining failures in calls // not marked as inline candidates. // // Arguments: // stmt - statement containing the call // call - the call itself // // Notes: // Used in debug only to try and place descriptions of inline failures // into the proper context in the inline tree. void Compiler::fgNoteNonInlineCandidate(GenTreeStmt* stmt, GenTreeCall* call) { if (call->IsInlineCandidate() || call->IsGuardedDevirtualizationCandidate()) { return; } InlineResult inlineResult(this, call, nullptr, "fgNotInlineCandidate"); InlineObservation currentObservation = InlineObservation::CALLSITE_NOT_CANDIDATE; // Try and recover the reason left behind when the jit decided // this call was not a candidate. InlineObservation priorObservation = call->gtInlineObservation; if (InlIsValidObservation(priorObservation)) { currentObservation = priorObservation; } // Propagate the prior failure observation to this result. inlineResult.NotePriorFailure(currentObservation); inlineResult.SetReported(); if (call->gtCallType == CT_USER_FUNC) { // Create InlineContext for the failure m_inlineStrategy->NewFailure(stmt, &inlineResult); } } #endif #if FEATURE_MULTIREG_RET /********************************************************************************* * * tree - The node which needs to be converted to a struct pointer. * * Return the pointer by either __replacing__ the tree node with a suitable pointer * type or __without replacing__ and just returning a subtree or by __modifying__ * a subtree. */ GenTree* Compiler::fgGetStructAsStructPtr(GenTree* tree) { noway_assert((tree->gtOper == GT_LCL_VAR) || (tree->gtOper == GT_FIELD) || (tree->gtOper == GT_IND) || (tree->gtOper == GT_BLK) || (tree->gtOper == GT_OBJ) || tree->OperIsSIMD() || // tree->gtOper == GT_CALL || cannot get address of call. // tree->gtOper == GT_MKREFANY || inlining should've been aborted due to mkrefany opcode. // tree->gtOper == GT_RET_EXPR || cannot happen after fgUpdateInlineReturnExpressionPlaceHolder (tree->gtOper == GT_COMMA)); switch (tree->OperGet()) { case GT_BLK: case GT_OBJ: case GT_IND: return tree->gtOp.gtOp1; case GT_COMMA: tree->gtOp.gtOp2 = fgGetStructAsStructPtr(tree->gtOp.gtOp2); tree->gtType = TYP_BYREF; return tree; default: return gtNewOperNode(GT_ADDR, TYP_BYREF, tree); } } /*************************************************************************************************** * child - The inlinee of the retExpr node. * retClsHnd - The struct class handle of the type of the inlinee. * * Assign the inlinee to a tmp, if it is a call, just assign it to a lclVar, else we can * use a copyblock to do the assignment. */ GenTree* Compiler::fgAssignStructInlineeToVar(GenTree* child, CORINFO_CLASS_HANDLE retClsHnd) { assert(child->gtOper != GT_RET_EXPR && child->gtOper != GT_MKREFANY); unsigned tmpNum = lvaGrabTemp(false DEBUGARG("RetBuf for struct inline return candidates.")); lvaSetStruct(tmpNum, retClsHnd, false); var_types structType = lvaTable[tmpNum].lvType; GenTree* dst = gtNewLclvNode(tmpNum, structType); // If we have a call, we'd like it to be: V00 = call(), but first check if // we have a ", , , call()" -- this is very defensive as we may never get // an inlinee that is made of commas. If the inlinee is not a call, then // we use a copy block to do the assignment. GenTree* src = child; GenTree* lastComma = nullptr; while (src->gtOper == GT_COMMA) { lastComma = src; src = src->gtOp.gtOp2; } GenTree* newInlinee = nullptr; if (src->gtOper == GT_CALL) { // If inlinee was just a call, new inlinee is v05 = call() newInlinee = gtNewAssignNode(dst, src); // When returning a multi-register value in a local var, make sure the variable is // marked as lvIsMultiRegRet, so it does not get promoted. if (src->AsCall()->HasMultiRegRetVal()) { lvaTable[tmpNum].lvIsMultiRegRet = true; } // If inlinee was comma, but a deeper call, new inlinee is (, , , v05 = call()) if (child->gtOper == GT_COMMA) { lastComma->gtOp.gtOp2 = newInlinee; newInlinee = child; } } else { // Inlinee is not a call, so just create a copy block to the tmp. src = child; GenTree* dstAddr = fgGetStructAsStructPtr(dst); GenTree* srcAddr = fgGetStructAsStructPtr(src); newInlinee = gtNewCpObjNode(dstAddr, srcAddr, retClsHnd, false); } GenTree* production = gtNewLclvNode(tmpNum, structType); return gtNewOperNode(GT_COMMA, structType, newInlinee, production); } /*************************************************************************************************** * tree - The tree pointer that has one of its child nodes as retExpr. * child - The inlinee child. * retClsHnd - The struct class handle of the type of the inlinee. * * V04 = call() assignments are okay as we codegen it. Everything else needs to be a copy block or * would need a temp. For example, a cast(ldobj) will then be, cast(v05 = ldobj, v05); But it is * a very rare (or impossible) scenario that we'd have a retExpr transform into a ldobj other than * a lclVar/call. So it is not worthwhile to do pattern matching optimizations like addr(ldobj(op1)) * can just be op1. */ void Compiler::fgAttachStructInlineeToAsg(GenTree* tree, GenTree* child, CORINFO_CLASS_HANDLE retClsHnd) { // We are okay to have: // 1. V02 = call(); // 2. copyBlk(dstAddr, srcAddr); assert(tree->gtOper == GT_ASG); // We have an assignment, we codegen only V05 = call(). if (child->gtOper == GT_CALL && tree->gtOp.gtOp1->gtOper == GT_LCL_VAR) { // If it is a multireg return on x64/ux, the local variable should be marked as lvIsMultiRegRet if (child->AsCall()->HasMultiRegRetVal()) { unsigned lclNum = tree->gtOp.gtOp1->gtLclVarCommon.gtLclNum; lvaTable[lclNum].lvIsMultiRegRet = true; } return; } GenTree* dstAddr = fgGetStructAsStructPtr(tree->gtOp.gtOp1); GenTree* srcAddr = fgGetStructAsStructPtr( (child->gtOper == GT_CALL) ? fgAssignStructInlineeToVar(child, retClsHnd) // Assign to a variable if it is a call. : child); // Just get the address, if not a call. tree->ReplaceWith(gtNewCpObjNode(dstAddr, srcAddr, retClsHnd, false), this); } #endif // FEATURE_MULTIREG_RET //------------------------------------------------------------------------ // fgUpdateInlineReturnExpressionPlaceHolder: callback to replace the // inline return expression placeholder. // // Arguments: // pTree -- pointer to tree to examine for updates // data -- context data for the tree walk // // Returns: // fgWalkResult indicating the walk should continue; that // is we wish to fully explore the tree. // // Notes: // Looks for GT_RET_EXPR nodes that arose from tree splitting done // during importation for inline candidates, and replaces them. // // For successful inlines, substitutes the return value expression // from the inline body for the GT_RET_EXPR. // // For failed inlines, rejoins the original call into the tree from // whence it was split during importation. // // The code doesn't actually know if the corresponding inline // succeeded or not; it relies on the fact that gtInlineCandidate // initially points back at the call and is modified in place to // the inlinee return expression if the inline is successful (see // tail end of fgInsertInlineeBlocks for the update of iciCall). // // If the return type is a struct type and we're on a platform // where structs can be returned in multiple registers, ensure the // call has a suitable parent. Compiler::fgWalkResult Compiler::fgUpdateInlineReturnExpressionPlaceHolder(GenTree** pTree, fgWalkData* data) { // All the operations here and in the corresponding postorder // callback (fgLateDevirtualization) are triggered by GT_CALL or // GT_RET_EXPR trees, and these (should) have the call side // effect flag. // // So bail out for any trees that don't have this flag. GenTree* tree = *pTree; if ((tree->gtFlags & GTF_CALL) == 0) { return WALK_SKIP_SUBTREES; } Compiler* comp = data->compiler; CORINFO_CLASS_HANDLE retClsHnd = NO_CLASS_HANDLE; if (tree->OperGet() == GT_RET_EXPR) { // We are going to copy the tree from the inlinee, // so record the handle now. // if (varTypeIsStruct(tree)) { retClsHnd = tree->gtRetExpr.gtRetClsHnd; } // Skip through chains of GT_RET_EXPRs (say from nested inlines) // to the actual tree to use. GenTree* inlineCandidate = tree->gtRetExprVal(); var_types retType = tree->TypeGet(); #ifdef DEBUG if (comp->verbose) { printf("\nReplacing the return expression placeholder "); printTreeID(tree); printf(" with "); printTreeID(inlineCandidate); printf("\n"); // Dump out the old return expression placeholder it will be overwritten by the ReplaceWith below comp->gtDispTree(tree); } #endif // DEBUG tree->ReplaceWith(inlineCandidate, comp); #ifdef DEBUG if (comp->verbose) { printf("\nInserting the inline return expression\n"); comp->gtDispTree(tree); printf("\n"); } #endif // DEBUG var_types newType = tree->TypeGet(); // If we end up swapping in an RVA static we may need to retype it here, // if we've reinterpreted it as a byref. if ((retType != newType) && (retType == TYP_BYREF) && (tree->OperGet() == GT_IND)) { assert(newType == TYP_I_IMPL); JITDUMP("Updating type of the return GT_IND expression to TYP_BYREF\n"); tree->gtType = TYP_BYREF; } } // If an inline was rejected and the call returns a struct, we may // have deferred some work when importing call for cases where the // struct is returned in register(s). // // See the bail-out clauses in impFixupCallStructReturn for inline // candidates. // // Do the deferred work now. if (retClsHnd != NO_CLASS_HANDLE) { structPassingKind howToReturnStruct; var_types returnType = comp->getReturnTypeForStruct(retClsHnd, &howToReturnStruct); GenTree* parent = data->parent; switch (howToReturnStruct) { #if FEATURE_MULTIREG_RET // Is this a type that is returned in multiple registers // or a via a primitve type that is larger than the struct type? // if so we need to force into into a form we accept. // i.e. LclVar = call() case SPK_ByValue: case SPK_ByValueAsHfa: { // See assert below, we only look one level above for an asg parent. if (parent->gtOper == GT_ASG) { // Either lhs is a call V05 = call(); or lhs is addr, and asg becomes a copyBlk. comp->fgAttachStructInlineeToAsg(parent, tree, retClsHnd); } else { // Just assign the inlinee to a variable to keep it simple. tree->ReplaceWith(comp->fgAssignStructInlineeToVar(tree, retClsHnd), comp); } } break; #endif // FEATURE_MULTIREG_RET case SPK_EnclosingType: { // For enclosing type returns, we must return the call value to a temp since // the return type is larger than the struct type. if (!tree->IsCall()) { break; } GenTreeCall* call = tree->AsCall(); assert(call->gtReturnType == TYP_STRUCT); if (call->gtReturnType != TYP_STRUCT) { break; } JITDUMP("\nCall returns small struct via enclosing type, retyping. Before:\n"); DISPTREE(call); // Create new struct typed temp for return value const unsigned tmpNum = comp->lvaGrabTemp(true DEBUGARG("small struct return temp for rejected inline")); comp->lvaSetStruct(tmpNum, retClsHnd, false); GenTree* assign = comp->gtNewTempAssign(tmpNum, call); // Modify assign tree and call return types to the primitive return type call->gtReturnType = returnType; call->gtType = returnType; assign->gtType = returnType; // Modify the temp reference in the assign as a primitive reference via GT_LCL_FLD GenTree* tempAsPrimitive = assign->gtOp.gtOp1; assert(tempAsPrimitive->gtOper == GT_LCL_VAR); tempAsPrimitive->gtType = returnType; tempAsPrimitive->ChangeOper(GT_LCL_FLD); // Return temp as value of call tree via comma GenTree* tempAsStruct = comp->gtNewLclvNode(tmpNum, TYP_STRUCT); GenTree* comma = comp->gtNewOperNode(GT_COMMA, TYP_STRUCT, assign, tempAsStruct); parent->ReplaceOperand(pTree, comma); JITDUMP("\nAfter:\n"); DISPTREE(comma); } break; case SPK_PrimitiveType: // We should have already retyped the call as a primitive type // when we first imported the call break; case SPK_ByReference: // We should have already added the return buffer // when we first imported the call break; default: noway_assert(!"Unexpected struct passing kind"); break; } } #if FEATURE_MULTIREG_RET #if defined(DEBUG) // Make sure we don't have a tree like so: V05 = (, , , retExpr); // Since we only look one level above for the parent for '=' and // do not check if there is a series of COMMAs. See above. // Importer and FlowGraph will not generate such a tree, so just // leaving an assert in here. This can be fixed by looking ahead // when we visit GT_ASG similar to fgAttachStructInlineeToAsg. // if (tree->OperGet() == GT_ASG) { GenTree* value = tree->gtOp.gtOp2; if (value->OperGet() == GT_COMMA) { GenTree* effectiveValue = value->gtEffectiveVal(/*commaOnly*/ true); noway_assert(!varTypeIsStruct(effectiveValue) || (effectiveValue->OperGet() != GT_RET_EXPR) || !comp->IsMultiRegReturnedType(effectiveValue->gtRetExpr.gtRetClsHnd)); } } #endif // defined(DEBUG) #endif // FEATURE_MULTIREG_RET return WALK_CONTINUE; } //------------------------------------------------------------------------ // fgLateDevirtualization: re-examine calls after inlining to see if we // can do more devirtualization // // Arguments: // pTree -- pointer to tree to examine for updates // data -- context data for the tree walk // // Returns: // fgWalkResult indicating the walk should continue; that // is we wish to fully explore the tree. // // Notes: // We used to check this opportunistically in the preorder callback for // calls where the `obj` was fed by a return, but we now re-examine // all calls. // // Late devirtualization (and eventually, perhaps, other type-driven // opts like cast optimization) can happen now because inlining or other // optimizations may have provided more accurate types than we saw when // first importing the trees. // // It would be nice to screen candidate sites based on the likelihood // that something has changed. Otherwise we'll waste some time retrying // an optimization that will just fail again. Compiler::fgWalkResult Compiler::fgLateDevirtualization(GenTree** pTree, fgWalkData* data) { GenTree* tree = *pTree; GenTree* parent = data->parent; Compiler* comp = data->compiler; // In some (rare) cases the parent node of tree will be smashed to a NOP during // the preorder by fgAttachStructToInlineeArg. // // jit\Methodical\VT\callconv\_il_reljumper3 for x64 linux // // If so, just bail out here. if (tree == nullptr) { assert((parent != nullptr) && parent->OperGet() == GT_NOP); return WALK_CONTINUE; } if (tree->OperGet() == GT_CALL) { GenTreeCall* call = tree->AsCall(); bool tryLateDevirt = call->IsVirtual() && (call->gtCallType == CT_USER_FUNC); #ifdef DEBUG tryLateDevirt = tryLateDevirt && (JitConfig.JitEnableLateDevirtualization() == 1); #endif // DEBUG if (tryLateDevirt) { #ifdef DEBUG if (comp->verbose) { printf("**** Late devirt opportunity\n"); comp->gtDispTree(call); } #endif // DEBUG CORINFO_METHOD_HANDLE method = call->gtCallMethHnd; unsigned methodFlags = 0; CORINFO_CONTEXT_HANDLE context = nullptr; const bool isLateDevirtualization = true; bool explicitTailCall = (call->gtCall.gtCallMoreFlags & GTF_CALL_M_EXPLICIT_TAILCALL) != 0; comp->impDevirtualizeCall(call, &method, &methodFlags, &context, nullptr, isLateDevirtualization, explicitTailCall); } } else if (tree->OperGet() == GT_ASG) { // If we're assigning to a ref typed local that has one definition, // we may be able to sharpen the type for the local. GenTree* lhs = tree->gtGetOp1()->gtEffectiveVal(); if ((lhs->OperGet() == GT_LCL_VAR) && (lhs->TypeGet() == TYP_REF)) { const unsigned lclNum = lhs->gtLclVarCommon.gtLclNum; LclVarDsc* lcl = comp->lvaGetDesc(lclNum); if (lcl->lvSingleDef) { GenTree* rhs = tree->gtGetOp2(); bool isExact = false; bool isNonNull = false; CORINFO_CLASS_HANDLE newClass = comp->gtGetClassHandle(rhs, &isExact, &isNonNull); if (newClass != NO_CLASS_HANDLE) { comp->lvaUpdateClass(lclNum, newClass, isExact); } } } } return WALK_CONTINUE; } #ifdef DEBUG /***************************************************************************** * Callback to make sure there is no more GT_RET_EXPR and GTF_CALL_INLINE_CANDIDATE nodes. */ /* static */ Compiler::fgWalkResult Compiler::fgDebugCheckInlineCandidates(GenTree** pTree, fgWalkData* data) { GenTree* tree = *pTree; if (tree->gtOper == GT_CALL) { assert((tree->gtFlags & GTF_CALL_INLINE_CANDIDATE) == 0); } else { assert(tree->gtOper != GT_RET_EXPR); } return WALK_CONTINUE; } #endif // DEBUG void Compiler::fgInvokeInlineeCompiler(GenTreeCall* call, InlineResult* inlineResult) { noway_assert(call->gtOper == GT_CALL); noway_assert((call->gtFlags & GTF_CALL_INLINE_CANDIDATE) != 0); noway_assert(opts.OptEnabled(CLFLG_INLINING)); // This is the InlineInfo struct representing a method to be inlined. InlineInfo inlineInfo; memset(&inlineInfo, 0, sizeof(inlineInfo)); CORINFO_METHOD_HANDLE fncHandle = call->gtCallMethHnd; inlineInfo.fncHandle = fncHandle; inlineInfo.iciCall = call; inlineInfo.iciStmt = fgMorphStmt; inlineInfo.iciBlock = compCurBB; inlineInfo.thisDereferencedFirst = false; inlineInfo.retExpr = nullptr; inlineInfo.retExprClassHnd = nullptr; inlineInfo.retExprClassHndIsExact = false; inlineInfo.inlineResult = inlineResult; #ifdef FEATURE_SIMD inlineInfo.hasSIMDTypeArgLocalOrReturn = false; #endif // FEATURE_SIMD InlineCandidateInfo* inlineCandidateInfo = call->gtInlineCandidateInfo; noway_assert(inlineCandidateInfo); // Store the link to inlineCandidateInfo into inlineInfo inlineInfo.inlineCandidateInfo = inlineCandidateInfo; unsigned inlineDepth = fgCheckInlineDepthAndRecursion(&inlineInfo); if (inlineResult->IsFailure()) { #ifdef DEBUG if (verbose) { printf("Recursive or deep inline recursion detected. Will not expand this INLINECANDIDATE \n"); } #endif // DEBUG return; } // Set the trap to catch all errors (including recoverable ones from the EE) struct Param { Compiler* pThis; GenTree* call; CORINFO_METHOD_HANDLE fncHandle; InlineCandidateInfo* inlineCandidateInfo; InlineInfo* inlineInfo; } param; memset(&param, 0, sizeof(param)); param.pThis = this; param.call = call; param.fncHandle = fncHandle; param.inlineCandidateInfo = inlineCandidateInfo; param.inlineInfo = &inlineInfo; bool success = eeRunWithErrorTrap<Param>( [](Param* pParam) { // Init the local var info of the inlinee pParam->pThis->impInlineInitVars(pParam->inlineInfo); if (pParam->inlineInfo->inlineResult->IsCandidate()) { /* Clear the temp table */ memset(pParam->inlineInfo->lclTmpNum, -1, sizeof(pParam->inlineInfo->lclTmpNum)); // // Prepare the call to jitNativeCode // pParam->inlineInfo->InlinerCompiler = pParam->pThis; if (pParam->pThis->impInlineInfo == nullptr) { pParam->inlineInfo->InlineRoot = pParam->pThis; } else { pParam->inlineInfo->InlineRoot = pParam->pThis->impInlineInfo->InlineRoot; } pParam->inlineInfo->argCnt = pParam->inlineCandidateInfo->methInfo.args.totalILArgs(); pParam->inlineInfo->tokenLookupContextHandle = pParam->inlineCandidateInfo->exactContextHnd; JITLOG_THIS(pParam->pThis, (LL_INFO100000, "INLINER: inlineInfo.tokenLookupContextHandle for %s set to 0x%p:\n", pParam->pThis->eeGetMethodFullName(pParam->fncHandle), pParam->pThis->dspPtr(pParam->inlineInfo->tokenLookupContextHandle))); JitFlags compileFlagsForInlinee = *pParam->pThis->opts.jitFlags; // The following flags are lost when inlining. // (This is checked in Compiler::compInitOptions().) compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_BBOPT); compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_BBINSTR); compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_PROF_ENTERLEAVE); compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_DEBUG_EnC); compileFlagsForInlinee.Clear(JitFlags::JIT_FLAG_DEBUG_INFO); compileFlagsForInlinee.Set(JitFlags::JIT_FLAG_SKIP_VERIFICATION); #ifdef DEBUG if (pParam->pThis->verbose) { printf("\nInvoking compiler for the inlinee method %s :\n", pParam->pThis->eeGetMethodFullName(pParam->fncHandle)); } #endif // DEBUG int result = jitNativeCode(pParam->fncHandle, pParam->inlineCandidateInfo->methInfo.scope, pParam->pThis->info.compCompHnd, &pParam->inlineCandidateInfo->methInfo, (void**)pParam->inlineInfo, nullptr, &compileFlagsForInlinee, pParam->inlineInfo); if (result != CORJIT_OK) { // If we haven't yet determined why this inline fails, use // a catch-all something bad happened observation. InlineResult* innerInlineResult = pParam->inlineInfo->inlineResult; if (!innerInlineResult->IsFailure()) { innerInlineResult->NoteFatal(InlineObservation::CALLSITE_COMPILATION_FAILURE); } } } }, &param); if (!success) { #ifdef DEBUG if (verbose) { printf("\nInlining failed due to an exception during invoking the compiler for the inlinee method %s.\n", eeGetMethodFullName(fncHandle)); } #endif // DEBUG // If we haven't yet determined why this inline fails, use // a catch-all something bad happened observation. if (!inlineResult->IsFailure()) { inlineResult->NoteFatal(InlineObservation::CALLSITE_COMPILATION_ERROR); } } if (inlineResult->IsFailure()) { return; } #ifdef DEBUG if (0 && verbose) { printf("\nDone invoking compiler for the inlinee method %s\n", eeGetMethodFullName(fncHandle)); } #endif // DEBUG // If there is non-NULL return, but we haven't set the pInlineInfo->retExpr, // That means we haven't imported any BB that contains CEE_RET opcode. // (This could happen for example for a BBJ_THROW block fall through a BBJ_RETURN block which // causes the BBJ_RETURN block not to be imported at all.) // Fail the inlining attempt if (inlineCandidateInfo->fncRetType != TYP_VOID && inlineInfo.retExpr == nullptr) { #ifdef DEBUG if (verbose) { printf("\nInlining failed because pInlineInfo->retExpr is not set in the inlinee method %s.\n", eeGetMethodFullName(fncHandle)); } #endif // DEBUG inlineResult->NoteFatal(InlineObservation::CALLEE_LACKS_RETURN); return; } if (inlineCandidateInfo->initClassResult & CORINFO_INITCLASS_SPECULATIVE) { // we defer the call to initClass() until inlining is completed in case it fails. If inlining succeeds, // we will call initClass(). if (!(info.compCompHnd->initClass(nullptr /* field */, fncHandle /* method */, inlineCandidateInfo->exactContextHnd /* context */) & CORINFO_INITCLASS_INITIALIZED)) { inlineResult->NoteFatal(InlineObservation::CALLEE_CLASS_INIT_FAILURE); return; } } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // The inlining attempt cannot be failed starting from this point. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // We've successfully obtain the list of inlinee's basic blocks. // Let's insert it to inliner's basic block list. fgInsertInlineeBlocks(&inlineInfo); #ifdef DEBUG if (verbose) { printf("Successfully inlined %s (%d IL bytes) (depth %d) [%s]\n", eeGetMethodFullName(fncHandle), inlineCandidateInfo->methInfo.ILCodeSize, inlineDepth, inlineResult->ReasonString()); } if (verbose) { printf("--------------------------------------------------------------------------------------------\n"); } #endif // DEBUG #if defined(DEBUG) impInlinedCodeSize += inlineCandidateInfo->methInfo.ILCodeSize; #endif // We inlined... inlineResult->NoteSuccess(); } //------------------------------------------------------------------------ // fgInsertInlineeBlocks: incorporate statements for an inline into the // root method. // // Arguments: // inlineInfo -- info for the inline // // Notes: // The inlining attempt cannot be failed once this method is called. // // Adds all inlinee statements, plus any glue statements needed // either before or after the inlined call. // // Updates flow graph and assigns weights to inlinee // blocks. Currently does not attempt to read IBC data for the // inlinee. // // Updates relevant root method status flags (eg optMethodFlags) to // include information from the inlinee. // // Marks newly added statements with an appropriate inline context. void Compiler::fgInsertInlineeBlocks(InlineInfo* pInlineInfo) { GenTreeCall* iciCall = pInlineInfo->iciCall; GenTreeStmt* iciStmt = pInlineInfo->iciStmt; BasicBlock* iciBlock = pInlineInfo->iciBlock; BasicBlock* block; noway_assert(iciBlock->bbTreeList != nullptr); noway_assert(iciStmt->gtStmtExpr != nullptr); assert(iciBlock->Contains(iciStmt) && (iciStmt->gtStmtExpr == iciCall)); noway_assert(iciCall->gtOper == GT_CALL); #ifdef DEBUG GenTreeStmt* currentDumpStmt = nullptr; if (verbose) { printf("\n\n----------- Statements (and blocks) added due to the inlining of call "); printTreeID(iciCall); printf(" -----------\n"); } #endif // DEBUG // Create a new inline context and mark the inlined statements with it InlineContext* calleeContext = m_inlineStrategy->NewSuccess(pInlineInfo); for (block = InlineeCompiler->fgFirstBB; block != nullptr; block = block->bbNext) { for (GenTreeStmt* stmt = block->firstStmt(); stmt; stmt = stmt->gtNextStmt) { stmt->gtInlineContext = calleeContext; } } // Prepend statements GenTreeStmt* stmtAfter = fgInlinePrependStatements(pInlineInfo); #ifdef DEBUG if (verbose) { currentDumpStmt = stmtAfter; printf("\nInlinee method body:"); } #endif // DEBUG BasicBlock* topBlock = iciBlock; BasicBlock* bottomBlock = nullptr; if (InlineeCompiler->fgBBcount == 1) { // When fgBBCount is 1 we will always have a non-NULL fgFirstBB // PREFAST_ASSUME(InlineeCompiler->fgFirstBB != nullptr); // DDB 91389: Don't throw away the (only) inlinee block // when its return type is not BBJ_RETURN. // In other words, we need its BBJ_ to perform the right thing. if (InlineeCompiler->fgFirstBB->bbJumpKind == BBJ_RETURN) { // Inlinee contains just one BB. So just insert its statement list to topBlock. if (InlineeCompiler->fgFirstBB->bbTreeList) { stmtAfter = fgInsertStmtListAfter(iciBlock, stmtAfter, InlineeCompiler->fgFirstBB->firstStmt()); // Copy inlinee bbFlags to caller bbFlags. const unsigned __int64 inlineeBlockFlags = InlineeCompiler->fgFirstBB->bbFlags; noway_assert((inlineeBlockFlags & BBF_HAS_JMP) == 0); noway_assert((inlineeBlockFlags & BBF_KEEP_BBJ_ALWAYS) == 0); iciBlock->bbFlags |= inlineeBlockFlags; } #ifdef DEBUG if (verbose) { noway_assert(currentDumpStmt); if (currentDumpStmt != stmtAfter) { do { currentDumpStmt = currentDumpStmt->getNextStmt(); printf("\n"); gtDispTree(currentDumpStmt); printf("\n"); } while (currentDumpStmt != stmtAfter); } } #endif // DEBUG // Append statements to null out gc ref locals, if necessary. fgInlineAppendStatements(pInlineInfo, iciBlock, stmtAfter); goto _Done; } } // // ======= Inserting inlinee's basic blocks =============== // bottomBlock = fgNewBBafter(topBlock->bbJumpKind, topBlock, true); bottomBlock->bbRefs = 1; bottomBlock->bbJumpDest = topBlock->bbJumpDest; bottomBlock->inheritWeight(topBlock); topBlock->bbJumpKind = BBJ_NONE; // Update block flags { const unsigned __int64 originalFlags = topBlock->bbFlags; noway_assert((originalFlags & BBF_SPLIT_NONEXIST) == 0); topBlock->bbFlags &= ~(BBF_SPLIT_LOST); bottomBlock->bbFlags |= originalFlags & BBF_SPLIT_GAINED; } // // Split statements between topBlock and bottomBlock // GenTree* topBlock_Begin; GenTree* topBlock_End; GenTree* bottomBlock_Begin; GenTree* bottomBlock_End; topBlock_Begin = nullptr; topBlock_End = nullptr; bottomBlock_Begin = nullptr; bottomBlock_End = nullptr; // // First figure out bottomBlock_Begin // bottomBlock_Begin = stmtAfter->gtNext; if (topBlock->bbTreeList == nullptr) { // topBlock is empty before the split. // In this case, both topBlock and bottomBlock should be empty noway_assert(bottomBlock_Begin == nullptr); topBlock->bbTreeList = nullptr; bottomBlock->bbTreeList = nullptr; } else if (topBlock->bbTreeList == bottomBlock_Begin) { noway_assert(bottomBlock_Begin); // topBlock contains at least one statement before the split. // And the split is before the first statement. // In this case, topBlock should be empty, and everything else should be moved to the bottonBlock. bottomBlock->bbTreeList = topBlock->bbTreeList; topBlock->bbTreeList = nullptr; } else if (bottomBlock_Begin == nullptr) { noway_assert(topBlock->bbTreeList); // topBlock contains at least one statement before the split. // And the split is at the end of the topBlock. // In this case, everything should be kept in the topBlock, and the bottomBlock should be empty bottomBlock->bbTreeList = nullptr; } else { noway_assert(topBlock->bbTreeList); noway_assert(bottomBlock_Begin); // This is the normal case where both blocks should contain at least one statement. topBlock_Begin = topBlock->bbTreeList; noway_assert(topBlock_Begin); topBlock_End = bottomBlock_Begin->gtPrev; noway_assert(topBlock_End); bottomBlock_End = topBlock->lastStmt(); noway_assert(bottomBlock_End); // Break the linkage between 2 blocks. topBlock_End->gtNext = nullptr; // Fix up all the pointers. topBlock->bbTreeList = topBlock_Begin; topBlock->bbTreeList->gtPrev = topBlock_End; bottomBlock->bbTreeList = bottomBlock_Begin; bottomBlock->bbTreeList->gtPrev = bottomBlock_End; } // // Set the try and handler index and fix the jump types of inlinee's blocks. // bool inheritWeight; inheritWeight = true; // The firstBB does inherit the weight from the iciBlock for (block = InlineeCompiler->fgFirstBB; block != nullptr; block = block->bbNext) { noway_assert(!block->hasTryIndex()); noway_assert(!block->hasHndIndex()); block->copyEHRegion(iciBlock); block->bbFlags |= iciBlock->bbFlags & BBF_BACKWARD_JUMP; if (iciStmt->gtStmtILoffsx != BAD_IL_OFFSET) { block->bbCodeOffs = jitGetILoffs(iciStmt->gtStmtILoffsx); block->bbCodeOffsEnd = block->bbCodeOffs + 1; // TODO: is code size of 1 some magic number for inlining? } else { block->bbCodeOffs = 0; // TODO: why not BAD_IL_OFFSET? block->bbCodeOffsEnd = 0; block->bbFlags |= BBF_INTERNAL; } if (block->bbJumpKind == BBJ_RETURN) { inheritWeight = true; // A return block does inherit the weight from the iciBlock noway_assert((block->bbFlags & BBF_HAS_JMP) == 0); if (block->bbNext) { block->bbJumpKind = BBJ_ALWAYS; block->bbJumpDest = bottomBlock; #ifdef DEBUG if (verbose) { printf("\nConvert bbJumpKind of " FMT_BB " to BBJ_ALWAYS to bottomBlock " FMT_BB "\n", block->bbNum, bottomBlock->bbNum); } #endif // DEBUG } else { #ifdef DEBUG if (verbose) { printf("\nConvert bbJumpKind of " FMT_BB " to BBJ_NONE\n", block->bbNum); } #endif // DEBUG block->bbJumpKind = BBJ_NONE; } } if (inheritWeight) { block->inheritWeight(iciBlock); inheritWeight = false; } else { block->modifyBBWeight(iciBlock->bbWeight / 2); } } // Insert inlinee's blocks into inliner's block list. topBlock->setNext(InlineeCompiler->fgFirstBB); InlineeCompiler->fgLastBB->setNext(bottomBlock); // // Add inlinee's block count to inliner's. // fgBBcount += InlineeCompiler->fgBBcount; // Append statements to null out gc ref locals, if necessary. fgInlineAppendStatements(pInlineInfo, bottomBlock, nullptr); #ifdef DEBUG if (verbose) { fgDispBasicBlocks(InlineeCompiler->fgFirstBB, InlineeCompiler->fgLastBB, true); } #endif // DEBUG _Done: // // At this point, we have successully inserted inlinee's code. // // // Copy out some flags // compLongUsed |= InlineeCompiler->compLongUsed; compFloatingPointUsed |= InlineeCompiler->compFloatingPointUsed; compLocallocUsed |= InlineeCompiler->compLocallocUsed; compLocallocOptimized |= InlineeCompiler->compLocallocOptimized; compQmarkUsed |= InlineeCompiler->compQmarkUsed; compUnsafeCastUsed |= InlineeCompiler->compUnsafeCastUsed; compNeedsGSSecurityCookie |= InlineeCompiler->compNeedsGSSecurityCookie; compGSReorderStackLayout |= InlineeCompiler->compGSReorderStackLayout; #ifdef FEATURE_SIMD if (InlineeCompiler->usesSIMDTypes()) { setUsesSIMDTypes(true); } #endif // FEATURE_SIMD // Update unmanaged call count info.compCallUnmanaged += InlineeCompiler->info.compCallUnmanaged; // Update optMethodFlags #ifdef DEBUG unsigned optMethodFlagsBefore = optMethodFlags; #endif optMethodFlags |= InlineeCompiler->optMethodFlags; #ifdef DEBUG if (optMethodFlags != optMethodFlagsBefore) { JITDUMP("INLINER: Updating optMethodFlags -- root:%0x callee:%0x new:%0x\n", optMethodFlagsBefore, InlineeCompiler->optMethodFlags, optMethodFlags); } #endif // If there is non-NULL return, replace the GT_CALL with its return value expression, // so later it will be picked up by the GT_RET_EXPR node. if ((pInlineInfo->inlineCandidateInfo->fncRetType != TYP_VOID) || (iciCall->gtReturnType == TYP_STRUCT)) { noway_assert(pInlineInfo->retExpr); #ifdef DEBUG if (verbose) { printf("\nReturn expression for call at "); printTreeID(iciCall); printf(" is\n"); gtDispTree(pInlineInfo->retExpr); } #endif // DEBUG // Replace the call with the return expression iciCall->ReplaceWith(pInlineInfo->retExpr, this); } // // Detach the GT_CALL node from the original statement by hanging a "nothing" node under it, // so that fgMorphStmts can remove the statement once we return from here. // iciStmt->gtStmtExpr = gtNewNothingNode(); } //------------------------------------------------------------------------ // fgInlinePrependStatements: prepend statements needed to match up // caller and inlined callee // // Arguments: // inlineInfo -- info for the inline // // Return Value: // The last statement that was added, or the original call if no // statements were added. // // Notes: // Statements prepended may include the following: // * This pointer null check // * Class initialization // * Zeroing of must-init locals in the callee // * Passing of call arguments via temps // // Newly added statements are placed just after the original call // and are are given the same inline context as the call any calls // added here will appear to have been part of the immediate caller. GenTreeStmt* Compiler::fgInlinePrependStatements(InlineInfo* inlineInfo) { BasicBlock* block = inlineInfo->iciBlock; GenTreeStmt* callStmt = inlineInfo->iciStmt; IL_OFFSETX callILOffset = callStmt->gtStmtILoffsx; GenTreeStmt* postStmt = callStmt->gtNextStmt; GenTreeStmt* afterStmt = callStmt; // afterStmt is the place where the new statements should be inserted after. GenTreeStmt* newStmt = nullptr; GenTreeCall* call = inlineInfo->iciCall->AsCall(); noway_assert(call->gtOper == GT_CALL); #ifdef DEBUG if (0 && verbose) { printf("\nfgInlinePrependStatements for iciCall= "); printTreeID(call); printf(":\n"); } #endif // Prepend statements for any initialization / side effects InlArgInfo* inlArgInfo = inlineInfo->inlArgInfo; InlLclVarInfo* lclVarInfo = inlineInfo->lclVarInfo; GenTree* tree; // Create the null check statement (but not appending it to the statement list yet) for the 'this' pointer if // necessary. // The NULL check should be done after "argument setup statements". // The only reason we move it here is for calling "impInlineFetchArg(0,..." to reserve a temp // for the "this" pointer. // Note: Here we no longer do the optimization that was done by thisDereferencedFirst in the old inliner. // However the assetionProp logic will remove any unecessary null checks that we may have added // GenTree* nullcheck = nullptr; if (call->gtFlags & GTF_CALL_NULLCHECK && !inlineInfo->thisDereferencedFirst) { // Call impInlineFetchArg to "reserve" a temp for the "this" pointer. nullcheck = gtNewOperNode(GT_IND, TYP_INT, impInlineFetchArg(0, inlArgInfo, lclVarInfo)); nullcheck->gtFlags |= GTF_EXCEPT; // The NULL-check statement will be inserted to the statement list after those statements // that assign arguments to temps and before the actual body of the inlinee method. } /* Treat arguments that had to be assigned to temps */ if (inlineInfo->argCnt) { #ifdef DEBUG if (verbose) { printf("\nArguments setup:\n"); } #endif // DEBUG for (unsigned argNum = 0; argNum < inlineInfo->argCnt; argNum++) { const InlArgInfo& argInfo = inlArgInfo[argNum]; const bool argIsSingleDef = !argInfo.argHasLdargaOp && !argInfo.argHasStargOp; GenTree* const argNode = inlArgInfo[argNum].argNode; if (argInfo.argHasTmp) { noway_assert(argInfo.argIsUsed); /* argBashTmpNode is non-NULL iff the argument's value was referenced exactly once by the original IL. This offers an opportunity to avoid an intermediate temp and just insert the original argument tree. However, if the temp node has been cloned somewhere while importing (e.g. when handling isinst or dup), or if the IL took the address of the argument, then argBashTmpNode will be set (because the value was only explicitly retrieved once) but the optimization cannot be applied. */ GenTree* argSingleUseNode = argInfo.argBashTmpNode; if ((argSingleUseNode != nullptr) && !(argSingleUseNode->gtFlags & GTF_VAR_CLONED) && argIsSingleDef) { // Change the temp in-place to the actual argument. // We currently do not support this for struct arguments, so it must not be a GT_OBJ. assert(argNode->gtOper != GT_OBJ); argSingleUseNode->ReplaceWith(argNode, this); continue; } else { // We're going to assign the argument value to the // temp we use for it in the inline body. const unsigned tmpNum = argInfo.argTmpNum; const var_types argType = lclVarInfo[argNum].lclTypeInfo; // Create the temp assignment for this argument CORINFO_CLASS_HANDLE structHnd = NO_CLASS_HANDLE; if (varTypeIsStruct(argType)) { structHnd = gtGetStructHandleIfPresent(argNode); noway_assert((structHnd != NO_CLASS_HANDLE) || (argType != TYP_STRUCT)); } // Unsafe value cls check is not needed for // argTmpNum here since in-linee compiler instance // would have iterated over these and marked them // accordingly. impAssignTempGen(tmpNum, argNode, structHnd, (unsigned)CHECK_SPILL_NONE, &afterStmt, callILOffset, block); // We used to refine the temp type here based on // the actual arg, but we now do this up front, when // creating the temp, over in impInlineFetchArg. CLANG_FORMAT_COMMENT_ANCHOR; #ifdef DEBUG if (verbose) { gtDispTree(afterStmt); } #endif // DEBUG } } else if (argInfo.argIsByRefToStructLocal) { // Do nothing. Arg was directly substituted as we read // the inlinee. } else { /* The argument is either not used or a const or lcl var */ noway_assert(!argInfo.argIsUsed || argInfo.argIsInvariant || argInfo.argIsLclVar); /* Make sure we didnt change argNode's along the way, or else subsequent uses of the arg would have worked with the bashed value */ if (argInfo.argIsInvariant) { assert(argNode->OperIsConst() || argNode->gtOper == GT_ADDR); } noway_assert((argInfo.argIsLclVar == 0) == (argNode->gtOper != GT_LCL_VAR || (argNode->gtFlags & GTF_GLOB_REF))); /* If the argument has side effects, append it */ if (argInfo.argHasSideEff) { noway_assert(argInfo.argIsUsed == false); newStmt = nullptr; bool append = true; if (argNode->gtOper == GT_OBJ || argNode->gtOper == GT_MKREFANY) { // Don't put GT_OBJ node under a GT_COMMA. // Codegen can't deal with it. // Just hang the address here in case there are side-effect. newStmt = gtNewStmt(gtUnusedValNode(argNode->gtOp.gtOp1), callILOffset); } else { // In some special cases, unused args with side effects can // trigger further changes. // // (1) If the arg is a static field access and the field access // was produced by a call to EqualityComparer<T>.get_Default, the // helper call to ensure the field has a value can be suppressed. // This helper call is marked as a "Special DCE" helper during // importation, over in fgGetStaticsCCtorHelper. // // (2) NYI. If, after tunneling through GT_RET_VALs, we find that // the actual arg expression has no side effects, we can skip // appending all together. This will help jit TP a bit. // // Chase through any GT_RET_EXPRs to find the actual argument // expression. GenTree* actualArgNode = argNode->gtRetExprVal(); // For case (1) // // Look for the following tree shapes // prejit: (IND (ADD (CONST, CALL(special dce helper...)))) // jit : (COMMA (CALL(special dce helper...), (FIELD ...))) if (actualArgNode->gtOper == GT_COMMA) { // Look for (COMMA (CALL(special dce helper...), (FIELD ...))) GenTree* op1 = actualArgNode->gtOp.gtOp1; GenTree* op2 = actualArgNode->gtOp.gtOp2; if (op1->IsCall() && ((op1->gtCall.gtCallMoreFlags & GTF_CALL_M_HELPER_SPECIAL_DCE) != 0) && (op2->gtOper == GT_FIELD) && ((op2->gtFlags & GTF_EXCEPT) == 0)) { JITDUMP("\nPerforming special dce on unused arg [%06u]:" " actual arg [%06u] helper call [%06u]\n", argNode->gtTreeID, actualArgNode->gtTreeID, op1->gtTreeID); // Drop the whole tree append = false; } } else if (actualArgNode->gtOper == GT_IND) { // Look for (IND (ADD (CONST, CALL(special dce helper...)))) GenTree* addr = actualArgNode->gtOp.gtOp1; if (addr->gtOper == GT_ADD) { GenTree* op1 = addr->gtOp.gtOp1; GenTree* op2 = addr->gtOp.gtOp2; if (op1->IsCall() && ((op1->gtCall.gtCallMoreFlags & GTF_CALL_M_HELPER_SPECIAL_DCE) != 0) && op2->IsCnsIntOrI()) { // Drop the whole tree JITDUMP("\nPerforming special dce on unused arg [%06u]:" " actual arg [%06u] helper call [%06u]\n", argNode->gtTreeID, actualArgNode->gtTreeID, op1->gtTreeID); append = false; } } } } if (!append) { assert(newStmt == nullptr); JITDUMP("Arg tree side effects were discardable, not appending anything for arg\n"); } else { // If we don't have something custom to append, // just append the arg node as an unused value. if (newStmt == nullptr) { newStmt = gtNewStmt(gtUnusedValNode(argNode), callILOffset); } afterStmt = fgInsertStmtAfter(block, afterStmt, newStmt); #ifdef DEBUG if (verbose) { gtDispTree(afterStmt); } #endif // DEBUG } } else if (argNode->IsBoxedValue()) { // Try to clean up any unnecessary boxing side effects // since the box itself will be ignored. gtTryRemoveBoxUpstreamEffects(argNode); } } } } // Add the CCTOR check if asked for. // Note: We no longer do the optimization that is done before by staticAccessedFirstUsingHelper in the old inliner. // Therefore we might prepend redundant call to HELPER.CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE // before the inlined method body, even if a static field of this type was accessed in the inlinee // using a helper before any other observable side-effect. if (inlineInfo->inlineCandidateInfo->initClassResult & CORINFO_INITCLASS_USE_HELPER) { CORINFO_CONTEXT_HANDLE exactContext = inlineInfo->inlineCandidateInfo->exactContextHnd; CORINFO_CLASS_HANDLE exactClass; if (((SIZE_T)exactContext & CORINFO_CONTEXTFLAGS_MASK) == CORINFO_CONTEXTFLAGS_CLASS) { exactClass = CORINFO_CLASS_HANDLE((SIZE_T)exactContext & ~CORINFO_CONTEXTFLAGS_MASK); } else { exactClass = info.compCompHnd->getMethodClass( CORINFO_METHOD_HANDLE((SIZE_T)exactContext & ~CORINFO_CONTEXTFLAGS_MASK)); } tree = fgGetSharedCCtor(exactClass); newStmt = gtNewStmt(tree, callILOffset); afterStmt = fgInsertStmtAfter(block, afterStmt, newStmt); } // Insert the nullcheck statement now. if (nullcheck) { newStmt = gtNewStmt(nullcheck, callILOffset); afterStmt = fgInsertStmtAfter(block, afterStmt, newStmt); } // // Now zero-init inlinee locals // CORINFO_METHOD_INFO* InlineeMethodInfo = InlineeCompiler->info.compMethodInfo; unsigned lclCnt = InlineeMethodInfo->locals.numArgs; // Does callee contain any zero-init local? if ((lclCnt != 0) && (InlineeMethodInfo->options & CORINFO_OPT_INIT_LOCALS) != 0) { #ifdef DEBUG if (verbose) { printf("\nZero init inlinee locals:\n"); } #endif // DEBUG for (unsigned lclNum = 0; lclNum < lclCnt; lclNum++) { unsigned tmpNum = inlineInfo->lclTmpNum[lclNum]; // Is the local used at all? if (tmpNum != BAD_VAR_NUM) { var_types lclTyp = (var_types)lvaTable[tmpNum].lvType; noway_assert(lclTyp == lclVarInfo[lclNum + inlineInfo->argCnt].lclTypeInfo); if (!varTypeIsStruct(lclTyp)) { // Unsafe value cls check is not needed here since in-linee compiler instance would have // iterated over locals and marked accordingly. impAssignTempGen(tmpNum, gtNewZeroConNode(genActualType(lclTyp)), NO_CLASS_HANDLE, (unsigned)CHECK_SPILL_NONE, &afterStmt, callILOffset, block); } else { CORINFO_CLASS_HANDLE structType = lclVarInfo[lclNum + inlineInfo->argCnt].lclVerTypeInfo.GetClassHandle(); if (fgStructTempNeedsExplicitZeroInit(lvaTable + tmpNum, block)) { tree = gtNewBlkOpNode(gtNewLclvNode(tmpNum, lclTyp), // Dest gtNewIconNode(0), // Value info.compCompHnd->getClassSize(structType), // Size false, // isVolatile false); // not copyBlock newStmt = gtNewStmt(tree, callILOffset); afterStmt = fgInsertStmtAfter(block, afterStmt, newStmt); } } #ifdef DEBUG if (verbose) { gtDispTree(afterStmt); } #endif // DEBUG } } } // Update any newly added statements with the appropriate context. InlineContext* context = callStmt->gtInlineContext; assert(context != nullptr); for (GenTreeStmt* addedStmt = callStmt->gtNextStmt; addedStmt != postStmt; addedStmt = addedStmt->gtNextStmt) { assert(addedStmt->gtInlineContext == nullptr); addedStmt->gtInlineContext = context; } return afterStmt; } //------------------------------------------------------------------------ // fgInlineAppendStatements: Append statements that are needed // after the inlined call. // // Arguments: // inlineInfo - information about the inline // block - basic block for the new statements // stmtAfter - (optional) insertion point for mid-block cases // // Notes: // If the call we're inlining is in tail position then // we skip nulling the locals, since it can interfere // with tail calls introduced by the local. void Compiler::fgInlineAppendStatements(InlineInfo* inlineInfo, BasicBlock* block, GenTreeStmt* stmtAfter) { // If this inlinee was passed a runtime lookup generic context and // ignores it, we can decrement the "generic context was used" ref // count, because we created a new lookup tree and incremented the // count when we imported the type parameter argument to pass to // the inlinee. See corresponding logic in impImportCall that // checks the sig for CORINFO_CALLCONV_PARAMTYPE. // // Does this method require a context (type) parameter? if ((inlineInfo->inlineCandidateInfo->methInfo.args.callConv & CORINFO_CALLCONV_PARAMTYPE) != 0) { // Did the computation of that parameter require the // caller to perform a runtime lookup? if (inlineInfo->inlineCandidateInfo->exactContextNeedsRuntimeLookup) { // Fetch the temp for the generic context as it would // appear in the inlinee's body. const unsigned typeCtxtArg = inlineInfo->typeContextArg; const unsigned tmpNum = inlineInfo->lclTmpNum[typeCtxtArg]; // Was it used in the inline body? if (tmpNum == BAD_VAR_NUM) { // No -- so the associated runtime lookup is not needed // and also no longer provides evidence that the generic // context should be kept alive. JITDUMP("Inlinee ignores runtime lookup generics context\n"); assert(lvaGenericsContextUseCount > 0); lvaGenericsContextUseCount--; } } } // Null out any gc ref locals if (!inlineInfo->HasGcRefLocals()) { // No ref locals, nothing to do. JITDUMP("fgInlineAppendStatements: no gc ref inline locals.\n"); return; } if (inlineInfo->iciCall->IsImplicitTailCall()) { JITDUMP("fgInlineAppendStatements: implicit tail call; skipping nulling.\n"); return; } JITDUMP("fgInlineAppendStatements: nulling out gc ref inlinee locals.\n"); GenTreeStmt* callStmt = inlineInfo->iciStmt; IL_OFFSETX callILOffset = callStmt->gtStmtILoffsx; CORINFO_METHOD_INFO* InlineeMethodInfo = InlineeCompiler->info.compMethodInfo; const unsigned lclCnt = InlineeMethodInfo->locals.numArgs; InlLclVarInfo* lclVarInfo = inlineInfo->lclVarInfo; unsigned gcRefLclCnt = inlineInfo->numberOfGcRefLocals; const unsigned argCnt = inlineInfo->argCnt; noway_assert(callStmt->gtOper == GT_STMT); for (unsigned lclNum = 0; lclNum < lclCnt; lclNum++) { // Is the local a gc ref type? Need to look at the // inline info for this since we will not have local // temps for unused inlinee locals. const var_types lclTyp = lclVarInfo[argCnt + lclNum].lclTypeInfo; if (!varTypeIsGC(lclTyp)) { // Nope, nothing to null out. continue; } // Ensure we're examining just the right number of locals. assert(gcRefLclCnt > 0); gcRefLclCnt--; // Fetch the temp for this inline local const unsigned tmpNum = inlineInfo->lclTmpNum[lclNum]; // Is the local used at all? if (tmpNum == BAD_VAR_NUM) { // Nope, nothing to null out. continue; } // Local was used, make sure the type is consistent. assert(lvaTable[tmpNum].lvType == lclTyp); // Does the local we're about to null out appear in the return // expression? If so we somehow messed up and didn't properly // spill the return value. See impInlineFetchLocal. GenTree* retExpr = inlineInfo->retExpr; if (retExpr != nullptr) { const bool interferesWithReturn = gtHasRef(inlineInfo->retExpr, tmpNum, false); noway_assert(!interferesWithReturn); } // Assign null to the local. GenTree* nullExpr = gtNewTempAssign(tmpNum, gtNewZeroConNode(lclTyp)); GenTreeStmt* nullStmt = gtNewStmt(nullExpr, callILOffset); if (stmtAfter == nullptr) { stmtAfter = fgInsertStmtAtBeg(block, nullStmt); } else { stmtAfter = fgInsertStmtAfter(block, stmtAfter, nullStmt); } #ifdef DEBUG if (verbose) { gtDispTree(nullStmt); } #endif // DEBUG } // There should not be any GC ref locals left to null out. assert(gcRefLclCnt == 0); } /*****************************************************************************/ /*static*/ Compiler::fgWalkResult Compiler::fgChkThrowCB(GenTree** pTree, fgWalkData* data) { GenTree* tree = *pTree; // If this tree doesn't have the EXCEPT flag set, then there is no // way any of the child nodes could throw, so we can stop recursing. if (!(tree->gtFlags & GTF_EXCEPT)) { return Compiler::WALK_SKIP_SUBTREES; } switch (tree->gtOper) { case GT_MUL: case GT_ADD: case GT_SUB: case GT_CAST: if (tree->gtOverflow()) { return Compiler::WALK_ABORT; } break; case GT_INDEX: case GT_INDEX_ADDR: // These two call CORINFO_HELP_RNGCHKFAIL for Debug code if (tree->gtFlags & GTF_INX_RNGCHK) { return Compiler::WALK_ABORT; } break; case GT_ARR_BOUNDS_CHECK: return Compiler::WALK_ABORT; default: break; } return Compiler::WALK_CONTINUE; } /*****************************************************************************/ /*static*/ Compiler::fgWalkResult Compiler::fgChkLocAllocCB(GenTree** pTree, fgWalkData* data) { GenTree* tree = *pTree; if (tree->gtOper == GT_LCLHEAP) { return Compiler::WALK_ABORT; } return Compiler::WALK_CONTINUE; } /*****************************************************************************/ /*static*/ Compiler::fgWalkResult Compiler::fgChkQmarkCB(GenTree** pTree, fgWalkData* data) { GenTree* tree = *pTree; if (tree->gtOper == GT_QMARK) { return Compiler::WALK_ABORT; } return Compiler::WALK_CONTINUE; } void Compiler::fgLclFldAssign(unsigned lclNum) { assert(varTypeIsStruct(lvaTable[lclNum].lvType)); if (lvaTable[lclNum].lvPromoted && lvaTable[lclNum].lvFieldCnt > 1) { lvaSetVarDoNotEnregister(lclNum DEBUGARG(DNER_LocalField)); } } //------------------------------------------------------------------------ // fgRemoveEmptyFinally: Remove try/finallys where the finally is empty // // Notes: // Removes all try/finallys in the method with empty finallys. // These typically arise from inlining empty Dispose methods. // // Converts callfinally to a jump to the finally continuation. // Removes the finally, and reparents all blocks in the try to the // enclosing try or method region. // // Currently limited to trivially empty finallys: those with one basic // block containing only single RETFILT statement. It is possible but // not likely that more complex-looking finallys will eventually become // empty (from say subsequent optimization). An SPMI run with // just the "detection" part of this phase run after optimization // found only one example where a new empty finally was detected. void Compiler::fgRemoveEmptyFinally() { JITDUMP("\n*************** In fgRemoveEmptyFinally()\n"); #if FEATURE_EH_FUNCLETS // We need to do this transformation before funclets are created. assert(!fgFuncletsCreated); #endif // FEATURE_EH_FUNCLETS // Assume we don't need to update the bbPreds lists. assert(!fgComputePredsDone); if (compHndBBtabCount == 0) { JITDUMP("No EH in this method, nothing to remove.\n"); return; } if (opts.MinOpts()) { JITDUMP("Method compiled with minOpts, no removal.\n"); return; } if (opts.compDbgCode) { JITDUMP("Method compiled with debug codegen, no removal.\n"); return; } #ifdef DEBUG if (verbose) { printf("\n*************** Before fgRemoveEmptyFinally()\n"); fgDispBasicBlocks(); fgDispHandlerTab(); printf("\n"); } #endif // DEBUG // Look for finallys or faults that are empty. unsigned finallyCount = 0; unsigned emptyCount = 0; unsigned XTnum = 0; while (XTnum < compHndBBtabCount) { EHblkDsc* const HBtab = &compHndBBtab[XTnum]; // Check if this is a try/finally. We could also look for empty // try/fault but presumably those are rare. if (!HBtab->HasFinallyHandler()) { JITDUMP("EH#%u is not a try-finally; skipping.\n", XTnum); XTnum++; continue; } finallyCount++; // Look at blocks involved. BasicBlock* const firstBlock = HBtab->ebdHndBeg; BasicBlock* const lastBlock = HBtab->ebdHndLast; // Limit for now to finallys that are single blocks. if (firstBlock != lastBlock) { JITDUMP("EH#%u finally has multiple basic blocks; skipping.\n", XTnum); XTnum++; continue; } // Limit for now to finallys that contain only a GT_RETFILT. bool isEmpty = true; for (GenTreeStmt* stmt = firstBlock->firstStmt(); stmt != nullptr; stmt = stmt->gtNextStmt) { GenTree* stmtExpr = stmt->gtStmtExpr; if (stmtExpr->gtOper != GT_RETFILT) { isEmpty = false; break; } } if (!isEmpty) { JITDUMP("EH#%u finally is not empty; skipping.\n", XTnum); XTnum++; continue; } JITDUMP("EH#%u has empty finally, removing the region.\n", XTnum); // Find all the call finallys that invoke this finally, // and modify them to jump to the return point. BasicBlock* firstCallFinallyRangeBlock = nullptr; BasicBlock* endCallFinallyRangeBlock = nullptr; ehGetCallFinallyBlockRange(XTnum, &firstCallFinallyRangeBlock, &endCallFinallyRangeBlock); BasicBlock* currentBlock = firstCallFinallyRangeBlock; while (currentBlock != endCallFinallyRangeBlock) { BasicBlock* nextBlock = currentBlock->bbNext; if ((currentBlock->bbJumpKind == BBJ_CALLFINALLY) && (currentBlock->bbJumpDest == firstBlock)) { // Retarget the call finally to jump to the return // point. // // We don't expect to see retless finallys here, since // the finally is empty. noway_assert(currentBlock->isBBCallAlwaysPair()); BasicBlock* const leaveBlock = currentBlock->bbNext; BasicBlock* const postTryFinallyBlock = leaveBlock->bbJumpDest; JITDUMP("Modifying callfinally " FMT_BB " leave " FMT_BB " finally " FMT_BB " continuation " FMT_BB "\n", currentBlock->bbNum, leaveBlock->bbNum, firstBlock->bbNum, postTryFinallyBlock->bbNum); JITDUMP("so that " FMT_BB " jumps to " FMT_BB "; then remove " FMT_BB "\n", currentBlock->bbNum, postTryFinallyBlock->bbNum, leaveBlock->bbNum); noway_assert(leaveBlock->bbJumpKind == BBJ_ALWAYS); currentBlock->bbJumpDest = postTryFinallyBlock; currentBlock->bbJumpKind = BBJ_ALWAYS; // Ref count updates. fgAddRefPred(postTryFinallyBlock, currentBlock); // fgRemoveRefPred(firstBlock, currentBlock); // Delete the leave block, which should be marked as // keep always. assert((leaveBlock->bbFlags & BBF_KEEP_BBJ_ALWAYS) != 0); nextBlock = leaveBlock->bbNext; leaveBlock->bbFlags &= ~BBF_KEEP_BBJ_ALWAYS; fgRemoveBlock(leaveBlock, true); // Cleanup the postTryFinallyBlock fgCleanupContinuation(postTryFinallyBlock); // Make sure iteration isn't going off the deep end. assert(leaveBlock != endCallFinallyRangeBlock); } currentBlock = nextBlock; } JITDUMP("Remove now-unreachable handler " FMT_BB "\n", firstBlock->bbNum); // Handler block should now be unreferenced, since the only // explicit references to it were in call finallys. firstBlock->bbRefs = 0; // Remove the handler block. const bool unreachable = true; firstBlock->bbFlags &= ~BBF_DONT_REMOVE; fgRemoveBlock(firstBlock, unreachable); // Find enclosing try region for the try, if any, and update // the try region. Note the handler region (if any) won't // change. BasicBlock* const firstTryBlock = HBtab->ebdTryBeg; BasicBlock* const lastTryBlock = HBtab->ebdTryLast; assert(firstTryBlock->getTryIndex() == XTnum); for (BasicBlock* block = firstTryBlock; block != nullptr; block = block->bbNext) { // Look for blocks directly contained in this try, and // update the try region appropriately. // // Try region for blocks transitively contained (say in a // child try) will get updated by the subsequent call to // fgRemoveEHTableEntry. if (block->getTryIndex() == XTnum) { if (firstBlock->hasTryIndex()) { block->setTryIndex(firstBlock->getTryIndex()); } else { block->clearTryIndex(); } } if (block == firstTryBlock) { assert((block->bbFlags & BBF_TRY_BEG) != 0); block->bbFlags &= ~BBF_TRY_BEG; } if (block == lastTryBlock) { break; } } // Remove the try-finally EH region. This will compact the EH table // so XTnum now points at the next entry. fgRemoveEHTableEntry(XTnum); emptyCount++; } if (emptyCount > 0) { JITDUMP("fgRemoveEmptyFinally() removed %u try-finally clauses from %u finallys\n", emptyCount, finallyCount); fgOptimizedFinally = true; #ifdef DEBUG if (verbose) { printf("\n*************** After fgRemoveEmptyFinally()\n"); fgDispBasicBlocks(); fgDispHandlerTab(); printf("\n"); } fgVerifyHandlerTab(); fgDebugCheckBBlist(false, false); #endif // DEBUG } } //------------------------------------------------------------------------ // fgRemoveEmptyTry: Optimize try/finallys where the try is empty // // Notes: // In runtimes where thread abort is not possible, `try {} finally {S}` // can be optimized to simply `S`. This method looks for such // cases and removes the try-finally from the EH table, making // suitable flow, block flag, statement, and region updates. // // This optimization is not legal in runtimes that support thread // abort because those runtimes ensure that a finally is completely // executed before continuing to process the thread abort. With // this optimization, the code block `S` can lose special // within-finally status and so complete execution is no longer // guaranteed. void Compiler::fgRemoveEmptyTry() { JITDUMP("\n*************** In fgRemoveEmptyTry()\n"); #if FEATURE_EH_FUNCLETS // We need to do this transformation before funclets are created. assert(!fgFuncletsCreated); #endif // FEATURE_EH_FUNCLETS // Assume we don't need to update the bbPreds lists. assert(!fgComputePredsDone); #ifdef FEATURE_CORECLR bool enableRemoveEmptyTry = true; #else // Code in a finally gets special treatment in the presence of // thread abort. bool enableRemoveEmptyTry = false; #endif // FEATURE_CORECLR #ifdef DEBUG // Allow override to enable/disable. enableRemoveEmptyTry = (JitConfig.JitEnableRemoveEmptyTry() == 1); #endif // DEBUG if (!enableRemoveEmptyTry) { JITDUMP("Empty try removal disabled.\n"); return; } if (compHndBBtabCount == 0) { JITDUMP("No EH in this method, nothing to remove.\n"); return; } if (opts.MinOpts()) { JITDUMP("Method compiled with minOpts, no removal.\n"); return; } if (opts.compDbgCode) { JITDUMP("Method compiled with debug codegen, no removal.\n"); return; } #ifdef DEBUG if (verbose) { printf("\n*************** Before fgRemoveEmptyTry()\n"); fgDispBasicBlocks(); fgDispHandlerTab(); printf("\n"); } #endif // DEBUG // Look for try-finallys where the try is empty. unsigned emptyCount = 0; unsigned XTnum = 0; while (XTnum < compHndBBtabCount) { EHblkDsc* const HBtab = &compHndBBtab[XTnum]; // Check if this is a try/finally. We could also look for empty // try/fault but presumably those are rare. if (!HBtab->HasFinallyHandler()) { JITDUMP("EH#%u is not a try-finally; skipping.\n", XTnum); XTnum++; continue; } // Examine the try region BasicBlock* const firstTryBlock = HBtab->ebdTryBeg; BasicBlock* const lastTryBlock = HBtab->ebdTryLast; BasicBlock* const firstHandlerBlock = HBtab->ebdHndBeg; BasicBlock* const lastHandlerBlock = HBtab->ebdHndLast; BasicBlock* const endHandlerBlock = lastHandlerBlock->bbNext; assert(firstTryBlock->getTryIndex() == XTnum); // Limit for now to trys that contain only a callfinally pair // or branch to same. if (!firstTryBlock->isEmpty()) { JITDUMP("EH#%u first try block " FMT_BB " not empty; skipping.\n", XTnum, firstTryBlock->bbNum); XTnum++; continue; } #if FEATURE_EH_CALLFINALLY_THUNKS // Look for blocks that are always jumps to a call finally // pair that targets the finally if (firstTryBlock->bbJumpKind != BBJ_ALWAYS) { JITDUMP("EH#%u first try block " FMT_BB " not jump to a callfinally; skipping.\n", XTnum, firstTryBlock->bbNum); XTnum++; continue; } BasicBlock* const callFinally = firstTryBlock->bbJumpDest; // Look for call always pair. Note this will also disqualify // empty try removal in cases where the finally doesn't // return. if (!callFinally->isBBCallAlwaysPair() || (callFinally->bbJumpDest != firstHandlerBlock)) { JITDUMP("EH#%u first try block " FMT_BB " always jumps but not to a callfinally; skipping.\n", XTnum, firstTryBlock->bbNum); XTnum++; continue; } // Try itself must be a single block. if (firstTryBlock != lastTryBlock) { JITDUMP("EH#%u first try block " FMT_BB " not only block in try; skipping.\n", XTnum, firstTryBlock->bbNext->bbNum); XTnum++; continue; } #else // Look for call always pair within the try itself. Note this // will also disqualify empty try removal in cases where the // finally doesn't return. if (!firstTryBlock->isBBCallAlwaysPair() || (firstTryBlock->bbJumpDest != firstHandlerBlock)) { JITDUMP("EH#%u first try block " FMT_BB " not a callfinally; skipping.\n", XTnum, firstTryBlock->bbNum); XTnum++; continue; } BasicBlock* const callFinally = firstTryBlock; // Try must be a callalways pair of blocks. if (firstTryBlock->bbNext != lastTryBlock) { JITDUMP("EH#%u block " FMT_BB " not last block in try; skipping.\n", XTnum, firstTryBlock->bbNext->bbNum); XTnum++; continue; } #endif // FEATURE_EH_CALLFINALLY_THUNKS JITDUMP("EH#%u has empty try, removing the try region and promoting the finally.\n", XTnum); // There should be just one callfinally that invokes this // finally, the one we found above. Verify this. BasicBlock* firstCallFinallyRangeBlock = nullptr; BasicBlock* endCallFinallyRangeBlock = nullptr; bool verifiedSingleCallfinally = true; ehGetCallFinallyBlockRange(XTnum, &firstCallFinallyRangeBlock, &endCallFinallyRangeBlock); for (BasicBlock* block = firstCallFinallyRangeBlock; block != endCallFinallyRangeBlock; block = block->bbNext) { if ((block->bbJumpKind == BBJ_CALLFINALLY) && (block->bbJumpDest == firstHandlerBlock)) { assert(block->isBBCallAlwaysPair()); if (block != callFinally) { JITDUMP("EH#%u found unexpected callfinally " FMT_BB "; skipping.\n"); verifiedSingleCallfinally = false; break; } block = block->bbNext; } } if (!verifiedSingleCallfinally) { JITDUMP("EH#%u -- unexpectedly -- has multiple callfinallys; skipping.\n"); XTnum++; assert(verifiedSingleCallfinally); continue; } // Time to optimize. // // (1) Convert the callfinally to a normal jump to the handler callFinally->bbJumpKind = BBJ_ALWAYS; // Identify the leave block and the continuation BasicBlock* const leave = callFinally->bbNext; BasicBlock* const continuation = leave->bbJumpDest; // (2) Cleanup the leave so it can be deleted by subsequent opts assert((leave->bbFlags & BBF_KEEP_BBJ_ALWAYS) != 0); leave->bbFlags &= ~BBF_KEEP_BBJ_ALWAYS; // (3) Cleanup the continuation fgCleanupContinuation(continuation); // (4) Find enclosing try region for the try, if any, and // update the try region for the blocks in the try. Note the // handler region (if any) won't change. // // Kind of overkill to loop here, but hey. for (BasicBlock* block = firstTryBlock; block != nullptr; block = block->bbNext) { // Look for blocks directly contained in this try, and // update the try region appropriately. // // The try region for blocks transitively contained (say in a // child try) will get updated by the subsequent call to // fgRemoveEHTableEntry. if (block->getTryIndex() == XTnum) { if (firstHandlerBlock->hasTryIndex()) { block->setTryIndex(firstHandlerBlock->getTryIndex()); } else { block->clearTryIndex(); } } if (block == firstTryBlock) { assert((block->bbFlags & BBF_TRY_BEG) != 0); block->bbFlags &= ~BBF_TRY_BEG; } if (block == lastTryBlock) { break; } } // (5) Update the directly contained handler blocks' handler index. // Handler index of any nested blocks will update when we // remove the EH table entry. Change handler exits to jump to // the continuation. Clear catch type on handler entry. // Decrement nesting level of enclosed GT_END_LFINs. for (BasicBlock* block = firstHandlerBlock; block != endHandlerBlock; block = block->bbNext) { if (block == firstHandlerBlock) { block->bbCatchTyp = BBCT_NONE; } if (block->getHndIndex() == XTnum) { if (firstTryBlock->hasHndIndex()) { block->setHndIndex(firstTryBlock->getHndIndex()); } else { block->clearHndIndex(); } if (block->bbJumpKind == BBJ_EHFINALLYRET) { GenTreeStmt* finallyRet = block->lastStmt(); GenTree* finallyRetExpr = finallyRet->gtStmtExpr; assert(finallyRetExpr->gtOper == GT_RETFILT); fgRemoveStmt(block, finallyRet); block->bbJumpKind = BBJ_ALWAYS; block->bbJumpDest = continuation; fgAddRefPred(continuation, block); } } #if !FEATURE_EH_FUNCLETS // If we're in a non-funclet model, decrement the nesting // level of any GT_END_LFIN we find in the handler region, // since we're removing the enclosing handler. for (GenTreeStmt* stmt = block->firstStmt(); stmt != nullptr; stmt = stmt->gtNextStmt) { GenTree* expr = stmt->gtStmtExpr; if (expr->gtOper == GT_END_LFIN) { const unsigned nestLevel = expr->gtVal.gtVal1; assert(nestLevel > 0); expr->gtVal.gtVal1 = nestLevel - 1; } } #endif // !FEATURE_EH_FUNCLETS } // (6) Remove the try-finally EH region. This will compact the // EH table so XTnum now points at the next entry and will update // the EH region indices of any nested EH in the (former) handler. fgRemoveEHTableEntry(XTnum); // Another one bites the dust... emptyCount++; } if (emptyCount > 0) { JITDUMP("fgRemoveEmptyTry() optimized %u empty-try try-finally clauses\n", emptyCount); fgOptimizedFinally = true; #ifdef DEBUG if (verbose) { printf("\n*************** After fgRemoveEmptyTry()\n"); fgDispBasicBlocks(); fgDispHandlerTab(); printf("\n"); } fgVerifyHandlerTab(); fgDebugCheckBBlist(false, false); #endif // DEBUG } } //------------------------------------------------------------------------ // fgCloneFinally: Optimize normal exit path from a try/finally // // Notes: // Handles finallys that are not enclosed by or enclosing other // handler regions. // // Converts the "normal exit" callfinally to a jump to a cloned copy // of the finally, which in turn jumps to the finally continuation. // // If all callfinallys for a given finally are converted to jump to // the clone, the try-finally is modified into a try-fault, // distingushable from organic try-faults by handler type // EH_HANDLER_FAULT_WAS_FINALLY vs the organic EH_HANDLER_FAULT. // // Does not yet handle thread abort. The open issues here are how // to maintain the proper description of the cloned finally blocks // as a handler (for thread abort purposes), how to prevent code // motion in or out of these blocks, and how to report this cloned // handler to the runtime. Some building blocks for thread abort // exist (see below) but more work needed. // // The first and last blocks of the cloned finally are marked with // BBF_CLONED_FINALLY_BEGIN and BBF_CLONED_FINALLY_END. However // these markers currently can get lost during subsequent // optimizations. void Compiler::fgCloneFinally() { JITDUMP("\n*************** In fgCloneFinally()\n"); #if FEATURE_EH_FUNCLETS // We need to do this transformation before funclets are created. assert(!fgFuncletsCreated); #endif // FEATURE_EH_FUNCLETS // Assume we don't need to update the bbPreds lists. assert(!fgComputePredsDone); #ifdef FEATURE_CORECLR bool enableCloning = true; #else // Finally cloning currently doesn't provide sufficient protection // for the cloned code in the presence of thread abort. bool enableCloning = false; #endif // FEATURE_CORECLR #ifdef DEBUG // Allow override to enable/disable. enableCloning = (JitConfig.JitEnableFinallyCloning() == 1); #endif // DEBUG if (!enableCloning) { JITDUMP("Finally cloning disabled.\n"); return; } if (compHndBBtabCount == 0) { JITDUMP("No EH in this method, no cloning.\n"); return; } if (opts.MinOpts()) { JITDUMP("Method compiled with minOpts, no cloning.\n"); return; } if (opts.compDbgCode) { JITDUMP("Method compiled with debug codegen, no cloning.\n"); return; } #ifdef DEBUG if (verbose) { printf("\n*************** Before fgCloneFinally()\n"); fgDispBasicBlocks(); fgDispHandlerTab(); printf("\n"); } // Verify try-finally exits look good before we start. fgDebugCheckTryFinallyExits(); #endif // DEBUG // Look for finallys that are not contained within other handlers, // and which do not themselves contain EH. // // Note these cases potentially could be handled, but are less // obviously profitable and require modification of the handler // table. unsigned XTnum = 0; EHblkDsc* HBtab = compHndBBtab; unsigned cloneCount = 0; for (; XTnum < compHndBBtabCount; XTnum++, HBtab++) { // Check if this is a try/finally if (!HBtab->HasFinallyHandler()) { JITDUMP("EH#%u is not a try-finally; skipping.\n", XTnum); continue; } // Check if enclosed by another handler. const unsigned enclosingHandlerRegion = ehGetEnclosingHndIndex(XTnum); if (enclosingHandlerRegion != EHblkDsc::NO_ENCLOSING_INDEX) { JITDUMP("EH#%u is enclosed by handler EH#%u; skipping.\n", XTnum, enclosingHandlerRegion); continue; } bool containsEH = false; unsigned exampleEnclosedHandlerRegion = 0; // Only need to look at lower numbered regions because the // handler table is ordered by nesting. for (unsigned i = 0; i < XTnum; i++) { if (ehGetEnclosingHndIndex(i) == XTnum) { exampleEnclosedHandlerRegion = i; containsEH = true; break; } } if (containsEH) { JITDUMP("Finally for EH#%u encloses handler EH#%u; skipping.\n", XTnum, exampleEnclosedHandlerRegion); continue; } // Look at blocks involved. BasicBlock* const firstBlock = HBtab->ebdHndBeg; BasicBlock* const lastBlock = HBtab->ebdHndLast; assert(firstBlock != nullptr); assert(lastBlock != nullptr); BasicBlock* nextBlock = lastBlock->bbNext; unsigned regionBBCount = 0; unsigned regionStmtCount = 0; bool hasFinallyRet = false; bool isAllRare = true; bool hasSwitch = false; for (const BasicBlock* block = firstBlock; block != nextBlock; block = block->bbNext) { if (block->bbJumpKind == BBJ_SWITCH) { hasSwitch = true; break; } regionBBCount++; // Should we compute statement cost here, or is it // premature...? For now just count statements I guess. for (GenTreeStmt* stmt = block->firstStmt(); stmt != nullptr; stmt = stmt->gtNextStmt) { regionStmtCount++; } hasFinallyRet = hasFinallyRet || (block->bbJumpKind == BBJ_EHFINALLYRET); isAllRare = isAllRare && block->isRunRarely(); } // Skip cloning if the finally has a switch. if (hasSwitch) { JITDUMP("Finally in EH#%u has a switch; skipping.\n", XTnum); continue; } // Skip cloning if the finally must throw. if (!hasFinallyRet) { JITDUMP("Finally in EH#%u does not return; skipping.\n", XTnum); continue; } // Skip cloning if the finally is rarely run code. if (isAllRare) { JITDUMP("Finally in EH#%u is run rarely; skipping.\n", XTnum); continue; } // Empirical studies from CoreCLR and CoreFX show that less // that 1% of finally regions have more than 15 // statements. So, to avoid potentially excessive code growth, // only clone finallys that have 15 or fewer statements. const unsigned stmtCountLimit = 15; if (regionStmtCount > stmtCountLimit) { JITDUMP("Finally in EH#%u has %u statements, limit is %u; skipping.\n", XTnum, regionStmtCount, stmtCountLimit); continue; } JITDUMP("EH#%u is a candidate for finally cloning:" " %u blocks, %u statements\n", XTnum, regionBBCount, regionStmtCount); // Walk the try region backwards looking for the last block // that transfers control to a callfinally. BasicBlock* const firstTryBlock = HBtab->ebdTryBeg; BasicBlock* const lastTryBlock = HBtab->ebdTryLast; assert(firstTryBlock->getTryIndex() == XTnum); assert(bbInTryRegions(XTnum, lastTryBlock)); BasicBlock* const beforeTryBlock = firstTryBlock->bbPrev; BasicBlock* normalCallFinallyBlock = nullptr; BasicBlock* normalCallFinallyReturn = nullptr; BasicBlock* cloneInsertAfter = HBtab->ebdTryLast; bool tryToRelocateCallFinally = false; for (BasicBlock* block = lastTryBlock; block != beforeTryBlock; block = block->bbPrev) { #if FEATURE_EH_CALLFINALLY_THUNKS // Blocks that transfer control to callfinallies are usually // BBJ_ALWAYS blocks, but the last block of a try may fall // through to a callfinally. BasicBlock* jumpDest = nullptr; if ((block->bbJumpKind == BBJ_NONE) && (block == lastTryBlock)) { jumpDest = block->bbNext; } else if (block->bbJumpKind == BBJ_ALWAYS) { jumpDest = block->bbJumpDest; } if (jumpDest == nullptr) { continue; } // The jumpDest must be a callfinally that in turn invokes the // finally of interest. if (!jumpDest->isBBCallAlwaysPair() || (jumpDest->bbJumpDest != firstBlock)) { continue; } #else // Look for call finally pair directly within the try if (!block->isBBCallAlwaysPair() || (block->bbJumpDest != firstBlock)) { continue; } BasicBlock* const jumpDest = block; #endif // FEATURE_EH_CALLFINALLY_THUNKS // Found our block. BasicBlock* const finallyReturnBlock = jumpDest->bbNext; BasicBlock* const postTryFinallyBlock = finallyReturnBlock->bbJumpDest; normalCallFinallyBlock = jumpDest; normalCallFinallyReturn = postTryFinallyBlock; #if FEATURE_EH_CALLFINALLY_THUNKS // When there are callfinally thunks, we don't expect to see the // callfinally within a handler region either. assert(!jumpDest->hasHndIndex()); // Update the clone insertion point to just after the // call always pair. cloneInsertAfter = finallyReturnBlock; // We will consider moving the callfinally so we can fall // through from the try into the clone. tryToRelocateCallFinally = true; JITDUMP("Chose path to clone: try block " FMT_BB " jumps to callfinally at " FMT_BB ";" " the call returns to " FMT_BB " which jumps to " FMT_BB "\n", block->bbNum, jumpDest->bbNum, finallyReturnBlock->bbNum, postTryFinallyBlock->bbNum); #else JITDUMP("Chose path to clone: try block " FMT_BB " is a callfinally;" " the call returns to " FMT_BB " which jumps to " FMT_BB "\n", block->bbNum, finallyReturnBlock->bbNum, postTryFinallyBlock->bbNum); #endif // FEATURE_EH_CALLFINALLY_THUNKS break; } // If there is no call to the finally, don't clone. if (normalCallFinallyBlock == nullptr) { JITDUMP("EH#%u: no calls from the try to the finally, skipping.\n", XTnum); continue; } JITDUMP("Will update callfinally block " FMT_BB " to jump to the clone;" " clone will jump to " FMT_BB "\n", normalCallFinallyBlock->bbNum, normalCallFinallyReturn->bbNum); // If there are multiple callfinallys and we're in the // callfinally thunk model, all the callfinallys are placed // just outside the try region. We'd like our chosen // callfinally to come first after the try, so we can fall out of the try // into the clone. BasicBlock* firstCallFinallyRangeBlock = nullptr; BasicBlock* endCallFinallyRangeBlock = nullptr; ehGetCallFinallyBlockRange(XTnum, &firstCallFinallyRangeBlock, &endCallFinallyRangeBlock); if (tryToRelocateCallFinally) { BasicBlock* firstCallFinallyBlock = nullptr; for (BasicBlock* block = firstCallFinallyRangeBlock; block != endCallFinallyRangeBlock; block = block->bbNext) { if (block->isBBCallAlwaysPair()) { if (block->bbJumpDest == firstBlock) { firstCallFinallyBlock = block; break; } } } // We better have found at least one call finally. assert(firstCallFinallyBlock != nullptr); // If there is more than one callfinally, we'd like to move // the one we are going to retarget to be first in the callfinally, // but only if it's targeted by the last block in the try range. if (firstCallFinallyBlock != normalCallFinallyBlock) { BasicBlock* const placeToMoveAfter = firstCallFinallyBlock->bbPrev; if ((placeToMoveAfter->bbJumpKind == BBJ_ALWAYS) && (placeToMoveAfter->bbJumpDest == normalCallFinallyBlock)) { JITDUMP("Moving callfinally " FMT_BB " to be first in line, before " FMT_BB "\n", normalCallFinallyBlock->bbNum, firstCallFinallyBlock->bbNum); BasicBlock* const firstToMove = normalCallFinallyBlock; BasicBlock* const lastToMove = normalCallFinallyBlock->bbNext; fgUnlinkRange(firstToMove, lastToMove); fgMoveBlocksAfter(firstToMove, lastToMove, placeToMoveAfter); #ifdef DEBUG // Sanity checks fgDebugCheckBBlist(false, false); fgVerifyHandlerTab(); #endif // DEBUG assert(nextBlock == lastBlock->bbNext); // Update where the callfinally range begins, since we might // have altered this with callfinally rearrangement, and/or // the range begin might have been pretty loose to begin with. firstCallFinallyRangeBlock = normalCallFinallyBlock; } else { JITDUMP("Can't move callfinally " FMT_BB " to be first in line" " -- last finally block " FMT_BB " doesn't jump to it\n", normalCallFinallyBlock->bbNum, placeToMoveAfter->bbNum); } } } // Clone the finally and retarget the normal return path and // any other path that happens to share that same return // point. For instance a construct like: // // try { } catch { } finally { } // // will have two call finally blocks, one for the normal exit // from the try, and the the other for the exit from the // catch. They'll both pass the same return point which is the // statement after the finally, so they can share the clone. // // Clone the finally body, and splice it into the flow graph // within in the parent region of the try. const unsigned finallyTryIndex = firstBlock->bbTryIndex; BasicBlock* insertAfter = nullptr; BlockToBlockMap blockMap(getAllocator()); bool clonedOk = true; unsigned cloneBBCount = 0; for (BasicBlock* block = firstBlock; block != nextBlock; block = block->bbNext) { BasicBlock* newBlock; if (block == firstBlock) { // Put first cloned finally block into the appropriate // region, somewhere within or after the range of // callfinallys, depending on the EH implementation. const unsigned hndIndex = 0; BasicBlock* const nearBlk = cloneInsertAfter; newBlock = fgNewBBinRegion(block->bbJumpKind, finallyTryIndex, hndIndex, nearBlk); // If the clone ends up just after the finally, adjust // the stopping point for finally traversal. if (newBlock->bbNext == nextBlock) { assert(newBlock->bbPrev == lastBlock); nextBlock = newBlock; } } else { // Put subsequent blocks in the same region... const bool extendRegion = true; newBlock = fgNewBBafter(block->bbJumpKind, insertAfter, extendRegion); } cloneBBCount++; assert(cloneBBCount <= regionBBCount); insertAfter = newBlock; blockMap.Set(block, newBlock); clonedOk = BasicBlock::CloneBlockState(this, newBlock, block); if (!clonedOk) { break; } // Update block flags. Note a block can be both first and last. if (block == firstBlock) { // Mark the block as the start of the cloned finally. newBlock->bbFlags |= BBF_CLONED_FINALLY_BEGIN; } if (block == lastBlock) { // Mark the block as the end of the cloned finally. newBlock->bbFlags |= BBF_CLONED_FINALLY_END; } // Make sure clone block state hasn't munged the try region. assert(newBlock->bbTryIndex == finallyTryIndex); // Cloned handler block is no longer within the handler. newBlock->clearHndIndex(); // Jump dests are set in a post-pass; make sure CloneBlockState hasn't tried to set them. assert(newBlock->bbJumpDest == nullptr); } if (!clonedOk) { // TODO: cleanup the partial clone? JITDUMP("Unable to clone the finally; skipping.\n"); continue; } // We should have cloned all the finally region blocks. assert(cloneBBCount == regionBBCount); JITDUMP("Cloned finally blocks are: " FMT_BB " ... " FMT_BB "\n", blockMap[firstBlock]->bbNum, blockMap[lastBlock]->bbNum); // Redirect redirect any branches within the newly-cloned // finally, and any finally returns to jump to the return // point. for (BasicBlock* block = firstBlock; block != nextBlock; block = block->bbNext) { BasicBlock* newBlock = blockMap[block]; if (block->bbJumpKind == BBJ_EHFINALLYRET) { GenTreeStmt* finallyRet = newBlock->lastStmt(); GenTree* finallyRetExpr = finallyRet->gtStmtExpr; assert(finallyRetExpr->gtOper == GT_RETFILT); fgRemoveStmt(newBlock, finallyRet); newBlock->bbJumpKind = BBJ_ALWAYS; newBlock->bbJumpDest = normalCallFinallyReturn; fgAddRefPred(normalCallFinallyReturn, newBlock); } else { optCopyBlkDest(block, newBlock); optRedirectBlock(newBlock, &blockMap); } } // Modify the targeting call finallys to branch to the cloned // finally. Make a note if we see some calls that can't be // retargeted (since they want to return to other places). BasicBlock* const firstCloneBlock = blockMap[firstBlock]; bool retargetedAllCalls = true; BasicBlock* currentBlock = firstCallFinallyRangeBlock; while (currentBlock != endCallFinallyRangeBlock) { BasicBlock* nextBlockToScan = currentBlock->bbNext; if (currentBlock->isBBCallAlwaysPair()) { if (currentBlock->bbJumpDest == firstBlock) { BasicBlock* const leaveBlock = currentBlock->bbNext; BasicBlock* const postTryFinallyBlock = leaveBlock->bbJumpDest; // Note we must retarget all callfinallies that have this // continuation, or we can't clean up the continuation // block properly below, since it will be reachable both // by the cloned finally and by the called finally. if (postTryFinallyBlock == normalCallFinallyReturn) { // This call returns to the expected spot, so // retarget it to branch to the clone. currentBlock->bbJumpDest = firstCloneBlock; currentBlock->bbJumpKind = BBJ_ALWAYS; // Ref count updates. fgAddRefPred(firstCloneBlock, currentBlock); // fgRemoveRefPred(firstBlock, currentBlock); // Delete the leave block, which should be marked as // keep always. assert((leaveBlock->bbFlags & BBF_KEEP_BBJ_ALWAYS) != 0); nextBlock = leaveBlock->bbNext; leaveBlock->bbFlags &= ~BBF_KEEP_BBJ_ALWAYS; fgRemoveBlock(leaveBlock, true); // Make sure iteration isn't going off the deep end. assert(leaveBlock != endCallFinallyRangeBlock); } else { // We can't retarget this call since it // returns somewhere else. JITDUMP("Can't retarget callfinally in " FMT_BB " as it jumps to " FMT_BB ", not " FMT_BB "\n", currentBlock->bbNum, postTryFinallyBlock->bbNum, normalCallFinallyReturn->bbNum); retargetedAllCalls = false; } } } currentBlock = nextBlockToScan; } // If we retargeted all calls, modify EH descriptor to be // try-fault instead of try-finally, and then non-cloned // finally catch type to be fault. if (retargetedAllCalls) { JITDUMP("All callfinallys retargeted; changing finally to fault.\n"); HBtab->ebdHandlerType = EH_HANDLER_FAULT_WAS_FINALLY; firstBlock->bbCatchTyp = BBCT_FAULT; } else { JITDUMP("Some callfinallys *not* retargeted, so region must remain as a finally.\n"); } // Modify first block of cloned finally to be a "normal" block. BasicBlock* firstClonedBlock = blockMap[firstBlock]; firstClonedBlock->bbCatchTyp = BBCT_NONE; // Cleanup the continuation fgCleanupContinuation(normalCallFinallyReturn); // Todo -- mark cloned blocks as a cloned finally.... // Done! JITDUMP("\nDone with EH#%u\n\n", XTnum); cloneCount++; } if (cloneCount > 0) { JITDUMP("fgCloneFinally() cloned %u finally handlers\n", cloneCount); fgOptimizedFinally = true; #ifdef DEBUG if (verbose) { printf("\n*************** After fgCloneFinally()\n"); fgDispBasicBlocks(); fgDispHandlerTab(); printf("\n"); } fgVerifyHandlerTab(); fgDebugCheckBBlist(false, false); fgDebugCheckTryFinallyExits(); #endif // DEBUG } } #ifdef DEBUG //------------------------------------------------------------------------ // fgDebugCheckTryFinallyExits: validate normal flow from try-finally // or try-fault-was-finally. // // Notes: // // Normal control flow exiting the try block of a try-finally must // pass through the finally. This checker attempts to verify that by // looking at the control flow graph. // // Each path that exits the try of a try-finally (including try-faults // that were optimized into try-finallys by fgCloneFinally) should // thus either execute a callfinally to the associated finally or else // jump to a block with the BBF_CLONED_FINALLY_BEGIN flag set. // // Depending on when this check is done, there may also be an empty // block along the path. // // Depending on the model for invoking finallys, the callfinallies may // lie within the try region (callfinally thunks) or in the enclosing // region. void Compiler::fgDebugCheckTryFinallyExits() { unsigned XTnum = 0; EHblkDsc* HBtab = compHndBBtab; unsigned cloneCount = 0; bool allTryExitsValid = true; for (; XTnum < compHndBBtabCount; XTnum++, HBtab++) { const EHHandlerType handlerType = HBtab->ebdHandlerType; const bool isFinally = (handlerType == EH_HANDLER_FINALLY); const bool wasFinally = (handlerType == EH_HANDLER_FAULT_WAS_FINALLY); // Screen out regions that are or were not finallys. if (!isFinally && !wasFinally) { continue; } // Walk blocks of the try, looking for normal control flow to // an ancestor region. BasicBlock* const firstTryBlock = HBtab->ebdTryBeg; BasicBlock* const lastTryBlock = HBtab->ebdTryLast; assert(firstTryBlock->getTryIndex() <= XTnum); assert(lastTryBlock->getTryIndex() <= XTnum); BasicBlock* const afterTryBlock = lastTryBlock->bbNext; BasicBlock* const finallyBlock = isFinally ? HBtab->ebdHndBeg : nullptr; for (BasicBlock* block = firstTryBlock; block != afterTryBlock; block = block->bbNext) { // Only check the directly contained blocks. assert(block->hasTryIndex()); if (block->getTryIndex() != XTnum) { continue; } // Look at each of the normal control flow possibilities. const unsigned numSuccs = block->NumSucc(); for (unsigned i = 0; i < numSuccs; i++) { BasicBlock* const succBlock = block->GetSucc(i); if (succBlock->hasTryIndex() && succBlock->getTryIndex() <= XTnum) { // Successor does not exit this try region. continue; } #if FEATURE_EH_CALLFINALLY_THUNKS // When there are callfinally thunks, callfinallies // logically "belong" to a child region and the exit // path validity will be checked when looking at the // try blocks in that region. if (block->bbJumpKind == BBJ_CALLFINALLY) { continue; } #endif // FEATURE_EH_CALLFINALLY_THUNKS // Now we know block lies directly within the try of a // try-finally, and succBlock is in an enclosing // region (possibly the method region). So this path // represents flow out of the try and should be // checked. // // There are various ways control can properly leave a // try-finally (or try-fault-was-finally): // // (a1) via a jump to a callfinally (only for finallys, only for call finally thunks) // (a2) via a callfinally (only for finallys, only for !call finally thunks) // (b) via a jump to a begin finally clone block // (c) via a jump to an empty block to (b) // (d) via a fallthrough to an empty block to (b) // (e) via the always half of a callfinally pair // (f) via an always jump clonefinally exit bool isCallToFinally = false; #if FEATURE_EH_CALLFINALLY_THUNKS if (succBlock->bbJumpKind == BBJ_CALLFINALLY) { // case (a1) isCallToFinally = isFinally && (succBlock->bbJumpDest == finallyBlock); } #else if (block->bbJumpKind == BBJ_CALLFINALLY) { // case (a2) isCallToFinally = isFinally && (block->bbJumpDest == finallyBlock); } #endif // FEATURE_EH_CALLFINALLY_THUNKS bool isJumpToClonedFinally = false; if (succBlock->bbFlags & BBF_CLONED_FINALLY_BEGIN) { // case (b) isJumpToClonedFinally = true; } else if (succBlock->bbJumpKind == BBJ_ALWAYS) { if (succBlock->isEmpty()) { // case (c) BasicBlock* const succSuccBlock = succBlock->bbJumpDest; if (succSuccBlock->bbFlags & BBF_CLONED_FINALLY_BEGIN) { isJumpToClonedFinally = true; } } } else if (succBlock->bbJumpKind == BBJ_NONE) { if (succBlock->isEmpty()) { BasicBlock* const succSuccBlock = succBlock->bbNext; // case (d) if (succSuccBlock->bbFlags & BBF_CLONED_FINALLY_BEGIN) { isJumpToClonedFinally = true; } } } bool isReturnFromFinally = false; // Case (e). Ideally we'd have something stronger to // check here -- eg that we are returning from a call // to the right finally -- but there are odd cases // like orphaned second halves of callfinally pairs // that we need to tolerate. if (block->bbFlags & BBF_KEEP_BBJ_ALWAYS) { isReturnFromFinally = true; } // Case (f) if (block->bbFlags & BBF_CLONED_FINALLY_END) { isReturnFromFinally = true; } const bool thisExitValid = isCallToFinally || isJumpToClonedFinally || isReturnFromFinally; if (!thisExitValid) { JITDUMP("fgCheckTryFinallyExitS: EH#%u exit via " FMT_BB " -> " FMT_BB " is invalid\n", XTnum, block->bbNum, succBlock->bbNum); } allTryExitsValid = allTryExitsValid & thisExitValid; } } } if (!allTryExitsValid) { JITDUMP("fgCheckTryFinallyExits: method contains invalid try exit paths\n"); assert(allTryExitsValid); } } #endif // DEBUG //------------------------------------------------------------------------ // fgCleanupContinuation: cleanup a finally continuation after a // finally is removed or converted to normal control flow. // // Notes: // The continuation is the block targeted by the second half of // a callfinally/always pair. // // Used by finally cloning, empty try removal, and empty // finally removal. // // BBF_FINALLY_TARGET bbFlag is left unchanged by this method // since it cannot be incrementally updated. Proper updates happen // when fgUpdateFinallyTargetFlags runs after all finally optimizations. void Compiler::fgCleanupContinuation(BasicBlock* continuation) { // The continuation may be a finalStep block. // It is now a normal block, so clear the special keep // always flag. continuation->bbFlags &= ~BBF_KEEP_BBJ_ALWAYS; #if !FEATURE_EH_FUNCLETS // Remove the GT_END_LFIN from the continuation, // Note we only expect to see one such statement. bool foundEndLFin = false; for (GenTreeStmt* stmt = continuation->firstStmt(); stmt != nullptr; stmt = stmt->gtNextStmt) { GenTree* expr = stmt->gtStmtExpr; if (expr->gtOper == GT_END_LFIN) { assert(!foundEndLFin); fgRemoveStmt(continuation, stmt); foundEndLFin = true; } } assert(foundEndLFin); #endif // !FEATURE_EH_FUNCLETS } //------------------------------------------------------------------------ // fgUpdateFinallyTargetFlags: recompute BBF_FINALLY_TARGET bits for all blocks // after finally optimizations have run. void Compiler::fgUpdateFinallyTargetFlags() { #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) // Any fixup required? if (!fgOptimizedFinally) { JITDUMP("In fgUpdateFinallyTargetFlags - no finally opts, no fixup required\n"); return; } JITDUMP("In fgUpdateFinallyTargetFlags, updating finally target flag bits\n"); fgClearAllFinallyTargetBits(); fgAddFinallyTargetFlags(); #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) } //------------------------------------------------------------------------ // fgClearAllFinallyTargetBits: Clear all BBF_FINALLY_TARGET bits; these will need to be // recomputed later. // void Compiler::fgClearAllFinallyTargetBits() { #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) JITDUMP("*************** In fgClearAllFinallyTargetBits()\n"); // Note that we clear the flags even if there are no EH clauses (compHndBBtabCount == 0) // in case bits are left over from EH clauses being deleted. // Walk all blocks, and reset the target bits. for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext) { block->bbFlags &= ~BBF_FINALLY_TARGET; } #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) } //------------------------------------------------------------------------ // fgAddFinallyTargetFlags: Add BBF_FINALLY_TARGET bits to all finally targets. // void Compiler::fgAddFinallyTargetFlags() { #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) JITDUMP("*************** In fgAddFinallyTargetFlags()\n"); if (compHndBBtabCount == 0) { JITDUMP("No EH in this method, no flags to set.\n"); return; } for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext) { if (block->isBBCallAlwaysPair()) { BasicBlock* const leave = block->bbNext; BasicBlock* const continuation = leave->bbJumpDest; if ((continuation->bbFlags & BBF_FINALLY_TARGET) == 0) { JITDUMP("Found callfinally " FMT_BB "; setting finally target bit on " FMT_BB "\n", block->bbNum, continuation->bbNum); continuation->bbFlags |= BBF_FINALLY_TARGET; } } } #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_) } //------------------------------------------------------------------------ // fgMergeFinallyChains: tail merge finally invocations // // Notes: // // Looks for common suffixes in chains of finally invocations // (callfinallys) and merges them. These typically arise from // try-finallys where there are multiple exit points in the try // that have the same target. void Compiler::fgMergeFinallyChains() { JITDUMP("\n*************** In fgMergeFinallyChains()\n"); #if FEATURE_EH_FUNCLETS // We need to do this transformation before funclets are created. assert(!fgFuncletsCreated); #endif // FEATURE_EH_FUNCLETS // Assume we don't need to update the bbPreds lists. assert(!fgComputePredsDone); if (compHndBBtabCount == 0) { JITDUMP("No EH in this method, nothing to merge.\n"); return; } if (opts.MinOpts()) { JITDUMP("Method compiled with minOpts, no merging.\n"); return; } if (opts.compDbgCode) { JITDUMP("Method compiled with debug codegen, no merging.\n"); return; } bool enableMergeFinallyChains = true; #if !FEATURE_EH_FUNCLETS // For non-funclet models (x86) the callfinallys may contain // statements and the continuations contain GT_END_LFINs. So no // merging is possible until the GT_END_LFIN blocks can be merged // and merging is not safe unless the callfinally blocks are split. JITDUMP("EH using non-funclet model; merging not yet implemented.\n"); enableMergeFinallyChains = false; #endif // !FEATURE_EH_FUNCLETS #if !FEATURE_EH_CALLFINALLY_THUNKS // For non-thunk EH models (arm32) the callfinallys may contain // statements, and merging is not safe unless the callfinally // blocks are split. JITDUMP("EH using non-callfinally thunk model; merging not yet implemented.\n"); enableMergeFinallyChains = false; #endif if (!enableMergeFinallyChains) { JITDUMP("fgMergeFinallyChains disabled\n"); return; } #ifdef DEBUG if (verbose) { printf("\n*************** Before fgMergeFinallyChains()\n"); fgDispBasicBlocks(); fgDispHandlerTab(); printf("\n"); } #endif // DEBUG // Look for finallys. bool hasFinally = false; for (unsigned XTnum = 0; XTnum < compHndBBtabCount; XTnum++) { EHblkDsc* const HBtab = &compHndBBtab[XTnum]; // Check if this is a try/finally. if (HBtab->HasFinallyHandler()) { hasFinally = true; break; } } if (!hasFinally) { JITDUMP("Method does not have any try-finallys; no merging.\n"); return; } // Process finallys from outside in, merging as we go. This gives // us the desired bottom-up tail merge order for callfinally // chains: outer merges may enable inner merges. bool canMerge = false; bool didMerge = false; BlockToBlockMap continuationMap(getAllocator()); // Note XTnum is signed here so we can count down. for (int XTnum = compHndBBtabCount - 1; XTnum >= 0; XTnum--) { EHblkDsc* const HBtab = &compHndBBtab[XTnum]; // Screen out non-finallys if (!HBtab->HasFinallyHandler()) { continue; } JITDUMP("Examining callfinallys for EH#%d.\n", XTnum); // Find all the callfinallys that invoke this finally. BasicBlock* firstCallFinallyRangeBlock = nullptr; BasicBlock* endCallFinallyRangeBlock = nullptr; ehGetCallFinallyBlockRange(XTnum, &firstCallFinallyRangeBlock, &endCallFinallyRangeBlock); // Clear out any stale entries in the continuation map continuationMap.RemoveAll(); // Build a map from each continuation to the "canonical" // callfinally for that continuation. unsigned callFinallyCount = 0; BasicBlock* const beginHandlerBlock = HBtab->ebdHndBeg; for (BasicBlock* currentBlock = firstCallFinallyRangeBlock; currentBlock != endCallFinallyRangeBlock; currentBlock = currentBlock->bbNext) { // Ignore "retless" callfinallys (where the finally doesn't return). if (currentBlock->isBBCallAlwaysPair() && (currentBlock->bbJumpDest == beginHandlerBlock)) { // The callfinally must be empty, so that we can // safely retarget anything that branches here to // another callfinally with the same contiuation. assert(currentBlock->isEmpty()); // This callfinally invokes the finally for this try. callFinallyCount++; // Locate the continuation BasicBlock* const leaveBlock = currentBlock->bbNext; BasicBlock* const continuationBlock = leaveBlock->bbJumpDest; // If this is the first time we've seen this // continuation, register this callfinally as the // canonical one. if (!continuationMap.Lookup(continuationBlock)) { continuationMap.Set(continuationBlock, currentBlock); } } } // Now we've seen all the callfinallys and their continuations. JITDUMP("EH#%i has %u callfinallys, %u continuations\n", XTnum, callFinallyCount, continuationMap.GetCount()); // If there are more callfinallys than continuations, some of the // callfinallys must share a continuation, and we can merge them. const bool tryMerge = callFinallyCount > continuationMap.GetCount(); if (!tryMerge) { JITDUMP("EH#%i does not have any mergeable callfinallys\n", XTnum); continue; } canMerge = true; // Walk the callfinally region, looking for blocks that jump // to a callfinally that invokes this try's finally, and make // sure they all jump to the appropriate canonical // callfinally. for (BasicBlock* currentBlock = firstCallFinallyRangeBlock; currentBlock != endCallFinallyRangeBlock; currentBlock = currentBlock->bbNext) { bool merged = fgRetargetBranchesToCanonicalCallFinally(currentBlock, beginHandlerBlock, continuationMap); didMerge = didMerge || merged; } } if (!canMerge) { JITDUMP("Method had try-finallys, but did not have any mergeable finally chains.\n"); } else { if (didMerge) { JITDUMP("Method had mergeable try-finallys and some callfinally merges were performed.\n"); #if DEBUG if (verbose) { printf("\n*************** After fgMergeFinallyChains()\n"); fgDispBasicBlocks(); fgDispHandlerTab(); printf("\n"); } #endif // DEBUG } else { // We may not end up doing any merges, because we are only // merging continuations for callfinallys that can // actually be invoked, and the importer may leave // unreachable callfinallys around (for instance, if it // is forced to re-import a leave). JITDUMP("Method had mergeable try-finallys but no callfinally merges were performed,\n" "likely the non-canonical callfinallys were unreachable\n"); } } } //------------------------------------------------------------------------ // fgRetargetBranchesToCanonicalCallFinally: find non-canonical callfinally // invocations and make them canonical. // // Arguments: // block -- block to examine for call finally invocation // handler -- start of the finally region for the try // continuationMap -- map giving the canonical callfinally for // each continuation // // Returns: // true iff the block's branch was retargeted. bool Compiler::fgRetargetBranchesToCanonicalCallFinally(BasicBlock* block, BasicBlock* handler, BlockToBlockMap& continuationMap) { // We expect callfinallys to be invoked by a BBJ_ALWAYS at this // stage in compilation. if (block->bbJumpKind != BBJ_ALWAYS) { // Possible paranoia assert here -- no flow successor of // this block should be a callfinally for this try. return false; } // Screen out cases that are not callfinallys to the right // handler. BasicBlock* const callFinally = block->bbJumpDest; if (!callFinally->isBBCallAlwaysPair()) { return false; } if (callFinally->bbJumpDest != handler) { return false; } // Ok, this is a callfinally that invokes the right handler. // Get its continuation. BasicBlock* const leaveBlock = callFinally->bbNext; BasicBlock* const continuationBlock = leaveBlock->bbJumpDest; // Find the canonical callfinally for that continuation. BasicBlock* const canonicalCallFinally = continuationMap[continuationBlock]; assert(canonicalCallFinally != nullptr); // If the block already jumps to the canoncial call finally, no work needed. if (block->bbJumpDest == canonicalCallFinally) { JITDUMP(FMT_BB " already canonical\n", block->bbNum); return false; } // Else, retarget it so that it does... JITDUMP("Redirecting branch in " FMT_BB " from " FMT_BB " to " FMT_BB ".\n", block->bbNum, callFinally->bbNum, canonicalCallFinally->bbNum); block->bbJumpDest = canonicalCallFinally; fgAddRefPred(canonicalCallFinally, block); assert(callFinally->bbRefs > 0); fgRemoveRefPred(callFinally, block); return true; } //------------------------------------------------------------------------ // fgMeasureIR: count and return the number of IR nodes in the function. // unsigned Compiler::fgMeasureIR() { unsigned nodeCount = 0; for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext) { if (!block->IsLIR()) { for (GenTreeStmt* stmt = block->firstStmt(); stmt != nullptr; stmt = stmt->getNextStmt()) { fgWalkTreePre(&stmt->gtStmtExpr, [](GenTree** slot, fgWalkData* data) -> Compiler::fgWalkResult { (*reinterpret_cast<unsigned*>(data->pCallbackData))++; return Compiler::WALK_CONTINUE; }, &nodeCount); } } else { for (GenTree* node : LIR::AsRange(block)) { nodeCount++; } } } return nodeCount; } //------------------------------------------------------------------------ // fgCompDominatedByExceptionalEntryBlocks: compute blocks that are // dominated by not normal entry. // void Compiler::fgCompDominatedByExceptionalEntryBlocks() { assert(fgEnterBlksSetValid); if (BlockSetOps::Count(this, fgEnterBlks) != 1) // There are exception entries. { for (unsigned i = 1; i <= fgBBNumMax; ++i) { BasicBlock* block = fgBBInvPostOrder[i]; if (BlockSetOps::IsMember(this, fgEnterBlks, block->bbNum)) { if (fgFirstBB != block) // skip the normal entry. { block->SetDominatedByExceptionalEntryFlag(); } } else if (block->bbIDom->IsDominatedByExceptionalEntryFlag()) { block->SetDominatedByExceptionalEntryFlag(); } } } } //------------------------------------------------------------------------ // fgNeedReturnSpillTemp: Answers does the inlinee need to spill all returns // as a temp. // // Return Value: // true if the inlinee has to spill return exprs. bool Compiler::fgNeedReturnSpillTemp() { assert(compIsForInlining()); return (lvaInlineeReturnSpillTemp != BAD_VAR_NUM); } //------------------------------------------------------------------------ // fgUseThrowHelperBlocks: Determinate does compiler use throw helper blocks. // // Note: // For debuggable code, codegen will generate the 'throw' code inline. // Return Value: // true if 'throw' helper block should be created. bool Compiler::fgUseThrowHelperBlocks() { return !opts.compDbgCode; }
{ "content_hash": "48bb7444378e27fe117165df027a7736", "timestamp": "", "source": "github", "line_count": 25718, "max_line_length": 134, "avg_line_length": 34.66144334707209, "alnum_prop": 0.5433099662001093, "repo_name": "wtgodbe/coreclr", "id": "62d958fa887190f23bc0b9a4e05061229c4d547f", "size": "891423", "binary": false, "copies": "15", "ref": "refs/heads/master", "path": "src/jit/flowgraph.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "976648" }, { "name": "Awk", "bytes": "6904" }, { "name": "Batchfile", "bytes": "167893" }, { "name": "C", "bytes": "4862319" }, { "name": "C#", "bytes": "154822068" }, { "name": "C++", "bytes": "64306017" }, { "name": "CMake", "bytes": "723128" }, { "name": "M4", "bytes": "15214" }, { "name": "Makefile", "bytes": "46117" }, { "name": "Objective-C", "bytes": "14116" }, { "name": "Perl", "bytes": "23653" }, { "name": "PowerShell", "bytes": "132755" }, { "name": "Python", "bytes": "480080" }, { "name": "Roff", "bytes": "672227" }, { "name": "Scala", "bytes": "4102" }, { "name": "Shell", "bytes": "513230" }, { "name": "Smalltalk", "bytes": "635930" }, { "name": "SuperCollider", "bytes": "650" }, { "name": "TeX", "bytes": "126781" }, { "name": "XSLT", "bytes": "1016" }, { "name": "Yacc", "bytes": "157492" } ], "symlink_target": "" }
#include "config.h" #include "ExceptionHelpers.h" #include "CodeBlock.h" #include "CallFrame.h" #include "JSGlobalObjectFunctions.h" #include "JSObject.h" #include "JSNotAnObject.h" #include "Interpreter.h" #include "Nodes.h" namespace JSC { class InterruptedExecutionError : public JSObject { public: InterruptedExecutionError(JSGlobalData* globalData) : JSObject(globalData->interruptedExecutionErrorStructure) { } virtual bool isWatchdogException() const { return true; } virtual UString toString(ExecState*) const { return "JavaScript execution exceeded timeout."; } }; JSValue createInterruptedExecutionException(JSGlobalData* globalData) { return new (globalData) InterruptedExecutionError(globalData); } static JSValue createError(ExecState* exec, ErrorType e, const char* msg) { return Error::create(exec, e, msg, -1, -1, 0); } JSValue createStackOverflowError(ExecState* exec) { return createError(exec, RangeError, "Maximum call stack size exceeded."); } JSValue createTypeError(ExecState* exec, const char* message) { return createError(exec, TypeError, message); } JSValue createUndefinedVariableError(ExecState* exec, const Identifier& ident, unsigned bytecodeOffset, CodeBlock* codeBlock) { int startOffset = 0; int endOffset = 0; int divotPoint = 0; int line = codeBlock->expressionRangeForBytecodeOffset(exec, bytecodeOffset, divotPoint, startOffset, endOffset); JSObject* exception = Error::create(exec, ReferenceError, makeString("Can't find variable: ", ident.ustring()), line, codeBlock->ownerExecutable()->sourceID(), codeBlock->ownerExecutable()->sourceURL()); exception->putWithAttributes(exec, Identifier(exec, expressionBeginOffsetPropertyName), jsNumber(exec, divotPoint - startOffset), ReadOnly | DontDelete); exception->putWithAttributes(exec, Identifier(exec, expressionCaretOffsetPropertyName), jsNumber(exec, divotPoint), ReadOnly | DontDelete); exception->putWithAttributes(exec, Identifier(exec, expressionEndOffsetPropertyName), jsNumber(exec, divotPoint + endOffset), ReadOnly | DontDelete); return exception; } static UString createErrorMessage(ExecState* exec, CodeBlock* codeBlock, int, int expressionStart, int expressionStop, JSValue value, UString error) { if (!expressionStop || expressionStart > codeBlock->source()->length()) return makeString(value.toString(exec), " is ", error); if (expressionStart < expressionStop) return makeString("Result of expression '", codeBlock->source()->getRange(expressionStart, expressionStop), "' [", value.toString(exec), "] is ", error, "."); // No range information, so give a few characters of context const UChar* data = codeBlock->source()->data(); int dataLength = codeBlock->source()->length(); int start = expressionStart; int stop = expressionStart; // Get up to 20 characters of context to the left and right of the divot, clamping to the line. // then strip whitespace. while (start > 0 && (expressionStart - start < 20) && data[start - 1] != '\n') start--; while (start < (expressionStart - 1) && isStrWhiteSpace(data[start])) start++; while (stop < dataLength && (stop - expressionStart < 20) && data[stop] != '\n') stop++; while (stop > expressionStart && isStrWhiteSpace(data[stop])) stop--; return makeString("Result of expression near '...", codeBlock->source()->getRange(start, stop), "...' [", value.toString(exec), "] is ", error, "."); } JSObject* createInvalidParamError(ExecState* exec, const char* op, JSValue value, unsigned bytecodeOffset, CodeBlock* codeBlock) { int startOffset = 0; int endOffset = 0; int divotPoint = 0; int line = codeBlock->expressionRangeForBytecodeOffset(exec, bytecodeOffset, divotPoint, startOffset, endOffset); UString errorMessage = createErrorMessage(exec, codeBlock, line, divotPoint, divotPoint + endOffset, value, makeString("not a valid argument for '", op, "'")); JSObject* exception = Error::create(exec, TypeError, errorMessage, line, codeBlock->ownerExecutable()->sourceID(), codeBlock->ownerExecutable()->sourceURL()); exception->putWithAttributes(exec, Identifier(exec, expressionBeginOffsetPropertyName), jsNumber(exec, divotPoint - startOffset), ReadOnly | DontDelete); exception->putWithAttributes(exec, Identifier(exec, expressionCaretOffsetPropertyName), jsNumber(exec, divotPoint), ReadOnly | DontDelete); exception->putWithAttributes(exec, Identifier(exec, expressionEndOffsetPropertyName), jsNumber(exec, divotPoint + endOffset), ReadOnly | DontDelete); return exception; } JSObject* createNotAConstructorError(ExecState* exec, JSValue value, unsigned bytecodeOffset, CodeBlock* codeBlock) { int startOffset = 0; int endOffset = 0; int divotPoint = 0; int line = codeBlock->expressionRangeForBytecodeOffset(exec, bytecodeOffset, divotPoint, startOffset, endOffset); // We're in a "new" expression, so we need to skip over the "new.." part int startPoint = divotPoint - (startOffset ? startOffset - 4 : 0); // -4 for "new " const UChar* data = codeBlock->source()->data(); while (startPoint < divotPoint && isStrWhiteSpace(data[startPoint])) startPoint++; UString errorMessage = createErrorMessage(exec, codeBlock, line, startPoint, divotPoint, value, "not a constructor"); JSObject* exception = Error::create(exec, TypeError, errorMessage, line, codeBlock->ownerExecutable()->sourceID(), codeBlock->ownerExecutable()->sourceURL()); exception->putWithAttributes(exec, Identifier(exec, expressionBeginOffsetPropertyName), jsNumber(exec, divotPoint - startOffset), ReadOnly | DontDelete); exception->putWithAttributes(exec, Identifier(exec, expressionCaretOffsetPropertyName), jsNumber(exec, divotPoint), ReadOnly | DontDelete); exception->putWithAttributes(exec, Identifier(exec, expressionEndOffsetPropertyName), jsNumber(exec, divotPoint + endOffset), ReadOnly | DontDelete); return exception; } JSValue createNotAFunctionError(ExecState* exec, JSValue value, unsigned bytecodeOffset, CodeBlock* codeBlock) { int startOffset = 0; int endOffset = 0; int divotPoint = 0; int line = codeBlock->expressionRangeForBytecodeOffset(exec, bytecodeOffset, divotPoint, startOffset, endOffset); UString errorMessage = createErrorMessage(exec, codeBlock, line, divotPoint - startOffset, divotPoint, value, "not a function"); JSObject* exception = Error::create(exec, TypeError, errorMessage, line, codeBlock->ownerExecutable()->sourceID(), codeBlock->ownerExecutable()->sourceURL()); exception->putWithAttributes(exec, Identifier(exec, expressionBeginOffsetPropertyName), jsNumber(exec, divotPoint - startOffset), ReadOnly | DontDelete); exception->putWithAttributes(exec, Identifier(exec, expressionCaretOffsetPropertyName), jsNumber(exec, divotPoint), ReadOnly | DontDelete); exception->putWithAttributes(exec, Identifier(exec, expressionEndOffsetPropertyName), jsNumber(exec, divotPoint + endOffset), ReadOnly | DontDelete); return exception; } JSNotAnObjectErrorStub* createNotAnObjectErrorStub(ExecState* exec, bool isNull) { return new (exec) JSNotAnObjectErrorStub(exec, isNull); } JSObject* createNotAnObjectError(ExecState* exec, JSNotAnObjectErrorStub* error, unsigned bytecodeOffset, CodeBlock* codeBlock) { // Both op_construct and op_instanceof require a use of op_get_by_id to get // the prototype property from an object. The exception messages for exceptions // thrown by these instances op_get_by_id need to reflect this. OpcodeID followingOpcodeID; if (codeBlock->getByIdExceptionInfoForBytecodeOffset(exec, bytecodeOffset, followingOpcodeID)) { ASSERT(followingOpcodeID == op_construct || followingOpcodeID == op_instanceof); if (followingOpcodeID == op_construct) return createNotAConstructorError(exec, error->isNull() ? jsNull() : jsUndefined(), bytecodeOffset, codeBlock); return createInvalidParamError(exec, "instanceof", error->isNull() ? jsNull() : jsUndefined(), bytecodeOffset, codeBlock); } int startOffset = 0; int endOffset = 0; int divotPoint = 0; int line = codeBlock->expressionRangeForBytecodeOffset(exec, bytecodeOffset, divotPoint, startOffset, endOffset); UString errorMessage = createErrorMessage(exec, codeBlock, line, divotPoint - startOffset, divotPoint, error->isNull() ? jsNull() : jsUndefined(), "not an object"); JSObject* exception = Error::create(exec, TypeError, errorMessage, line, codeBlock->ownerExecutable()->sourceID(), codeBlock->ownerExecutable()->sourceURL()); exception->putWithAttributes(exec, Identifier(exec, expressionBeginOffsetPropertyName), jsNumber(exec, divotPoint - startOffset), ReadOnly | DontDelete); exception->putWithAttributes(exec, Identifier(exec, expressionCaretOffsetPropertyName), jsNumber(exec, divotPoint), ReadOnly | DontDelete); exception->putWithAttributes(exec, Identifier(exec, expressionEndOffsetPropertyName), jsNumber(exec, divotPoint + endOffset), ReadOnly | DontDelete); return exception; } } // namespace JSC
{ "content_hash": "e1270fe844ad604524d5cc28db446887", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 207, "avg_line_length": 55.806060606060605, "alnum_prop": 0.7437011294526499, "repo_name": "stephaneAG/PengPod700", "id": "9bb740e309c6f70cbeb01b17669dbbf2078ffba6", "size": "10780", "binary": false, "copies": "16", "ref": "refs/heads/master", "path": "QtEsrc/backup_qt/qt-everywhere-opensource-src-4.8.5/src/3rdparty/javascriptcore/JavaScriptCore/runtime/ExceptionHelpers.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "167426" }, { "name": "Batchfile", "bytes": "25368" }, { "name": "C", "bytes": "3755463" }, { "name": "C#", "bytes": "9282" }, { "name": "C++", "bytes": "177871700" }, { "name": "CSS", "bytes": "600936" }, { "name": "GAP", "bytes": "758872" }, { "name": "GLSL", "bytes": "32226" }, { "name": "Groff", "bytes": "106542" }, { "name": "HTML", "bytes": "273585110" }, { "name": "IDL", "bytes": "1194" }, { "name": "JavaScript", "bytes": "435912" }, { "name": "Makefile", "bytes": "289373" }, { "name": "Objective-C", "bytes": "1898658" }, { "name": "Objective-C++", "bytes": "3222428" }, { "name": "PHP", "bytes": "6074" }, { "name": "Perl", "bytes": "291672" }, { "name": "Prolog", "bytes": "102468" }, { "name": "Python", "bytes": "22546" }, { "name": "QML", "bytes": "3580408" }, { "name": "QMake", "bytes": "2191574" }, { "name": "Scilab", "bytes": "2390" }, { "name": "Shell", "bytes": "116533" }, { "name": "TypeScript", "bytes": "42452" }, { "name": "Visual Basic", "bytes": "8370" }, { "name": "XQuery", "bytes": "25094" }, { "name": "XSLT", "bytes": "252382" } ], "symlink_target": "" }
<resources> <string name="sdk_name">appaloosa-android-tools</string> <string name="server_url" translatable="false">https://www.appaloosa-store.com/</string> <!-- The version code and name should stay here not be directly in the manifest. They are sent with the analytics and since the Manifest is ignored when the library is added to an app, the only way to retrieve them without code duplication is here. --> <string name="version_code" translatable="false">10</string> <string name="version_name" translatable="false">0.3.5</string> <string name="not_an_activity" translatable="false"> The argument given to the checkBlacklist method is not an activity.\n You should pass an Object extending Activity and implementing ApplicationAuthorizationInterface.\n SDK stops here.\n </string> <string name="blacklist_dialog_title">Unauthorized Access</string> <string name="blacklist_dialog_ok">OK</string> <string name="missing_store_params">Missing store ID or store token</string> <string name="not_authorized_message">You are not allowed to access this application.</string> <string name="unknown_status_message">Could not fetch application authorization status from Appaloosa.</string> <string name="starting_sdk">Starting SDK</string> <string name="event_not_recorded">Event was not recorded</string> <string name="ip_address_no_retrieved">IP address could not be retrieved</string> <!-- AutoUpdate Strings --> <string name="check_last_update_error">An error occurred when looking for the last update on Appaloosa.</string> <string name="get_download_url_error">An error occurred when retrieving the last update download URL on Appaloosa.</string> <string name="download_apk_error">An error occurred when downloading the last update apk on Appaloosa.</string> <string name="downloading_progress_message">"New version download: "</string> <string name="download_failed">Download error</string> </resources>
{ "content_hash": "771481b086abb5976b6a1abf555595f6", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 127, "avg_line_length": 67.53333333333333, "alnum_prop": 0.7339585389930898, "repo_name": "appaloosa-store/appaloosa-android-tools", "id": "7cb0d638d437f2c7daf52b693d41d3a6d33e747b", "size": "2026", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/values/strings.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "61359" } ], "symlink_target": "" }
package com.packtpub.java7.concurrency.chapter1.recipe7.task; import java.util.Date; import java.util.Deque; import java.util.concurrent.TimeUnit; import com.packtpub.java7.concurrency.chapter1.recipe7.event.Event; /** * Runnable class that generates and event every second * */ public class WriterTask implements Runnable { /** * Data structure to stores the events */ Deque<Event> deque; /** * Constructor of the class * @param deque data structure that stores the event */ public WriterTask (Deque<Event> deque){ this.deque=deque; } /** * Main class of the Runnable */ @Override public void run() { // Writes 100 events for (int i=1; i<100; i++) { // Creates and initializes the Event objects Event event=new Event(); event.setDate(new Date()); event.setEvent(String.format("The thread %s has generated an event",Thread.currentThread().getId())); // Add to the data structure deque.addFirst(event); try { // Sleeps during one second TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }
{ "content_hash": "ce29f67bf7842933fb2061e27e19031e", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 104, "avg_line_length": 21.88235294117647, "alnum_prop": 0.6845878136200717, "repo_name": "xuelvming/Java7ConcurrencyCookbook", "id": "d3bc4baaaf9e51ee541386c77a9192cc55669267", "size": "1116", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "7881_code/Chapter 1/ch1_recipe07/src/main/java/com/packtpub/java7/concurrency/chapter1/recipe7/task/WriterTask.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "322450" } ], "symlink_target": "" }
import { inject, TestBed } from '@angular/core/testing'; import { UsersService } from './users.service'; import { HttpClient, HttpClientModule } from '@angular/common/http'; describe('UsersService', () => { let usersService; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientModule], providers: [UsersService, HttpClient] }); usersService = TestBed.get(UsersService); }); it('should be created', inject([UsersService], (service: UsersService) => { expect(service).toBeTruthy(); })); });
{ "content_hash": "50330a370daba583a95427e7b2524f87", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 77, "avg_line_length": 28.94736842105263, "alnum_prop": 0.6672727272727272, "repo_name": "TF-Banksters/Vacations", "id": "4fc34c641f19baf345b5491eb0a8f785955b87b0", "size": "550", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TFVacations/src/app/user-list/users.service.spec.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "4694" }, { "name": "CSS", "bytes": "83" }, { "name": "HTML", "bytes": "635" }, { "name": "JavaScript", "bytes": "1645" }, { "name": "TypeScript", "bytes": "11068" } ], "symlink_target": "" }
package org.springframework.rules.constraint; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.springframework.rules.constraint.Constraint; import org.springframework.rules.reporting.TypeResolvable; import org.springframework.rules.reporting.TypeResolvableSupport; /** * A constraint based on a regular expression pattern. * * @see TypeResolvable * @see Pattern * * @author Keith Donald */ public class RegexpConstraint extends TypeResolvableSupport implements Constraint { private Pattern pattern; /** * Creates a RegexpConstraint with the provided regular expression pattern * string. * * @param regex The regular expression */ public RegexpConstraint(String regex) { this(regex, null); } /** * Creates a RegexpConstraint with the provided regular expression pattern * string and sets the type of the constraint to provide specific messages. * * @param regex the regular expression. * @param type id used to fetch the message. */ public RegexpConstraint(String regex, String type) { super(type); pattern = Pattern.compile(regex); } /** * Test if the argument matches the pattern. */ public boolean test(Object argument) { if (argument == null) { argument = ""; } Matcher m = pattern.matcher((CharSequence) argument); return m.matches(); } public String toString() { return getDefaultMessage() + " " + pattern.pattern(); } }
{ "content_hash": "5f248e738f77ce7d9611261f0d307c58", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 83, "avg_line_length": 24.135593220338983, "alnum_prop": 0.7324438202247191, "repo_name": "springrichclient/springrcp", "id": "3e931e37e3a8ef9cb94f63f5ce49c2e214947ca3", "size": "2039", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "spring-richclient-core/src/main/java/org/springframework/rules/constraint/RegexpConstraint.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Haskell", "bytes": "1484" }, { "name": "Java", "bytes": "4963844" }, { "name": "JavaScript", "bytes": "22973" }, { "name": "Shell", "bytes": "2550" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "3ba95c9b0f139dbd566523ffb8210203", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "9b3b1048232aa492b150df83da7f50b588c3d494", "size": "199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Saccharomycetes/Saccharomycetales/Lipomycetaceae/Dipodascopsis/Dipodascopsis uninucleata/ Syn. Dipodascopsis uninucleata wickerhamii/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import collections import json import os from os import path import subprocess import sys import unittest import yaml INV_DIR = 'playbooks/inventory' SCRIPT_FILENAME = 'dynamic_inventory.py' INV_SCRIPT = path.join(os.getcwd(), INV_DIR, SCRIPT_FILENAME) sys.path.append(path.join(os.getcwd(), INV_DIR)) import dynamic_inventory as di TARGET_DIR = path.join(os.getcwd(), 'tests', 'inventory') USER_CONFIG_FILE = path.join(TARGET_DIR, "openstack_user_config.yml") # These files will be placed in TARGET_DIR by INV_SCRIPT. # They should be cleaned up between each test. CLEANUP = [ 'openstack_inventory.json', 'openstack_hostnames_ips.yml', 'backup_openstack_inventory.tar' ] def cleanup(): for f_name in CLEANUP: f_file = path.join(TARGET_DIR, f_name) if os.path.exists(f_file): os.remove(f_file) def get_inventory(): "Return the inventory mapping in a dict." try: cmd = [INV_SCRIPT, '--config', TARGET_DIR] inventory_string = subprocess.check_output( cmd, stderr=subprocess.STDOUT ) inventory = json.loads(inventory_string) return inventory finally: # Remove the file system artifacts since we want to force fresh runs cleanup() class TestAnsibleInventoryFormatConstraints(unittest.TestCase): inventory = None expected_groups = [ 'aio1_containers', 'all', 'all_containers', 'aodh_alarm_evaluator', 'aodh_alarm_notifier', 'aodh_all', 'aodh_api', 'aodh_container', 'aodh_listener', 'ceilometer_agent_central', 'ceilometer_agent_compute', 'ceilometer_agent_notification', 'ceilometer_all', 'ceilometer_api', 'ceilometer_api_container', 'ceilometer_collector', 'ceilometer_collector_container', 'cinder_all', 'cinder_api', 'cinder_api_container', 'cinder_backup', 'cinder_scheduler', 'cinder_scheduler_container', 'cinder_volume', 'cinder_volumes_container', 'compute_all', 'compute_containers', 'compute_hosts', 'galera', 'galera_all', 'galera_container', 'glance_all', 'glance_api', 'glance_container', 'glance_registry', 'haproxy', 'haproxy_all', 'haproxy_container', 'haproxy_containers', 'haproxy_hosts', 'heat_all', 'heat_api', 'heat_api_cfn', 'heat_api_cloudwatch', 'heat_apis_container', 'heat_engine', 'heat_engine_container', 'horizon', 'horizon_all', 'horizon_container', 'hosts', 'identity_all', 'identity_containers', 'identity_hosts', 'infra_containers', 'infra_hosts', 'ironic-server_hosts', 'ironic_conductor_container', 'ironic_api_container', 'ironic_conductor', 'ironic-infra_containers', 'ironic-infra_hosts', 'ironic_servers', 'ironic-server_containers', 'ironic_all', 'ironic_server', 'ironic_server_container', 'ironic_api', 'keystone', 'keystone_all', 'keystone_container', 'log_all', 'log_containers', 'log_hosts', 'memcached', 'memcached_all', 'memcached_container', 'metering-alarm_containers', 'metering-alarm_hosts', 'metering-compute_container', 'metering-compute_containers', 'metering-compute_hosts', 'metering-infra_containers', 'metering-infra_hosts', 'network_all', 'network_containers', 'network_hosts', 'neutron_agent', 'neutron_agents_container', 'neutron_all', 'neutron_dhcp_agent', 'neutron_l3_agent', 'neutron_lbaas_agent', 'neutron_linuxbridge_agent', 'neutron_metadata_agent', 'neutron_metering_agent', 'neutron_server', 'neutron_server_container', 'nova_all', 'nova_api_metadata', 'nova_api_metadata_container', 'nova_api_os_compute', 'nova_api_os_compute_container', 'nova_cert', 'nova_cert_container', 'nova_compute', 'nova_compute_container', 'nova_conductor', 'nova_conductor_container', 'nova_console', 'nova_console_container', 'nova_scheduler', 'nova_scheduler_container', 'os-infra_all', 'os-infra_containers', 'os-infra_hosts', 'pkg_repo', 'rabbit_mq_container', 'rabbitmq', 'rabbitmq_all', 'remote', 'remote_containers', 'repo-infra_all', 'repo-infra_containers', 'repo-infra_hosts', 'repo_all', 'repo_container', 'rsyslog', 'rsyslog_all', 'rsyslog_container', 'shared-infra_all', 'shared-infra_containers', 'shared-infra_hosts', 'storage-infra_all', 'storage-infra_containers', 'storage-infra_hosts', 'storage_all', 'storage_containers', 'storage_hosts', 'swift-proxy_containers', 'swift-proxy_hosts', 'swift-remote_containers', 'swift-remote_hosts', 'swift_acc', 'swift_acc_container', 'swift_all', 'swift_cont', 'swift_cont_container', 'swift_containers', 'swift_hosts', 'swift_obj', 'swift_obj_container', 'swift_proxy', 'swift_proxy_container', 'swift_remote', 'swift_remote_all', 'swift_remote_container', 'utility', 'utility_all', 'utility_container', ] @classmethod def setUpClass(cls): cls.inventory = get_inventory() def test_meta(self): meta = self.inventory['_meta'] self.assertIsNotNone(meta, "_meta missing from inventory") self.assertIsInstance(meta, dict, "_meta is not a dict") def test_hostvars(self): hostvars = self.inventory['_meta']['hostvars'] self.assertIsNotNone(hostvars, "hostvars missing from _meta") self.assertIsInstance(hostvars, dict, "hostvars is not a dict") def test_group_vars_all(self): group_vars_all = self.inventory['all'] self.assertIsNotNone(group_vars_all, "group vars all missing from inventory") self.assertIsInstance(group_vars_all, dict, "group vars all is not a dict") the_vars = group_vars_all['vars'] self.assertIsNotNone(the_vars, "vars missing from group vars all") self.assertIsInstance(the_vars, dict, "vars in group vars all is not a dict") def test_expected_host_groups_present(self): for group in self.expected_groups: the_group = self.inventory[group] self.assertIsNotNone(the_group, "Required host group: %s is missing " "from inventory" % group) self.assertIsInstance(the_group, dict) if group != 'all': self.assertIn('hosts', the_group) self.assertIsInstance(the_group['hosts'], list) def test_only_expected_host_groups_present(self): all_keys = list(self.expected_groups) all_keys.append('_meta') self.assertEqual(set(all_keys), set(self.inventory.keys())) class TestUserConfiguration(unittest.TestCase): def setUp(self): self.longMessage = True self.loaded_user_configuration = di.load_user_configuration(TARGET_DIR) def test_loading_user_configuration(self): """Test that the user configuration can be loaded""" self.assertIsInstance(self.loaded_user_configuration, dict) class TestDuplicateIps(unittest.TestCase): def setUp(self): # Allow custom assertion errors. self.longMessage = True def test_duplicates(self): """Test that no duplicate IPs are made on any network.""" for i in xrange(0, 99): inventory = get_inventory() ips = collections.defaultdict(int) hostvars = inventory['_meta']['hostvars'] for host, var_dict in hostvars.items(): nets = var_dict['container_networks'] for net, vals in nets.items(): if 'address' in vals.keys(): addr = vals['address'] ips[addr] += 1 self.assertEqual(1, ips[addr], msg="IP %s duplicated." % addr) class TestConfigChecks(unittest.TestCase): def setUp(self): self.user_defined_config = dict() with open(USER_CONFIG_FILE, 'rb') as f: self.user_defined_config.update(yaml.safe_load(f.read()) or {}) def setup_config_file(self, user_defined_config, key): try: if key in user_defined_config: del user_defined_config[key] elif key in user_defined_config['global_overrides']: del user_defined_config['global_overrides'][key] else: raise KeyError("can't find specified key in user config") finally: # rename temporarily our user_config_file so we can use the new one os.rename(USER_CONFIG_FILE, USER_CONFIG_FILE + ".tmp") # Save new user_config_file with open(USER_CONFIG_FILE, 'wb') as f: f.write(yaml.dump(user_defined_config)) def test_provider_networks_check(self): # create config file without provider networks self.setup_config_file(self.user_defined_config, 'provider_networks') # check if provider networks absence is Caught with self.assertRaises(subprocess.CalledProcessError) as context: get_inventory() expectedLog = "provider networks can't be found under global_overrides" self.assertTrue(expectedLog in context.exception.output) def test_global_overrides_check(self): # create config file without global_overrides self.setup_config_file(self.user_defined_config, 'global_overrides') # check if global_overrides absence is Caught with self.assertRaises(subprocess.CalledProcessError) as context: get_inventory() expectedLog = "global_overrides can't be found in user config\n" self.assertEqual(context.exception.output, expectedLog) def tearDown(self): # get back our initial user config file os.remove(USER_CONFIG_FILE) os.rename(USER_CONFIG_FILE + ".tmp", USER_CONFIG_FILE) if __name__ == '__main__': unittest.main()
{ "content_hash": "b9c135749b4b7b3e65a3ec80a7ae7ebf", "timestamp": "", "source": "github", "line_count": 346, "max_line_length": 79, "avg_line_length": 31.59248554913295, "alnum_prop": 0.5765254779983533, "repo_name": "mrda/openstack-ansible", "id": "feedb0dc27b9271ccb4eeca40f58099e3954c134", "size": "10954", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/test_inventory.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "666" }, { "name": "Python", "bytes": "252679" }, { "name": "Shell", "bytes": "76190" } ], "symlink_target": "" }
class ObjectRecognitionLabelNameTranslator { public: ObjectRecognitionLabelNameTranslator(); virtual ~ObjectRecognitionLabelNameTranslator(); std::string Translate(size_t id); private: virtual std::string DoTranslate(size_t id) = 0; class ObjectRecognitionLabelNameTranslatorD* d_; }; #endif // _OBJECT_RECOGNITION_LABEL_NAME_TRANSLATOR_H_
{ "content_hash": "35b3140b511e9d183b2e9b4393ff16a6", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 55, "avg_line_length": 25.5, "alnum_prop": 0.7787114845938375, "repo_name": "lisa0314/node-realsense-1", "id": "88c690eaba7f0218755b67a79fafb303d85f1119", "size": "650", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/object-recognition/object_recognition_label_name_translator.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1254" }, { "name": "C++", "bytes": "594866" }, { "name": "Gnuplot", "bytes": "538" }, { "name": "JavaScript", "bytes": "471326" }, { "name": "Python", "bytes": "21049" }, { "name": "Shell", "bytes": "3885" } ], "symlink_target": "" }
using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Portal; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI; using Microsoft.UI.Xaml.Media; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; namespace ArcGISRuntime.WinUI.Samples.SymbolStylesFromWebStyles { [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Create symbol styles from web styles", category: "Symbology", description: "Create symbol styles from a style file hosted on a portal.", instructions: "The sample displays a map with a set of symbols that represent the categories of the features within the dataset. Pan and zoom on the map and view the legend to explore the appearance and names of the different symbols from the selected symbol style.", tags: new[] { "renderer", "symbol", "symbology", "web style" })] public partial class SymbolStylesFromWebStyles { // Hold a reference to the renderer. private UniqueValueRenderer _renderer; // Hold a reference to the feature layer. private FeatureLayer _webStyleLayer; // Hold a list of symbol data for the legend. private readonly ObservableCollection<SymbolLegendInfo> _symbolLegendCollection = new ObservableCollection<SymbolLegendInfo>(); public SymbolStylesFromWebStyles() { InitializeComponent(); _ = Initialize(); } private async Task Initialize() { try { // Create a new basemap and assign it to the map view. MyMapView.Map = new Map(BasemapStyle.ArcGISNavigation); // URL for a feature layer that contains points of interest in varying categories across LA County. Uri webStyleLayerUri = new Uri("https://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/LA_County_Points_of_Interest/FeatureServer/0"); // Create the feature layer from the given URL. _webStyleLayer = new FeatureLayer(webStyleLayerUri); // Instantiate a UniqueValueRenderer, this will impact specific features based on the values of the specified FieldName(s). _renderer = new UniqueValueRenderer(); _renderer.FieldNames.Add("cat2"); // The UniqueValueRenderer defines how features of a FeatureLayer are styled. // Without an overriding UniqueValueRenderer features will use the web layer's default gray circle style. _webStyleLayer.Renderer = _renderer; // Add the feature layer to the map view. MyMapView.Map.OperationalLayers.Add(_webStyleLayer); // Set the scale at which feature symbols and text will appear at their default size. MyMapView.Map.ReferenceScale = 100000; // Set the the initial view point for the map view. MapPoint centerPoint = new MapPoint(-118.44186, 34.28301, SpatialReferences.Wgs84); MyMapView.Map.InitialViewpoint = new Viewpoint(centerPoint, 7000); // Set the item source for the legend to the ObservableCollection containing legend data. LegendItemsControl.ItemsSource = _symbolLegendCollection; // Load the symbols from portal and add them to the renderer. await CreateSymbolStyles(); } catch (Exception ex) { await new MessageDialog2(ex.Message, ex.GetType().Name).ShowAsync(); } } private async Task CreateSymbolStyles() { // Create a dictionary of symbol categories and their associated symbol name. Dictionary<string, List<string>> symbolCategories = CreateCategoriesMap(); // Create a portal to enable access to the symbols. ArcGISPortal portal = await ArcGISPortal.CreateAsync(); // Create a SymbolStyle, this is used to return symbols based on provided symbol keys from portal. SymbolStyle esri2DPointSymbolStyle = await SymbolStyle.OpenAsync("Esri2DPointSymbolsStyle", portal); // Loop through each of the keys in the symbol categories dictionary and retrieve each symbol from portal. foreach (string symbolName in symbolCategories.Keys) { // This call is used to retrieve a single symbol for a given symbol name, if multiple symbol names are provided // a multilayer symbol assembled and returned for the given symbol names. Symbol symbol = await esri2DPointSymbolStyle.GetSymbolAsync(new List<string> { symbolName }); // Get the image source for the symbol to populate the legend UI. RuntimeImage symbolSwatch = await symbol.CreateSwatchAsync(); ImageSource imageSource = await RuntimeImageExtensions.ToImageSourceAsync(symbolSwatch); // Add the symbol the ObservableCollection containing the symbol legend data. _symbolLegendCollection.Add(new SymbolLegendInfo() { Name = symbolName, ImageSource = imageSource }); // Loop through each of the categories in the symbol categories dictionary for the given symbol name. // This needs to be done to ensure that a UniqueValue is created for each symbol category. // Numerous categories can have the same matching symbol name, however each category needs their own UniqueValue. foreach (string symbolCategory in symbolCategories[symbolName]) { // Create a UniqueValue for a given symbol category, name and symbol. // If multiple categories are passed in this UniqueValue will only be used in cases where every given category is matched in our data set. // In the data set used in this sample each point of interest is only represented by a single category so we only use a single category in this case. UniqueValue uniqueValue = new UniqueValue(symbolCategory, symbolName, symbol, new List<string> { symbolCategory }); // Add the UniqueValue to the renderer. _renderer.UniqueValues.Add(uniqueValue); } } } private Dictionary<string, List<string>> CreateCategoriesMap() { Dictionary<string, List<string>> symbolCategories = new Dictionary<string, List<string>>(); symbolCategories.Add("atm", new List<string>() { "Banking and Finance" }); symbolCategories.Add("beach", new List<string>() { "Beaches and Marinas" }); symbolCategories.Add("campground", new List<string>() { "Campgrounds" }); symbolCategories.Add("city-hall", new List<string>() { "City Halls", "Government Offices" }); symbolCategories.Add("hospital", new List<string>() { "Hospitals and Medical Centers", "Health Screening and Testing", "Health Centers", "Mental Health Centers" }); symbolCategories.Add("library", new List<string>() { "Libraries" }); symbolCategories.Add("park", new List<string>() { "Parks and Gardens" }); symbolCategories.Add("place-of-worship", new List<string>() { "Churches" }); symbolCategories.Add("police-station", new List<string>() { "Sheriff and Police Stations" }); symbolCategories.Add("post-office", new List<string>() { "DHL Locations", "Federal Express Locations" }); symbolCategories.Add("school", new List<string>() { "Public High Schools", "Public Elementary Schools", "Private and Charter Schools" }); symbolCategories.Add("trail", new List<string>() { "Trails" }); return symbolCategories; } private void MapViewExtentChanged(object sender, EventArgs e) { // Set scale symbols to true when we zoom in so the symbols don't take up the entire view. _webStyleLayer.ScaleSymbols = MyMapView.MapScale >= 80000; } } public class SymbolLegendInfo { public string Name { get; set; } public ImageSource ImageSource { get; set; } } }
{ "content_hash": "f3c86af3fd5746a92cefc30d17fd88b5", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 275, "avg_line_length": 54.94736842105263, "alnum_prop": 0.6518199233716475, "repo_name": "Esri/arcgis-runtime-samples-dotnet", "id": "6ccc150d294d7c0ab640e494fa665f1e61731a8b", "size": "8917", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/WinUI/ArcGISRuntime.WinUI.Viewer/Samples/Symbology/SymbolStylesFromWebStyles/SymbolStylesFromWebStyles.xaml.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "10343309" }, { "name": "CSS", "bytes": "154816" }, { "name": "Dockerfile", "bytes": "1021" }, { "name": "Python", "bytes": "93169" }, { "name": "Ruby", "bytes": "597" } ], "symlink_target": "" }
../../node_modules/karma/bin/karma $1 $2
{ "content_hash": "e458840308845844ed973216b1140cc8", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 40, "avg_line_length": 40, "alnum_prop": 0.65, "repo_name": "tkaplan/apollo", "id": "6cfe2608a4a89c1403cda23a8f973935e23e188b", "size": "40", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/vendor/caas/modules/apollo/karma.sh", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "623371" }, { "name": "JavaScript", "bytes": "1360530" }, { "name": "PHP", "bytes": "0" }, { "name": "Shell", "bytes": "74" } ], "symlink_target": "" }
package main import ( "context" database "cloud.google.com/go/spanner/admin/database/apiv1" "google.golang.org/api/iterator" databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" ) func main() { ctx := context.Background() c, err := database.NewDatabaseAdminClient(ctx) if err != nil { // TODO: Handle error. } defer c.Close() req := &databasepb.ListBackupsRequest{ // TODO: Fill request struct fields. // See https://pkg.go.dev/google.golang.org/genproto/googleapis/spanner/admin/database/v1#ListBackupsRequest. } it := c.ListBackups(ctx, req) for { resp, err := it.Next() if err == iterator.Done { break } if err != nil { // TODO: Handle error. } // TODO: Use resp. _ = resp } } // [END spanner_v1_generated_DatabaseAdmin_ListBackups_sync]
{ "content_hash": "a53af04925c25e82041487bb5939bc56", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 111, "avg_line_length": 21.89189189189189, "alnum_prop": 0.6851851851851852, "repo_name": "googleapis/google-cloud-go", "id": "9cdd83a7fe7e78b4b7923c7fb644727a09fd9dfd", "size": "1549", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "internal/generated/snippets/spanner/admin/database/apiv1/DatabaseAdminClient/ListBackups/main.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "10349" }, { "name": "C", "bytes": "74" }, { "name": "Dockerfile", "bytes": "1841" }, { "name": "Go", "bytes": "7626642" }, { "name": "M4", "bytes": "43723" }, { "name": "Makefile", "bytes": "1455" }, { "name": "Python", "bytes": "718" }, { "name": "Shell", "bytes": "27309" } ], "symlink_target": "" }
@interface PodsDummy_SGVInstanceSwizzling_Swift_OSX : NSObject @end @implementation PodsDummy_SGVInstanceSwizzling_Swift_OSX @end
{ "content_hash": "d57e9f5f021c4b9982ba1af155b38062", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 62, "avg_line_length": 32.5, "alnum_prop": 0.8538461538461538, "repo_name": "sanekgusev/SGVInstanceSwizzling", "id": "354d39fd1b86df37ac021ebf72f4211cefef8dc3", "size": "164", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Example/Pods/Target Support Files/SGVInstanceSwizzling-Swift-OSX/SGVInstanceSwizzling-Swift-OSX-dummy.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "4453" }, { "name": "Objective-C", "bytes": "30457" }, { "name": "Ruby", "bytes": "2377" }, { "name": "Shell", "bytes": "54344" }, { "name": "Swift", "bytes": "15807" } ], "symlink_target": "" }
package mobi.cangol.mobile; import android.test.ApplicationTestCase; import mobi.cangol.mobile.service.AppService; import mobi.cangol.mobile.service.conf.ConfigService; /** * Created by weixuewu on 16/6/11. */ public class CoreApplicationTest extends ApplicationTestCase<CoreApplication> { private CoreApplication coreApplication; public CoreApplicationTest() { super(CoreApplication.class); } @Override protected void setUp() throws Exception { super.setUp(); createApplication(); coreApplication=getApplication(); } public void testGetAppService() { ConfigService configService= (ConfigService) coreApplication.getAppService(AppService.CONFIG_SERVICE); assertNotNull(configService.getAppDir()); } }
{ "content_hash": "ad73acbc81078958b4f977f589ed8023", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 110, "avg_line_length": 27.17241379310345, "alnum_prop": 0.7296954314720813, "repo_name": "Cangol/Cangol-appcore", "id": "9406118dc103590b88ad534dd4af8071b11d2a00", "size": "788", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "appcore/src/androidTest/java/mobi/cangol/mobile/CoreApplicationTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "914714" } ], "symlink_target": "" }
"""uncompyle6 packaging information""" # To the extent possible we make this file look more like a # configuration file rather than code like setup.py. I find putting # configuration stuff in the middle of a function call in setup.py, # which for example requires commas in between parameters, is a little # less elegant than having it here with reduced code, albeit there # still is some room for improvement. # Things that change more often go here. copyright = """ Copyright (C) 2015-2017 Rocky Bernstein <rb@dustyfeet.com>. """ classifiers = ['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.1', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Software Development :: Debuggers', 'Topic :: Software Development :: Libraries :: Python Modules', ] # The rest in alphabetic order author = "Rocky Bernstein, Hartmut Goebel, John Aycock, and others" author_email = "rb@dustyfeet.com" entry_points={ 'console_scripts': [ 'uncompyle6=uncompyle6.bin.uncompile:main_bin', 'pydisassemble=uncompyle6.bin.pydisassemble:main', ]} ftp_url = None install_requires = ['spark-parser >= 1.6.0, < 1.7.0', 'xdis >= 3.3.0, < 3.4.0'] license = 'MIT' mailing_list = 'python-debugger@googlegroups.com' modname = 'uncompyle6' py_modules = None short_desc = 'Python cross-version byte-code deparser' web = 'https://github.com/rocky/python-uncompyle6/' # tracebacks in zip files are funky and not debuggable zip_safe = True import os.path def get_srcdir(): filename = os.path.normcase(os.path.dirname(os.path.abspath(__file__))) return os.path.realpath(filename) srcdir = get_srcdir() def read(*rnames): return open(os.path.join(srcdir, *rnames)).read() # Get info from files; set: long_description and VERSION long_description = ( read("README.rst") + '\n' ) exec(read('uncompyle6/version.py'))
{ "content_hash": "c3eaa89eeb1f71eba58526ef7897c65b", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 79, "avg_line_length": 39.776119402985074, "alnum_prop": 0.6097560975609756, "repo_name": "moagstar/python-uncompyle6", "id": "a216d2d61e1b0ab469d128100f33fbe65e623f9d", "size": "2665", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "__pkginfo__.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "3365" }, { "name": "Makefile", "bytes": "8956" }, { "name": "PowerShell", "bytes": "7195" }, { "name": "Python", "bytes": "1690289" }, { "name": "Shell", "bytes": "535" } ], "symlink_target": "" }
Order: 130 --- Sharing variables and state across your builds can currently be achieved in a handful of different ways, depending on what state you want to share and across what scope. ## Typed Context **_This only applies to Cake version `0.28.0` and later_** > For more background on typed context, check out [the release blog post](https://cakebuild.net/blog/2018/05/cake-v0.28.0-released#typed-context) You can use a typed context to easily share complex state across tasks *without* using global variables or static members. Using typed context in your script is done in 3 parts: the context itself, the `Setup` method, and individual `Task` methods. ### Creating your typed context First, you will need a class to act as the typed context. This can be any standard C#, and doesn't need to include any Cake-specific code. For this example, we'll use the following simple class: ```csharp public class BuildData { public string Configuration { get; } public bool BuildPackages { get; } public List<string> Frameworks {get; set;} // you can use read-only or mutable properties public BuildData( string configuration, bool buildPackages) { Configuration = configuration; BuildPackages = buildPackages; } } ``` ### Returning your context from `Setup` To have your script use a typed context, you need to return an instance of your setup class from your (correctly-typed) `Setup` method. You can use this method to change how your tasks will run later. Using the example above: ```csharp Setup<BuildData>(setupContext => { return new BuildData( configuration: Argument("configuration", "Release"), buildPackages: !BuildSystem.IsLocalBuild ) { Frameworks = IsRunningOnUnix() ? new List<string> { "netcoreapp2.1" } : new List<string> { "net472", "netcoreapp2.1" ;} } }); ``` ### Using your context in a `Task` Finally, you can access your typed context from any task, by supplying a type parameter to the `Does`, `DoesForEach` or `WithCriteria` method of your task declaration: ```csharp Task("Build-Packages") .WithCriteria<BuildData>((context, data) => data.BuildPackages) //Your typed context is the second argument .Does<BuildData>(data => //make sure you use the right type parameter here { Information("Packages were {0}", data.BuildPackages ? "built" : "not built"); }); ``` You can also use your typed context in the `Teardown` method: ```csharp Teardown<BuildData>((context, data) => // make sure you use the type parameter here { Information($"Completed build for {(string.Join(", ", data.Frameworks))}"); }); ``` ## Global Variables The simplest approach to sharing variables or state across your build is using global variables in your build script. To do this, simply declare any variables outside the scope of your `Task` methods. The convention for these variables is to place them at the start of the script. ```csharp /////////////////////////////////////////////////////////////////////////////// // VARIABLES /////////////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); var artifacts = "./dist/"; var testResultsPath = MakeAbsolute(Directory(artifacts + "./test-results")); ``` You can then access these variables in any of your `Task` methods. ```csharp Setup(setupContext => { Information($"Using {configuration} build configuration"); }); Task("Clean") .Does(() => { // Clean artifacts directory CleanDirectory(artifacts); }); ```
{ "content_hash": "0687d13f421ea4e16af6eca55f5322e8", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 248, "avg_line_length": 34.528301886792455, "alnum_prop": 0.6762295081967213, "repo_name": "devlead/website", "id": "6953228b52b1bce1ae23ff317bbe62fe179eedb4", "size": "3660", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "input/docs/fundamentals/sharing-build-state.md", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "691" }, { "name": "Batchfile", "bytes": "77" }, { "name": "C#", "bytes": "13471" }, { "name": "CSS", "bytes": "542" }, { "name": "HTML", "bytes": "20891" }, { "name": "PowerShell", "bytes": "5588" }, { "name": "Shell", "bytes": "2513" } ], "symlink_target": "" }
describe("InterventionPlotBand", function() { describe(".toHighChartsDate", function() { describe("good input", function() { it("returns a correct JavaScript UTC date for HighCharts", function() { var input = { year: 2015, month: 8, day: 14 }; var high_charts_date = InterventionPlotBand.toHighChartsDate(input); expect(high_charts_date).toEqual(1439510400000); expect(new Date(high_charts_date).toGMTString()).toEqual('Fri, 14 Aug 2015 00:00:00 GMT'); }); }); }); describe("#toHighCharts", function() { describe("good input", function() { it("returns a correct HighCharts configuration", function() { var attributes = { name: "Extra math help", start_date: { year: 2015, month: 8, day: 14 }, end_date: { year: 2015, month: 8, day: 15 } }; var intervention_plot_band = new InterventionPlotBand(attributes); var to_highcharts = intervention_plot_band.toHighCharts(); expect(to_highcharts.from).toEqual(1439510400000); expect(to_highcharts.to).toEqual(1439596800000); }); }); }); });
{ "content_hash": "0752087682c421dff39028d174da2030", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 98, "avg_line_length": 41.888888888888886, "alnum_prop": 0.6268788682581786, "repo_name": "codeforamerica/somerville-teacher-tool", "id": "b46543ebbd284fd33c74af38b99a6151872ad687", "size": "1131", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "spec/javascripts/charts/intervention_plot_band_spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "20653" }, { "name": "HTML", "bytes": "44884" }, { "name": "JavaScript", "bytes": "141571" }, { "name": "Ruby", "bytes": "297999" }, { "name": "Shell", "bytes": "22203" } ], "symlink_target": "" }
@interface MOBProjectionEPSG6062 : MOBProjection @end
{ "content_hash": "816c49c05cc93fe29b48d4dfea9a0433", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 48, "avg_line_length": 18.333333333333332, "alnum_prop": 0.8363636363636363, "repo_name": "jkdubr/Proj4", "id": "9227d97254cc7fd005d053f94078ebe6eaed5a0d", "size": "82", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Pod/Classes/Projection/MOBProjectionEPSG6062.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1141" }, { "name": "Objective-C", "bytes": "1689233" }, { "name": "Ruby", "bytes": "1604" }, { "name": "Shell", "bytes": "7202" } ], "symlink_target": "" }
layout: page title: "Skadeförebyggande arbete" meta_title: "Skadeförebyggande arbete" subheadline: "" teaser: "" header: image_fullwidth: "header_forening.jpg" permalink: "/forening/skadeforebyggande_arbete/" ---
{ "content_hash": "a1e36055765b008196d96504803aa530", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 48, "avg_line_length": 24, "alnum_prop": 0.7592592592592593, "repo_name": "sonjacolmsjo/Ultimatesweden1", "id": "775442d327bf4291464eb6487699ed6ed1506855", "size": "222", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pages/forening/skadeforebyggande_arbete.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "420214" }, { "name": "HTML", "bytes": "156221" }, { "name": "JavaScript", "bytes": "576748" }, { "name": "PostScript", "bytes": "517305" }, { "name": "Ruby", "bytes": "5832" }, { "name": "XSLT", "bytes": "5064" } ], "symlink_target": "" }
package org.apache.derby.impl.sql.execute.rts; import org.apache.derby.iapi.sql.execute.ResultSetStatistics; import org.apache.derby.iapi.services.io.StoredFormatIds; import org.apache.derby.iapi.services.i18n.MessageService; import org.apache.derby.iapi.reference.SQLState; import org.apache.derby.iapi.services.io.FormatableHashtable; import org.apache.derby.catalog.UUID; import org.apache.derby.impl.sql.catalog.XPLAINResultSetDescriptor; import org.apache.derby.impl.sql.catalog.XPLAINResultSetTimingsDescriptor; import org.apache.derby.impl.sql.execute.xplain.XPLAINUtil; import org.apache.derby.iapi.sql.execute.xplain.XPLAINVisitor; import java.io.ObjectOutput; import java.io.ObjectInput; import java.io.IOException; /** ResultSetStatistics implemenation for AnyResultSet. */ public class RealAnyResultSetStatistics extends RealNoPutResultSetStatistics { /* Leave these fields public for object inspectors */ public int subqueryNumber; public int pointOfAttachment; public ResultSetStatistics childResultSetStatistics; // CONSTRUCTORS /** * * */ public RealAnyResultSetStatistics( int numOpens, int rowsSeen, int rowsFiltered, long constructorTime, long openTime, long nextTime, long closeTime, int resultSetNumber, int subqueryNumber, int pointOfAttachment, double optimizerEstimatedRowCount, double optimizerEstimatedCost, ResultSetStatistics childResultSetStatistics) { super( numOpens, rowsSeen, rowsFiltered, constructorTime, openTime, nextTime, closeTime, resultSetNumber, optimizerEstimatedRowCount, optimizerEstimatedCost ); this.subqueryNumber = subqueryNumber; this.pointOfAttachment = pointOfAttachment; this.childResultSetStatistics = childResultSetStatistics; } // ResultSetStatistics interface /** * Return the statement execution plan as a String. * * @param depth Indentation level. * * @return String The statement execution plan as a String. */ public String getStatementExecutionPlanText(int depth) { String attachmentString = (pointOfAttachment == -1) ? ":" : (" (" + MessageService.getTextMessage(SQLState.RTS_ATTACHED_TO) + " " + pointOfAttachment + "):"); initFormatInfo(depth); return indent + MessageService.getTextMessage(SQLState.RTS_BEGIN_SQ_NUMBER) + " " + subqueryNumber + "\n" + indent + MessageService.getTextMessage(SQLState.RTS_ANY_RS) + " " + attachmentString + "\n" + indent + MessageService.getTextMessage(SQLState.RTS_NUM_OPENS) + " = " + numOpens + "\n" + indent + MessageService.getTextMessage(SQLState.RTS_ROWS_SEEN) + " = " + rowsSeen + "\n" + dumpTimeStats(indent, subIndent) + "\n" + dumpEstimatedCosts(subIndent) + "\n" + indent + MessageService.getTextMessage(SQLState.RTS_SOURCE_RS) + ":\n" + childResultSetStatistics.getStatementExecutionPlanText(sourceDepth) + "\n" + indent + MessageService.getTextMessage(SQLState.RTS_END_SQ_NUMBER) + " " + subqueryNumber + "\n"; } /** * Return information on the scan nodes from the statement execution * plan as a String. * * @param tableName if not-NULL then return information for this table only * @param depth Indentation level. * * @return String The information on the scan nodes from the * statement execution plan as a String. */ public String getScanStatisticsText(String tableName, int depth) { return childResultSetStatistics.getScanStatisticsText(tableName, depth); } // Class implementation public String toString() { return getStatementExecutionPlanText(0); } public java.util.Vector<ResultSetStatistics> getChildren(){ java.util.Vector<ResultSetStatistics> children = new java.util.Vector<ResultSetStatistics>(); children.addElement(childResultSetStatistics); return children; } /** * Format for display, a name for this node. * */ public String getNodeName(){ return MessageService.getTextMessage(SQLState.RTS_ANY_RS); } // ----------------------------------------------------- // XPLAINable Implementation // ----------------------------------------------------- public void accept(XPLAINVisitor visitor) { // I have only one child visitor.setNumberOfChildren(1); // pre-order, depth-first traversal // me first visitor.visit(this); // then my child childResultSetStatistics.accept(visitor); } public String getRSXplainType() { return XPLAINUtil.OP_ANY; } public String getRSXplainDetails() { String attachmentString = (this.pointOfAttachment == -1) ? "" : "ATTACHED:" + this.pointOfAttachment; return attachmentString + ";" + this.resultSetNumber; } }
{ "content_hash": "bf47190ae8e3535e3b5a2b5a1e82d00d", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 97, "avg_line_length": 28.15028901734104, "alnum_prop": 0.691170431211499, "repo_name": "trejkaz/derby", "id": "82ae1b6df9223434dfda1d6ef9dc98adb90a42bf", "size": "5751", "binary": false, "copies": "2", "ref": "refs/heads/trunk", "path": "java/engine/org/apache/derby/impl/sql/execute/rts/RealAnyResultSetStatistics.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "13737" }, { "name": "HTML", "bytes": "287079" }, { "name": "Java", "bytes": "42740679" }, { "name": "PLSQL", "bytes": "48958" }, { "name": "PLpgSQL", "bytes": "11719" }, { "name": "SQLPL", "bytes": "69828" }, { "name": "Shell", "bytes": "30682" }, { "name": "XSLT", "bytes": "15231" } ], "symlink_target": "" }
* 1.1.4 - Ease of use * Create single method call to disable cache on UI AgentPolicy. * Add notifyCompletion() and notifyProgress() methods on AbstractAgent. * 1.1.3 - Open Source Release * 1.1.1 - Bugfix * Fix temporarily leaking most recent AgentListener. * 1.1.0 - GroundControl static API * Create a single point of contact with the AgentExecutor, AgentPolicy and UI lifecycle helper components. * 1.0.0 - First Release * Allow developer to specify arbitrary background thread priority when composing system. * Ensure that background loopers run at developer specified thread priority. * Ensure HandlerCache is threadsafe. * 0.9.9 - RC 3 * Set thread prioritization to match AsyncTask background operation priority. * 0.9.8 - RC 2 * Add ability to clear a previously cached value for current and all future requests. * 0.9.7 - RC 1 * Fix special case where reentrant code modified a synchronized set during iteration. Create unit test for same. * Fix thread-local cache issue with unit test. * Enforce background callbacks bypass cache. * 0.9.6 - Beta 4 * Range check on AbstractAgent * Concurrent dequeue prevention * 0.9.5 - Beta 3 * Fixed API < 19 issue not reported by IDE. * Clean up warnings and minor issues. * Synchronized several iterations over lists/keys. * 0.9.4 - Beta 2 * Fixed another concurrency issue * Code clean up * 0.9.3 - Beta 1 * Fixed some concurrency issues * Added easy ability to reattach to an ongoing one-time operation with UIOneTimeAgentHelper * Improved throughput in high volume situations * Created unit tests to spam from multiple simultaneous threads * Sample application works for upload and display of Imgur images * 0.9.2 - Alpha 3 * AgentPolicyBuilder did not return builder instance if setting parallelBackgroundTimeoutMs * Sample application has more Imgur operations * 0.9.1 - Alpha 2 * The AgentExecutor an Agent is running on is provided to the Agent to use if spawning other Agents * Sample application adding OAuth2.0 demonstration (Imgur API) * 0.9.0 - Alpha 1 * Initial internal release * Sample app supports complicated Coca-Cola Freestyle brand fetch and extract operation
{ "content_hash": "12f491b60ae0c75997b6f3c42d20817d", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 118, "avg_line_length": 51.955555555555556, "alnum_prop": 0.7091531223267751, "repo_name": "BottleRocketStudios/Android-GroundControl", "id": "ff6934990fc2759c79dae0c922263ce73c239735", "size": "2368", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "CHANGELOG.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "372644" } ], "symlink_target": "" }
package com.android.app.function.onekeyshare.theme.skyblue; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.android.app.function.onekeyshare.CustomerLogo; import com.android.app.function.onekeyshare.ShareCore; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import cn.sharesdk.framework.Platform; import static cn.sharesdk.framework.utils.R.getBitmapRes; import static cn.sharesdk.framework.utils.R.getIdRes; import static cn.sharesdk.framework.utils.R.getLayoutRes; public class PlatformGridViewAdapter extends BaseAdapter implements View.OnClickListener { private final Context context; private List<Object> logos = new ArrayList<Object>(); private List<Integer> checkedPositionList = new ArrayList<Integer>(); private int directOnlyPosition = -1; static class ViewHolder { public Integer position; public ImageView logoImageView; public ImageView checkedImageView; public TextView nameTextView; } public PlatformGridViewAdapter(Context context) { this.context = context; } @Override public int getCount() { return logos.size(); } @Override public Object getItem(int i) { return logos.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int position, View view, ViewGroup viewGroup) { ViewHolder viewHolder; if(view == null) { view = LayoutInflater.from(context).inflate(getLayoutRes(context, "skyblue_share_platform_list_item"), null); viewHolder = new ViewHolder(); viewHolder.checkedImageView = (ImageView) view.findViewById(getIdRes(context, "checkedImageView")); viewHolder.logoImageView = (ImageView) view.findViewById(getIdRes(context, "logoImageView")); viewHolder.nameTextView = (TextView) view.findViewById(getIdRes(context, "nameTextView")); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) view.getTag(); } Bitmap logo; String label; Object item = getItem(position); boolean disabled; boolean isDirectShare = item instanceof Platform ? ShareCore.isDirectShare((Platform) item) : true; if(directOnlyPosition == -1) { disabled = !checkedPositionList.isEmpty() && isDirectShare; } else { disabled = position != directOnlyPosition; } if (item instanceof Platform) { logo = getIcon((Platform) item, disabled ? "" : "_checked"); label = getName((Platform) item); view.setOnClickListener(this); } else { CustomerLogo customerLogo = (CustomerLogo) item; logo = disabled ? customerLogo.disableLogo : customerLogo.enableLogo; label = customerLogo.label; view.setOnClickListener(this); //TODO 需要整理 // view.setOnClickListener(((CustomerLogo) item).listener); } String checkedResName = directOnlyPosition != -1 && directOnlyPosition != position ? "skyblue_platform_checked_disabled" : "skyblue_platform_checked"; viewHolder.position = position; viewHolder.checkedImageView.setImageBitmap(BitmapFactory.decodeResource(context.getResources(), getBitmapRes(context, checkedResName))); viewHolder.checkedImageView.setVisibility(checkedPositionList.contains(viewHolder.position) ? View.VISIBLE : View.GONE); viewHolder.nameTextView.setText(label); viewHolder.logoImageView.setImageBitmap(logo); return view; } @Override public void onClick(View view) { ViewHolder viewHolder = (ViewHolder) view.getTag(); Integer position = viewHolder.position; //直接分享平台选中后,其它的不可用 if(directOnlyPosition != -1 && position != directOnlyPosition) return; Object item = getItem(position); boolean direct = false; //normal platform if(item instanceof Platform){ direct = ShareCore.isDirectShare((Platform) item); }else{ //自定义图标 direct = true; } //EditPage Platforms only if(direct && directOnlyPosition == -1 && !checkedPositionList.isEmpty()) return; if(checkedPositionList.contains(position)) { checkedPositionList.remove(position); if(direct) directOnlyPosition = -1; } else { checkedPositionList.add(position); if(direct) directOnlyPosition = position; } notifyDataSetChanged(); } public void setData(Platform[] platforms, HashMap<String, String> hiddenPlatforms) { if(platforms == null) return; if (hiddenPlatforms != null && hiddenPlatforms.size() > 0) { ArrayList<Platform> ps = new ArrayList<Platform>(); for (Platform p : platforms) { if (hiddenPlatforms.containsKey(p.getName())) { continue; } ps.add(p); } logos.addAll(ps); } else { logos.addAll(Arrays.asList(platforms)); } checkedPositionList.clear(); notifyDataSetChanged(); } public void setCustomerLogos(ArrayList<CustomerLogo> customers) { if(customers == null || customers.size() == 0) return; logos.addAll(customers); } public List<Object> getCheckedItems() { ArrayList<Object> list = new ArrayList<Object>(); if(directOnlyPosition != -1) { list.add(getItem(directOnlyPosition)); return list; } Object item; for(Integer position : checkedPositionList) { item = getItem(position); list.add(item); } return list; } private Bitmap getIcon(Platform plat, String subfix) { String resName = "skyblue_logo_" + plat.getName() + subfix; int resId = getBitmapRes(context, resName); return BitmapFactory.decodeResource(context.getResources(), resId); } private String getName(Platform plat) { if (plat == null) { return ""; } String name = plat.getName(); if (name == null) { return ""; } int resId = cn.sharesdk.framework.utils.R.getStringRes(context, plat.getName()); if (resId > 0) { return context.getString(resId); } return null; } }
{ "content_hash": "4f66bcd9495d5e33700f9a879864d09b", "timestamp": "", "source": "github", "line_count": 207, "max_line_length": 152, "avg_line_length": 28.47342995169082, "alnum_prop": 0.7312521208008144, "repo_name": "frodoking/GradleAndroid-App", "id": "699ee90fff8bf7f59611654a65127d7614c36fb3", "size": "6331", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "function/src/main/java/com/android/app/function/onekeyshare/theme/skyblue/PlatformGridViewAdapter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "4697" }, { "name": "Java", "bytes": "1007071" }, { "name": "JavaScript", "bytes": "99491" } ], "symlink_target": "" }
<!DOCTYPE HTML> <html lang="en"> <head> <title>Source code</title> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <main role="main"> <div class="sourceContainer"> <pre><span class="sourceLineNo">001</span><a id="line.1">package io.ebean;</a> <span class="sourceLineNo">002</span><a id="line.2"></a> <span class="sourceLineNo">003</span><a id="line.3">import java.sql.ResultSet;</a> <span class="sourceLineNo">004</span><a id="line.4">import java.sql.SQLException;</a> <span class="sourceLineNo">005</span><a id="line.5"></a> <span class="sourceLineNo">006</span><a id="line.6">/**</a> <span class="sourceLineNo">007</span><a id="line.7"> * Used with SqlQuery to map raw JDBC ResultSet to objects.</a> <span class="sourceLineNo">008</span><a id="line.8"> * &lt;p&gt;</a> <span class="sourceLineNo">009</span><a id="line.9"> * This provides a low level mapping option with direct use of JDBC ResultSet</a> <span class="sourceLineNo">010</span><a id="line.10"> * with the option of having logic in the mapping. For example, only map some</a> <span class="sourceLineNo">011</span><a id="line.11"> * columns depending on the values read from other columns.</a> <span class="sourceLineNo">012</span><a id="line.12"> * &lt;/p&gt;</a> <span class="sourceLineNo">013</span><a id="line.13"> * &lt;p&gt;</a> <span class="sourceLineNo">014</span><a id="line.14"> * For straight mapping into beans then DtoQuery would be the first choice as</a> <span class="sourceLineNo">015</span><a id="line.15"> * it can automatically map the ResultSet into beans.</a> <span class="sourceLineNo">016</span><a id="line.16"> * &lt;/p&gt;</a> <span class="sourceLineNo">017</span><a id="line.17"> *</a> <span class="sourceLineNo">018</span><a id="line.18"> * &lt;pre&gt;{@code</a> <span class="sourceLineNo">019</span><a id="line.19"> *</a> <span class="sourceLineNo">020</span><a id="line.20"> * //</a> <span class="sourceLineNo">021</span><a id="line.21"> * // Map from ResultSet to CustomerDto bean</a> <span class="sourceLineNo">022</span><a id="line.22"> * //</a> <span class="sourceLineNo">023</span><a id="line.23"> * class CustomerMapper implements RowMapper&lt;CustomerDto&gt; {</a> <span class="sourceLineNo">024</span><a id="line.24"> *</a> <span class="sourceLineNo">025</span><a id="line.25"> * @Override</a> <span class="sourceLineNo">026</span><a id="line.26"> * public CustomerDto map(ResultSet rset, int rowNum) throws SQLException {</a> <span class="sourceLineNo">027</span><a id="line.27"> *</a> <span class="sourceLineNo">028</span><a id="line.28"> * long id = rset.getLong(1);</a> <span class="sourceLineNo">029</span><a id="line.29"> * String name = rset.getString(2);</a> <span class="sourceLineNo">030</span><a id="line.30"> * String status = rset.getString(3);</a> <span class="sourceLineNo">031</span><a id="line.31"> *</a> <span class="sourceLineNo">032</span><a id="line.32"> * return new CustomerDto(id, name, status);</a> <span class="sourceLineNo">033</span><a id="line.33"> * }</a> <span class="sourceLineNo">034</span><a id="line.34"> * }</a> <span class="sourceLineNo">035</span><a id="line.35"> *</a> <span class="sourceLineNo">036</span><a id="line.36"> *</a> <span class="sourceLineNo">037</span><a id="line.37"> * //</a> <span class="sourceLineNo">038</span><a id="line.38"> * // Then use the mapper</a> <span class="sourceLineNo">039</span><a id="line.39"> * //</a> <span class="sourceLineNo">040</span><a id="line.40"> *</a> <span class="sourceLineNo">041</span><a id="line.41"> * String sql = "select id, name, status from o_customer where name = ?";</a> <span class="sourceLineNo">042</span><a id="line.42"> *</a> <span class="sourceLineNo">043</span><a id="line.43"> * CustomerDto rob = DB.sqlQuery(sql)</a> <span class="sourceLineNo">044</span><a id="line.44"> * .setParameter(1, "Rob")</a> <span class="sourceLineNo">045</span><a id="line.45"> * .mapTo(CUSTOMER_MAPPER)</a> <span class="sourceLineNo">046</span><a id="line.46"> * .findOne();</a> <span class="sourceLineNo">047</span><a id="line.47"> *</a> <span class="sourceLineNo">048</span><a id="line.48"> *</a> <span class="sourceLineNo">049</span><a id="line.49"> * }&lt;/pre&gt;</a> <span class="sourceLineNo">050</span><a id="line.50"> *</a> <span class="sourceLineNo">051</span><a id="line.51"> * @param &lt;T&gt; The type the row data is mapped into.</a> <span class="sourceLineNo">052</span><a id="line.52"> */</a> <span class="sourceLineNo">053</span><a id="line.53">@FunctionalInterface</a> <span class="sourceLineNo">054</span><a id="line.54">public interface RowMapper&lt;T&gt; {</a> <span class="sourceLineNo">055</span><a id="line.55"></a> <span class="sourceLineNo">056</span><a id="line.56"> /**</a> <span class="sourceLineNo">057</span><a id="line.57"> * Read the data from the ResultSet and map to the return type.</a> <span class="sourceLineNo">058</span><a id="line.58"> *</a> <span class="sourceLineNo">059</span><a id="line.59"> * @param resultSet The JDBC ResultSet positioned to the current row</a> <span class="sourceLineNo">060</span><a id="line.60"> * @param rowNum The number of the current row being mapped.</a> <span class="sourceLineNo">061</span><a id="line.61"> */</a> <span class="sourceLineNo">062</span><a id="line.62"> T map(ResultSet resultSet, int rowNum) throws SQLException;</a> <span class="sourceLineNo">063</span><a id="line.63">}</a> </pre> </div> </main> </body> </html>
{ "content_hash": "8dbb8a9f2fb4bf824307e532cde53de3", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 136, "avg_line_length": 40.74452554744526, "alnum_prop": 0.6519168756718022, "repo_name": "ebean-orm/ebean-orm.github.io", "id": "477a550b7b285f2114f750b93781b4ae4fbda755", "size": "5582", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apidoc/12/src-html/io/ebean/RowMapper.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "133613" }, { "name": "HTML", "bytes": "49047496" }, { "name": "Java", "bytes": "2615" }, { "name": "JavaScript", "bytes": "74774" }, { "name": "Kotlin", "bytes": "1347" }, { "name": "Shell", "bytes": "1829" } ], "symlink_target": "" }
using System.Diagnostics.CodeAnalysis; namespace xFunc.Maths.Analyzers.TypeAnalyzers; /// <summary> /// Extensions method for the <see cref="ResultTypes"/> enum. /// </summary> internal static class ResultTypesExtensions { /// <summary> /// Helper method for throw the <see cref="ParameterTypeMismatchException"/> exception. /// </summary> /// <param name="expected">The expected result type.</param> /// <param name="actual">The actual result type.</param> /// <returns>Always throws <see cref="ParameterTypeMismatchException"/>.</returns> [DoesNotReturn] internal static ResultTypes ThrowFor(this ResultTypes expected, ResultTypes actual) => throw new ParameterTypeMismatchException(expected, actual); /// <summary> /// Helper method for throw the <see cref="BinaryParameterTypeMismatchException"/> exception. /// </summary> /// <param name="expected">The expected result type.</param> /// <param name="actual">The actual result type.</param> /// <returns>Always throws <see cref="BinaryParameterTypeMismatchException"/>.</returns> [DoesNotReturn] internal static ResultTypes ThrowForLeft(this ResultTypes expected, ResultTypes actual) => throw new BinaryParameterTypeMismatchException(expected, actual, BinaryParameterType.Left); /// <summary> /// Helper method for throw the <see cref="BinaryParameterTypeMismatchException"/> exception. /// </summary> /// <param name="expected">The expected result type.</param> /// <param name="actual">The actual result type.</param> /// <returns>Always throws <see cref="BinaryParameterTypeMismatchException"/>.</returns> [DoesNotReturn] internal static ResultTypes ThrowForRight(this ResultTypes expected, ResultTypes actual) => throw new BinaryParameterTypeMismatchException(expected, actual, BinaryParameterType.Right); }
{ "content_hash": "1d0bc08406c3f372ad4f6b4fe9a3c8a7", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 100, "avg_line_length": 48.43589743589744, "alnum_prop": 0.7215457914240339, "repo_name": "sys27/xFunc", "id": "264dd7f9b2a6a4dd7c724716777776872f6e8492", "size": "2049", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "xFunc.Maths/Analyzers/TypeAnalyzers/ResultTypesExtensions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "1950012" } ], "symlink_target": "" }
// The MIT License (MIT) // Copyright (c) 2014 Rasmus Mikkelsen // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using Serilog.Configuration; using Serilog.Events; namespace Serilog.Sinks.LogReceiver { public static class LoggerConfigurationLogReceiverExtensions { public static LoggerConfiguration LogReceiver( this LoggerSinkConfiguration loggerConfiguration, string host = "localhost", int port = 50000, LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum, int batchPostingLimit = LogReceiverSink.DefaultBatchPostingLimit, TimeSpan? period = null, IFormatProvider formatProvider = null) { if (loggerConfiguration == null) throw new ArgumentNullException("loggerConfiguration"); return loggerConfiguration.Sink(new LogReceiverSink( host, port, batchPostingLimit, formatProvider, period.HasValue ? period.Value : LogReceiverSink.DefaultPeriod)); } } }
{ "content_hash": "92877f73c774fdc5d9b927702198e26c", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 100, "avg_line_length": 43.285714285714285, "alnum_prop": 0.7114568599717115, "repo_name": "jnus/Serilog.Sinks.LogReceiver", "id": "b73f767c43b6e3ef55c5686c341d313585c85d77", "size": "2123", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Source/Serilog.Sinks.LogReceiver/LoggerConfigurationLogReceiverExtensions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "9157" } ], "symlink_target": "" }
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { if (head == NULL) return NULL; ListNode *tail = NULL; if (m == 1) { ListNode *tail = NULL; ListNode *p = splitList(head, n - m + 1, tail); reverseList(head); head->next = p; return tail; } else { ListNode *p = splitList(head, m - 1, tail); ListNode *ptail = NULL; ListNode *q = splitList(p, n - m + 1, ptail); reverseList(p); p->next = q; tail->next = ptail; return head; } } ListNode *splitList(ListNode *head, int n, ListNode *&tail) { tail = NULL; for (int i = 1; i < n && head; i++, head = head->next); if (head == NULL) return head; ListNode *p = head->next; tail = head; head->next = NULL; return p; } ListNode *reverseList(ListNode *head) { ListNode *cur = NULL; ListNode *next = NULL; while (head) { next = head->next; head->next = cur; cur = head; head = next; } return cur; } };
{ "content_hash": "498133568cf6ab84f50b39d032570ec6", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 65, "avg_line_length": 27.62, "alnum_prop": 0.4663287472845764, "repo_name": "yplusplus/LeetCode", "id": "5fa4ff730edb2b610f2001e271e069dcd75d5757", "size": "1381", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ReverseLinkedListII.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "152751" } ], "symlink_target": "" }
require 'spec_helper' feature HomeController do background do visit root_path end scenario "Show top page" do page.should have_content 'Home#index' page.should have_content 'Find me in app/views/home/index.html.slim' end end
{ "content_hash": "9752e640b7c4eeb01471ebbfe8e03b85", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 72, "avg_line_length": 20.5, "alnum_prop": 0.7276422764227642, "repo_name": "patorash/rails_template", "id": "e9c196d717d61deb7bf5c483179f48985599338f", "size": "262", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/features/home_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "11535" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Trans. Wis. Acad. Sci. Arts Lett. 19(2): 668 (1919) #### Original name Ascochyta saniculae Davis ### Remarks null
{ "content_hash": "459c8b0b6c44962d5e0673153ab4c961", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 51, "avg_line_length": 13.615384615384615, "alnum_prop": 0.6892655367231638, "repo_name": "mdoering/backbone", "id": "cb615a3f4e8c44b2a834abf848970ec2504e9f25", "size": "247", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Ascochyta/Ascochyta thaspii/Ascochyta thaspii saniculae/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System.Configuration; using System.IO; namespace ZBuildLights.Core.Configuration { public class ApplicationConfiguration : IApplicationConfiguration { public string StorageFilePath { get { var value = Required("StorageFilePath"); var fullPath = Path.GetFullPath(value); return fullPath; } } private string Required(string key) { var value = ConfigurationManager.AppSettings[key]; if (string.IsNullOrEmpty(value)) throw new ConfigurationErrorsException(string.Format("AppSetting {0} is required.", key)); return value; } } }
{ "content_hash": "f3594d1ca49c427be461e3f794f3809a", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 106, "avg_line_length": 28, "alnum_prop": 0.5796703296703297, "repo_name": "Vector241-Eric/ZBuildLights", "id": "7f23bac5eb38fd5e645697fa895cec250f49c54f", "size": "730", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/ZBuildLights.Core/Configuration/ApplicationConfiguration.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "107" }, { "name": "Batchfile", "bytes": "306" }, { "name": "C#", "bytes": "349894" }, { "name": "CSS", "bytes": "767" }, { "name": "HTML", "bytes": "5127" }, { "name": "JavaScript", "bytes": "82442" }, { "name": "PowerShell", "bytes": "4692" } ], "symlink_target": "" }
package com.adaptris.http; /** * <p> * Root of all custom <code>Exception</code>s in the <code>http</code> package * and sub-packages. * </p> */ public class HttpException extends Exception { /** * <code>serialVersionUID</code> */ private static final long serialVersionUID = -2006020601L; /** * <p> * Creates a new instance. * </p> */ public HttpException() { } /** * <p> * Creates a new instance with a reference to a previous * <code>Throwable</code>. * </p> * @param cause a previous, causal <code>Throwable</code> */ public HttpException(Throwable cause) { super(cause); } /** * <p> * Creates a new instance with a description of the <code>Exception</code>. * </p> * @param description description of the <code>Exception</code> */ public HttpException(String description) { super(description); } /** * <p> * Creates a new instance with a reference to a previous * <code>Throwable</code> and a description of the <code>Exception</code>. * </p> * @param description of the <code>Exception</code> * @param cause previous <code>Throwable</code> */ public HttpException(String description, Throwable cause) { super(description, cause); } }
{ "content_hash": "7ca1fc23543eae7a295c12cc336d9193", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 78, "avg_line_length": 20.78688524590164, "alnum_prop": 0.6309148264984227, "repo_name": "mcwarman/interlok", "id": "ec64e9e3827ccd2e4edced77208cdb04813a3bec", "size": "1866", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "adapter/src/test/java/com/adaptris/http/HttpException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "14797" }, { "name": "Java", "bytes": "9045936" }, { "name": "SQLPL", "bytes": "12123" }, { "name": "XSLT", "bytes": "98810" } ], "symlink_target": "" }
using System.Collections; using Game; using Game.Enums; using Photon; using Photon.Enums; using UnityEngine; namespace Mod.Interface { public class CreateRoom : Gui { private readonly SimpleAES _aes; private Texture2D _background; private Texture2D _selectedNormal; private Texture2D _selectedHover; private Texture2D _selectedActive; private Texture2D _normal; private Texture2D _hover; private Texture2D _active; private GUIStyle _textField; private GUIStyle _label; private GUIStyle _button; private GUIStyle _buttonSelected; private const float Width = 1280; private const float Height = 720; private float _width; private float _height; private bool _isSingleplayer; private bool _animationDone; public CreateRoom() { _aes = new SimpleAES(); } protected override void OnShow() { _background = Texture(255, 255, 255, 63); _selectedNormal = Texture(230, 230, 230, 160); _selectedHover = Texture(230, 230, 230, 200); _selectedActive = Texture(230, 230, 230); _normal = Texture(200, 200, 200, 69); _hover = Texture(200, 200, 200, 120); _active = Texture(200, 200, 200); _label = new GUIStyle { alignment = TextAnchor.MiddleRight, fontSize = 22, }; _button = new GUIStyle { normal = {background = _normal}, active = {background = _active}, hover = {background = _hover}, alignment = TextAnchor.MiddleCenter, fontSize = 24 }; _buttonSelected = new GUIStyle(_button) { normal = {background = _selectedNormal}, hover = {background = _selectedHover}, active = {background = _selectedActive} }; _textField = new GUIStyle { normal = { textColor = UnityEngine.Color.white }, alignment = TextAnchor.MiddleLeft, fontSize = 22, }; _animationDone = false; _width = 0f; _height = 0f; } private void Animation() { if (_width < Width || _height < Height) { const float changeInValue = 1.5f; const float slowdown = 0.5f; _width += (Width * changeInValue - _width * slowdown) * Time.deltaTime; _height += (Height * changeInValue - _height * slowdown) * Time.deltaTime; if (_width < Width && _height < Height) return; _animationDone = true; _width = Width; _height = Height; } } private static int CustomButton(Rect rect, string txt, GUIStyle style) { GUI.DrawTexture(rect, style.normal.background); GUI.Label(rect, txt, style); Vector3 pos = Input.mousePosition; pos.y = -(pos.y - Screen.height + 1); if (!rect.Contains(new Vector2(pos.x, pos.y))) return 0; if (Event.current.type == EventType.MouseUp) { switch (Event.current.button) { case 0: GUI.DrawTexture(rect, style.active.background); GUI.Label(rect, txt, style); return 1; case 1: GUI.DrawTexture(rect, style.active.background); GUI.Label(rect, txt, style); return -1; } } GUI.DrawTexture(rect, style.hover.background); GUI.Label(rect, txt, style); return 0; } private string roomName = "Room name"; private string roomCharacter = "LEVI"; //TODO: Character customization private string roomPassword = string.Empty; private int roomMapIndex = 1; private string roomMaxPlayers = "10"; private string roomTime = "99999"; private int roomDifficultySingle; private string roomDifficulty; private Daylight _roomDaylight = Daylight.Day; private bool roomOpen = true; private bool roomVisible = true; protected override void Render() { Rect rect; GUI.DrawTexture(rect = new Rect(Screen.width / 2f - _width/2, Screen.height / 2f - _height/2, _width, _height), _background); Animation(); if (!_animationDone) return; if (GUI.Button(new Rect(rect.x + rect.width / 2f - 150, rect.y + 50, 100, 40), "Online", _isSingleplayer ? _button : _buttonSelected)) _isSingleplayer = false; if (GUI.Button(new Rect(rect.x + rect.width / 2f + 50, rect.y + 50, 100, 40), "Offline", !_isSingleplayer ? _button : _buttonSelected)) _isSingleplayer = true; if (_isSingleplayer) SingleplayerUI(new Rect(rect.x + rect.width / 100f * 10, rect.y + 120f, rect.width - rect.width / 100f * 20, rect.height - 200f)); else MultiplayerUI(new Rect(rect.x + rect.width / 100f * 10, rect.y + 120f, rect.width - rect.width / 100f * 20, rect.height - 200f)); } private void SingleplayerUI(Rect areaRect) { GUI.DrawTexture(new Rect(areaRect.x + areaRect.width / 2f - 1, areaRect.y, 2, 160), _hover); SmartRect rect = new SmartRect(areaRect.x, areaRect.y, areaRect.width / 2f - 20, 30); GUI.Label(rect, "Character", _label); GUI.Label(rect.TranslateY(rect.Height + 3), "Map", _label); GUI.Label(rect.TranslateY(rect.Height + 3), "Time", _label); GUI.Label(rect.TranslateY(rect.Height + 3), "Difficulty", _label); GUI.Label(rect.TranslateY(rect.Height + 3), "Daylight", _label); rect = new SmartRect(areaRect.x + areaRect.width / 2f + 20, areaRect.y, areaRect.width / 2f - 20, 30); roomCharacter = GUI.TextField(rect, roomCharacter, _textField); switch (CustomButton(rect.TranslateY(rect.Height + 3), LevelInfoManager.Levels[roomMapIndex].Name, _button)) { case 1: roomMapIndex = LevelInfoManager.Levels.Length - 1 == roomMapIndex ? 0 : roomMapIndex + 1; break; case -1: roomMapIndex = roomMapIndex == 0 ? LevelInfoManager.Levels.Length - 1 : roomMapIndex - 1; break; } roomTime = GUI.TextField(rect.TranslateY(rect.Height + 3), roomTime, _textField); rect.TranslateY(rect.Height + 3); if (GUI.Button(new Rect(rect.X, rect.Y, rect.Width / 3 - 20, rect.Height), "Easy", roomDifficultySingle == 0 ? _buttonSelected : _button)) roomDifficultySingle = 0; if (GUI.Button(new Rect(rect.X + rect.Width / 3 + 10, rect.Y, rect.Width / 3 - 20, rect.Height), "Normal", roomDifficultySingle == 1 ? _buttonSelected : _button)) roomDifficultySingle = 1; if (GUI.Button(new Rect(rect.X + rect.Width / 3 * 2 + 20, rect.Y, rect.Width / 3 - 20, rect.Height), "Hard", roomDifficultySingle == 2 ? _buttonSelected : _button)) roomDifficultySingle = 2; rect.TranslateY(rect.Height + 3); if (GUI.Button(new Rect(rect.X, rect.Y, rect.Width / 3 - 20, rect.Height), "Day", _roomDaylight == Daylight.Day ? _buttonSelected : _button)) _roomDaylight = Daylight.Day; if (GUI.Button(new Rect(rect.X + rect.Width / 3 + 10, rect.Y, rect.Width / 3 - 20, rect.Height), "Dawn", _roomDaylight == Daylight.Dawn ? _buttonSelected : _button)) _roomDaylight = Daylight.Dawn; if (GUI.Button(new Rect(rect.X + rect.Width / 3 * 2 + 20, rect.Y, rect.Width / 3 - 20, rect.Height), "Night", _roomDaylight == Daylight.Night ? _buttonSelected : _button)) _roomDaylight = Daylight.Night; if (GUI.Button(new Rect(areaRect.x + areaRect.width / 2f - 100f, areaRect.y + areaRect.height - 90f, 200f, 70f), "Play", _button)) { PhotonNetwork.Disconnect(); IN_GAME_MAIN_CAMERA.GameType = GameType.Singleplayer; IN_GAME_MAIN_CAMERA.singleCharacter = roomCharacter.ToUpper(); IN_GAME_MAIN_CAMERA.difficulty = roomDifficultySingle; if (IN_GAME_MAIN_CAMERA.cameraMode == CameraType.TPS) Screen.lockCursor = true; Screen.showCursor = false; // if (LevelInfoManager.Levels[roomMapIndex].Map == "trainning_0") Does not exist in LevelInfoManager TODO: Check why // IN_GAME_MAIN_CAMERA.difficulty = -1; GameManager.Level = LevelInfoManager.Levels[roomMapIndex].Name; Application.LoadLevel(LevelInfoManager.Levels[roomMapIndex].LevelName); Shelter.OnJoinedGame(); } } private void MultiplayerUI(Rect areaRect) { GUI.DrawTexture(new Rect(areaRect.x + areaRect.width / 2f - 1, areaRect.y, 2, 300), _hover); SmartRect rect = new SmartRect(areaRect.x, areaRect.y, areaRect.width / 2f - 20, 30); GUI.Label(rect , "Name", _label); GUI.Label(rect.TranslateY(rect.Height + 3), "Password", _label); GUI.Label(rect.TranslateY(rect.Height + 3), "Map", _label); GUI.Label(rect.TranslateY(rect.Height + 3), "Players", _label); GUI.Label(rect.TranslateY(rect.Height + 3), "Time", _label); GUI.Label(rect.TranslateY(rect.Height + 3), "Difficulty", _label); GUI.Label(rect.TranslateY(rect.Height + 3), "Daylight", _label); GUI.Label(rect.TranslateY(rect.Height + 3), "Open", _label); GUI.Label(rect.TranslateY(rect.Height + 3), "Visible", _label); rect = new SmartRect(areaRect.x + areaRect.width / 2f + 20, areaRect.y, areaRect.width / 2f - 20, 30); roomName = GUI.TextField(rect, roomName, _textField); roomPassword = GUI.TextField(rect.TranslateY(rect.Height + 3), roomPassword, _textField); switch (CustomButton(rect.TranslateY(rect.Height + 3), LevelInfoManager.Levels[roomMapIndex].Name + " " + roomMapIndex, _button)) { case 1: roomMapIndex = LevelInfoManager.Levels.Length - 1 == roomMapIndex ? 0 : roomMapIndex + 1; break; case -1: roomMapIndex = roomMapIndex == 0 ? LevelInfoManager.Levels.Length - 1 : roomMapIndex - 1; break; } roomMaxPlayers = GUI.TextField(rect = rect.TranslateY(rect.Height + 3), roomMaxPlayers, _textField); roomTime = GUI.TextField(rect.TranslateY(rect.Height + 3), roomTime, _textField); rect.TranslateY(rect.Height + 3); if (GUI.Button(new Rect(rect.X, rect.Y, rect.Width / 3 - 20, rect.Height), "Easy", roomDifficulty == "easy" ? _buttonSelected : _button)) roomDifficulty = "easy"; if (GUI.Button(new Rect(rect.X + rect.Width / 3 + 10, rect.Y, rect.Width / 3 - 20, rect.Height), "Normal", roomDifficulty == "normal" ? _buttonSelected : _button)) roomDifficulty = "normal"; if (GUI.Button(new Rect(rect.X + rect.Width / 3 * 2 + 20, rect.Y, rect.Width / 3 - 20, rect.Height), "Hard", roomDifficulty == "hard" ? _buttonSelected : _button)) roomDifficulty = "hard"; rect.TranslateY(rect.Height + 3); if (GUI.Button(new Rect(rect.X, rect.Y, rect.Width / 3 - 20, rect.Height), "Day", _roomDaylight == Daylight.Day ? _buttonSelected : _button)) _roomDaylight = Daylight.Day; if (GUI.Button(new Rect(rect.X + rect.Width / 3 + 10, rect.Y, rect.Width / 3 - 20, rect.Height), "Dawn", _roomDaylight == Daylight.Dawn ? _buttonSelected : _button)) _roomDaylight = Daylight.Dawn; if (GUI.Button(new Rect(rect.X + rect.Width / 3 * 2 + 20, rect.Y, rect.Width / 3 - 20, rect.Height), "Night", _roomDaylight == Daylight.Night ? _buttonSelected : _button)) _roomDaylight = Daylight.Night; if (GUI.Button(rect = rect.TranslateY(rect.Height + 3), roomOpen.ToString(), _button)) roomOpen = !roomOpen; if (GUI.Button(new Rect(rect.X, rect.Y + rect.Height + 3, rect.Width, rect.Height), roomVisible.ToString(), _button)) roomVisible = !roomVisible; if (GUI.Button(new Rect(areaRect.x + areaRect.width / 2f - 100f, areaRect.y + areaRect.height - 90f, 200f, 70f), !isRunning ? "Play" : "Connecting", _button) && !isRunning) //FIXME: Possible to click while joining the game. StartCoroutine(AwaitConnect()); } private bool isRunning; private IEnumerator AwaitConnect() { isRunning = true; while (PhotonNetwork.connectionStatesDetailed != ClientState.JoinedLobby && PhotonNetwork.connectionStatesDetailed != ClientState.Joined) yield return null; string roomFullName = $"{roomName}`{LevelInfoManager.Levels[roomMapIndex].Name}`{roomDifficulty}`{roomMaxPlayers}`{_roomDaylight}`{(roomPassword != string.Empty ? _aes.Encrypt(roomPassword) : roomPassword)}`{roomTime}"; PhotonNetwork.CreateRoom(roomFullName, roomVisible, roomOpen, roomMaxPlayers.ToInt()); isRunning = false; } protected override void OnHide() { // aes.Dispose(); Destroy(_background); Destroy(_normal); Destroy(_hover); Destroy(_active); Destroy(_selectedNormal); Destroy(_selectedActive); Destroy(_selectedHover); } } }
{ "content_hash": "31ba9def4febc283b57846c7dad106e1", "timestamp": "", "source": "github", "line_count": 290, "max_line_length": 235, "avg_line_length": 49.56896551724138, "alnum_prop": 0.5538086956521739, "repo_name": "ITALIA195/Shelter", "id": "2fe1a2be3c783b3379e21899e89a75350933d357", "size": "14377", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Shelter/Mod/Interface/CreateRoom.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "2724106" } ], "symlink_target": "" }
#include <unistd.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/ioctl.h> #include <cutils/properties.h> #include <utils/RefBase.h> #include <linux/android_pmem.h> #include "gr.h" #include "gpu.h" #include "memalloc.h" #include "alloc_controller.h" using namespace gralloc; using android::sp; int fb_device_open(const hw_module_t* module, const char* name, hw_device_t** device); static int gralloc_device_open(const hw_module_t* module, const char* name, hw_device_t** device); extern int gralloc_lock(gralloc_module_t const* module, buffer_handle_t handle, int usage, int l, int t, int w, int h, void** vaddr); extern int gralloc_unlock(gralloc_module_t const* module, buffer_handle_t handle); extern int gralloc_register_buffer(gralloc_module_t const* module, buffer_handle_t handle); extern int gralloc_unregister_buffer(gralloc_module_t const* module, buffer_handle_t handle); extern int gralloc_perform(struct gralloc_module_t const* module, int operation, ... ); // HAL module methods static struct hw_module_methods_t gralloc_module_methods = { open: gralloc_device_open }; // HAL module initialize struct private_module_t HAL_MODULE_INFO_SYM = { base: { common: { tag: HARDWARE_MODULE_TAG, version_major: 1, version_minor: 0, id: GRALLOC_HARDWARE_MODULE_ID, name: "Graphics Memory Allocator Module", author: "The Android Open Source Project", methods: &gralloc_module_methods, dso: 0, reserved: {0}, }, registerBuffer: gralloc_register_buffer, unregisterBuffer: gralloc_unregister_buffer, lock: gralloc_lock, unlock: gralloc_unlock, perform: gralloc_perform, reserved_proc: {0}, }, framebuffer: 0, fbFormat: 0, flags: 0, numBuffers: 0, bufferMask: 0, lock: PTHREAD_MUTEX_INITIALIZER, currentBuffer: 0, }; // Open Gralloc device int gralloc_device_open(const hw_module_t* module, const char* name, hw_device_t** device) { int status = -EINVAL; if (!strcmp(name, GRALLOC_HARDWARE_GPU0)) { const private_module_t* m = reinterpret_cast<const private_module_t*>( module); gpu_context_t *dev; sp<IAllocController> alloc_ctrl = IAllocController::getInstance(true); dev = new gpu_context_t(m, alloc_ctrl); *device = &dev->common; status = 0; } else { status = fb_device_open(module, name, device); } return status; }
{ "content_hash": "f5f4277a17532ac12bc3e8ba2bed5a62", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 78, "avg_line_length": 27.275510204081634, "alnum_prop": 0.6318742985409652, "repo_name": "Zuli/device_sony_lt28", "id": "a98baf8a8aa117e6de746e756bf7b7668ac7e693", "size": "3356", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "display/libgralloc/gralloc.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3879916" }, { "name": "C++", "bytes": "4042146" }, { "name": "Makefile", "bytes": "144410" }, { "name": "Objective-C", "bytes": "2309" }, { "name": "Shell", "bytes": "1240" } ], "symlink_target": "" }
package com.swrve.sdk.rest; import java.io.UnsupportedEncodingException; import java.util.Map; /** * Used internally to define a REST client. */ public interface IRESTClient { void get(String endpoint, IRESTResponseListener callback); void get(String endpoint, Map<String, String> params, IRESTResponseListener callback) throws UnsupportedEncodingException; void post(String endpoint, String encodedBody, IRESTResponseListener callback); void post(String endpoint, String encodedBody, IRESTResponseListener callback, String contentType); }
{ "content_hash": "5974cd02a5d1e7d70d2e9d807e6c314c", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 126, "avg_line_length": 33.11764705882353, "alnum_prop": 0.7921847246891652, "repo_name": "leandroz/cordova-swrve", "id": "51ad9deaa1747b17f37b754e095205f6f7a8b30f", "size": "563", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/android/Swrve_Android_SDK/SwrveCommonSDK/src/main/java/com/swrve/sdk/rest/IRESTClient.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "353" }, { "name": "Java", "bytes": "322589" }, { "name": "JavaScript", "bytes": "480" }, { "name": "Objective-C", "bytes": "348817" }, { "name": "Ruby", "bytes": "709" } ], "symlink_target": "" }
{% macro dev_heading(webapp, mkt) %} <h3> {% set details_complete = webapp.details_complete() %} {% if details_complete %}<a href="{{ webapp.get_dev_url() }}">{% endif %} <img class="icon" src="{{ webapp.get_icon_url(64) }}"> {{ webapp.name }}{% if details_complete %}</a>{% endif %} </h3> {% endmacro %}
{ "content_hash": "b604f527c08f0876598d158e33c36381", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 77, "avg_line_length": 40.625, "alnum_prop": 0.563076923076923, "repo_name": "shahbaz17/zamboni", "id": "f66e3b08610fb876df3126cb6e226bf0323175ba", "size": "325", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mkt/developers/templates/developers/apps/listing/macros.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "357511" }, { "name": "HTML", "bytes": "2331440" }, { "name": "JavaScript", "bytes": "536153" }, { "name": "Makefile", "bytes": "4281" }, { "name": "Python", "bytes": "4400945" }, { "name": "Shell", "bytes": "11200" }, { "name": "Smarty", "bytes": "1159" } ], "symlink_target": "" }
using System; using System.Text; using System.Security.Permissions; using System.Runtime.Serialization; using OpenADK.Library; using OpenADK.Library.Global; using OpenADK.Library.us.Common; namespace OpenADK.Library.us.Instr{ /// <summary>A StandardSettingBody</summary> /// <remarks> /// /// <para>Author: Generated by adkgen</para> /// <para>Version: 2.6</para> /// <para>Since: 2.2</para> /// </remarks> [Serializable] public class StandardSettingBody : SifKeyedElement { /// <summary> /// Creates an instance of a StandardSettingBody /// </summary> public StandardSettingBody() : base ( InstrDTD.STANDARDSETTINGBODY ){} /// <summary> /// Constructor that accepts values for all mandatory fields /// </summary> ///<param name="country">The country of the standard setting body.</param> /// public StandardSettingBody( CountryCode country ) : base( InstrDTD.STANDARDSETTINGBODY ) { this.SetCountry( country ); } /// <summary> /// Constructor used by the .Net Serialization formatter /// </summary> [SecurityPermission( SecurityAction.Demand, SerializationFormatter=true )] protected StandardSettingBody( SerializationInfo info, StreamingContext context ) : base( info, context ) {} /// <summary> /// Gets the metadata fields that make up the key of this object /// </summary> /// <value> /// an array of metadata fields that make up the object's key /// </value> public override IElementDef[] KeyFields { get { return new IElementDef[] { InstrDTD.STANDARDSETTINGBODY_COUNTRY }; } } /// <summary> /// Gets or sets the value of the <c>&lt;Country&gt;</c> element. /// </summary> /// <value> The <c>Country</c> element of this object.</value> /// <remarks> /// <para>The SIF specification defines the meaning of this element as: "The country of the standard setting body."</para> /// <para>Version: 2.6</para> /// <para>Since: 2.2</para> /// </remarks> public string Country { get { return GetFieldValue( InstrDTD.STANDARDSETTINGBODY_COUNTRY ); } set { SetField( InstrDTD.STANDARDSETTINGBODY_COUNTRY, value ); } } /// <summary> /// Sets the value of the <c>&lt;Country&gt;</c> element. /// </summary> /// <param name="val">A CountryCode object</param> /// <remarks> /// <para>The SIF specification defines the meaning of this element as: "The country of the standard setting body."</para> /// <para>Version: 2.6</para> /// <para>Since: 2.2</para> /// </remarks> public void SetCountry( CountryCode val ) { SetField( InstrDTD.STANDARDSETTINGBODY_COUNTRY, val ); } /// <summary> /// Gets or sets the value of the <c>&lt;StateProvince&gt;</c> element. /// </summary> /// <value> The <c>StateProvince</c> element of this object.</value> /// <remarks> /// <para>The SIF specification defines the meaning of this element as: "The state or province of the standard setting body. "</para> /// <para>Version: 2.6</para> /// <para>Since: 2.2</para> /// </remarks> public string StateProvince { get { return GetFieldValue( InstrDTD.STANDARDSETTINGBODY_STATEPROVINCE ); } set { SetField( InstrDTD.STANDARDSETTINGBODY_STATEPROVINCE, value ); } } /// <summary> /// Sets the value of the <c>&lt;StateProvince&gt;</c> element. /// </summary> /// <param name="val">A StatePrCode object</param> /// <remarks> /// <para>The SIF specification defines the meaning of this element as: "The state or province of the standard setting body. "</para> /// <para>Version: 2.6</para> /// <para>Since: 2.2</para> /// </remarks> public void SetStateProvince( StatePrCode val ) { SetField( InstrDTD.STANDARDSETTINGBODY_STATEPROVINCE, val ); } /// <summary> /// Gets or sets the value of the <c>&lt;NCESId&gt;</c> element. /// </summary> /// <value> The <c>NCESId</c> element of this object.</value> /// <remarks> /// <para>The SIF specification defines the meaning of this element as: "National Center for Education Statistics Id. "</para> /// <para>Version: 2.6</para> /// <para>Since: 2.2</para> /// </remarks> public string NCESId { get { return (string) GetSifSimpleFieldValue( InstrDTD.STANDARDSETTINGBODY_NCESID ) ; } set { SetFieldValue( InstrDTD.STANDARDSETTINGBODY_NCESID, new SifString( value ), value ); } } /// <summary> /// Gets or sets the value of the <c>&lt;SettingBodyName&gt;</c> element. /// </summary> /// <value> The <c>SettingBodyName</c> element of this object.</value> /// <remarks> /// <para>The SIF specification defines the meaning of this element as: "This is the text version of the organization's name."</para> /// <para>Version: 2.6</para> /// <para>Since: 2.2</para> /// </remarks> public string SettingBodyName { get { return (string) GetSifSimpleFieldValue( InstrDTD.STANDARDSETTINGBODY_SETTINGBODYNAME ) ; } set { SetFieldValue( InstrDTD.STANDARDSETTINGBODY_SETTINGBODYNAME, new SifString( value ), value ); } } }}
{ "content_hash": "7fa90beb1e4e7c95bb44c9fdce96dd5f", "timestamp": "", "source": "github", "line_count": 163, "max_line_length": 134, "avg_line_length": 30.116564417177916, "alnum_prop": 0.6801792625789367, "repo_name": "open-adk/OpenADK-csharp", "id": "1b6e16524112b873b095dd4f0b8df2f7563489ff", "size": "5072", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/us/sdo/Instr/StandardSettingBody.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "16903092" } ], "symlink_target": "" }
#ifndef QKBDVFB_QWS_H #define QKBDVFB_QWS_H #include <QtGui/qkbd_qws.h> QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Gui) #ifndef QT_NO_QWS_KEYBOARD #ifndef QT_NO_QWS_KBD_QVFB class QSocketNotifier; class QVFbKeyboardHandler : public QObject, public QWSKeyboardHandler { Q_OBJECT public: QVFbKeyboardHandler(const QString &device); virtual ~QVFbKeyboardHandler(); private Q_SLOTS: void readKeyboardData(); private: QString terminalName; int kbdFD; int kbdIdx; int kbdBufferLen; unsigned char *kbdBuffer; QSocketNotifier *notifier; }; #endif // QT_NO_QWS_KBD_QVFB #endif // QT_NO_QWS_KEYBOARD QT_END_NAMESPACE QT_END_HEADER #endif // QKBDVFB_QWS_H
{ "content_hash": "87fa41d7dd4e59b88404bfe4c7497854", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 69, "avg_line_length": 14.97872340425532, "alnum_prop": 0.7201704545454546, "repo_name": "kzhong1991/Flight-AR.Drone-2", "id": "509955ab10bd35a1a36ec285f7a6c03baa8e26ec", "size": "2670", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/3rdparty/Qt4.8.4/src/gui/embedded/qkbdvfb_qws.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "8366" }, { "name": "C++", "bytes": "172001" }, { "name": "Objective-C", "bytes": "7651" }, { "name": "QMake", "bytes": "1293" } ], "symlink_target": "" }
package io.cattle.platform.iaas.api.auth.github; import io.github.ibuildthecloud.gdapi.annotation.Field; import io.github.ibuildthecloud.gdapi.annotation.Type; @Type(name = "token") public class Token { private final String jwt; private String code; public Token(String jwt) { this.jwt = jwt; } public String getJwt() { return jwt; } public void setCode(String code) { this.code = code; } @Field(required = true) public String getCode() { return code; } }
{ "content_hash": "6e3bcd0b872d089c6f4369d16eca1379", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 55, "avg_line_length": 18.620689655172413, "alnum_prop": 0.6370370370370371, "repo_name": "alena1108/cattle", "id": "78a78012a091adb5c36ae4890c3a38d27bfe44a8", "size": "540", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code/iaas/api-logic/src/main/java/io/cattle/platform/iaas/api/auth/github/Token.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "3287143" }, { "name": "Makefile", "bytes": "6771" }, { "name": "Python", "bytes": "193716" }, { "name": "Shell", "bytes": "54068" } ], "symlink_target": "" }
import { Events24 } from "../../"; export = Events24;
{ "content_hash": "e6c748026f2c108ad5881250733bfdf0", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 34, "avg_line_length": 18.333333333333332, "alnum_prop": 0.5818181818181818, "repo_name": "markogresak/DefinitelyTyped", "id": "ea5ef16f9ced006509cd57ae72af0f331ab49bde", "size": "55", "binary": false, "copies": "20", "ref": "refs/heads/master", "path": "types/carbon__icons-react/lib/events/24.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "15" }, { "name": "Protocol Buffer", "bytes": "678" }, { "name": "TypeScript", "bytes": "17426898" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name Hepetis multiramosa Mez ### Remarks null
{ "content_hash": "58280e7f7d224608840c250efe1c1c41", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 11.76923076923077, "alnum_prop": 0.7189542483660131, "repo_name": "mdoering/backbone", "id": "93ababbf5ed883a3b3c0b87b90eca15fc1297c5a", "size": "209", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Bromeliaceae/Pitcairnia/Pitcairnia multiramosa/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.19: https://docutils.sourceforge.io/" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="_static/stylesheets/application.css"/> <link rel="stylesheet" href="_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="_static/javascripts/modernizr.js"></script> <title>About statsmodels &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="_static/icons/favicon-16x16.png"> <link rel="manifest" href="_static/icons/site.webmanifest"> <link rel="mask-icon" href="_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="_static/icons/browserconfig.xml"> <link rel="stylesheet" href="_static/stylesheets/examples.css"> <link rel="stylesheet" href="_static/stylesheets/deprecation.css"> <link rel="stylesheet" type="text/css" href="_static/pygments.css" /> <link rel="stylesheet" type="text/css" href="_static/material.css" /> <link rel="stylesheet" type="text/css" href="_static/graphviz.css" /> <link rel="stylesheet" type="text/css" href="_static/plot_directive.css" /> <script data-url_root="./" id="documentation_options" src="_static/documentation_options.js"></script> <script src="_static/jquery.js"></script> <script src="_static/underscore.js"></script> <script src="_static/_sphinx_javascript_frameworks_compat.js"></script> <script src="_static/doctools.js"></script> <script src="_static/sphinx_highlight.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <link rel="shortcut icon" href="_static/favicon.ico"/> <link rel="author" title="About these documents" href="#" /> <link rel="index" title="Index" href="genindex.html" /> <link rel="search" title="Search" href="search.html" /> <link rel="next" title="statsmodels.tools.print_version.show_versions" href="generated/statsmodels.tools.print_version.show_versions.html" /> <link rel="prev" title="statsmodels.formula.api.conditional_poisson" href="generated/statsmodels.formula.api.conditional_poisson.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#about" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels 0.14.0 (+596)</span> <span class="md-header-nav__topic"> About statsmodels </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="search.html" method="get" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../versions-v2.json", target_loc = "../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="index.html" title="statsmodels">statsmodels 0.14.0 (+596)</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="user-guide.html" class="md-nav__link">User Guide</a> </li> <li class="md-nav__item"> <a href="examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <input class="md-toggle md-nav__toggle" data-md-toggle="toc" type="checkbox" id="__toc"> <label class="md-nav__link md-nav__link--active" for="__toc"> About statsmodels </label> <a href="#" class="md-nav__link md-nav__link--active">About statsmodels</a> <nav class="md-nav md-nav--secondary"> <label class="md-nav__title" for="__toc">Contents</label> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a href="#about--page-root" class="md-nav__link">About statsmodels</a><nav class="md-nav"> <ul class="md-nav__list"> <li class="md-nav__item"><a href="#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"><a href="#testing" class="md-nav__link">Testing</a><nav class="md-nav"> <ul class="md-nav__list"> <li class="md-nav__item"><a href="#code-stability" class="md-nav__link">Code Stability</a> </li> <li class="md-nav__item"><a href="#reporting-bugs" class="md-nav__link">Reporting Bugs</a> </li></ul> </nav> </li> <li class="md-nav__item"><a href="#financial-support" class="md-nav__link">Financial Support</a> </li> <li class="md-nav__item"><a href="#brand-marks" class="md-nav__link">Brand Marks</a><nav class="md-nav"> <ul class="md-nav__list"> <li class="md-nav__item"><a href="#color" class="md-nav__link">Color</a> </li> <li class="md-nav__item"><a href="#monochrome-dark" class="md-nav__link">Monochrome (Dark)</a> </li> <li class="md-nav__item"><a href="#monochrome-light" class="md-nav__link">Monochrome (Light)</a> </li></ul> </nav> </li></ul> </nav> </li> <li class="md-nav__item"><a class="md-nav__extra_link" href="_sources/about.rst.txt">Show Source</a> </li> </ul> </nav> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="#testing" class="md-nav__link">Testing</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="#code-stability" class="md-nav__link">Code Stability</a> </li> <li class="md-nav__item"> <a href="#reporting-bugs" class="md-nav__link">Reporting Bugs</a> </li></ul> </li> <li class="md-nav__item"> <a href="#financial-support" class="md-nav__link">Financial Support</a> </li> <li class="md-nav__item"> <a href="#brand-marks" class="md-nav__link">Brand Marks</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="#color" class="md-nav__link">Color</a> </li> <li class="md-nav__item"> <a href="#monochrome-dark" class="md-nav__link">Monochrome (Dark)</a> </li> <li class="md-nav__item"> <a href="#monochrome-light" class="md-nav__link">Monochrome (Light)</a> </li></ul> </li></ul> </li> <li class="md-nav__item"> <a href="dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <label class="md-nav__title" for="__toc">Contents</label> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a href="#about--page-root" class="md-nav__link">About statsmodels</a><nav class="md-nav"> <ul class="md-nav__list"> <li class="md-nav__item"><a href="#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"><a href="#testing" class="md-nav__link">Testing</a><nav class="md-nav"> <ul class="md-nav__list"> <li class="md-nav__item"><a href="#code-stability" class="md-nav__link">Code Stability</a> </li> <li class="md-nav__item"><a href="#reporting-bugs" class="md-nav__link">Reporting Bugs</a> </li></ul> </nav> </li> <li class="md-nav__item"><a href="#financial-support" class="md-nav__link">Financial Support</a> </li> <li class="md-nav__item"><a href="#brand-marks" class="md-nav__link">Brand Marks</a><nav class="md-nav"> <ul class="md-nav__list"> <li class="md-nav__item"><a href="#color" class="md-nav__link">Color</a> </li> <li class="md-nav__item"><a href="#monochrome-dark" class="md-nav__link">Monochrome (Dark)</a> </li> <li class="md-nav__item"><a href="#monochrome-light" class="md-nav__link">Monochrome (Light)</a> </li></ul> </nav> </li></ul> </nav> </li> <li class="md-nav__item"><a class="md-nav__extra_link" href="_sources/about.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <span class="target" id="module-statsmodels"></span><section id="about-statsmodels"> <h1 id="about--page-root">About statsmodels<a class="headerlink" href="#about--page-root" title="Permalink to this heading">¶</a></h1> <section id="background"> <h2 id="background">Background<a class="headerlink" href="#background" title="Permalink to this heading">¶</a></h2> <p>The <code class="docutils literal notranslate"><span class="pre">models</span></code> module of <code class="docutils literal notranslate"><span class="pre">scipy.stats</span></code> was originally written by Jonathan Taylor. For some time it was part of scipy but was later removed. During the Google Summer of Code 2009, <code class="docutils literal notranslate"><span class="pre">statsmodels</span></code> was corrected, tested, improved and released as a new package. Since then, the statsmodels development team has continued to add new models, plotting tools, and statistical methods.</p> </section> <section id="testing"> <h2 id="testing">Testing<a class="headerlink" href="#testing" title="Permalink to this heading">¶</a></h2> <p>Most results have been verified with at least one other statistical package: R, Stata or SAS. The guiding principle for the initial rewrite and for continued development is that all numbers have to be verified. Some statistical methods are tested with Monte Carlo studies. While we strive to follow this test-driven approach, there is no guarantee that the code is bug-free and always works. Some auxiliary function are still insufficiently tested, some edge cases might not be correctly taken into account, and the possibility of numerical problems is inherent to many of the statistical models. We especially appreciate any help and reports for these kind of problems so we can keep improving the existing models.</p> <section id="code-stability"> <h3 id="code-stability">Code Stability<a class="headerlink" href="#code-stability" title="Permalink to this heading">¶</a></h3> <p>The existing models are mostly settled in their user interface and we do not expect many large changes going forward. For the existing code, although there is no guarantee yet on API stability, we have long deprecation periods in all but very special cases, and we try to keep changes that require adjustments by existing users to a minimal level. For newer models we might adjust the user interface as we gain more experience and obtain feedback. These changes will always be noted in our release notes available in the documentation.</p> </section> <section id="reporting-bugs"> <h3 id="reporting-bugs">Reporting Bugs<a class="headerlink" href="#reporting-bugs" title="Permalink to this heading">¶</a></h3> <p>If you encounter a bug or an unexpected behavior, please report it on <a class="reference external" href="https://github.com/statsmodels/statsmodels/issues">the issue tracker</a>. Use the <code class="docutils literal notranslate"><span class="pre">show_versions</span></code> command to list the installed versions of statsmodels and its dependencies.</p> <table class="autosummary longtable docutils align-default"> <tbody> <tr class="row-odd"><td><p><a class="reference internal" href="generated/statsmodels.tools.print_version.show_versions.html#statsmodels.tools.print_version.show_versions" title="statsmodels.tools.print_version.show_versions"><code class="xref py py-obj docutils literal notranslate"><span class="pre">show_versions</span></code></a>([show_dirs])</p></td> <td><p>List the versions of statsmodels and any installed dependencies</p></td> </tr> </tbody> </table> </section> </section> <section id="financial-support"> <h2 id="financial-support">Financial Support<a class="headerlink" href="#financial-support" title="Permalink to this heading">¶</a></h2> <p>We are grateful for the financial support that we obtained for the development of statsmodels:</p> <ul class="simple"> <li><p>Google <a class="reference external" href="https://www.google.com/">www.google.com</a> : Google Summer of Code (GSOC) 2009-2017.</p></li> <li><p>AQR <a class="reference external" href="https://www.aqr.com/">www.aqr.com</a> : financial sponsor for the work on Vector Autoregressive Models (VAR) by Wes McKinney</p></li> </ul> <p>We would also like to thank our hosting providers, <a class="reference external" href="https://github.com/">github</a> for the public code repository, <a class="reference external" href="https://www.statsmodels.org/stable/index.html">github.io</a> for hosting our documentation and <a class="reference external" href="https://www.python.org/">python.org</a> for making our downloads available on PyPi.</p> <p>We also thank our current and previous continuous integration providers, <a class="reference external" href="https://azure.microsoft.com/">Azure</a>, <a class="reference external" href="https://travis-ci.org/">Travis CI</a> and <a class="reference external" href="https://ci.appveyor.com">AppVeyor</a> for unit testing, and <a class="reference external" href="https://codecov.io">Codecov</a> and <a class="reference external" href="https://coveralls.io">Coveralls</a> for code coverage.</p> </section> <section id="brand-marks"> <h2 id="brand-marks">Brand Marks<a class="headerlink" href="#brand-marks" title="Permalink to this heading">¶</a></h2> <p>Please make use of the statsmodels logos when preparing demonstrations involving statsmodels code.</p> <section id="color"> <h3 id="color">Color<a class="headerlink" href="#color" title="Permalink to this heading">¶</a></h3> <table> <tbody> <tr class="row-odd"><td><p>Horizontal</p></td> <td><p><a class="reference internal" href="_images/statsmodels-logo-v2-horizontal.svg"><img alt="color-horizontal" src="_images/statsmodels-logo-v2-horizontal.svg" width="50%"/></a></p></td> </tr> <tr class="row-even"><td><p>Vertical</p></td> <td><p><a class="reference internal" href="_images/statsmodels-logo-v2.svg"><img alt="color-vertical" src="_images/statsmodels-logo-v2.svg" width="14%"/></a></p></td> </tr> <tr class="row-odd"><td><p>Logo Only</p></td> <td><p><a class="reference internal" href="_images/statsmodels-logo-v2-no-text.svg"><img alt="color-notext" src="_images/statsmodels-logo-v2-no-text.svg" width="9%"/></a></p></td> </tr> </tbody> </table> </section> <section id="monochrome-dark"> <h3 id="monochrome-dark">Monochrome (Dark)<a class="headerlink" href="#monochrome-dark" title="Permalink to this heading">¶</a></h3> <table> <tbody> <tr class="row-odd"><td><p>Horizontal</p></td> <td><p><a class="reference internal" href="_images/statsmodels-logo-v2-horizontal-dark.svg"><img alt="dark-horizontal" src="_images/statsmodels-logo-v2-horizontal-dark.svg" width="50%"/></a></p></td> </tr> <tr class="row-even"><td><p>Vertical</p></td> <td><p><a class="reference internal" href="_images/statsmodels-logo-v2-dark.svg"><img alt="dark-vertical" src="_images/statsmodels-logo-v2-dark.svg" width="14%"/></a></p></td> </tr> <tr class="row-odd"><td><p>Logo Only</p></td> <td><p><a class="reference internal" href="_images/statsmodels-logo-v2-no-text-dark.svg"><img alt="dark-notext" src="_images/statsmodels-logo-v2-no-text-dark.svg" width="9%"/></a></p></td> </tr> </tbody> </table> </section> <section id="monochrome-light"> <h3 id="monochrome-light">Monochrome (Light)<a class="headerlink" href="#monochrome-light" title="Permalink to this heading">¶</a></h3> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The light brand marks are light grey on transparent, and so are difficult to see on this page. They are intended for use on a dark background.</p> </div> <table> <tbody> <tr class="row-odd"><td><p>Horizontal</p></td> <td><p><a class="reference internal" href="_images/statsmodels-logo-v2-horizontal-light.svg"><img alt="light-horizontal" src="_images/statsmodels-logo-v2-horizontal-light.svg" width="50%"/></a></p></td> </tr> <tr class="row-even"><td><p>Vertical</p></td> <td><p><a class="reference internal" href="_images/statsmodels-logo-v2-light.svg"><img alt="light-vertical" src="_images/statsmodels-logo-v2-light.svg" width="14%"/></a></p></td> </tr> <tr class="row-odd"><td><p>Logo Only</p></td> <td><p><a class="reference internal" href="_images/statsmodels-logo-v2-no-text-light.svg"><img alt="light-notext" src="_images/statsmodels-logo-v2-no-text-light.svg" width="9%"/></a></p></td> </tr> </tbody> </table> </section> </section> </section> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="generated/statsmodels.formula.api.conditional_poisson.html" title="statsmodels.formula.api.conditional_poisson" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.formula.api.conditional_poisson </span> </div> </a> <a href="generated/statsmodels.tools.print_version.show_versions.html" title="statsmodels.tools.print_version.show_versions" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.tools.print_version.show_versions </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Nov 11, 2022. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 5.3.0. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
{ "content_hash": "a383a77af14521f40562072c2e4903ad", "timestamp": "", "source": "github", "line_count": 618, "max_line_length": 999, "avg_line_length": 43.63915857605178, "alnum_prop": 0.6283881493566688, "repo_name": "statsmodels/statsmodels.github.io", "id": "21f0c7871b8d9e680517d897d9764c1c5ae4f37d", "size": "26981", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "devel/about.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Owl Carousel - Images Demo</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="jQuery Responsive Carousel - Owl Carusel"> <meta name="author" content="Bartosz Wojciechowski"> <link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,400,300,600,700' rel='stylesheet' type='text/css'> <link href="../assets/css/bootstrapTheme.css" rel="stylesheet"> <link href="../assets/css/custom.css" rel="stylesheet"> <!-- Owl Carousel Assets --> <link href="../owl-carousel/owl.carousel.css" rel="stylesheet"> <link href="../owl-carousel/owl.theme.css" rel="stylesheet"> <!-- Prettify --> <link href="../assets/js/google-code-prettify/prettify.css" rel="stylesheet"> <!-- Le fav and touch icons --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png"> <link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png"> <link rel="shortcut icon" href="../assets/ico/favicon.png"> </head> <body> <div id="top-nav" class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container"> <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <div class="nav-collapse collapse"> <ul class="nav pull-right"> <li><a href="../index.html"><i class="icon-chevron-left"></i> Back to Frontpage</a></li> <li><a href="../owl.carousel.zip" class="download download-on" data-spy="affix" data-offset-top="450">Download</a></li> </ul> <ul class="nav pull-left"> </ul> </div> </div> </div> </div> <div id="title"> <div class="container"> <div class="row"> <div class="span12"> <h1>Navigation on top by callback</h1> </div> </div> </div> </div> <div id="demo"> <div class="container"> <div class="row"> <div class="span12"> <div id="owl-demo" class="owl-carousel"> <div class="item"><img src="assets/owl1.jpg" alt="Owl Image"></div> <div class="item"><img src="assets/owl2.jpg" alt="Owl Image"></div> <div class="item"><img src="assets/owl3.jpg" alt="Owl Image"></div> <div class="item"><img src="assets/owl4.jpg" alt="Owl Image"></div> <div class="item"><img src="assets/owl5.jpg" alt="Owl Image"></div> <div class="item"><img src="assets/owl6.jpg" alt="Owl Image"></div> <div class="item"><img src="assets/owl7.jpg" alt="Owl Image"></div> <div class="item"><img src="assets/owl8.jpg" alt="Owl Image"></div> </div> </div> </div> </div> </div> <div id="example-info"> <div class="container"> <div class="row"> <div class="span12"> <h1>Setup</h1> <p>Navigation moved on top by <code>afterInit</code> callback</p> <ul class="nav nav-tabs" id="myTab"> <li class="active"><a href="#javascript">Javascript</a></li> <li><a href="#HTML">HTML</a></li> <li><a href="#CSS">CSS</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="javascript"> <pre class="pre-show prettyprint linenums"> $(document).ready(function() { $("#owl-demo").owlCarousel({ navigation:true, afterInit : function(elem){ var that = this that.owlControls.prependTo(elem) } }); }); </pre> </div> <div class="tab-pane" id="HTML"> <pre class="pre-show prettyprint linenums"> &lt;div id="owl-demo"&gt; &lt;div class="item"&gt;&lt;img src="assets/owl1.jpg" alt="Owl Image"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;img src="assets/owl2.jpg" alt="Owl Image"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;img src="assets/owl3.jpg" alt="Owl Image"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;img src="assets/owl4.jpg" alt="Owl Image"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;img src="assets/owl5.jpg" alt="Owl Image"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;img src="assets/owl6.jpg" alt="Owl Image"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;img src="assets/owl7.jpg" alt="Owl Image"&gt;&lt;/div&gt; &lt;div class="item"&gt;&lt;img src="assets/owl8.jpg" alt="Owl Image"&gt;&lt;/div&gt; &lt;/div&gt; </pre> </div> <div class="tab-pane" id="CSS"> <pre class="pre-show prettyprint linenums"> #owl-demo .item{ margin: 3px; } #owl-demo .item img{ display: block; width: 100%; height: auto; } </pre> </div> </div> <!--End Tab Content--> </div> </div> </div> </div> <div id="more"> <div class="container"> <div class="row"> <div class="span12"> <h1>More Demos</h1> </div> </div> <div class="row demos-row"> <div class="span3"> <a href="images.html" class="demo-box"> <div class="demo-wrapper demo-images clearfix"> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> </div> <h3>Images</h3> </a> </div> <div class="span3"> <a href="custom.html" class="demo-box"> <div class="demo-wrapper demo-custom clearfix"> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> </div> <h3>Custom</h3> </a> </div> <div class="span3"> <a href="itemsCustom.html" class="demo-box"> <div class="demo-wrapper demo-full clearfix"> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> </div> <h3>Custom 2</h3> </a> </div> <div class="span3"> <a href="one.html" class="demo-box"> <div class="demo-wrapper demo-one clearfix"> <div class="demo-slide"> <div class="bg"></div> </div> </div> <h3>One Slide</h3> </a> </div> </div> <div class="row demos-row"> <div class="span3"> <a href="json.html" class="demo-box"> <div class="demo-wrapper demo-Json clearfix"> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> </div> <h3>JSON</h3> </a> </div> <div class="span3"> <a href="customJson.html" class="demo-box"> <div class="demo-wrapper demo-Json-custom clearfix"> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> </div> <h3>JSON Custom</h3> </a> </div> <div class="span3"> <a href="lazyLoad.html" class="demo-box"> <div class="demo-wrapper demo-lazy clearfix"> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> <div class="demo-slide"> <div class="bg"></div> </div> </div> <h3>Lazy Load</h3> </a> </div> <div class="span3"> <a href="autoHeight.html" class="demo-box"> <div class="demo-wrapper demo-height clearfix"> <div class="demo-slide"> <div class="bg"></div> </div> </div> <h3>Auto Height</h3> </a> </div> </div> </div> </div> <div id="footer"> <div class="container"> <div class="row"> <div class="span12"> <h5>Bartosz Wojciechowski 2013 / @OwlFonk / <a href="mailto:owl@owlgraphic.com?subject=Hey Owl!">email</a> / <a href="../changelog.html">changelog</a> / <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=EFSGXZS7V2U9N">donate</a> / <a href="https://twitter.com/share" class="twitter-share-button" data-url="http://owlgraphic.com/owlcarousel/" data-text="Awesome jQuery Owl Carousel Responsive Plugin" data-via="OwlFonk" data-count="none" data-hashtags="owlcarousel"></a> <script> var owldomain = window.location.hostname.indexOf("owlgraphic"); if (owldomain !== -1) { !function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location) ? 'http' : 'https'; if (!d.getElementById(id)) { js = d.createElement(s); js.id = id; js.src = p + '://platform.twitter.com/widgets.js'; fjs.parentNode.insertBefore(js, fjs); } }(document, 'script', 'twitter-wjs'); } </script> </h5> </div> </div> </div> </div> <script src="../assets/js/jquery-1.9.1.min.js"></script> <script src="../owl-carousel/owl.carousel.js"></script> <!-- Demo --> <style> #owl-demo .item { margin: 3px; } #owl-demo .item img { display: block; width: 100%; height: auto; } </style> <script> $(document).ready(function () { $("#owl-demo").owlCarousel({ navigation: true, afterInit: function (elem) { var that = this that.owlControls.prependTo(elem) } }); }); </script> <script src="../assets/js/bootstrap-collapse.js"></script> <script src="../assets/js/bootstrap-transition.js"></script> <script src="../assets/js/bootstrap-tab.js"></script> <script src="../assets/js/google-code-prettify/prettify.js"></script> <script src="../assets/js/application.js"></script> </body> </html>
{ "content_hash": "86ba6d4d451d67ae10cb2a2a5ab8b5c6", "timestamp": "", "source": "github", "line_count": 401, "max_line_length": 125, "avg_line_length": 36.19950124688279, "alnum_prop": 0.4237393221273078, "repo_name": "carlngan/cmp-dmp", "id": "813cc5cce72ff626fc0b34e63984cb4d9dade077", "size": "14516", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "public/vendors/owl-carousel/demos/navOnTop2.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "13820905" }, { "name": "CoffeeScript", "bytes": "12832" }, { "name": "HTML", "bytes": "1371924" }, { "name": "JavaScript", "bytes": "610624" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <?eclipse version="3.4"?> <plugin> <extension id="abaplintBuilder" name="Abaplint Project Builder" point="org.eclipse.core.resources.builders"> <builder hasNature="true"> <run class="org.abaplint.eclipse.builder.AbaplintBuilder"> </run> </builder> </extension> <extension id="abaplintNature" name="Abaplint Project Nature" point="org.eclipse.core.resources.natures"> <runtime> <run class="org.abaplint.eclipse.builder.AbaplintNature"> </run> </runtime> <builder id="org.abaplint.eclipse.abaplintBuilder"> </builder> </extension> <extension point="org.eclipse.ui.commands"> <category name="Abaplint Project Nature commands" id="org.abaplint.eclipse.abaplintNature.category"> </category> <command name="Add/RemoveAbaplint Project Nature" defaultHandler="org.abaplint.eclipse.builder.AddRemoveAbaplintNatureHandler" categoryId="org.abaplint.eclipse.abaplintNature.category" id="org.abaplint.eclipse.addRemoveAbaplintNature"> </command> </extension> <extension point="org.eclipse.ui.menus"> <menuContribution locationURI="popup:org.eclipse.ui.projectConfigure?after=additions"> <command commandId="org.abaplint.eclipse.addRemoveAbaplintNature" label="Disable abaplint" style="push"> <visibleWhen checkEnabled="false"> <with variable="selection"> <count value="1"> </count> <iterate> <adapt type="org.eclipse.core.resources.IProject"> <test value="org.abaplint.eclipse.abaplintNature" property="org.eclipse.core.resources.projectNature"> </test> </adapt> </iterate> </with> </visibleWhen> </command> <command commandId="org.abaplint.eclipse.addRemoveAbaplintNature" label="Enable abaplint" style="push"> <visibleWhen checkEnabled="false"> <with variable="selection"> <count value="1"> </count> <iterate> <adapt type="org.eclipse.core.resources.IProject"> <not> <test value="org.abaplint.eclipse.abaplintNature" property="org.eclipse.core.resources.projectNature"> </test> </not> </adapt> </iterate> </with> </visibleWhen> </command> </menuContribution> </extension> <extension id="abaplintProblem" name="abaplint Problem" point="org.eclipse.core.resources.markers"> <super type="org.eclipse.core.resources.problemmarker"> </super> <persistent value="true"> </persistent> </extension> </plugin>
{ "content_hash": "66303013240ea9f63bc585f573abb443", "timestamp": "", "source": "github", "line_count": 108, "max_line_length": 88, "avg_line_length": 33.06481481481482, "alnum_prop": 0.48249789974796975, "repo_name": "larshp/abaplint-eclipse", "id": "89036dbfcaa8114c5cf4c5a0985e8fd0b4032135", "size": "3571", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "org.abaplint.eclipse/plugin.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "13407" } ], "symlink_target": "" }
<!DOCTYPE html> <!-- | Generated by Apache Maven Doxia Site Renderer 1.7.4 at 2017-09-28 | Rendered using Apache Maven Fluido Skin 1.6 --> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="Date-Revision-yyyymmdd" content="20170928" /> <meta http-equiv="Content-Language" content="en" /> <title>dollar-redis-plugin &#x2013; Developer Activity Report</title> <link rel="stylesheet" href="./css/apache-maven-fluido-1.6.min.css" /> <link rel="stylesheet" href="./css/site.css" /> <link rel="stylesheet" href="./css/print.css" media="print" /> <script type="text/javascript" src="./js/apache-maven-fluido-1.6.min.js"></script> </head> <body class="topBarEnabled"> <a href="https://github.com/neilellis/dollar"> <img style="position: absolute; top: 0; right: 0; border: 0; z-index: 10000;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"> </a> <div id="topbar" class="navbar navbar-fixed-top "> <div class="navbar-inner"> <div class="container-fluid"> <a data-target=".nav-collapse" data-toggle="collapse" class="btn btn-navbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="http://neilellis.github.io/dollar/" title="Dollar"><img src="http://neilellis.github.io/dollar/images/logo-32x32.png" alt="Dollar" /> </a> <ul class="nav"> </ul> </div> </div> </div> </div> <div class="container-fluid"> <div id="banner"> <div class="pull-left"><div id="bannerLeft"><h2>dollar-redis-plugin</h2> </div> </div> <div class="pull-right"></div> <div class="clear"><hr/></div> </div> <div id="breadcrumbs"> <ul class="breadcrumb"> <li id="publishDate">Last Published: 2017-09-28<span class="divider">|</span> </li> <li id="projectVersion">Version: 0.4.5195</li> </ul> </div> <div class="row-fluid"> <div id="leftColumn" class="span2"> <div class="well sidebar-nav"> <ul class="nav nav-list"> </ul> <hr /> <div id="poweredBy"> <script type="text/javascript">asyncJs( 'https://apis.google.com/js/plusone.js' )</script> <div class="g-plusone" data-href="http://sillelien.github.io/dollar/dollar-plugins/dollar-redis-plugin/" data-size="tall" ></div> <div class="clear"></div> <iframe src="https://www.facebook.com/plugins/like.php?href=http://sillelien.github.io/dollar/dollar-plugins/dollar-redis-plugin/&send=false&layout=box_count&show-faces=false&action=like&colorscheme=light" scrolling="no" frameborder="0" style="border:none; width:48px; height:63px; margin-top: 10px;" ></iframe> <div class="clear"></div> <div id="twitter"> <a href="https://twitter.com/neilellis" class="twitter-follow-button" data-show-count="true" data-align="left" data-size="medium" data-show-screen-name="true" data-lang="en">Follow neilellis</a> <script type="text/javascript">!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script> </div> <div class="clear"></div> <div class="clear"></div> <a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy"><img class="builtBy" alt="Built by Maven" src="./images/logos/maven-feather.png" /></a> </div> </div> </div> <div id="bodyColumn" class="span10" > <div class="section"> <h2><a name="Developer_Activity_Report"></a>Developer Activity Report</h2> <div class="section"> <h3><a name="Changes_between_2017-08-29_and_2017-09-29"></a>Changes between 2017-08-29 and 2017-09-29</h3> <p>Total commits: 1<br />Total number of files changed: 1</p> <table border="0" class="table table-striped"> <tr class="a"> <th>Developer</th> <th>Total commits</th> <th>Total Number of Files Changed</th></tr> <tr class="b"> <td>neilellis &lt;neil@vizz.buzz&gt;</td> <td>1</td> <td>1</td></tr></table></div></div> </div> </div> </div> <hr/> <footer> <div class="container-fluid"> <div class="row-fluid"> <p>Copyright &copy;2017. All rights reserved.</p> </div> <div id="ohloh" class="pull-right"> <script type="text/javascript" src="https://www.ohloh.net/p/dollar_script/widgets/project_users_logo.js"></script> </div> </div> </footer> </body> </html>
{ "content_hash": "4f1e2138c87eba2d4e03acfdc7bc3b5b", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 274, "avg_line_length": 44.63963963963964, "alnum_prop": 0.6020181634712412, "repo_name": "sillelien/dollar", "id": "5e3e0fc84917a9095ebd4191efa5488e22ea3bb7", "size": "4955", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/dev/dollar-plugins/dollar-redis-plugin/dev-activity.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "5403" }, { "name": "Java", "bytes": "1134511" }, { "name": "Shell", "bytes": "11580" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <animated-rotate xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/spinner" android:pivotX="50%" android:pivotY="50%" />
{ "content_hash": "6ee4a18ae9d76103f7156097301a3153", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 76, "avg_line_length": 41.2, "alnum_prop": 0.6990291262135923, "repo_name": "sayan801/Android-Loader-Progressbar-with-backbutton", "id": "66328683f6ff1c3399d8586410f3db0f3d2f9baa", "size": "206", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AndroidCustomProgress/app/src/main/res/drawable-xxhdpi/loader4_progress.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "8687" } ], "symlink_target": "" }
"use strict"; const prompt = require('prompt'); const db = require('../models'); const pass = require('../pass'); const schema = { properties: { username: { pattern: /^[a-zA-Z\s\-]+$/, message: 'Name must be only letters, spaces, or dashes', required: true }, email: { required: true, pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/ }, password: { hidden: true } } }; prompt.start(); prompt.get(schema, function(err, result) { var hashedpw = pass.hash(result.password); db.user.forge({ username: result.username, email: result.email, password: hashedpw }) .save() .then(function(user) { console.log("User created succesfully!"); process.exit(0); }) .catch(function(err) { console.error(err.stack); process.exit(1); }) .finally(function() { db.bookshelf.knex.destroy(function() { console.log("exiting"); }); }); });
{ "content_hash": "a0abcca3584d7201c913044417564d4a", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 66, "avg_line_length": 19.591836734693878, "alnum_prop": 0.565625, "repo_name": "electrified/notes", "id": "c8313d02496d15220aad26509ab9b8e0b24b938f", "size": "980", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bin/adduser.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "19508" }, { "name": "Dockerfile", "bytes": "307" }, { "name": "HTML", "bytes": "7111" }, { "name": "JavaScript", "bytes": "60977" }, { "name": "SCSS", "bytes": "19137" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Text; namespace DP.Web.UI { [Serializable] public class ClientInfo { string _IP = string.Empty; string _Name = string.Empty; string _Browser = string.Empty; string _Language = string.Empty; string _Request_Method = string.Empty; string _OS = string.Empty; string _MacAddress = string.Empty; /// <summary> /// /// </summary> public string OS { get { return _OS; } set { _OS = value; } } /// <summary> /// HTTP请求的方法(Post或Get) /// </summary> public string Request_Method { get { return _Request_Method; } set { _Request_Method = value; } } /// <summary> /// 客户端的语言环境 /// </summary> public string Language { get { return _Language; } set { _Language = value; } } /// <summary> /// 客户端浏览器信息 /// </summary> public string Browser { get { return _Browser; } set { _Browser = value; } } /// <summary> /// 客户端主机名称 /// </summary> public string Name { get { return _Name; } set { _Name = value; } } /// <summary> /// 客户端IP /// </summary> public string IP { get { return _IP; } set { _IP = value; } } /// <summary> /// Gets or sets the mac address. /// </summary> /// <value> /// The mac address. /// </value> public string MacAddress { get { return _MacAddress; } set { _MacAddress = value; } } } }
{ "content_hash": "b00739e2c028c5f694519d95fa5486a7", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 46, "avg_line_length": 21.72093023255814, "alnum_prop": 0.4277301927194861, "repo_name": "dpflower/dptools", "id": "d96bd2104f72b65fbece3bb1594fb7e65712b3f5", "size": "1934", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DP/Core/DP/Web/UI/ClientInfo.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "104" }, { "name": "C#", "bytes": "1790900" }, { "name": "CSS", "bytes": "17112" }, { "name": "HTML", "bytes": "477" }, { "name": "JavaScript", "bytes": "18006" }, { "name": "PowerShell", "bytes": "105406" } ], "symlink_target": "" }
/** * <p>cc.LabelTTF is a subclass of cc.TextureNode that knows how to render text labels with system font or a ttf font file<br/> * All features from cc.Sprite are valid in cc.LabelTTF<br/> * cc.LabelTTF objects are slow for js-binding on mobile devices.<br/> * Consider using cc.LabelAtlas or cc.LabelBMFont instead.<br/> * You can create a cc.LabelTTF from a font name, alignment, dimension and font size or a cc.FontDefinition object.</p> * @class * @extends cc.Sprite * * @param {String} text * @param {String|cc.FontDefinition} [fontName="Arial"] * @param {Number} [fontSize=16] * @param {cc.Size} [dimensions=cc.size(0,0)] * @param {Number} [hAlignment=cc.TEXT_ALIGNMENT_LEFT] * @param {Number} [vAlignment=cc.VERTICAL_TEXT_ALIGNMENT_TOP] * @example * var myLabel = new cc.LabelTTF('label text', 'Times New Roman', 32, cc.size(320,32), cc.TEXT_ALIGNMENT_LEFT); * * var fontDef = new cc.FontDefinition(); * fontDef.fontName = "Arial"; * fontDef.fontSize = "32"; * var myLabel = new cc.LabelTTF('label text', fontDef); * * @property {String} string - Content string of label * @property {Number} textAlign - Horizontal Alignment of label: cc.TEXT_ALIGNMENT_LEFT|cc.TEXT_ALIGNMENT_CENTER|cc.TEXT_ALIGNMENT_RIGHT * @property {Number} verticalAlign - Vertical Alignment of label: cc.VERTICAL_TEXT_ALIGNMENT_TOP|cc.VERTICAL_TEXT_ALIGNMENT_CENTER|cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM * @property {Number} fontSize - Font size of label * @property {String} fontName - Font name of label * @property {String} font - The label font with a style string: e.g. "18px Verdana" * @property {Number} boundingWidth - Width of the bounding box of label, the real content width is limited by boundingWidth * @property {Number} boundingHeight - Height of the bounding box of label, the real content height is limited by boundingHeight * @property {cc.Color} fillStyle - The fill color * @property {cc.Color} strokeStyle - The stroke color * @property {Number} lineWidth - The line width for stroke * @property {Number} shadowOffsetX - The x axis offset of shadow * @property {Number} shadowOffsetY - The y axis offset of shadow * @property {Number} shadowOpacity - The opacity of shadow * @property {Number} shadowBlur - The blur size of shadow */ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{ _dimensions: null, _hAlignment: cc.TEXT_ALIGNMENT_CENTER, _vAlignment: cc.VERTICAL_TEXT_ALIGNMENT_TOP, _fontName: null, _fontSize: 0.0, _string: "", _originalText: null, _isMultiLine: false, _fontStyleStr: null, // font shadow _shadowEnabled: false, _shadowOffset: null, _shadowOpacity: 0, _shadowBlur: 0, _shadowColorStr: null, // font stroke _strokeEnabled: false, _strokeColor: null, _strokeSize: 0, _strokeColorStr: null, // font tint _textFillColor: null, _fillColorStr: null, _strokeShadowOffsetX: 0, _strokeShadowOffsetY: 0, _needUpdateTexture: false, _labelCanvas: null, _labelContext: null, _lineWidths: null, _className: "LabelTTF", /** * Initializes the cc.LabelTTF with a font name, alignment, dimension and font size, do not call it by yourself, you should pass the correct arguments in constructor to initialize the label. * @param {String} label string * @param {String} fontName * @param {Number} fontSize * @param {cc.Size} [dimensions=] * @param {Number} [hAlignment=] * @param {Number} [vAlignment=] * @return {Boolean} return false on error */ initWithString: function (label, fontName, fontSize, dimensions, hAlignment, vAlignment) { var strInfo; if (label) strInfo = label + ""; else strInfo = ""; fontSize = fontSize || 16; dimensions = dimensions || cc.size(0, 0/*fontSize*/); hAlignment = hAlignment || cc.TEXT_ALIGNMENT_LEFT; vAlignment = vAlignment || cc.VERTICAL_TEXT_ALIGNMENT_TOP; this._opacityModifyRGB = false; this._dimensions = cc.size(dimensions.width, dimensions.height); this._fontName = fontName || "Arial"; this._hAlignment = hAlignment; this._vAlignment = vAlignment; //this._fontSize = (cc._renderType === cc._RENDER_TYPE_CANVAS) ? fontSize : fontSize * cc.contentScaleFactor(); this._fontSize = fontSize; this._fontStyleStr = this._fontSize + "px '" + fontName + "'"; this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(fontName, this._fontSize); this.string = strInfo; this._setColorsString(); this._updateTexture(); this._needUpdateTexture = false; return true; }, ctor: function (text, fontName, fontSize, dimensions, hAlignment, vAlignment) { cc.Sprite.prototype.ctor.call(this); this._dimensions = cc.size(0, 0); this._hAlignment = cc.TEXT_ALIGNMENT_LEFT; this._vAlignment = cc.VERTICAL_TEXT_ALIGNMENT_TOP; this._opacityModifyRGB = false; this._fontStyleStr = ""; this._fontName = "Arial"; this._isMultiLine = false; this._shadowEnabled = false; this._shadowOffset = cc.p(0, 0); this._shadowOpacity = 0; this._shadowBlur = 0; this._shadowColorStr = "rgba(128, 128, 128, 0.5)"; this._strokeEnabled = false; this._strokeColor = cc.color(255, 255, 255, 255); this._strokeSize = 0; this._strokeColorStr = ""; this._textFillColor = cc.color(255, 255, 255, 255); this._fillColorStr = "rgba(255,255,255,1)"; this._strokeShadowOffsetX = 0; this._strokeShadowOffsetY = 0; this._needUpdateTexture = false; this._lineWidths = []; this._setColorsString(); if (fontName && fontName instanceof cc.FontDefinition) { this.initWithStringAndTextDefinition(text, fontName); } else { cc.LabelTTF.prototype.initWithString.call(this, text, fontName, fontSize, dimensions, hAlignment, vAlignment); } }, init: function () { return this.initWithString(" ", this._fontName, this._fontSize); }, _measureConfig: function () { this._getLabelContext().font = this._fontStyleStr; }, _measure: function (text) { return this._getLabelContext().measureText(text).width; }, description: function () { return "<cc.LabelTTF | FontName =" + this._fontName + " FontSize = " + this._fontSize.toFixed(1) + ">"; }, setColor: null, _setColorsString: null, updateDisplayedColor: null, setOpacity: null, updateDisplayedOpacity: null, updateDisplayedOpacityForCanvas: function (parentOpacity) { cc.Node.prototype.updateDisplayedOpacity.call(this, parentOpacity); this._setColorsString(); }, /** * Returns the text of the label * @return {String} */ getString: function () { return this._string; }, /** * Returns Horizontal Alignment of cc.LabelTTF * @return {cc.TEXT_ALIGNMENT_LEFT|cc.TEXT_ALIGNMENT_CENTER|cc.TEXT_ALIGNMENT_RIGHT} */ getHorizontalAlignment: function () { return this._hAlignment; }, /** * Returns Vertical Alignment of cc.LabelTTF * @return {cc.VERTICAL_TEXT_ALIGNMENT_TOP|cc.VERTICAL_TEXT_ALIGNMENT_CENTER|cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM} */ getVerticalAlignment: function () { return this._vAlignment; }, /** * Returns the dimensions of cc.LabelTTF, the dimension is the maximum size of the label, set it so that label will automatically change lines when necessary. * @see cc.LabelTTF#setDimensions, cc.LabelTTF#boundingWidth and cc.LabelTTF#boundingHeight * @return {cc.Size} */ getDimensions: function () { return cc.size(this._dimensions); }, /** * Returns font size of cc.LabelTTF * @return {Number} */ getFontSize: function () { return this._fontSize; }, /** * Returns font name of cc.LabelTTF * @return {String} */ getFontName: function () { return this._fontName; }, /** * Initializes the CCLabelTTF with a font name, alignment, dimension and font size, do not call it by yourself, you should pass the correct arguments in constructor to initialize the label. * @param {String} text * @param {cc.FontDefinition} textDefinition * @return {Boolean} */ initWithStringAndTextDefinition: null, /** * Sets the text definition used by this label * @param {cc.FontDefinition} theDefinition */ setTextDefinition: function (theDefinition) { if (theDefinition) this._updateWithTextDefinition(theDefinition, true); }, /** * Extract the text definition used by this label * @return {cc.FontDefinition} */ getTextDefinition: function () { return this._prepareTextDefinition(false); }, /** * Enable or disable shadow for the label * @param {Number} shadowOffsetX The x axis offset of the shadow * @param {Number} shadowOffsetY The y axis offset of the shadow * @param {Number} shadowOpacity The opacity of the shadow (0 to 1) * @param {Number} shadowBlur The blur size of the shadow */ enableShadow: function (shadowOffsetX, shadowOffsetY, shadowOpacity, shadowBlur) { shadowOpacity = shadowOpacity || 0.5; if (false === this._shadowEnabled) this._shadowEnabled = true; var locShadowOffset = this._shadowOffset; if (locShadowOffset && (locShadowOffset.x != shadowOffsetX) || (locShadowOffset._y != shadowOffsetY)) { locShadowOffset.x = shadowOffsetX; locShadowOffset.y = shadowOffsetY; } if (this._shadowOpacity != shadowOpacity) { this._shadowOpacity = shadowOpacity; } this._setColorsString(); if (this._shadowBlur != shadowBlur) this._shadowBlur = shadowBlur; this._needUpdateTexture = true; }, _getShadowOffsetX: function () { return this._shadowOffset.x; }, _setShadowOffsetX: function (x) { if (false === this._shadowEnabled) this._shadowEnabled = true; if (this._shadowOffset.x != x) { this._shadowOffset.x = x; this._needUpdateTexture = true; } }, _getShadowOffsetY: function () { return this._shadowOffset._y; }, _setShadowOffsetY: function (y) { if (false === this._shadowEnabled) this._shadowEnabled = true; if (this._shadowOffset._y != y) { this._shadowOffset._y = y; this._needUpdateTexture = true; } }, _getShadowOffset: function () { return cc.p(this._shadowOffset.x, this._shadowOffset.y); }, _setShadowOffset: function (offset) { if (false === this._shadowEnabled) this._shadowEnabled = true; if (this._shadowOffset.x != offset.x || this._shadowOffset.y != offset.y) { this._shadowOffset.x = offset.x; this._shadowOffset.y = offset.y; this._needUpdateTexture = true; } }, _getShadowOpacity: function () { return this._shadowOpacity; }, _setShadowOpacity: function (shadowOpacity) { if (false === this._shadowEnabled) this._shadowEnabled = true; if (this._shadowOpacity != shadowOpacity) { this._shadowOpacity = shadowOpacity; this._setColorsString(); this._needUpdateTexture = true; } }, _getShadowBlur: function () { return this._shadowBlur; }, _setShadowBlur: function (shadowBlur) { if (false === this._shadowEnabled) this._shadowEnabled = true; if (this._shadowBlur != shadowBlur) { this._shadowBlur = shadowBlur; this._needUpdateTexture = true; } }, /** * Disable shadow rendering */ disableShadow: function () { if (this._shadowEnabled) { this._shadowEnabled = false; this._needUpdateTexture = true; } }, /** * Enable label stroke with stroke parameters * @param {cc.Color} strokeColor The color of stroke * @param {Number} strokeSize The size of stroke */ enableStroke: function (strokeColor, strokeSize) { if (this._strokeEnabled === false) this._strokeEnabled = true; var locStrokeColor = this._strokeColor; if ((locStrokeColor.r !== strokeColor.r) || (locStrokeColor.g !== strokeColor.g) || (locStrokeColor.b !== strokeColor.b)) { locStrokeColor.r = strokeColor.r; locStrokeColor.g = strokeColor.g; locStrokeColor.b = strokeColor.b; this._setColorsString(); } if (this._strokeSize !== strokeSize) this._strokeSize = strokeSize || 0; this._needUpdateTexture = true; }, _getStrokeStyle: function () { return this._strokeColor; }, _setStrokeStyle: function (strokeStyle) { if (this._strokeEnabled === false) this._strokeEnabled = true; var locStrokeColor = this._strokeColor; if ((locStrokeColor.r !== strokeStyle.r) || (locStrokeColor.g !== strokeStyle.g) || (locStrokeColor.b !== strokeStyle.b)) { locStrokeColor.r = strokeStyle.r; locStrokeColor.g = strokeStyle.g; locStrokeColor.b = strokeStyle.b; this._setColorsString(); this._needUpdateTexture = true; } }, _getLineWidth: function () { return this._strokeSize; }, _setLineWidth: function (lineWidth) { if (this._strokeEnabled === false) this._strokeEnabled = true; if (this._strokeSize !== lineWidth) { this._strokeSize = lineWidth || 0; this._needUpdateTexture = true; } }, /** * Disable label stroke */ disableStroke: function () { if (this._strokeEnabled) { this._strokeEnabled = false; this._needUpdateTexture = true; } }, /** * Sets the text fill color * @function * @param {cc.Color} fillColor The fill color of the label */ setFontFillColor: null, _getFillStyle: function () { return this._textFillColor; }, //set the text definition for this label _updateWithTextDefinition: function (textDefinition, mustUpdateTexture) { if (textDefinition.fontDimensions) { this._dimensions.width = textDefinition.boundingWidth; this._dimensions.height = textDefinition.boundingHeight; } else { this._dimensions.width = 0; this._dimensions.height = 0; } this._hAlignment = textDefinition.textAlign; this._vAlignment = textDefinition.verticalAlign; this._fontName = textDefinition.fontName; this._fontSize = textDefinition.fontSize || 12; this._fontStyleStr = this._fontSize + "px '" + this._fontName + "'"; this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(this._fontName, this._fontSize); // shadow if (textDefinition.shadowEnabled) this.enableShadow(textDefinition.shadowOffsetX, textDefinition.shadowOffsetY, textDefinition.shadowOpacity, textDefinition.shadowBlur); // stroke if (textDefinition.strokeEnabled) this.enableStroke(textDefinition.strokeStyle, textDefinition.lineWidth); // fill color this.setFontFillColor(textDefinition.fillStyle); if (mustUpdateTexture) this._updateTexture(); }, _prepareTextDefinition: function (adjustForResolution) { var texDef = new cc.FontDefinition(); if (adjustForResolution) { //texDef.fontSize = (cc._renderType === cc._RENDER_TYPE_CANVAS) ? this._fontSize : this._fontSize * cc.contentScaleFactor(); texDef.fontSize = this._fontSize; texDef.boundingWidth = cc.contentScaleFactor() * this._dimensions.width; texDef.boundingHeight = cc.contentScaleFactor() * this._dimensions.height; } else { texDef.fontSize = this._fontSize; texDef.boundingWidth = this._dimensions.width; texDef.boundingHeight = this._dimensions.height; } texDef.fontName = this._fontName; texDef.textAlign = this._hAlignment; texDef.verticalAlign = this._vAlignment; // stroke if (this._strokeEnabled) { texDef.strokeEnabled = true; var locStrokeColor = this._strokeColor; texDef.strokeStyle = cc.color(locStrokeColor.r, locStrokeColor.g, locStrokeColor.b); texDef.lineWidth = this._strokeSize; } else texDef.strokeEnabled = false; // shadow if (this._shadowEnabled) { texDef.shadowEnabled = true; texDef.shadowBlur = this._shadowBlur; texDef.shadowOpacity = this._shadowOpacity; texDef.shadowOffsetX = (adjustForResolution ? cc.contentScaleFactor() : 1) * this._shadowOffset.x; texDef.shadowOffsetY = (adjustForResolution ? cc.contentScaleFactor() : 1) * this._shadowOffset.y; } else texDef._shadowEnabled = false; // text tint var locTextFillColor = this._textFillColor; texDef.fillStyle = cc.color(locTextFillColor.r, locTextFillColor.g, locTextFillColor.b); return texDef; }, _fontClientHeight: 18, /** * Changes the text content of the label * @warning Changing the string is as expensive as creating a new cc.LabelTTF. To obtain better performance use cc.LabelAtlas * @param {String} text Text content for the label */ setString: function (text) { text = String(text); if (this._originalText != text) { this._originalText = text + ""; this._updateString(); // Force update this._needUpdateTexture = true; } }, _updateString: function () { this._string = this._originalText; }, /** * Sets Horizontal Alignment of cc.LabelTTF * @param {cc.TEXT_ALIGNMENT_LEFT|cc.TEXT_ALIGNMENT_CENTER|cc.TEXT_ALIGNMENT_RIGHT} alignment Horizontal Alignment */ setHorizontalAlignment: function (alignment) { if (alignment !== this._hAlignment) { this._hAlignment = alignment; // Force update this._needUpdateTexture = true; } }, /** * Sets Vertical Alignment of cc.LabelTTF * @param {cc.VERTICAL_TEXT_ALIGNMENT_TOP|cc.VERTICAL_TEXT_ALIGNMENT_CENTER|cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM} verticalAlignment */ setVerticalAlignment: function (verticalAlignment) { if (verticalAlignment != this._vAlignment) { this._vAlignment = verticalAlignment; // Force update this._needUpdateTexture = true; } }, /** * Set Dimensions of cc.LabelTTF, the dimension is the maximum size of the label, set it so that label will automatically change lines when necessary. * @param {cc.Size|Number} dim dimensions or width of dimensions * @param {Number} [height] height of dimensions */ setDimensions: function (dim, height) { var width; if(height === undefined){ width = dim.width; height = dim.height; }else width = dim; if (width != this._dimensions.width || height != this._dimensions.height) { this._dimensions.width = width; this._dimensions.height = height; this._updateString(); // Force udpate this._needUpdateTexture = true; } }, _getBoundingWidth: function () { return this._dimensions.width; }, _setBoundingWidth: function (width) { if (width != this._dimensions.width) { this._dimensions.width = width; this._updateString(); // Force udpate this._needUpdateTexture = true; } }, _getBoundingHeight: function () { return this._dimensions.height; }, _setBoundingHeight: function (height) { if (height != this._dimensions.height) { this._dimensions.height = height; this._updateString(); // Force udpate this._needUpdateTexture = true; } }, /** * Sets font size of cc.LabelTTF * @param {Number} fontSize */ setFontSize: function (fontSize) { if (this._fontSize !== fontSize) { this._fontSize = fontSize; this._fontStyleStr = fontSize + "px '" + this._fontName + "'"; this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(this._fontName, fontSize); // Force update this._needUpdateTexture = true; } }, /** * Sets font name of cc.LabelTTF * @param {String} fontName */ setFontName: function (fontName) { if (this._fontName && this._fontName != fontName) { this._fontName = fontName; this._fontStyleStr = this._fontSize + "px '" + fontName + "'"; this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(fontName, this._fontSize); // Force update this._needUpdateTexture = true; } }, _getFont: function () { return this._fontStyleStr; }, _setFont: function (fontStyle) { var res = cc.LabelTTF._fontStyleRE.exec(fontStyle); if (res) { this._fontSize = parseInt(res[1]); this._fontName = res[2]; this._fontStyleStr = fontStyle; this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(this._fontName, this._fontSize); // Force update this._needUpdateTexture = true; } }, _drawTTFInCanvas: function (context) { if (!context) return; var locStrokeShadowOffsetX = this._strokeShadowOffsetX, locStrokeShadowOffsetY = this._strokeShadowOffsetY; var locContentSizeHeight = this._contentSize.height - locStrokeShadowOffsetY, locVAlignment = this._vAlignment, locHAlignment = this._hAlignment, locFontHeight = this._fontClientHeight, locStrokeSize = this._strokeSize; context.setTransform(1, 0, 0, 1, 0 + locStrokeShadowOffsetX * 0.5, locContentSizeHeight + locStrokeShadowOffsetY * 0.5); //this is fillText for canvas if (context.font != this._fontStyleStr) context.font = this._fontStyleStr; context.fillStyle = this._fillColorStr; var xOffset = 0, yOffset = 0; //stroke style setup var locStrokeEnabled = this._strokeEnabled; if (locStrokeEnabled) { context.lineWidth = locStrokeSize * 2; context.strokeStyle = this._strokeColorStr; } //shadow style setup if (this._shadowEnabled) { var locShadowOffset = this._shadowOffset; context.shadowColor = this._shadowColorStr; context.shadowOffsetX = locShadowOffset.x; context.shadowOffsetY = -locShadowOffset.y; context.shadowBlur = this._shadowBlur; } context.textBaseline = cc.LabelTTF._textBaseline[locVAlignment]; context.textAlign = cc.LabelTTF._textAlign[locHAlignment]; var locContentWidth = this._contentSize.width - locStrokeShadowOffsetX; if (locHAlignment === cc.TEXT_ALIGNMENT_RIGHT) xOffset += locContentWidth; else if (locHAlignment === cc.TEXT_ALIGNMENT_CENTER) xOffset += locContentWidth / 2; else xOffset += 0; if (this._isMultiLine) { var locStrLen = this._strings.length; if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM) yOffset = locFontHeight + locContentSizeHeight - locFontHeight * locStrLen; else if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_CENTER) yOffset = locFontHeight / 2 + (locContentSizeHeight - locFontHeight * locStrLen) / 2; for (var i = 0; i < locStrLen; i++) { var line = this._strings[i]; var tmpOffsetY = -locContentSizeHeight + (locFontHeight * i) + yOffset; if (locStrokeEnabled) context.strokeText(line, xOffset, tmpOffsetY); context.fillText(line, xOffset, tmpOffsetY); } } else { if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM) { if (locStrokeEnabled) context.strokeText(this._string, xOffset, yOffset); context.fillText(this._string, xOffset, yOffset); } else if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_TOP) { yOffset -= locContentSizeHeight; if (locStrokeEnabled) context.strokeText(this._string, xOffset, yOffset); context.fillText(this._string, xOffset, yOffset); } else { yOffset -= locContentSizeHeight * 0.5; if (locStrokeEnabled) context.strokeText(this._string, xOffset, yOffset); context.fillText(this._string, xOffset, yOffset); } } }, _getLabelContext: function () { if (this._labelContext) return this._labelContext; if (!this._labelCanvas) { var locCanvas = cc.newElement("canvas"); var labelTexture = new cc.Texture2D(); labelTexture.initWithElement(locCanvas); this.texture = labelTexture; this._labelCanvas = locCanvas; } this._labelContext = this._labelCanvas.getContext("2d"); return this._labelContext; }, _checkWarp: function(strArr, i, maxWidth){ var text = strArr[i]; var allWidth = this._measure(text); if(allWidth > maxWidth && text.length > 1){ var fuzzyLen = text.length * ( maxWidth / allWidth ) | 0; var tmpText = text.substr(fuzzyLen); var width = allWidth - this._measure(tmpText); var sLine; var pushNum = 0; //Increased while cycle maximum ceiling. default 100 time var checkWhile = 0; //Exceeded the size while(width > maxWidth && checkWhile++ < 100){ fuzzyLen *= maxWidth / width; fuzzyLen = fuzzyLen | 0; tmpText = text.substr(fuzzyLen); width = allWidth - this._measure(tmpText); } checkWhile = 0; //Find the truncation point while(width < maxWidth && checkWhile++ < 100){ if(tmpText){ var exec = cc.LabelTTF._wordRex.exec(tmpText); pushNum = exec ? exec[0].length : 1; sLine = tmpText; } fuzzyLen = fuzzyLen + pushNum; tmpText = text.substr(fuzzyLen); width = allWidth - this._measure(tmpText); } fuzzyLen -= pushNum; var sText = text.substr(0, fuzzyLen); //symbol in the first if(cc.LabelTTF.wrapInspection){ if(cc.LabelTTF._symbolRex.test(sLine || tmpText)){ var result = cc.LabelTTF._lastWordRex.exec(sText); fuzzyLen -= result ? result[0].length : 0; sLine = text.substr(fuzzyLen); sText = text.substr(0, fuzzyLen); } } //To judge whether a English words are truncated if(cc.LabelTTF._firsrEnglish.test(sLine)){ var result = cc.LabelTTF._lastEnglish.exec(sText); if(result && sText !== result[0]){ fuzzyLen -= result[0].length; sLine = text.substr(fuzzyLen); sText = text.substr(0, fuzzyLen); } } strArr[i] = sLine || tmpText; strArr.splice(i, 0, sText); } }, _updateTTF: function () { var locDimensionsWidth = this._dimensions.width, i, strLength; var locLineWidth = this._lineWidths; locLineWidth.length = 0; this._isMultiLine = false; this._measureConfig(); if (locDimensionsWidth !== 0) { // Content processing this._strings = this._string.split('\n'); for(i = 0; i < this._strings.length; i++){ this._checkWarp(this._strings, i, locDimensionsWidth); } } else { this._strings = this._string.split('\n'); for (i = 0, strLength = this._strings.length; i < strLength; i++) { locLineWidth.push(this._measure(this._strings[i])); } } if (this._strings.length > 0) this._isMultiLine = true; var locSize, locStrokeShadowOffsetX = 0, locStrokeShadowOffsetY = 0; if (this._strokeEnabled) locStrokeShadowOffsetX = locStrokeShadowOffsetY = this._strokeSize * 2; if (this._shadowEnabled) { var locOffsetSize = this._shadowOffset; locStrokeShadowOffsetX += Math.abs(locOffsetSize.x) * 2; locStrokeShadowOffsetY += Math.abs(locOffsetSize.y) * 2; } //get offset for stroke and shadow if (locDimensionsWidth === 0) { if (this._isMultiLine) locSize = cc.size(0 | (Math.max.apply(Math, locLineWidth) + locStrokeShadowOffsetX), 0 | ((this._fontClientHeight * this._strings.length) + locStrokeShadowOffsetY)); else locSize = cc.size(0 | (this._measure(this._string) + locStrokeShadowOffsetX), 0 | (this._fontClientHeight + locStrokeShadowOffsetY)); } else { if (this._dimensions.height === 0) { if (this._isMultiLine) locSize = cc.size(0 | (locDimensionsWidth + locStrokeShadowOffsetX), 0 | ((this._fontClientHeight * this._strings.length) + locStrokeShadowOffsetY)); else locSize = cc.size(0 | (locDimensionsWidth + locStrokeShadowOffsetX), 0 | (this._fontClientHeight + locStrokeShadowOffsetY)); } else { //dimension is already set, contentSize must be same as dimension locSize = cc.size(0 | (locDimensionsWidth + locStrokeShadowOffsetX), 0 | (this._dimensions.height + locStrokeShadowOffsetY)); } } this.setContentSize(locSize); this._strokeShadowOffsetX = locStrokeShadowOffsetX; this._strokeShadowOffsetY = locStrokeShadowOffsetY; // need computing _anchorPointInPoints var locAP = this._anchorPoint; this._anchorPointInPoints.x = (locStrokeShadowOffsetX * 0.5) + ((locSize.width - locStrokeShadowOffsetX) * locAP.x); this._anchorPointInPoints.y = (locStrokeShadowOffsetY * 0.5) + ((locSize.height - locStrokeShadowOffsetY) * locAP.y); }, /** * Returns the actual content size of the label, the content size is the real size that the label occupied while dimension is the outer bounding box of the label. * @returns {cc.Size} The content size */ getContentSize: function () { if (this._needUpdateTexture) this._updateTTF(); return cc.Sprite.prototype.getContentSize.call(this); }, _getWidth: function () { if (this._needUpdateTexture) this._updateTTF(); return cc.Sprite.prototype._getWidth.call(this); }, _getHeight: function () { if (this._needUpdateTexture) this._updateTTF(); return cc.Sprite.prototype._getHeight.call(this); }, _updateTexture: function () { var locContext = this._getLabelContext(), locLabelCanvas = this._labelCanvas; var locContentSize = this._contentSize; if (this._string.length === 0) { locLabelCanvas.width = 1; locLabelCanvas.height = locContentSize.height || 1; this._texture && this._texture.handleLoadedTexture(); this.setTextureRect(cc.rect(0, 0, 1, locContentSize.height)); return true; } //set size for labelCanvas locContext.font = this._fontStyleStr; this._updateTTF(); var width = locContentSize.width, height = locContentSize.height; var flag = locLabelCanvas.width == width && locLabelCanvas.height == height; locLabelCanvas.width = width; locLabelCanvas.height = height; if (flag) locContext.clearRect(0, 0, width, height); //draw text to labelCanvas this._drawTTFInCanvas(locContext); this._texture && this._texture.handleLoadedTexture(); this.setTextureRect(cc.rect(0, 0, width, height)); return true; }, visit: function (ctx) { if (!this._string || this._string == "") return; if (this._needUpdateTexture) { this._needUpdateTexture = false; this._updateTexture(); } var context = ctx || cc._renderContext; cc.Sprite.prototype.visit.call(this, context); }, draw: null, _setTextureCoords: function (rect) { var tex = this._batchNode ? this.textureAtlas.texture : this._texture; if (!tex) return; var atlasWidth = tex.pixelsWidth; var atlasHeight = tex.pixelsHeight; var left, right, top, bottom, tempSwap, locQuad = this._quad; if (this._rectRotated) { if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) { left = (2 * rect.x + 1) / (2 * atlasWidth); right = left + (rect.height * 2 - 2) / (2 * atlasWidth); top = (2 * rect.y + 1) / (2 * atlasHeight); bottom = top + (rect.width * 2 - 2) / (2 * atlasHeight); } else { left = rect.x / atlasWidth; right = (rect.x + rect.height) / atlasWidth; top = rect.y / atlasHeight; bottom = (rect.y + rect.width) / atlasHeight; }// CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL if (this._flippedX) { tempSwap = top; top = bottom; bottom = tempSwap; } if (this._flippedY) { tempSwap = left; left = right; right = tempSwap; } locQuad.bl.texCoords.u = left; locQuad.bl.texCoords.v = top; locQuad.br.texCoords.u = left; locQuad.br.texCoords.v = bottom; locQuad.tl.texCoords.u = right; locQuad.tl.texCoords.v = top; locQuad.tr.texCoords.u = right; locQuad.tr.texCoords.v = bottom; } else { if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) { left = (2 * rect.x + 1) / (2 * atlasWidth); right = left + (rect.width * 2 - 2) / (2 * atlasWidth); top = (2 * rect.y + 1) / (2 * atlasHeight); bottom = top + (rect.height * 2 - 2) / (2 * atlasHeight); } else { left = rect.x / atlasWidth; right = (rect.x + rect.width) / atlasWidth; top = rect.y / atlasHeight; bottom = (rect.y + rect.height) / atlasHeight; } // ! CC_FIX_ARTIFACTS_BY_STRECHING_TEXEL if (this._flippedX) { tempSwap = left; left = right; right = tempSwap; } if (this._flippedY) { tempSwap = top; top = bottom; bottom = tempSwap; } locQuad.bl.texCoords.u = left; locQuad.bl.texCoords.v = bottom; locQuad.br.texCoords.u = right; locQuad.br.texCoords.v = bottom; locQuad.tl.texCoords.u = left; locQuad.tl.texCoords.v = top; locQuad.tr.texCoords.u = right; locQuad.tr.texCoords.v = top; } this._quadDirty = true; } }); if (cc._renderType === cc._RENDER_TYPE_CANVAS) { var _p = cc.LabelTTF.prototype; _p.setColor = function (color3) { cc.Node.prototype.setColor.call(this, color3); this._setColorsString(); }; _p._setColorsString = function () { this._needUpdateTexture = true; var locDisplayColor = this._displayedColor, locDisplayedOpacity = this._displayedOpacity; var locStrokeColor = this._strokeColor, locFontFillColor = this._textFillColor; this._shadowColorStr = "rgba(" + (0 | (locDisplayColor.r * 0.5)) + "," + (0 | (locDisplayColor.g * 0.5)) + "," + (0 | (locDisplayColor.b * 0.5)) + "," + this._shadowOpacity + ")"; this._fillColorStr = "rgba(" + (0 | (locDisplayColor.r / 255 * locFontFillColor.r)) + "," + (0 | (locDisplayColor.g / 255 * locFontFillColor.g)) + "," + (0 | (locDisplayColor.b / 255 * locFontFillColor.b)) + ", " + locDisplayedOpacity / 255 + ")"; this._strokeColorStr = "rgba(" + (0 | (locDisplayColor.r / 255 * locStrokeColor.r)) + "," + (0 | (locDisplayColor.g / 255 * locStrokeColor.g)) + "," + (0 | (locDisplayColor.b / 255 * locStrokeColor.b)) + ", " + locDisplayedOpacity / 255 + ")"; }; _p.updateDisplayedColor = function (parentColor) { cc.Node.prototype.updateDisplayedColor.call(this, parentColor); this._setColorsString(); }; _p.setOpacity = function (opacity) { if (this._opacity === opacity) return; cc.Sprite.prototype.setOpacity.call(this, opacity); this._setColorsString(); this._needUpdateTexture = true; }; //TODO: _p._updateDisplayedOpacityForCanvas _p.updateDisplayedOpacity = cc.Sprite.prototype.updateDisplayedOpacity; _p.initWithStringAndTextDefinition = function (text, textDefinition) { // prepare everything needed to render the label this._updateWithTextDefinition(textDefinition, false); // set the string this.string = text; return true; }; _p.setFontFillColor = function (tintColor) { var locTextFillColor = this._textFillColor; if (locTextFillColor.r != tintColor.r || locTextFillColor.g != tintColor.g || locTextFillColor.b != tintColor.b) { locTextFillColor.r = tintColor.r; locTextFillColor.g = tintColor.g; locTextFillColor.b = tintColor.b; this._setColorsString(); this._needUpdateTexture = true; } }; _p.draw = cc.Sprite.prototype.draw; _p.setTextureRect = function (rect, rotated, untrimmedSize) { this._rectRotated = rotated || false; untrimmedSize = untrimmedSize || rect; this.setContentSize(untrimmedSize); this.setVertexRect(rect); var locTextureCoordRect = this._textureRect_Canvas; locTextureCoordRect.x = rect.x; locTextureCoordRect.y = rect.y; locTextureCoordRect.width = rect.width; locTextureCoordRect.height = rect.height; locTextureCoordRect.validRect = !(locTextureCoordRect.width === 0 || locTextureCoordRect.height === 0 || locTextureCoordRect.x < 0 || locTextureCoordRect.y < 0); var relativeOffset = this._unflippedOffsetPositionFromCenter; if (this._flippedX) relativeOffset.x = -relativeOffset.x; if (this._flippedY) relativeOffset.y = -relativeOffset.y; this._offsetPosition.x = relativeOffset.x + (this._contentSize.width - this._rect.width) / 2; this._offsetPosition.y = relativeOffset.y + (this._contentSize.height - this._rect.height) / 2; // rendering using batch node if (this._batchNode) { this.dirty = true; } }; _p = null; } else { cc.assert(typeof cc._tmp.WebGLLabelTTF === "function", cc._LogInfos.MissingFile, "LabelTTFWebGL.js"); cc._tmp.WebGLLabelTTF(); delete cc._tmp.WebGLLabelTTF; } cc.assert(typeof cc._tmp.PrototypeLabelTTF === "function", cc._LogInfos.MissingFile, "LabelTTFPropertyDefine.js"); cc._tmp.PrototypeLabelTTF(); delete cc._tmp.PrototypeLabelTTF; cc.LabelTTF._textAlign = ["left", "center", "right"]; cc.LabelTTF._textBaseline = ["top", "middle", "bottom"]; //check the first character cc.LabelTTF.wrapInspection = true; //Support: English French German //Other as Oriental Language cc.LabelTTF._wordRex = /([a-zA-Z0-9"A"O"U"a"oüsséècàùê^a^i^o^u]+|\S)/; cc.LabelTTF._symbolRex = /^[!,.:;}\]%\?>、‘“》?。,!]/; cc.LabelTTF._lastWordRex = /([a-zA-Z0-9"A"O"U"a"oüsséècàùê^a^i^o^u]+|\S)$/; cc.LabelTTF._lastEnglish = /[a-zA-Z0-9"A"O"U"a"oüsséècàùê^a^i^o^u]+$/; cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9"A"O"U"a"oüsséècàùê^a^i^o^u]/; // Only support style in this format: "18px Verdana" or "18px 'Helvetica Neue'" cc.LabelTTF._fontStyleRE = /^(\d+)px\s+['"]?([\w\s\d]+)['"]?$/; /** * creates a cc.LabelTTF from a font name, alignment, dimension and font size * @deprecated since v3.0, please use the new construction instead * @see cc.LabelTTF * @static * @param {String} text * @param {String|cc.FontDefinition} [fontName="Arial"] * @param {Number} [fontSize=16] * @param {cc.Size} [dimensions=cc.size(0,0)] * @param {Number} [hAlignment=cc.TEXT_ALIGNMENT_LEFT] * @param {Number} [vAlignment=cc.VERTICAL_TEXT_ALIGNMENT_TOP] * @return {cc.LabelTTF|Null} */ cc.LabelTTF.create = function (text, fontName, fontSize, dimensions, hAlignment, vAlignment) { return new cc.LabelTTF(text, fontName, fontSize, dimensions, hAlignment, vAlignment); }; /** * @deprecated since v3.0, please use the new construction instead * @function * @static */ cc.LabelTTF.createWithFontDefinition = cc.LabelTTF.create; if (cc.USE_LA88_LABELS) cc.LabelTTF._SHADER_PROGRAM = cc.SHADER_POSITION_TEXTURECOLOR; else cc.LabelTTF._SHADER_PROGRAM = cc.SHADER_POSITION_TEXTUREA8COLOR; cc.LabelTTF.__labelHeightDiv = cc.newElement("div"); cc.LabelTTF.__labelHeightDiv.style.fontFamily = "Arial"; cc.LabelTTF.__labelHeightDiv.style.position = "absolute"; cc.LabelTTF.__labelHeightDiv.style.left = "-100px"; cc.LabelTTF.__labelHeightDiv.style.top = "-100px"; cc.LabelTTF.__labelHeightDiv.style.lineHeight = "normal"; document.body ? document.body.appendChild(cc.LabelTTF.__labelHeightDiv) : cc._addEventListener(window, 'load', function () { this.removeEventListener('load', arguments.callee, false); document.body.appendChild(cc.LabelTTF.__labelHeightDiv); }, false); cc.LabelTTF.__getFontHeightByDiv = function (fontName, fontSize) { var clientHeight = cc.LabelTTF.__fontHeightCache[fontName + "." + fontSize]; if (clientHeight > 0) return clientHeight; var labelDiv = cc.LabelTTF.__labelHeightDiv; labelDiv.innerHTML = "ajghl~!"; labelDiv.style.fontFamily = fontName; labelDiv.style.fontSize = fontSize + "px"; clientHeight = labelDiv.clientHeight; cc.LabelTTF.__fontHeightCache[fontName + "." + fontSize] = clientHeight; labelDiv.innerHTML = ""; return clientHeight; }; cc.LabelTTF.__fontHeightCache = {};
{ "content_hash": "d9ccc73a91201b989fc0ff2235540bb5", "timestamp": "", "source": "github", "line_count": 1201, "max_line_length": 194, "avg_line_length": 36.456286427976686, "alnum_prop": 0.5942810158962178, "repo_name": "lxp521125/weixin", "id": "401b6f6d52631a3e1802a7fb58315cb28c7070d7", "size": "45177", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "game/more/games/symdsb/frameworks/cocos2d-html5/CCLabelTTF.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "295653" }, { "name": "HTML", "bytes": "2241764" }, { "name": "Hack", "bytes": "43655" }, { "name": "JavaScript", "bytes": "14017272" }, { "name": "PHP", "bytes": "231958" }, { "name": "Ruby", "bytes": "300" }, { "name": "TSQL", "bytes": "1946" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "3b6ae28f0b970a03364a725dd4245195", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "abe7a7dcc74fb737d2618ee3ba8ddad2467344ac", "size": "182", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Elachanthus glaber/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<?php namespace Phoebe; interface ConnectionInterface extends \Phergie\Irc\ConnectionInterface { }
{ "content_hash": "6c069ccd8bc3eebba5ce095f0f1073fd", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 70, "avg_line_length": 16.5, "alnum_prop": 0.8282828282828283, "repo_name": "stil/phoebe", "id": "62e4b3a4d01d387866c9cfff7443feccd3672816", "size": "99", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ConnectionInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "59673" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_35) on Tue Oct 16 22:49:47 ICT 2012 --> <TITLE> org.apache.fop.render.bitmap Class Hierarchy (Apache FOP 1.1 API) </TITLE> <META NAME="date" CONTENT="2012-10-16"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.fop.render.bitmap Class Hierarchy (Apache FOP 1.1 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> fop 1.1</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/fop/render/awt/viewer/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/fop/render/extensions/prepress/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/fop/render/bitmap/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> Hierarchy For Package org.apache.fop.render.bitmap </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B><DD><A HREF="../../../../../overview-tree.html">All Packages</A></DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">java.lang.Object<UL> <LI TYPE="circle">org.apache.fop.render.<A HREF="../../../../../org/apache/fop/render/AbstractConfigurator.html" title="class in org.apache.fop.render"><B>AbstractConfigurator</B></A><UL> <LI TYPE="circle">org.apache.fop.render.<A HREF="../../../../../org/apache/fop/render/AbstractRendererConfigurator.html" title="class in org.apache.fop.render"><B>AbstractRendererConfigurator</B></A><UL> <LI TYPE="circle">org.apache.fop.render.<A HREF="../../../../../org/apache/fop/render/PrintRendererConfigurator.html" title="class in org.apache.fop.render"><B>PrintRendererConfigurator</B></A> (implements org.apache.fop.render.intermediate.<A HREF="../../../../../org/apache/fop/render/intermediate/IFDocumentHandlerConfigurator.html" title="interface in org.apache.fop.render.intermediate">IFDocumentHandlerConfigurator</A>, org.apache.fop.render.<A HREF="../../../../../org/apache/fop/render/RendererConfigurator.html" title="interface in org.apache.fop.render">RendererConfigurator</A>) <UL> <LI TYPE="circle">org.apache.fop.render.java2d.<A HREF="../../../../../org/apache/fop/render/java2d/Java2DRendererConfigurator.html" title="class in org.apache.fop.render.java2d"><B>Java2DRendererConfigurator</B></A><UL> <LI TYPE="circle">org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/BitmapRendererConfigurator.html" title="class in org.apache.fop.render.bitmap"><B>BitmapRendererConfigurator</B></A> (implements org.apache.fop.render.intermediate.<A HREF="../../../../../org/apache/fop/render/intermediate/IFDocumentHandlerConfigurator.html" title="interface in org.apache.fop.render.intermediate">IFDocumentHandlerConfigurator</A>) <UL> <LI TYPE="circle">org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/TIFFRendererConfigurator.html" title="class in org.apache.fop.render.bitmap"><B>TIFFRendererConfigurator</B></A></UL> </UL> </UL> </UL> </UL> <LI TYPE="circle">org.apache.fop.render.intermediate.<A HREF="../../../../../org/apache/fop/render/intermediate/AbstractIFDocumentHandler.html" title="class in org.apache.fop.render.intermediate"><B>AbstractIFDocumentHandler</B></A> (implements org.apache.fop.render.intermediate.<A HREF="../../../../../org/apache/fop/render/intermediate/IFDocumentHandler.html" title="interface in org.apache.fop.render.intermediate">IFDocumentHandler</A>) <UL> <LI TYPE="circle">org.apache.fop.render.intermediate.<A HREF="../../../../../org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.html" title="class in org.apache.fop.render.intermediate"><B>AbstractBinaryWritingIFDocumentHandler</B></A><UL> <LI TYPE="circle">org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.html" title="class in org.apache.fop.render.bitmap"><B>AbstractBitmapDocumentHandler</B></A><UL> <LI TYPE="circle">org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/PNGDocumentHandler.html" title="class in org.apache.fop.render.bitmap"><B>PNGDocumentHandler</B></A><LI TYPE="circle">org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/TIFFDocumentHandler.html" title="class in org.apache.fop.render.bitmap"><B>TIFFDocumentHandler</B></A></UL> </UL> </UL> <LI TYPE="circle">org.apache.fop.render.intermediate.<A HREF="../../../../../org/apache/fop/render/intermediate/AbstractIFDocumentHandlerMaker.html" title="class in org.apache.fop.render.intermediate"><B>AbstractIFDocumentHandlerMaker</B></A><UL> <LI TYPE="circle">org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/PNGDocumentHandlerMaker.html" title="class in org.apache.fop.render.bitmap"><B>PNGDocumentHandlerMaker</B></A><LI TYPE="circle">org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/TIFFDocumentHandlerMaker.html" title="class in org.apache.fop.render.bitmap"><B>TIFFDocumentHandlerMaker</B></A></UL> <LI TYPE="circle">org.apache.fop.render.<A HREF="../../../../../org/apache/fop/render/AbstractRenderer.html" title="class in org.apache.fop.render"><B>AbstractRenderer</B></A> (implements org.apache.fop.fo.<A HREF="../../../../../org/apache/fop/fo/Constants.html" title="interface in org.apache.fop.fo">Constants</A>, org.apache.fop.render.<A HREF="../../../../../org/apache/fop/render/Renderer.html" title="interface in org.apache.fop.render">Renderer</A>) <UL> <LI TYPE="circle">org.apache.fop.render.<A HREF="../../../../../org/apache/fop/render/PrintRenderer.html" title="class in org.apache.fop.render"><B>PrintRenderer</B></A><UL> <LI TYPE="circle">org.apache.fop.render.<A HREF="../../../../../org/apache/fop/render/AbstractPathOrientedRenderer.html" title="class in org.apache.fop.render"><B>AbstractPathOrientedRenderer</B></A><UL> <LI TYPE="circle">org.apache.fop.render.java2d.<A HREF="../../../../../org/apache/fop/render/java2d/Java2DRenderer.html" title="class in org.apache.fop.render.java2d"><B>Java2DRenderer</B></A> (implements java.awt.print.Printable) <UL> <LI TYPE="circle">org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/PNGRenderer.html" title="class in org.apache.fop.render.bitmap"><B>PNGRenderer</B></A><LI TYPE="circle">org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/TIFFRenderer.html" title="class in org.apache.fop.render.bitmap"><B>TIFFRenderer</B></A> (implements org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/TIFFConstants.html" title="interface in org.apache.fop.render.bitmap">TIFFConstants</A>) </UL> </UL> </UL> </UL> <LI TYPE="circle">org.apache.fop.render.<A HREF="../../../../../org/apache/fop/render/AbstractRendererMaker.html" title="class in org.apache.fop.render"><B>AbstractRendererMaker</B></A><UL> <LI TYPE="circle">org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/PNGRendererMaker.html" title="class in org.apache.fop.render.bitmap"><B>PNGRendererMaker</B></A><LI TYPE="circle">org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/TIFFRendererMaker.html" title="class in org.apache.fop.render.bitmap"><B>TIFFRendererMaker</B></A></UL> <LI TYPE="circle">org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/BitmapRendererEventProducer.Provider.html" title="class in org.apache.fop.render.bitmap"><B>BitmapRendererEventProducer.Provider</B></A><LI TYPE="circle">org.apache.fop.render.java2d.<A HREF="../../../../../org/apache/fop/render/java2d/Java2DRenderingSettings.html" title="class in org.apache.fop.render.java2d"><B>Java2DRenderingSettings</B></A><UL> <LI TYPE="circle">org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/BitmapRenderingSettings.html" title="class in org.apache.fop.render.bitmap"><B>BitmapRenderingSettings</B></A> (implements org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/TIFFConstants.html" title="interface in org.apache.fop.render.bitmap">TIFFConstants</A>) </UL> <LI TYPE="circle">org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/MultiFileRenderingUtil.html" title="class in org.apache.fop.render.bitmap"><B>MultiFileRenderingUtil</B></A></UL> </UL> <H2> Interface Hierarchy </H2> <UL> <LI TYPE="circle">org.apache.fop.events.<A HREF="../../../../../org/apache/fop/events/EventProducer.html" title="interface in org.apache.fop.events"><B>EventProducer</B></A><UL> <LI TYPE="circle">org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/BitmapRendererEventProducer.html" title="interface in org.apache.fop.render.bitmap"><B>BitmapRendererEventProducer</B></A></UL> <LI TYPE="circle">org.apache.fop.render.bitmap.<A HREF="../../../../../org/apache/fop/render/bitmap/TIFFConstants.html" title="interface in org.apache.fop.render.bitmap"><B>TIFFConstants</B></A></UL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> fop 1.1</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/fop/render/awt/viewer/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../../org/apache/fop/render/extensions/prepress/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/fop/render/bitmap/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright 1999-2012 The Apache Software Foundation. All Rights Reserved. </BODY> </HTML>
{ "content_hash": "4bd121802262233cd1dcf1db03a619d3", "timestamp": "", "source": "github", "line_count": 197, "max_line_length": 590, "avg_line_length": 71.30964467005076, "alnum_prop": 0.6749715261958997, "repo_name": "pconrad/ucsb-cs56-tutorials-fop", "id": "050d8f5b307b15ad44285d88c099a7c6b3fa7309", "size": "14048", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "fop-1.1/javadocs/org/apache/fop/render/bitmap/package-tree.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "23208" }, { "name": "Erlang", "bytes": "15684" }, { "name": "Java", "bytes": "210811" }, { "name": "JavaScript", "bytes": "28643" }, { "name": "Perl", "bytes": "12013" }, { "name": "R", "bytes": "223" }, { "name": "Shell", "bytes": "24838" }, { "name": "XSLT", "bytes": "25384" } ], "symlink_target": "" }
@import url(http://fonts.googleapis.com/css?family=Limelight); @import url(http://fonts.googleapis.com/css?family=Oswald); @import url(http://fonts.googleapis.com/css?family=Codystar); @import url(http://fonts.googleapis.com/css?family=Didact+Gothic); html, body { background: white; margin: 0; padding: 0; } nav, .navbar, .navbar-inner, .navbar-default, .navbar-default .navbar-collapse, .navbar-collapse { border-radius: 0px; background: none; border: none; } nav, .navbar-default { height: 0; } .navbar-inner a, .navbar-inner a:visited, .navbar-nav a, .navbar-nav a:visited, .navbar-default .navbar-nav > li > a, .navbar-default .navbar-nav > li > a:visited { margin-top: 5px; color: white; font-family: 'Didact Gothic'; font-size: 16px; transition-duration: .5s; transition-property: color; } .navbar-inner a:hover, .navbar-nav a:hover, .navbar-default .navbar-nav > li > a:hover { color: white; transition-duration: .5s; transition-property: color; } nav { width: 100%; position: fixed; z-index: 4; display: none; background: none; border-radius: 0px; border: none; } .navbar-inner { border-radius: 0px; border: none; background: rgb(1, 18, 25); /*Fall-back for browsers that don't support rgba */ background: rgba(1, 18, 25, .85); } nav input { /*border: 1px solid black;*/ /*font-family: 'Didact Gothic';*/ /*font-size: 15px;*/ /*padding-left: 30px;*/ /*padding-top: 5px;*/ /*line-height: 1.5;*/ } body#scroll a#weather-anchor { color: red; background: pink; }
{ "content_hash": "c2d5706acf30b8944934124b917ed72d", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 82, "avg_line_length": 19.14814814814815, "alnum_prop": 0.6698903932946486, "repo_name": "KorenLeslieCohen/worldview", "id": "089bf78c4f4c9b9f57a3a97c4b6df02bb9600203", "size": "1551", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/assets/stylesheets/nav.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "20235" }, { "name": "JavaScript", "bytes": "65000" }, { "name": "Ruby", "bytes": "47523" } ], "symlink_target": "" }
$(document).ready(function(){ var editor = ace.edit($(".z-ace-editor")[0]); editor.setTheme("ace/theme/clouds_midnight"); editor.getSession().setMode("ace/mode/html"); $('.z-editor-save').click(function(event) { var waitingStateButton = $ZentralButtons.wait($(this)); console.log(waitingStateButton); var post = $.post( "http://localhost:8080/leaf/save", { "leaf": editor.getValue() } ); post.done(function( data ) { var description = data.description; var title = "Success"; if(data.error) { description = data.error; title = "Failed"; alert("error"); } waitingStateButton.succeedAndReset(); }); post.fail(function(){ alert("failed"); }); event.preventDefault(); }); });
{ "content_hash": "d82b0cd2616c5290ee14df043dc5ce30", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 94, "avg_line_length": 27.59375, "alnum_prop": 0.5288788221970555, "repo_name": "ZENTRALALEX/LeafEditor", "id": "aca35158e2567be65eaaa60812c567dbd061f21b", "size": "883", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Public/assets/js/app/app.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3798" }, { "name": "JavaScript", "bytes": "3307" }, { "name": "Swift", "bytes": "4355" } ], "symlink_target": "" }
<?xml version="1.0"?> <!-- --> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <body> <referenceBlock name="checkout.cart.shipping"> <arguments> <argument name="jsLayout" xsi:type="array"> <item name="components" xsi:type="array"> <item name="summary-block-config" xsi:type="array"> <item name="children" xsi:type="array"> <item name="shipping-rates-validation" xsi:type="array"> <item name="children" xsi:type="array"> <item name="ups-rates-validation" xsi:type="array"> <item name="component" xsi:type="string">Magento_Ups/js/view/shipping-rates-validation</item> </item> </item> </item> </item> </item> </item> </argument> </arguments> </referenceBlock> </body> </page>
{ "content_hash": "8fdf80b8c2f85eee813029bb6e70ed3c", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 153, "avg_line_length": 46.81481481481482, "alnum_prop": 0.4438291139240506, "repo_name": "enettolima/magento-training", "id": "6cd979b862a6598b41f2ca6d6d4bb183373258ad", "size": "1362", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "magento2ce/app/code/Magento/Ups/view/frontend/layout/checkout_cart_index.xml", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "22648" }, { "name": "CSS", "bytes": "3382928" }, { "name": "HTML", "bytes": "8749335" }, { "name": "JavaScript", "bytes": "7355635" }, { "name": "PHP", "bytes": "58607662" }, { "name": "Perl", "bytes": "10258" }, { "name": "Shell", "bytes": "41887" }, { "name": "XSLT", "bytes": "19889" } ], "symlink_target": "" }
An Elixir module for generating [Gravatar](http://gravatar.com) urls. Make sure to check out the [Gravatar documentation](https://en.gravatar.com/site/implement/images/) for all available options. ## Usage ```elixir Exgravatar.generate "jdoe@example.com" #=> "http://gravatar.com/avatar/694ea0904ceaf766c6738166ed89bafb" Exgravatar.generate("jdoe@example.com", %{s: 256}) #=> "http://gravatar.com/avatar/694ea0904ceaf766c6738166ed89bafb?s=256" Exgravatar.generate("jdoe@example.com", %{}, true) #=> "https://secure.gravatar.com/avatar/694ea0904ceaf766c6738166ed89bafb" ```
{ "content_hash": "063fc71252788a23c6363badaa9e1c17", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 80, "avg_line_length": 30.473684210526315, "alnum_prop": 0.7599309153713298, "repo_name": "optikfluffel/exgravatar", "id": "6c82c7e91c361b490cdd7c4e67b3626c8c75fbe5", "size": "593", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Elixir", "bytes": "2762" } ], "symlink_target": "" }
id: tutorial-ingestion-spec title: "Tutorial: Writing an ingestion spec" sidebar_label: "Writing an ingestion spec" --- <!-- ~ Licensed to the Apache Software Foundation (ASF) under one ~ or more contributor license agreements. See the NOTICE file ~ distributed with this work for additional information ~ regarding copyright ownership. The ASF licenses this file ~ to you under the Apache License, Version 2.0 (the ~ "License"); you may not use this file except in compliance ~ with the License. You may obtain a copy of the License at ~ ~ http://www.apache.org/licenses/LICENSE-2.0 ~ ~ Unless required by applicable law or agreed to in writing, ~ software distributed under the License is distributed on an ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ~ KIND, either express or implied. See the License for the ~ specific language governing permissions and limitations ~ under the License. --> This tutorial will guide the reader through the process of defining an ingestion spec, pointing out key considerations and guidelines. For this tutorial, we'll assume you've already downloaded Apache Druid as described in the [single-machine quickstart](index.md) and have it running on your local machine. It will also be helpful to have finished [Tutorial: Loading a file](../tutorials/tutorial-batch.md), [Tutorial: Querying data](../tutorials/tutorial-query.md), and [Tutorial: Rollup](../tutorials/tutorial-rollup.md). ## Example data Suppose we have the following network flow data: * `srcIP`: IP address of sender * `srcPort`: Port of sender * `dstIP`: IP address of receiver * `dstPort`: Port of receiver * `protocol`: IP protocol number * `packets`: number of packets transmitted * `bytes`: number of bytes transmitted * `cost`: the cost of sending the traffic ```json {"ts":"2018-01-01T01:01:35Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2", "srcPort":2000, "dstPort":3000, "protocol": 6, "packets":10, "bytes":1000, "cost": 1.4} {"ts":"2018-01-01T01:01:51Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2", "srcPort":2000, "dstPort":3000, "protocol": 6, "packets":20, "bytes":2000, "cost": 3.1} {"ts":"2018-01-01T01:01:59Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2", "srcPort":2000, "dstPort":3000, "protocol": 6, "packets":30, "bytes":3000, "cost": 0.4} {"ts":"2018-01-01T01:02:14Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2", "srcPort":5000, "dstPort":7000, "protocol": 6, "packets":40, "bytes":4000, "cost": 7.9} {"ts":"2018-01-01T01:02:29Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2", "srcPort":5000, "dstPort":7000, "protocol": 6, "packets":50, "bytes":5000, "cost": 10.2} {"ts":"2018-01-01T01:03:29Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2", "srcPort":5000, "dstPort":7000, "protocol": 6, "packets":60, "bytes":6000, "cost": 4.3} {"ts":"2018-01-01T02:33:14Z","srcIP":"7.7.7.7", "dstIP":"8.8.8.8", "srcPort":4000, "dstPort":5000, "protocol": 17, "packets":100, "bytes":10000, "cost": 22.4} {"ts":"2018-01-01T02:33:45Z","srcIP":"7.7.7.7", "dstIP":"8.8.8.8", "srcPort":4000, "dstPort":5000, "protocol": 17, "packets":200, "bytes":20000, "cost": 34.5} {"ts":"2018-01-01T02:35:45Z","srcIP":"7.7.7.7", "dstIP":"8.8.8.8", "srcPort":4000, "dstPort":5000, "protocol": 17, "packets":300, "bytes":30000, "cost": 46.3} ``` Save the JSON contents above into a file called `ingestion-tutorial-data.json` in `quickstart/`. Let's walk through the process of defining an ingestion spec that can load this data. For this tutorial, we will be using the native batch indexing task. When using other task types, some aspects of the ingestion spec will differ, and this tutorial will point out such areas. ## Defining the schema The core element of a Druid ingestion spec is the `dataSchema`. The `dataSchema` defines how to parse input data into a set of columns that will be stored in Druid. Let's start with an empty `dataSchema` and add fields to it as we progress through the tutorial. Create a new file called `ingestion-tutorial-index.json` in `quickstart/` with the following contents: ```json "dataSchema" : {} ``` We will be making successive edits to this ingestion spec as we progress through the tutorial. ### Datasource name The datasource name is specified by the `dataSource` parameter in the `dataSchema`. ```json "dataSchema" : { "dataSource" : "ingestion-tutorial", } ``` Let's call the tutorial datasource `ingestion-tutorial`. ### Time column The `dataSchema` needs to know how to extract the main timestamp field from the input data. The timestamp column in our input data is named "ts", containing ISO 8601 timestamps, so let's add a `timestampSpec` with that information to the `dataSchema`: ```json "dataSchema" : { "dataSource" : "ingestion-tutorial", "timestampSpec" : { "format" : "iso", "column" : "ts" } } ``` ### Column types Now that we've defined the time column, let's look at definitions for other columns. Druid supports the following column types: String, Long, Float, Double. We will see how these are used in the following sections. Before we move on to how we define our other non-time columns, let's discuss `rollup` first. ### Rollup When ingesting data, we must consider whether we wish to use rollup or not. * If rollup is enabled, we will need to separate the input columns into two categories, "dimensions" and "metrics". "Dimensions" are the grouping columns for rollup, while "metrics" are the columns that will be aggregated. * If rollup is disabled, then all columns are treated as "dimensions" and no pre-aggregation occurs. For this tutorial, let's enable rollup. This is specified with a `granularitySpec` on the `dataSchema`. ```json "dataSchema" : { "dataSource" : "ingestion-tutorial", "timestampSpec" : { "format" : "iso", "column" : "ts" }, "granularitySpec" : { "rollup" : true } } ``` #### Choosing dimensions and metrics For this example dataset, the following is a sensible split for "dimensions" and "metrics": * Dimensions: srcIP, srcPort, dstIP, dstPort, protocol * Metrics: packets, bytes, cost The dimensions here are a group of properties that identify a unidirectional flow of IP traffic, while the metrics represent facts about the IP traffic flow specified by a dimension grouping. Let's look at how to define these dimensions and metrics within the ingestion spec. #### Dimensions Dimensions are specified with a `dimensionsSpec` inside the `dataSchema`. ```json "dataSchema" : { "dataSource" : "ingestion-tutorial", "timestampSpec" : { "format" : "iso", "column" : "ts" }, "dimensionsSpec" : { "dimensions": [ "srcIP", { "name" : "srcPort", "type" : "long" }, { "name" : "dstIP", "type" : "string" }, { "name" : "dstPort", "type" : "long" }, { "name" : "protocol", "type" : "string" } ] }, "granularitySpec" : { "rollup" : true } } ``` Each dimension has a `name` and a `type`, where `type` can be "long", "float", "double", or "string". Note that `srcIP` is a "string" dimension; for string dimensions, it is enough to specify just a dimension name, since "string" is the default dimension type. Also note that `protocol` is a numeric value in the input data, but we are ingesting it as a "string" column; Druid will coerce the input longs to strings during ingestion. ##### Strings vs. Numerics Should a numeric input be ingested as a numeric dimension or as a string dimension? Numeric dimensions have the following pros/cons relative to String dimensions: * Pros: Numeric representation can result in smaller column sizes on disk and lower processing overhead when reading values from the column * Cons: Numeric dimensions do not have indices, so filtering on them will often be slower than filtering on an equivalent String dimension (which has bitmap indices) #### Metrics Metrics are specified with a `metricsSpec` inside the `dataSchema`: ```json "dataSchema" : { "dataSource" : "ingestion-tutorial", "timestampSpec" : { "format" : "iso", "column" : "ts" }, "dimensionsSpec" : { "dimensions": [ "srcIP", { "name" : "srcPort", "type" : "long" }, { "name" : "dstIP", "type" : "string" }, { "name" : "dstPort", "type" : "long" }, { "name" : "protocol", "type" : "string" } ] }, "metricsSpec" : [ { "type" : "count", "name" : "count" }, { "type" : "longSum", "name" : "packets", "fieldName" : "packets" }, { "type" : "longSum", "name" : "bytes", "fieldName" : "bytes" }, { "type" : "doubleSum", "name" : "cost", "fieldName" : "cost" } ], "granularitySpec" : { "rollup" : true } } ``` When defining a metric, it is necessary to specify what type of aggregation should be performed on that column during rollup. Here we have defined long sum aggregations on the two long metric columns, `packets` and `bytes`, and a double sum aggregation for the `cost` column. Note that the `metricsSpec` is on a different nesting level than `dimensionSpec` or `parseSpec`; it belongs on the same nesting level as `parser` within the `dataSchema`. Note that we have also defined a `count` aggregator. The count aggregator will track how many rows in the original input data contributed to a "rolled up" row in the final ingested data. ### No rollup If we were not using rollup, all columns would be specified in the `dimensionsSpec`, e.g.: ```json "dimensionsSpec" : { "dimensions": [ "srcIP", { "name" : "srcPort", "type" : "long" }, { "name" : "dstIP", "type" : "string" }, { "name" : "dstPort", "type" : "long" }, { "name" : "protocol", "type" : "string" }, { "name" : "packets", "type" : "long" }, { "name" : "bytes", "type" : "long" }, { "name" : "srcPort", "type" : "double" } ] }, ``` ### Define granularities At this point, we are done defining the `parser` and `metricsSpec` within the `dataSchema` and we are almost done writing the ingestion spec. There are some additional properties we need to set in the `granularitySpec`: * Type of granularitySpec: `uniform` and `arbitrary` are the two supported types. For this tutorial, we will use a `uniform` granularity spec, where all segments have uniform interval sizes (for example, all segments cover an hour's worth of data). * The segment granularity: what size of time interval should a single segment contain data for? e.g., `DAY`, `WEEK` * The bucketing granularity of the timestamps in the time column (referred to as `queryGranularity`) #### Segment granularity Segment granularity is configured by the `segmentGranularity` property in the `granularitySpec`. For this tutorial, we'll create hourly segments: ```json "dataSchema" : { "dataSource" : "ingestion-tutorial", "timestampSpec" : { "format" : "iso", "column" : "ts" }, "dimensionsSpec" : { "dimensions": [ "srcIP", { "name" : "srcPort", "type" : "long" }, { "name" : "dstIP", "type" : "string" }, { "name" : "dstPort", "type" : "long" }, { "name" : "protocol", "type" : "string" } ] }, "metricsSpec" : [ { "type" : "count", "name" : "count" }, { "type" : "longSum", "name" : "packets", "fieldName" : "packets" }, { "type" : "longSum", "name" : "bytes", "fieldName" : "bytes" }, { "type" : "doubleSum", "name" : "cost", "fieldName" : "cost" } ], "granularitySpec" : { "type" : "uniform", "segmentGranularity" : "HOUR", "rollup" : true } } ``` Our input data has events from two separate hours, so this task will generate two segments. #### Query granularity The query granularity is configured by the `queryGranularity` property in the `granularitySpec`. For this tutorial, let's use minute granularity: ```json "dataSchema" : { "dataSource" : "ingestion-tutorial", "timestampSpec" : { "format" : "iso", "column" : "ts" }, "dimensionsSpec" : { "dimensions": [ "srcIP", { "name" : "srcPort", "type" : "long" }, { "name" : "dstIP", "type" : "string" }, { "name" : "dstPort", "type" : "long" }, { "name" : "protocol", "type" : "string" } ] }, "metricsSpec" : [ { "type" : "count", "name" : "count" }, { "type" : "longSum", "name" : "packets", "fieldName" : "packets" }, { "type" : "longSum", "name" : "bytes", "fieldName" : "bytes" }, { "type" : "doubleSum", "name" : "cost", "fieldName" : "cost" } ], "granularitySpec" : { "type" : "uniform", "segmentGranularity" : "HOUR", "queryGranularity" : "MINUTE", "rollup" : true } } ``` To see the effect of the query granularity, let's look at this row from the raw input data: ```json {"ts":"2018-01-01T01:03:29Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2", "srcPort":5000, "dstPort":7000, "protocol": 6, "packets":60, "bytes":6000, "cost": 4.3} ``` When this row is ingested with minute queryGranularity, Druid will floor the row's timestamp to minute buckets: ```json {"ts":"2018-01-01T01:03:00Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2", "srcPort":5000, "dstPort":7000, "protocol": 6, "packets":60, "bytes":6000, "cost": 4.3} ``` #### Define an interval (batch only) For batch tasks, it is necessary to define a time interval. Input rows with timestamps outside of the time interval will not be ingested. The interval is also specified in the `granularitySpec`: ```json "dataSchema" : { "dataSource" : "ingestion-tutorial", "timestampSpec" : { "format" : "iso", "column" : "ts" }, "dimensionsSpec" : { "dimensions": [ "srcIP", { "name" : "srcPort", "type" : "long" }, { "name" : "dstIP", "type" : "string" }, { "name" : "dstPort", "type" : "long" }, { "name" : "protocol", "type" : "string" } ] }, "metricsSpec" : [ { "type" : "count", "name" : "count" }, { "type" : "longSum", "name" : "packets", "fieldName" : "packets" }, { "type" : "longSum", "name" : "bytes", "fieldName" : "bytes" }, { "type" : "doubleSum", "name" : "cost", "fieldName" : "cost" } ], "granularitySpec" : { "type" : "uniform", "segmentGranularity" : "HOUR", "queryGranularity" : "MINUTE", "intervals" : ["2018-01-01/2018-01-02"], "rollup" : true } } ``` ## Define the task type We've now finished defining our `dataSchema`. The remaining steps are to place the `dataSchema` we created into an ingestion task spec, and specify the input source. The `dataSchema` is shared across all task types, but each task type has its own specification format. For this tutorial, we will use the native batch ingestion task: ```json { "type" : "index_parallel", "spec" : { "dataSchema" : { "dataSource" : "ingestion-tutorial", "timestampSpec" : { "format" : "iso", "column" : "ts" }, "dimensionsSpec" : { "dimensions": [ "srcIP", { "name" : "srcPort", "type" : "long" }, { "name" : "dstIP", "type" : "string" }, { "name" : "dstPort", "type" : "long" }, { "name" : "protocol", "type" : "string" } ] }, "metricsSpec" : [ { "type" : "count", "name" : "count" }, { "type" : "longSum", "name" : "packets", "fieldName" : "packets" }, { "type" : "longSum", "name" : "bytes", "fieldName" : "bytes" }, { "type" : "doubleSum", "name" : "cost", "fieldName" : "cost" } ], "granularitySpec" : { "type" : "uniform", "segmentGranularity" : "HOUR", "queryGranularity" : "MINUTE", "intervals" : ["2018-01-01/2018-01-02"], "rollup" : true } } } } ``` ## Define the input source Now let's define our input source, which is specified in an `ioConfig` object. Each task type has its own type of `ioConfig`. To read input data, we need to specify an `inputSource`. The example netflow data we saved earlier needs to be read from a local file, which is configured below: ```json "ioConfig" : { "type" : "index_parallel", "inputSource" : { "type" : "local", "baseDir" : "quickstart/", "filter" : "ingestion-tutorial-data.json" } } ``` ### Define the format of the data Since our input data is represented as JSON strings, we'll use a `inputFormat` to `json` format: ```json "ioConfig" : { "type" : "index_parallel", "inputSource" : { "type" : "local", "baseDir" : "quickstart/", "filter" : "ingestion-tutorial-data.json" }, "inputFormat" : { "type" : "json" } } ``` ```json { "type" : "index_parallel", "spec" : { "dataSchema" : { "dataSource" : "ingestion-tutorial", "timestampSpec" : { "format" : "iso", "column" : "ts" }, "dimensionsSpec" : { "dimensions": [ "srcIP", { "name" : "srcPort", "type" : "long" }, { "name" : "dstIP", "type" : "string" }, { "name" : "dstPort", "type" : "long" }, { "name" : "protocol", "type" : "string" } ] }, "metricsSpec" : [ { "type" : "count", "name" : "count" }, { "type" : "longSum", "name" : "packets", "fieldName" : "packets" }, { "type" : "longSum", "name" : "bytes", "fieldName" : "bytes" }, { "type" : "doubleSum", "name" : "cost", "fieldName" : "cost" } ], "granularitySpec" : { "type" : "uniform", "segmentGranularity" : "HOUR", "queryGranularity" : "MINUTE", "intervals" : ["2018-01-01/2018-01-02"], "rollup" : true } }, "ioConfig" : { "type" : "index_parallel", "inputSource" : { "type" : "local", "baseDir" : "quickstart/", "filter" : "ingestion-tutorial-data.json" }, "inputFormat" : { "type" : "json" } } } } ``` ## Additional tuning Each ingestion task has a `tuningConfig` section that allows users to tune various ingestion parameters. As an example, let's add a `tuningConfig` that sets a target segment size for the native batch ingestion task: ```json "tuningConfig" : { "type" : "index_parallel", "maxRowsPerSegment" : 5000000 } ``` Note that each ingestion task has its own type of `tuningConfig`. ## Final spec We've finished defining the ingestion spec, it should now look like the following: ```json { "type" : "index_parallel", "spec" : { "dataSchema" : { "dataSource" : "ingestion-tutorial", "timestampSpec" : { "format" : "iso", "column" : "ts" }, "dimensionsSpec" : { "dimensions": [ "srcIP", { "name" : "srcPort", "type" : "long" }, { "name" : "dstIP", "type" : "string" }, { "name" : "dstPort", "type" : "long" }, { "name" : "protocol", "type" : "string" } ] }, "metricsSpec" : [ { "type" : "count", "name" : "count" }, { "type" : "longSum", "name" : "packets", "fieldName" : "packets" }, { "type" : "longSum", "name" : "bytes", "fieldName" : "bytes" }, { "type" : "doubleSum", "name" : "cost", "fieldName" : "cost" } ], "granularitySpec" : { "type" : "uniform", "segmentGranularity" : "HOUR", "queryGranularity" : "MINUTE", "intervals" : ["2018-01-01/2018-01-02"], "rollup" : true } }, "ioConfig" : { "type" : "index_parallel", "inputSource" : { "type" : "local", "baseDir" : "quickstart/", "filter" : "ingestion-tutorial-data.json" }, "inputFormat" : { "type" : "json" } }, "tuningConfig" : { "type" : "index_parallel", "maxRowsPerSegment" : 5000000 } } } ``` ## Submit the task and query the data From the apache-druid-{{DRUIDVERSION}} package root, run the following command: ```bash bin/post-index-task --file quickstart/ingestion-tutorial-index.json --url http://localhost:8081 ``` After the script completes, we will query the data. Let's run `bin/dsql` and issue a `select * from "ingestion-tutorial";` query to see what data was ingested. ```bash $ bin/dsql Welcome to dsql, the command-line client for Druid SQL. Type "\h" for help. dsql> select * from "ingestion-tutorial"; ┌──────────────────────────┬───────┬──────┬───────┬─────────┬─────────┬─────────┬──────────┬─────────┬─────────┐ │ __time │ bytes │ cost │ count │ dstIP │ dstPort │ packets │ protocol │ srcIP │ srcPort │ ├──────────────────────────┼───────┼──────┼───────┼─────────┼─────────┼─────────┼──────────┼─────────┼─────────┤ │ 2018-01-01T01:01:00.000Z │ 6000 │ 4.9 │ 3 │ 2.2.2.2 │ 3000 │ 60 │ 6 │ 1.1.1.1 │ 2000 │ │ 2018-01-01T01:02:00.000Z │ 9000 │ 18.1 │ 2 │ 2.2.2.2 │ 7000 │ 90 │ 6 │ 1.1.1.1 │ 5000 │ │ 2018-01-01T01:03:00.000Z │ 6000 │ 4.3 │ 1 │ 2.2.2.2 │ 7000 │ 60 │ 6 │ 1.1.1.1 │ 5000 │ │ 2018-01-01T02:33:00.000Z │ 30000 │ 56.9 │ 2 │ 8.8.8.8 │ 5000 │ 300 │ 17 │ 7.7.7.7 │ 4000 │ │ 2018-01-01T02:35:00.000Z │ 30000 │ 46.3 │ 1 │ 8.8.8.8 │ 5000 │ 300 │ 17 │ 7.7.7.7 │ 4000 │ └──────────────────────────┴───────┴──────┴───────┴─────────┴─────────┴─────────┴──────────┴─────────┴─────────┘ Retrieved 5 rows in 0.12s. dsql> ```
{ "content_hash": "001c6ffbafbe85ec12348b286ae3a69e", "timestamp": "", "source": "github", "line_count": 605, "max_line_length": 287, "avg_line_length": 35.23801652892562, "alnum_prop": 0.5985740419344246, "repo_name": "gianm/druid", "id": "821c376f637fcfee97c3191dd02d43caf0a07e39", "size": "22127", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "docs/tutorials/tutorial-ingestion-spec.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "5110" }, { "name": "CSS", "bytes": "3878" }, { "name": "Dockerfile", "bytes": "10908" }, { "name": "HTML", "bytes": "1395" }, { "name": "Java", "bytes": "32481190" }, { "name": "JavaScript", "bytes": "58501" }, { "name": "Makefile", "bytes": "659" }, { "name": "PostScript", "bytes": "5" }, { "name": "Python", "bytes": "54400" }, { "name": "R", "bytes": "17002" }, { "name": "Roff", "bytes": "3617" }, { "name": "SCSS", "bytes": "109059" }, { "name": "Shell", "bytes": "77140" }, { "name": "Stylus", "bytes": "7682" }, { "name": "TeX", "bytes": "399468" }, { "name": "Thrift", "bytes": "1003" }, { "name": "TypeScript", "bytes": "1179506" } ], "symlink_target": "" }
require "yaml" module CtsPapertrailSerializer extend self # makes all instance methods become module methods as well def load(string) hash = ::YAML.load string if hash.key?('properties') properties_hash = ::JSON.parse(hash['properties']) properties_hash.each do | key, value| hash[key] = value end end hash end def dump(object) ::YAML.dump object end # Returns a SQL LIKE condition to be used to match the given field and # value in the serialized object. def where_object_condition(arel_field, field, value) arel_field.matches("%\n#{field}: #{value}\n%") end # Returns a SQL LIKE condition to be used to match the given field and # value in the serialized `object_changes`. def where_object_changes_condition(*) raise <<-STR.squish.freeze where_object_changes no longer supports reading YAML from a text column. The old implementation was inaccurate, returning more records than you wanted. This feature was deprecated in 8.1.0 and removed in 9.0.0. The json and jsonb datatypes are still supported. See discussion at https://github.com/airblade/paper_trail/pull/997 STR end end
{ "content_hash": "9e976ddc15bfef991a2907a532079cca", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 75, "avg_line_length": 30.025, "alnum_prop": 0.694421315570358, "repo_name": "ministryofjustice/correspondence_tool_staff", "id": "693e971140b78fb58269c731abb8fc90536e531f", "size": "1232", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "lib/cts_papertrail_serializer.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "383" }, { "name": "Dockerfile", "bytes": "1559" }, { "name": "HTML", "bytes": "83918" }, { "name": "JavaScript", "bytes": "50629" }, { "name": "Procfile", "bytes": "174" }, { "name": "Python", "bytes": "5159" }, { "name": "Ruby", "bytes": "4621757" }, { "name": "SCSS", "bytes": "38011" }, { "name": "Shell", "bytes": "11912" }, { "name": "Slim", "bytes": "253831" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "0b875820d9fa6dfdc611dab70b0ea661", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "21fda662312de3fe87ee6e360196ebf3f7302ec8", "size": "187", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Campanulaceae/Clermontia/Clermontia calophylla/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "82946dfa77760a81d33af3256fba84a5", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "0e3442a3ea813c8430059162bf4d3c8334bea62e", "size": "190", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Cornales/Cornaceae/Thelycrania/Thelycrania asperifolia/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
export TEXINPUTS=../tex//: all: thesis.pdf # LaTeX must be run multiple times to get references right thesis.pdf: thesis.tex $(wildcard *.tex) bibliography-jabref.bib thesis.xmpdata pdflatex $< bibtex thesis pdflatex $< pdflatex $< pdflatex $< clean: rm -f *.log *.dvi *.aux *.toc *.lof *.lot *.out *.bbl *.blg *.xmpi rm -f thesis.pdf
{ "content_hash": "51ea472a79e93b4180953c33ccba43a3", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 79, "avg_line_length": 23, "alnum_prop": 0.6811594202898551, "repo_name": "oskopek/TransportEditor", "id": "1db0146700cd625a1ce445a76c4f64ccfb46495a", "size": "345", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "transport-docs/bp/en/Makefile", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "10460" }, { "name": "CSS", "bytes": "814" }, { "name": "FreeMarker", "bytes": "11453" }, { "name": "HTML", "bytes": "115896" }, { "name": "Java", "bytes": "962140" }, { "name": "Makefile", "bytes": "801" }, { "name": "Prolog", "bytes": "14778" }, { "name": "Python", "bytes": "29590" }, { "name": "Shell", "bytes": "43125" }, { "name": "TeX", "bytes": "532024" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_27) on Wed Nov 21 16:03:52 EST 2012 --> <TITLE> org.pentaho.di.trans.steps.rest </TITLE> <META NAME="date" CONTENT="2012-11-21"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.pentaho.di.trans.steps.rest"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../org/pentaho/di/trans/steps/reservoirsampling/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../org/pentaho/di/trans/steps/rowgenerator/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/pentaho/di/trans/steps/rest/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <H2> Package org.pentaho.di.trans.steps.rest </H2> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Class Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/pentaho/di/trans/steps/rest/Rest.html" title="class in org.pentaho.di.trans.steps.rest">Rest</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/pentaho/di/trans/steps/rest/RestData.html" title="class in org.pentaho.di.trans.steps.rest">RestData</A></B></TD> <TD>&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD WIDTH="15%"><B><A HREF="../../../../../../org/pentaho/di/trans/steps/rest/RestMeta.html" title="class in org.pentaho.di.trans.steps.rest">RestMeta</A></B></TD> <TD>&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <DL> </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-use.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../../org/pentaho/di/trans/steps/reservoirsampling/package-summary.html"><B>PREV PACKAGE</B></A>&nbsp; &nbsp;<A HREF="../../../../../../org/pentaho/di/trans/steps/rowgenerator/package-summary.html"><B>NEXT PACKAGE</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/pentaho/di/trans/steps/rest/package-summary.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-summary.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
{ "content_hash": "d90c5baca8bf2e95dd5d035ca8b5bd36", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 163, "avg_line_length": 42.012121212121215, "alnum_prop": 0.6090594345066359, "repo_name": "ColFusion/PentahoKettle", "id": "07590e7ed1eb1c419b3dc688f5a9b03468cae71b", "size": "6932", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kettle-data-integration/docs/api/org/pentaho/di/trans/steps/rest/package-summary.html", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "21071" }, { "name": "Batchfile", "bytes": "21366" }, { "name": "C", "bytes": "7006" }, { "name": "CSS", "bytes": "1952277" }, { "name": "Groff", "bytes": "684" }, { "name": "Groovy", "bytes": "33843" }, { "name": "HTML", "bytes": "197173221" }, { "name": "Java", "bytes": "3685348" }, { "name": "JavaScript", "bytes": "31972698" }, { "name": "PHP", "bytes": "224688" }, { "name": "Perl", "bytes": "6881" }, { "name": "PigLatin", "bytes": "7496" }, { "name": "Python", "bytes": "109487" }, { "name": "Shell", "bytes": "43881" }, { "name": "Smarty", "bytes": "2952" }, { "name": "XQuery", "bytes": "798" }, { "name": "XSLT", "bytes": "562453" } ], "symlink_target": "" }
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v0.11.0-master-3e34e02 */ goog.provide('ng.material.components.toolbar'); goog.require('ng.material.components.content'); goog.require('ng.material.core'); /** * @ngdoc module * @name material.components.toolbar */ angular.module('material.components.toolbar', [ 'material.core', 'material.components.content' ]) .directive('mdToolbar', mdToolbarDirective); /** * @ngdoc directive * @name mdToolbar * @module material.components.toolbar * @restrict E * @description * `md-toolbar` is used to place a toolbar in your app. * * Toolbars are usually used above a content area to display the title of the * current page, and show relevant action buttons for that page. * * You can change the height of the toolbar by adding either the * `md-medium-tall` or `md-tall` class to the toolbar. * * @usage * <hljs lang="html"> * <div layout="column" layout-fill> * <md-toolbar> * * <div class="md-toolbar-tools"> * <span>My App's Title</span> * * <!-- fill up the space between left and right area --> * <span flex></span> * * <md-button> * Right Bar Button * </md-button> * </div> * * </md-toolbar> * <md-content> * Hello! * </md-content> * </div> * </hljs> * * @param {boolean=} md-scroll-shrink Whether the header should shrink away as * the user scrolls down, and reveal itself as the user scrolls up. * _**Note (1):** for scrollShrink to work, the toolbar must be a sibling of a * `md-content` element, placed before it. See the scroll shrink demo._ * _**Note (2):** The `md-scroll-shrink` attribute is only parsed on component * initialization, it does not watch for scope changes._ * * * @param {number=} md-shrink-speed-factor How much to change the speed of the toolbar's * shrinking by. For example, if 0.25 is given then the toolbar will shrink * at one fourth the rate at which the user scrolls down. Default 0.5. */ function mdToolbarDirective($$rAF, $mdConstant, $mdUtil, $mdTheming, $animate) { var translateY = angular.bind(null, $mdUtil.supplant, 'translate3d(0,{0}px,0)'); return { restrict: 'E', link: function(scope, element, attr) { $mdTheming(element); if (angular.isDefined(attr.mdScrollShrink)) { setupScrollShrink(); } function setupScrollShrink() { var toolbarHeight; var contentElement; var disableScrollShrink = angular.noop; // Current "y" position of scroll // Store the last scroll top position var y = 0; var prevScrollTop = 0; var shrinkSpeedFactor = attr.mdShrinkSpeedFactor || 0.5; var debouncedContentScroll = $$rAF.throttle(onContentScroll); var debouncedUpdateHeight = $mdUtil.debounce(updateToolbarHeight, 5 * 1000); // Wait for $mdContentLoaded event from mdContent directive. // If the mdContent element is a sibling of our toolbar, hook it up // to scroll events. scope.$on('$mdContentLoaded', onMdContentLoad); // If the toolbar is used inside an ng-if statement, we may miss the // $mdContentLoaded event, so we attempt to fake it if we have a // md-content close enough. attr.$observe('mdScrollShrink', onChangeScrollShrink); // If the scope is destroyed (which could happen with ng-if), make sure // to disable scroll shrinking again scope.$on('$destroy', disableScrollShrink); /** * */ function onChangeScrollShrink(shrinkWithScroll) { var closestContent = element.parent().find('md-content'); // If we have a content element, fake the call; this might still fail // if the content element isn't a sibling of the toolbar if (!contentElement && closestContent.length) { onMdContentLoad(null, closestContent); } // Evaluate the expression shrinkWithScroll = scope.$eval(shrinkWithScroll); // Disable only if the attribute's expression evaluates to false if (shrinkWithScroll === false) { disableScrollShrink(); } else { disableScrollShrink = enableScrollShrink(); } } /** * */ function onMdContentLoad($event, newContentEl) { // Toolbar and content must be siblings if (newContentEl && element.parent()[0] === newContentEl.parent()[0]) { // unhook old content event listener if exists if (contentElement) { contentElement.off('scroll', debouncedContentScroll); } contentElement = newContentEl; disableScrollShrink = enableScrollShrink(); } } /** * */ function onContentScroll(e) { var scrollTop = e ? e.target.scrollTop : prevScrollTop; debouncedUpdateHeight(); y = Math.min( toolbarHeight / shrinkSpeedFactor, Math.max(0, y + scrollTop - prevScrollTop) ); element.css($mdConstant.CSS.TRANSFORM, translateY([-y * shrinkSpeedFactor])); contentElement.css($mdConstant.CSS.TRANSFORM, translateY([(toolbarHeight - y) * shrinkSpeedFactor])); prevScrollTop = scrollTop; $mdUtil.nextTick(function() { var hasWhiteFrame = element.hasClass('md-whiteframe-z1'); if (hasWhiteFrame && !y) { $animate.removeClass(element, 'md-whiteframe-z1'); } else if (!hasWhiteFrame && y) { $animate.addClass(element, 'md-whiteframe-z1'); } }); } /** * */ function enableScrollShrink() { if (!contentElement) return angular.noop; // no md-content contentElement.on('scroll', debouncedContentScroll); contentElement.attr('scroll-shrink', 'true'); $$rAF(updateToolbarHeight); return function disableScrollShrink() { contentElement.off('scroll', debouncedContentScroll); contentElement.attr('scroll-shrink', 'false'); $$rAF(updateToolbarHeight); } } /** * */ function updateToolbarHeight() { toolbarHeight = element.prop('offsetHeight'); // Add a negative margin-top the size of the toolbar to the content el. // The content will start transformed down the toolbarHeight amount, // so everything looks normal. // // As the user scrolls down, the content will be transformed up slowly // to put the content underneath where the toolbar was. var margin = (-toolbarHeight * shrinkSpeedFactor) + 'px'; contentElement.css({ "margin-top": margin, "margin-bottom": margin }); onContentScroll(); } } } }; } mdToolbarDirective.$inject = ["$$rAF", "$mdConstant", "$mdUtil", "$mdTheming", "$animate"]; ng.material.components.toolbar = angular.module("material.components.toolbar");
{ "content_hash": "8b96cda6dd930dd38156e52d5d41e1f2", "timestamp": "", "source": "github", "line_count": 234, "max_line_length": 111, "avg_line_length": 30.94017094017094, "alnum_prop": 0.6053867403314918, "repo_name": "jzucadi/bower-material", "id": "da8ab319f5bb7eb61f8f7d0035344fb6f8e7b1ce", "size": "7240", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/closure/toolbar/toolbar.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "854675" }, { "name": "JavaScript", "bytes": "1546843" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>maths: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.7.1+1 / maths - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> maths <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-11-12 06:37:06 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-12 06:37:06 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.7.1+1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.04.2 The OCaml compiler (virtual package) ocaml-base-compiler 4.04.2 Official 4.04.2 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/maths&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Maths&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: mathematics&quot; &quot;category: Mathematics/Arithmetic and Number Theory/Number theory&quot; ] authors: [ &quot;Jean-Christophe Filliâtre&quot; ] bug-reports: &quot;https://github.com/coq-contribs/maths/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/maths.git&quot; synopsis: &quot;Basic mathematics&quot; description: &quot;&quot;&quot; Basic mathematics (gcd, primality, etc.) from French ``Mathematiques Superieures&#39;&#39; (first year of preparation to high schools)&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/maths/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=c41fb2a85a1a015d2c6188dbe75211ec&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-maths.8.8.0 coq.8.7.1+1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+1). The following dependencies couldn&#39;t be met: - coq-maths -&gt; coq &gt;= 8.8 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-maths.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "076babacd6c7d5f06eee3993d5c7c789", "timestamp": "", "source": "github", "line_count": 168, "max_line_length": 159, "avg_line_length": 41.357142857142854, "alnum_prop": 0.5392918825561313, "repo_name": "coq-bench/coq-bench.github.io", "id": "2f960fdbeb4f0b431c789696fab54b44f0057683", "size": "6974", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.04.2-2.0.5/released/8.7.1+1/maths/8.8.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
"use strict"; const _serializer = _ros_msg_utils.Serialize; const _arraySerializer = _serializer.Array; const _deserializer = _ros_msg_utils.Deserialize; const _arrayDeserializer = _deserializer.Array; const _finder = _ros_msg_utils.Find; const _getByteLength = _ros_msg_utils.getByteLength; //----------------------------------------------------------- //----------------------------------------------------------- class LoadControllerRequest { constructor(initObj={}) { if (initObj === null) { // initObj === null is a special case for deserialization where we don't initialize fields this.name = null; } else { if (initObj.hasOwnProperty('name')) { this.name = initObj.name } else { this.name = ''; } } } static serialize(obj, buffer, bufferOffset) { // Serializes a message object of type LoadControllerRequest // Serialize message field [name] bufferOffset = _serializer.string(obj.name, buffer, bufferOffset); return bufferOffset; } static deserialize(buffer, bufferOffset=[0]) { //deserializes a message object of type LoadControllerRequest let len; let data = new LoadControllerRequest(null); // Deserialize message field [name] data.name = _deserializer.string(buffer, bufferOffset); return data; } static getMessageSize(object) { let length = 0; length += object.name.length; return length + 4; } static datatype() { // Returns string type for a service object return 'controller_manager_msgs/LoadControllerRequest'; } static md5sum() { //Returns md5sum for a message object return 'c1f3d28f1b044c871e6eff2e9fc3c667'; } static messageDefinition() { // Returns full string definition for message return ` string name `; } static Resolve(msg) { // deep-construct a valid message object instance of whatever was passed in if (typeof msg !== 'object' || msg === null) { msg = {}; } const resolved = new LoadControllerRequest(null); if (msg.name !== undefined) { resolved.name = msg.name; } else { resolved.name = '' } return resolved; } }; class LoadControllerResponse { constructor(initObj={}) { if (initObj === null) { // initObj === null is a special case for deserialization where we don't initialize fields this.ok = null; } else { if (initObj.hasOwnProperty('ok')) { this.ok = initObj.ok } else { this.ok = false; } } } static serialize(obj, buffer, bufferOffset) { // Serializes a message object of type LoadControllerResponse // Serialize message field [ok] bufferOffset = _serializer.bool(obj.ok, buffer, bufferOffset); return bufferOffset; } static deserialize(buffer, bufferOffset=[0]) { //deserializes a message object of type LoadControllerResponse let len; let data = new LoadControllerResponse(null); // Deserialize message field [ok] data.ok = _deserializer.bool(buffer, bufferOffset); return data; } static getMessageSize(object) { return 1; } static datatype() { // Returns string type for a service object return 'controller_manager_msgs/LoadControllerResponse'; } static md5sum() { //Returns md5sum for a message object return '6f6da3883749771fac40d6deb24a8c02'; } static messageDefinition() { // Returns full string definition for message return ` bool ok `; } static Resolve(msg) { // deep-construct a valid message object instance of whatever was passed in if (typeof msg !== 'object' || msg === null) { msg = {}; } const resolved = new LoadControllerResponse(null); if (msg.ok !== undefined) { resolved.ok = msg.ok; } else { resolved.ok = false } return resolved; } }; module.exports = { Request: LoadControllerRequest, Response: LoadControllerResponse, md5sum() { return '647e5c54b8d6468952d8d31f1efe96c0'; }, datatype() { return 'controller_manager_msgs/LoadController'; } };
{ "content_hash": "6031d226d3872007e0053f197a5f9c75", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 96, "avg_line_length": 24.304093567251464, "alnum_prop": 0.6239172281039461, "repo_name": "robotic-ultrasound-image-system/ur5", "id": "b4b25bb4db2e1e5874a8f8005ed5370c51a8a2a0", "size": "4235", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "devel/share/gennodejs/ros/controller_manager_msgs/srv/LoadController.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "17111" }, { "name": "C++", "bytes": "4358268" }, { "name": "CMake", "bytes": "1608648" }, { "name": "Common Lisp", "bytes": "443315" }, { "name": "JavaScript", "bytes": "154418" }, { "name": "Makefile", "bytes": "7723731" }, { "name": "Python", "bytes": "1088943" }, { "name": "Shell", "bytes": "19219" } ], "symlink_target": "" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_memcpy_14.c Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.string.label.xml Template File: sources-sink-14.tmpl.c */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using malloc() and set data pointer to a small buffer * GoodSource: Allocate using malloc() and set data pointer to a large buffer * Sink: memcpy * BadSink : Copy string to data using memcpy * Flow Variant: 14 Control flow: if(globalFive==5) and if(globalFive!=5) * * */ #include "std_testcase.h" #include <wchar.h> #ifndef OMITBAD void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_memcpy_14_bad() { wchar_t * data; data = NULL; if(globalFive==5) { /* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */ data = (wchar_t *)malloc(50*sizeof(wchar_t)); if (data == NULL) {exit(-1);} data[0] = L'\0'; /* null terminate */ } { wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ memcpy(data, source, 100*sizeof(wchar_t)); data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ printWLine(data); free(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the globalFive==5 to globalFive!=5 */ static void goodG2B1() { wchar_t * data; data = NULL; if(globalFive!=5) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = (wchar_t *)malloc(100*sizeof(wchar_t)); if (data == NULL) {exit(-1);} data[0] = L'\0'; /* null terminate */ } { wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ memcpy(data, source, 100*sizeof(wchar_t)); data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ printWLine(data); free(data); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { wchar_t * data; data = NULL; if(globalFive==5) { /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */ data = (wchar_t *)malloc(100*sizeof(wchar_t)); if (data == NULL) {exit(-1);} data[0] = L'\0'; /* null terminate */ } { wchar_t source[100]; wmemset(source, L'C', 100-1); /* fill with L'C's */ source[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ memcpy(data, source, 100*sizeof(wchar_t)); data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ printWLine(data); free(data); } } void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_memcpy_14_good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_memcpy_14_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_memcpy_14_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "content_hash": "2ebe803719e580974ce59b922905d4e3", "timestamp": "", "source": "github", "line_count": 136, "max_line_length": 123, "avg_line_length": 32.86764705882353, "alnum_prop": 0.6031319910514541, "repo_name": "JianpingZeng/xcc", "id": "ec096ebbc61a31662c2d5c15b53c1757aaef7bdb", "size": "4470", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xcc/test/juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s08/CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_memcpy_14.c", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
var certificate_panel = $("#CertificatePanel"); var domain_panel = $("#DomainPanel"); var ip_panel = $("#IpPanel"); var alert_panel = $("#AlertPanel"); var certificate_url = "/monitors/view_certificates"; var domain_url = "/monitors/view_domains"; var ip_url = "/monitors/view_ips"; var alert_url = "/monitors/view_alerts"; var main_content = $("#content"); function initialize_datatable(table_element) { $(table_element).dataTable({ "iDisplayLength": 25, "info": false, "bLengthChange": false, "bFilter": true, "aaSorting": [[2, "desc"]] }); } // Load a specified panel section with a given URL function load_panel(target_panel, target_url) { $.ajax({ url: target_url, type: "GET", success:function(content){ // Load ajax results into target panel and identify item count target_panel.html(content); var panel_count = target_panel.find('table[data-count]').attr('data-count'); var panel_table = target_panel.find('table').attr('id'); if (panel_table !== undefined) { initialize_datatable("#"+panel_table); } // Find corresponding tab list header item for badge population var panel_tab = $('ul[role=tablist]').find('a[href=#' + target_panel.attr('id') + ']').find('span.badge'); panel_tab.text(panel_count); } }); } function get_active_panel_choices() { var active_panel = main_content.find("li.active").children("a").attr("href"); var addData = $(active_panel).find("form").serializeArray(); addData.shift(); return addData; } $(document).ready(function(){ load_panel(certificate_panel, certificate_url); load_panel(domain_panel, domain_url); load_panel(ip_panel, ip_url); load_panel(alert_panel, alert_url); }); $(".modal-body").on('submit', 'form', function(event) { // Capture form submission event within modal content event.preventDefault(); // Grab reference to form within event context var form = $(this); // convert form to array and push additional params var data = form.serializeArray(); if (form.hasClass("choice_selector")) { var addData = get_active_panel_choices(); $.each(addData, function( index, value ) { data.push(value); }); } var formData = $.param(data); var formURL = form.attr("action"); var formMethod = form.attr("method"); $.ajax({ type: formMethod, url: formURL, data: formData, success: function(response) { if (form.hasClass("no-refresh")) { form.closest(".modal-body").html(response) } else { document.open(); document.write(response); document.close(); } } }); }); $(".modal-content").on('click', 'button[data-link]', function() { var form = $(this).siblings("form"); var formURL = $(this).attr("data-link"); // convert form to array and push additional params var data = form.serializeArray(); if (form.hasClass("choice_selector")) { var addData = get_active_panel_choices(); $.each(addData, function( index, value ) { data.push(value); }); } var formData = $.param(data); var formMethod = form.attr("method"); $.ajax({ type: formMethod, url: formURL, data: formData, success: function(response) { if (form.hasClass("no-refresh")) { var target = form.closest(".modal-body"); $(target).html(response); $(target).find('.selectpicker').selectpicker(); } else { document.open(); document.write(response); document.close(); } } }); }); $(document).on( "click", "button[data-toggle=modal]", function() { // Grab reference to link within event context var link = $(this).attr("data-link"); var target = $(this).attr("data-target"); $(target).find(".modal-body").load(link, function() { $(target).find('.selectpicker').selectpicker(); }); }); $(document).on( "click", "a[data-toggle=modal]", function() { // Grab reference to link within event context var link = $(this).attr("data-link"); var target = $(this).attr("data-target"); $(target).find(".modal-body").load(link, function() { console.log("I don't think we need to do anything here. It's a callback once loading is complete."); }); }); // End modal functions and events //
{ "content_hash": "519c45f43c65b71a21082402d920f102", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 118, "avg_line_length": 28.993788819875775, "alnum_prop": 0.5717652099400171, "repo_name": "gdit-cnd/RAPID", "id": "0103f564e6c05b7e18d6692a4842b668e24a131c", "size": "4668", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "static/js/monitor.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "184203" }, { "name": "DIGITAL Command Language", "bytes": "15410" }, { "name": "HTML", "bytes": "7183756" }, { "name": "JavaScript", "bytes": "834725" }, { "name": "PHP", "bytes": "55444" }, { "name": "Python", "bytes": "403696" }, { "name": "Shell", "bytes": "33782" } ], "symlink_target": "" }
package ua.edu.odeku.ceem.mapRadar.tools.adminBorder.viewManager import javax.swing.JPanel import ua.edu.odeku.ceem.mapRadar.tools.{CeemRadarTool, ToolFrame} /** * User: Aleo Bakalov * Date: 26.03.2014 * Time: 9:51 */ class AdminBorderViewManagerTool extends CeemRadarTool { val form = new AdminBorderViewForm override def rootPanel: JPanel = form.rootPanel() override def endFunction: (ToolFrame) => Unit = (tool: ToolFrame) => {} override def startFunction: (ToolFrame) => Unit = (tool: ToolFrame) => {} /** * Метод для инициализации инструмента, * вызовется при мервом вызове, а не в помент создания */ override def init(): Unit = { val handler = new AdminBorderViewManagerFormHandler(this) } }
{ "content_hash": "ff363d5e5a0b2cddfcdd41c45f784828", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 74, "avg_line_length": 23.516129032258064, "alnum_prop": 0.7229080932784636, "repo_name": "aleo72/ww-ceem-radar", "id": "071edc5f172d40cc557651730578dfb92f79d088", "size": "872", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/ua/edu/odeku/ceem/mapRadar/tools/adminBorder/viewManager/AdminBorderViewManagerTool.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "123250" }, { "name": "Java", "bytes": "16779309" }, { "name": "Scala", "bytes": "219030" } ], "symlink_target": "" }
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Polymer BrowserTest fixture and aXe-core accessibility audit. GEN_INCLUDE([ '//chrome/test/data/webui/a11y/accessibility_test.js', '//chrome/test/data/webui/polymer_browser_test_base.js', ]); GEN('#include "chrome/browser/ui/webui/welcome/helpers.h"'); GEN('#include "content/public/test/browser_test.h"'); WelcomeA11y = class extends PolymerTest { /** @override */ get browsePreload() { return 'chrome://welcome/'; } /** @override */ get featureList() { return {enabled: ['welcome::kForceEnabled']}; } /** @override */ get extraLibraries() { return [ '//third_party/mocha/mocha.js', '//chrome/test/data/webui/mocha_adapter.js', ]; } }; AccessibilityTest.define('WelcomeA11y', { // Must be unique within the test fixture and cannot have spaces. name: 'WelcomeFlow', // Optional. Configuration for axe-core. Can be used to disable a test. axeOptions: { 'rules': { // TODO(crbug.com/761461): enable after addressing flaky tests. 'color-contrast': {enabled: false}, } }, // Optional. Filter on failures. Use this for individual false positives. violationFilter: {}, // Optional. Any setup required for all tests. This will run before each one. setup: function() {}, tests: { 'Landing Page': function() { // Make sure we're in the right page. assertEquals( 'Make Chrome your own', document.body.querySelector('welcome-app') .shadowRoot.querySelector('landing-view') .shadowRoot.querySelector('h1') .textContent); }, }, });
{ "content_hash": "5a3b5ea479dc03ff3746350fbe208c2c", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 79, "avg_line_length": 28.11111111111111, "alnum_prop": 0.6476566911349521, "repo_name": "ric2b/Vivaldi-browser", "id": "f350173f6b60c4fc5d7451136e8cd2d83c55091b", "size": "1771", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "chromium/chrome/test/data/webui/welcome/a11y_tests.js", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
layout: default --- {% include blog-migrated.html %} <article class="post" itemscope itemtype="http://schema.org/BlogPosting"> <header class="post-header"> <h1 class="post-title" itemprop="name headline">{{ page.title }}</h1> <p class="post-meta"><time datetime="{{ page.date | date_to_xmlschema }}" itemprop="datePublished">{{ page.date | date: "%b %-d, %Y" }}</time>{% if page.author %} • <span itemprop="author" itemscope itemtype="http://schema.org/Person"><span itemprop="name">{{ page.author }}</span></span>{% endif %}</p> </header> <div class="post-content" itemprop="articleBody"> {{ content }} </div> <div class="social-share"> <span> Share: </span> <a href="https://twitter.com/share" class="twitter-share-button" data-show-count="false">Tweet</a><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script> <div class="g-plus" data-action="share" data-annotation="none"><script src="https://apis.google.com/js/platform.js" async defer></script></div> </div> {% include disqus.html %} </article>
{ "content_hash": "f9830eaa028a1e10e8af164c607d5803", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 307, "avg_line_length": 53.3, "alnum_prop": 0.6594746716697936, "repo_name": "APIs-guru/APIs-guru.github.io", "id": "7bff75a57532397978fa734e0977ad769503f8a8", "size": "1072", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/_layouts/post.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "25361" }, { "name": "JavaScript", "bytes": "9267" }, { "name": "Liquid", "bytes": "1564" }, { "name": "Nunjucks", "bytes": "314" }, { "name": "SCSS", "bytes": "44705" } ], "symlink_target": "" }
FROM locustio/locust WORKDIR /tasks COPY tasks.py . COPY test-config test-config RUN pip install -U locust
{ "content_hash": "17f7617bf21faf4e1f04cbbe9c690cda", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 28, "avg_line_length": 18, "alnum_prop": 0.7870370370370371, "repo_name": "GoogleCloudPlatform/mlops-on-gcp", "id": "3c211ca0f14573633c0403c85ca06f044a449cd7", "size": "706", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "workshops/mlep-qwiklabs/tfserving-canary-gke/archive/locust/locust-image/Dockerfile", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "15195" }, { "name": "HCL", "bytes": "8348" }, { "name": "JavaScript", "bytes": "1143" }, { "name": "Jupyter Notebook", "bytes": "6737030" }, { "name": "Mustache", "bytes": "1946" }, { "name": "Python", "bytes": "1235643" }, { "name": "Shell", "bytes": "30775" } ], "symlink_target": "" }
{% extends "layout.html" %} {% block content %} <div class="jumbotron"> <h1>Welcome to Whose turn is it anyway?</h1> <p>Start tracking whose turn it is to perform those boring, fun or repetitive tasks!</p> {% if not current_user.is_authenticated() %} <p><a href="{{ url_for('public.register') }}" class="btn btn-primary btn-large">Register here &raquo;</a></p> {% endif %} </div> {% endblock %}
{ "content_hash": "1248f588373acb7705bbac99b72b8692", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 111, "avg_line_length": 24, "alnum_prop": 0.6470588235294118, "repo_name": "apollux/whose_turn_is_it_anyway", "id": "4b8adc7236a9985661c1ff76a0e08bc811a8286c", "size": "409", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "whose_turn_is_it_anyway/templates/public/home.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1170" }, { "name": "HTML", "bytes": "11994" }, { "name": "JavaScript", "bytes": "181413" }, { "name": "Python", "bytes": "35814" } ], "symlink_target": "" }
export { Hd32 as default } from "../../";
{ "content_hash": "a424e52df1a2e472af2517488d086fb3", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 41, "avg_line_length": 42, "alnum_prop": 0.5476190476190477, "repo_name": "georgemarshall/DefinitelyTyped", "id": "462f45bd6c3593bb41890324d6cbd70138bc626b", "size": "42", "binary": false, "copies": "24", "ref": "refs/heads/master", "path": "types/carbon__icons-react/es/HD/32.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "16338312" }, { "name": "Ruby", "bytes": "40" }, { "name": "Shell", "bytes": "73" }, { "name": "TypeScript", "bytes": "17728346" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2010 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <device-admin xmlns:android="http://schemas.android.com/apk/res/android" android:visible="false"> <uses-policies> <limit-password /> <watch-login /> <force-lock /> <wipe-data /> <expire-password /> <encrypted-storage /> <disable-camera /> <disable-keyguard-features /> </uses-policies> </device-admin>
{ "content_hash": "20a75d35d8a015ab39888ba1d1b12206", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 77, "avg_line_length": 36.310344827586206, "alnum_prop": 0.6628679962013295, "repo_name": "craigacgomez/flaming_monkey_packages_apps_Email", "id": "10648df70b51c5df97ead0f1b9fd4a1a3da48c9d", "size": "1053", "binary": false, "copies": "3", "ref": "refs/heads/android-4.3.1_r1", "path": "res/xml/device_admin.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "4820405" }, { "name": "Shell", "bytes": "1671" } ], "symlink_target": "" }
<?hh namespace beatbox\test; use beatbox; class FormTest extends beatbox\Test { /** * @group fast */ public function testCSRF() { // Make sure that a csrf input is added. $form = <bb:form />; $this->assertContains('name="__csrf"', (string)$form); } /** * @group fast */ public function testFragmentHandling() { $form = <bb:form />; $form->forFragment(ImmVector {'a', 'b'}, 'test'); $this->assertEquals('post', $form->getAttribute('method')); $this->assertEquals('a/b?fragments=test', $form->getAttribute('action')); $form->setAttribute('method', 'get'); $form->forFragment(ImmVector {'b', 'b'}, 'testing'); // Overriding shouldn't happen $this->assertEquals('get', $form->getAttribute('method')); $this->assertEquals('a/b?fragments=test', $form->getAttribute('action')); $form->removeAttribute('action'); // Special case $form->forFragment(ImmVector {'/'}, 'testing'); $this->assertEquals('get', $form->getAttribute('method')); $this->assertEquals('/?fragments=testing', $form->getAttribute('action')); } /** * @group fast */ public function testLoadData() { $f1 = <bb:form:text name="Field1" />; $f2 = <bb:form:text name="Field2" />; $form = <bb:form> {$f1} <div> {$f2} </div> </bb:form>; $form->loadData(['Field1' => 'Value1', 'Field2' => 'Value2']); $this->assertEquals('Value1', $f1->getValue()); $this->assertEquals('Value2', $f2->getValue()); $form->loadData(['Field1' => 'Value3'], true); $this->assertEquals('Value3', $f1->getValue()); $this->assertEmpty($f2->getValue()); } /** * @group fast */ public function testLoadNestedData() { $f1 = <bb:form:text name="Field1[]" />; $f2 = <bb:form:text name="Field1[]" />; $f3 = <bb:form:text name="Field3[]" />; $f4 = <bb:form:text name="Field3[]" />; $form = <bb:form> {$f1}{$f3} {$f2}{$f4} </bb:form>; $form->loadData(['Field1' => ['a', 'b'], 'Field3' => ['c', 'd']]); $this->assertEquals('a', $f1->getValue()); $this->assertEquals('b', $f2->getValue()); $this->assertEquals('c', $f3->getValue()); $this->assertEquals('d', $f4->getValue()); $form->loadData(['Field1' => ['a'], 'Field3' => ['c']], true); $this->assertEquals('a', $f1->getValue()); $this->assertEmpty($f2->getValue()); $this->assertEquals('c', $f3->getValue()); $this->assertEmpty($f4->getValue()); $f1 = <bb:form:text name="Field[f1][]" />; $f2 = <bb:form:text name="Field[f1][]" />; $f3 = <bb:form:text name="Field[f3][]" />; $f4 = <bb:form:text name="Field[f3][]" />; $form = <bb:form> {$f1}{$f3} {$f2}{$f4} </bb:form>; $form->loadData(['Field' => ['f1' => ['a', 'b'], 'f3' => ['c', 'd']]]); $this->assertEquals('a', $f1->getValue()); $this->assertEquals('b', $f2->getValue()); $this->assertEquals('c', $f3->getValue()); $this->assertEquals('d', $f4->getValue()); $form->loadData(['Field' => ['f1' => ['a'], 'f3' => ['c']]], true); $this->assertEquals('a', $f1->getValue()); $this->assertEmpty($f2->getValue()); $this->assertEquals('c', $f3->getValue()); $this->assertEmpty($f4->getValue()); } /** * @group fast */ public function testValidate() { $field = <bb:form:text name="Field" value="Value" required="true" />; $form = <bb:form>{$field}</bb:form>; $called = false; $form->setAttribute('validator', function($fields, $errors) use($field, &$called) { $called = true; $this->assertSame($fields['Field'], $field); return true; }); $this->assertTrue($form->validate()); $this->assertTrue($called); $field->setValue(null); $called = false; $this->assertFalse($form->validate()); $this->assertTrue($called); $field->setValue('Value'); $this->assertTrue($form->validate()); $form->setAttribute('validator', function($fields, $errors) { $errors['Field'] = 'Error'; }); $this->assertFalse($form->validate()); } /** * @group fast */ public function testValidSubmission() { $field = <bb:form:text name="Field" value="Value" required="true" />; $form = <bb:form>{$field}</bb:form>; $called = false; $_POST['Field'] = 'test'; $_SERVER['REQUEST_METHOD'] = 'POST'; $form->setAttribute('handler', function($f, $d) use($form, &$called) { $called = true; $this->assertSame($form, $f); $this->assertEquals('test', $d['Field']); }); $form->forFragment(ImmVector {'/'}, 'form'); $this->assertTrue($called); } /** * @group fast */ public function testInvalidSubmission() { $field = <bb:form:text name="Field" value="Value" required="true" />; $form = <bb:form>{$field}</bb:form>; $called = false; $_POST['Field'] = ''; $_SERVER['REQUEST_METHOD'] = 'POST'; $_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHTTPRequest'; $form->setAttribute('handler', function($f, $d) use($form, &$called) { $called = true; $this->assertSame($form, $f); }); $res = $form->forFragment(ImmVector {'/'}, 'form'); $this->assertFalse($called); $this->assertSame($form, $res); try { $_SERVER['HTTP_X_REQUESTED_WITH'] = 'No AJAX'; $form->forFragment(ImmVector {'/'}, 'form'); $this->fail('Non-AJAX form validation should throw an exception'); } catch(beatbox\errors\HTTP_Exception $e) { $this->assertEquals(302, $e->getBaseCode()); } } /** * @group fast * @depends testLoadData */ public function testReloadData() { $field = <bb:form:text name="Field" value="Value" required="true" />; $form = <bb:form>{$field}</bb:form>; $called = false; $_POST['Field'] = ''; $_SERVER['REQUEST_METHOD'] = 'POST'; try { $this->assertEquals('Value', $field->getValue()); $form->forFragment(ImmVector {'/'}, 'form'); $this->fail('Should have errored'); } catch(beatbox\errors\HTTP_Exception $e) { $this->assertEquals('', $field->getValue()); } $field->setValue('Value'); $_SERVER['REQUEST_METHOD'] = 'GET'; $form->forFragment(ImmVector {'/'}, 'form'); $this->assertEquals('', $field->getValue()); } /** * @group fast * @depends testValidSubmission */ public function testPullOutNestedData() { $form = <bb:form> <bb:form:text name="Field[]" value="Value" required="true" />; <bb:form:text name="Field[]" value="Value" required="true" />; <bb:form:text name="Field[]" value="Value" required="true" />; </bb:form>; $called = false; $_POST['Field'] = ['test', 'testing', 'd']; $_SERVER['REQUEST_METHOD'] = 'POST'; $form->setAttribute('handler', function($f, $d) use($form, &$called) { $called = true; $this->assertSame($form, $f); $this->assertEquals(Map { 'Field' => Vector {'test', 'testing', 'd'} }, $d); }); $form->forFragment(ImmVector {'/'}, 'form'); $this->assertTrue($called); $form = <bb:form> <bb:form:text name="Field[a][]" value="Value" required="true" />; <bb:form:text name="Field[b][]" value="Value" required="true" />; <bb:form:text name="Field[a][]" value="Value" required="true" />; </bb:form>; $called = false; $_POST['Field'] = ['a' => ['a', 'c'], 'b' => ['b']]; $_SERVER['REQUEST_METHOD'] = 'POST'; $form->setAttribute('handler', function($f, $d) use($form, &$called) { $called = true; $this->assertSame($form, $f); $this->assertEquals(Map { 'Field' => Map { 'a' => Vector {'a', 'c'}, 'b' => Vector {'b'} } }, $d); }); $form->forFragment(ImmVector {'/'}, 'form'); $this->assertTrue($called); } }
{ "content_hash": "32a80fc23ae8e199d6585eb03ed6e6d8", "timestamp": "", "source": "github", "line_count": 281, "max_line_length": 85, "avg_line_length": 26.24199288256228, "alnum_prop": 0.5797396257119609, "repo_name": "PocketRent/beatbox", "id": "5d9a2c0e688a4cb70b40d3852ac0a4bab91d592d", "size": "7374", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/forms/FormTest.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1137" }, { "name": "HTML", "bytes": "2528" }, { "name": "Hack", "bytes": "456040" }, { "name": "JavaScript", "bytes": "278517" }, { "name": "PHP", "bytes": "3469083" }, { "name": "Shell", "bytes": "913" } ], "symlink_target": "" }
// BoundaryTree.cpp: implementation of the CBoundaryTree class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "BoundaryTree.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// IMPLEMENT_SERIAL( CBoundaryTree, CObject, 1 ); CBoundaryTree::CBoundaryTree() { } CBoundaryTree::CBoundaryTree( const CPath& path ) { CBoundaryTreeNode rootNode(path); rootIdx = data.Add(rootNode); } CBoundaryTree::CBoundaryTree( const CBoundaryTree& s ) { data.Copy(s.data); } CBoundaryTree::~CBoundaryTree() { FreeAll(); } bool CBoundaryTree::IsValid() { //make sure that the tree data structure is valid return(this->IsKindOf(RUNTIME_CLASS( CBoundaryTree ))>0); } bool CBoundaryTree::IsValidIndex( int idx ) { //make sure that the index is valid return( (idx < data.GetSize()) && (idx >= 0) ); } void CBoundaryTree::FreeAll() { data.RemoveAll(); rootIdx = -1; } void CBoundaryTree::Draw(CVec basecolor, bool bPathNormals) { for(int i = 0; i < data.GetSize(); i++) { data[i].boundary.Draw(bPathNormals, basecolor); } } /*//--------------------------------------------------------------------------- template <> void AFXAPI DestructElements <CBoundaryTree> ( CBoundaryTree* pObjects, int nCount ) //--------------------------------------------------------------------------- {// for ( int i=0; i<nCount; i++, pObjects++ ) { // call default destructor directly pObjects->~CBoundaryTree(); } }*/ //--------------------------------------------------------------------------- template <> void AFXAPI SerializeElements <CBoundaryTree> ( CArchive& ar, CBoundaryTree* pNewObjects, int nCount ) //--------------------------------------------------------------------------- {// serialize an array for ( int i = 0; i < nCount; i++, pNewObjects++ ) { // Serialize each object pNewObjects->Serialize(ar); } } void CBoundaryTree::Serialize(CArchive &ar) {// Save / Load int version = 1; if (ar.IsStoring()) { //add storing code here ar << version; // save data ar << rootIdx; data.Serialize(ar); ar << version; } else { // add loading code here int version1, version2; ar >> version1; if (version1 < 1 || version1 > version) throw 6; // load data ar >> rootIdx; data.Serialize(ar); ar >> version2; if (version2 != version1) throw 6; } } int CBoundaryTree::InsertRootNode( CPath& path ) { //empty the tree, then insert a new root node with path as boundary FreeAll(); CBoundaryTreeNode root(path); root.nodeIdx = 0; rootIdx = data.Add(root); return(rootIdx); } CBoundaryTreeNode& CBoundaryTree::Root() { //return the root node ASSERT(IsValidIndex(rootIdx)); return( data[rootIdx] ); } CBoundaryTreeNode* CBoundaryTree::pRoot() { //return a pointer to the root node if(IsValidIndex(rootIdx)) return( &(data[rootIdx]) ); return NULL; } int CBoundaryTree::RootIdx() { return( rootIdx ); } int CBoundaryTree::InsertChildNode( int parIdx, CPath& path ) { //Insert the node into the tree as a child of the node at parIdx. //Return the array index of the inserted node. //The node should be a leaf - no parent, children, or siblings. //If any errors, return -1. //check the validity of inputs if( !IsValidIndex(parIdx) ) return -1; CBoundaryTreeNode node(path); //set the parentIdx for the node node.parentIdx = parIdx; //insert the node and record its location node.nodeIdx = data.Add(node); data[node.nodeIdx].nodeIdx = node.nodeIdx; //check if the parent has any children; if so, establish siblings if(IsValidIndex(data[parIdx].lChildIdx)) { int tempIdx = data[parIdx].lChildIdx; while(IsValidIndex(data[tempIdx].rSiblingIdx)) { tempIdx = data[tempIdx].rSiblingIdx; } //add the new node as the right sibling of the rightmost child of the node at parIdx data[tempIdx].rSiblingIdx = node.nodeIdx; } else { //no left children, so set left child to the new node's index data[parIdx].lChildIdx = node.nodeIdx; } return node.nodeIdx; } CBoundaryTreeNode& CBoundaryTree::Ref( int nodeIdx ) { //return reference to the node at nodeIdx ASSERT( (nodeIdx < data.GetSize()) && (nodeIdx >= 0) ); return( data[nodeIdx] ); } CBoundaryTreeNode* CBoundaryTree::pNode( int nodeIdx ) { //return a pointer to the node at nodeIdx if(IsValidIndex(nodeIdx)) return( &(data[nodeIdx]) ); return NULL; } CBoundaryTreeNode* CBoundaryTree::pParent(CBoundaryTreeNode* pNode) { //return a pointer to the parent node of this node //if the node has no parent (e.g. is a root), return NULL ASSERT( pNode->IsValid() ); if( IsValidIndex(pNode->parentIdx) ) { return( &(data[pNode->parentIdx]) ); } return(NULL); } CBoundaryTreeNode* CBoundaryTree::pLChild(CBoundaryTreeNode* pNode) { //return a reference to the left child node of this node //if the node has no left child, return NULL ASSERT( pNode->IsValid() ); if( IsValidIndex(pNode->lChildIdx) ) { return( &(data[pNode->lChildIdx]) ); } return(NULL); } CBoundaryTreeNode* CBoundaryTree::pRSibling(CBoundaryTreeNode* pNode) { //return a reference to the right sibling node of this node //if the node has not right sibling, return NULL ASSERT( pNode->IsValid() ); if( IsValidIndex(pNode->rSiblingIdx) ) { return( &(data[pNode->rSiblingIdx]) ); } return(NULL); } /*void CBoundaryTree::InsertChildSubtree( CBoundaryTree& subtree ) //Insert the subtree, assigning THIS as parentIdx { //start by assigning THIS as parentIdx subtree.parentIdx = this; //if THIS has no children, update THIS show subtree as left child if(lChildIdx == NULL) { lChildIdx = &subtree; } else { //insert after the rightmost sibling of this's left child CBoundaryTree *temp; temp = this->lChildIdx; while(temp->rSiblingIdx != NULL) { temp = temp->rSiblingIdx; } temp->rSiblingIdx = &subtree; } } void CBoundaryTree::ReplaceSubtree( CBoundaryTree& subtree ) //Insert subtree, replacing the subtree Boundary at THIS //Free the memory associated with THIS subtree { ASSERT(subtree != NULL); ASSERT(subtree.rSiblingIdx == NULL); //set the parent of subtree to the parent of THIS subtree.parentIdx = parentIdx; if(parentIdx != NULL) { if(parentIdx->lChildIdx == this) { //THIS is the left child, so adopt subtree parentIdx->lChildIdx == &subtree; } } if(rSiblingIdx != NULL) { //THIS has right siblings, so make subtree a sibling subtree.rSiblingIdx = rSiblingIdx; } //then set the parent of THIS to NULL parentIdx = NULL; //and free THIS subtree FreeAll(); }*/ CBoundaryTree& CBoundaryTree::operator=(const CBoundaryTree& s) { data.Copy(s.data); return(*this); } bool CBoundaryTree::operator==(const CBoundaryTree& s) { //assumes that the data is all in the same order for(int i = 0; i < data.GetSize(); i++) { if(!(data[i] == s.data[i])) return false; } return true; } /*CBoundaryTree* CBoundaryTree::FindItem(<Class T>& it) { //search the subtree Boundary at THIS for the item (it) //return the first node containing it or NULL if not found //recursive if(it == NULL) return NULL; CBoundaryTree* temp; temp = this; if(temp->item == it) return temp; else { if( temp->pLeftChild != NULL ) { return( temp->pLeftChild->FindItem(it) ); } else { return( temp->pRightSibling->FindItem(it) ); } } }*/ /*int CBoundaryTree::Depth() { //calculate the depth of THIS node in its parent tree //root of tree is zero depth int d = 0; CBoundaryTree* temp = parentIdx; //walk up the tree toward the root while(temp != NULL) { d++; temp = temp.parentIdx; } return(d); }*/ /*bool CBoundaryTree::Sibling( CBoundaryTree& node ) { //return true if THIS and node have same parent return(parentIdx == node.parentIdx); }*/ ///////////////////////////////////////////////////////////////////////////////////////////// ///////IMPLEMENTATION FOR CBOUNDARYTREENODE////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////// IMPLEMENT_SERIAL( CBoundaryTreeNode, CObject, 1 ); CBoundaryTreeNode::CBoundaryTreeNode() { } CBoundaryTreeNode::CBoundaryTreeNode(const CBoundaryTreeNode& s) { boundary = s.boundary; nodeIdx = s.nodeIdx; parentIdx = s.parentIdx; lChildIdx = s.lChildIdx; rSiblingIdx = s.rSiblingIdx; } CBoundaryTreeNode::CBoundaryTreeNode(const CPath& path) { boundary = path; nodeIdx = -1; parentIdx = -1; lChildIdx = -1; rSiblingIdx = -1; } CBoundaryTreeNode::CBoundaryTreeNode(const CPath& path, int ndIdx, int pIdx, int lCIdx, int rSIdx) { boundary = path; nodeIdx = ndIdx; parentIdx = pIdx; lChildIdx = lCIdx; rSiblingIdx = rSIdx; } bool CBoundaryTreeNode::IsValid() { //make sure that the node is valid return(this->IsKindOf(RUNTIME_CLASS( CBoundaryTreeNode ))>0); } bool CBoundaryTreeNode::HasChild() { //return true if this node has a child return(this->lChildIdx >= 0); } bool CBoundaryTreeNode::HasSibling() { //return true if this node has a right sibling return(this->rSiblingIdx >= 0); } CBoundaryTreeNode::~CBoundaryTreeNode() { } CBoundaryTreeNode& CBoundaryTreeNode::operator=(const CBoundaryTreeNode& s) { boundary = s.boundary; nodeIdx = s.nodeIdx; parentIdx = s.parentIdx; lChildIdx = s.lChildIdx; rSiblingIdx = s.rSiblingIdx; return(*this); } bool CBoundaryTreeNode::operator==(const CBoundaryTreeNode& s) { return((boundary == s.boundary) && (nodeIdx == s.nodeIdx) && (parentIdx == s.parentIdx) && (lChildIdx == s.lChildIdx) && (rSiblingIdx == s.rSiblingIdx)); } bool CBoundaryTreeNode::operator==(const CPath& path) { return(boundary == path); } /*//--------------------------------------------------------------------------- template <> void AFXAPI DestructElements <CBoundaryTreeNode> ( CBoundaryTreeNode* pObjects, int nCount ) //--------------------------------------------------------------------------- {// for ( int i=0; i<nCount; i++, pObjects++ ) { // call default destructor directly pObjects->~CBoundaryTreeNode(); } }*/ //--------------------------------------------------------------------------- template <> void AFXAPI SerializeElements <CBoundaryTreeNode> ( CArchive& ar, CBoundaryTreeNode* pNewObjects, int nCount ) //--------------------------------------------------------------------------- {// serialize an array for ( int i = 0; i < nCount; i++, pNewObjects++ ) { // Serialize each object pNewObjects->Serialize(ar); } } void CBoundaryTreeNode::Serialize(CArchive &ar) {// Save / Load int version = 1; if (ar.IsStoring()) { //add storing code here ar << version; // save data ar << nodeIdx; ar << parentIdx; ar << lChildIdx; ar << rSiblingIdx; boundary.Serialize(ar); ar << version; } else { // add loading code here int version1, version2; ar >> version1; if (version1 < 1 || version1 > version) throw 6; // load data ar >> nodeIdx; ar >> parentIdx; ar >> lChildIdx; ar >> rSiblingIdx; boundary.Serialize(ar); ar >> version2; if (version2 != version1) throw 6; } }
{ "content_hash": "2e26c18701b9364f444fa7ed7fd303f7", "timestamp": "", "source": "github", "line_count": 503, "max_line_length": 122, "avg_line_length": 22.660039761431413, "alnum_prop": 0.6175644849973679, "repo_name": "karlgluck/fabathome", "id": "6929376a785fb7c2bc62cdbef6ea94649bb17858", "size": "11398", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "FabInterpreter - 4.26.2010 - Revision 22/projects/FabStudio v0/Fab@Home Studio/BoundaryTree.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "75589" }, { "name": "C++", "bytes": "2574993" }, { "name": "CSS", "bytes": "13598" }, { "name": "IDL", "bytes": "7929" }, { "name": "Java", "bytes": "4849" }, { "name": "JavaScript", "bytes": "22458" }, { "name": "M", "bytes": "1463" }, { "name": "Matlab", "bytes": "23198" }, { "name": "Objective-C", "bytes": "7220" }, { "name": "Perl", "bytes": "2634" }, { "name": "Shell", "bytes": "1265" } ], "symlink_target": "" }
// Copyright 2015 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import {assertInstanceof} from 'chrome://resources/js/assert.js'; import {Menu} from './menu.js'; import {MenuItem} from './menu_item.js'; /** * Menu item with ripple animation. */ export class FilesMenuItem extends MenuItem { constructor() { super(); /** @private {boolean} */ this.animating_ = false; /** @private {(boolean|undefined)} */ this.hidden_ = undefined; /** @private {?HTMLElement} */ this.label_ = null; /** @private {?HTMLElement} */ this.iconStart_ = null; /** @private {?HTMLElement} */ this.iconManaged_ = null; /** @private {?HTMLElement} */ this.iconEnd_ = null; /** @private {?HTMLElement} */ this.ripple_ = null; /** @public @type {?chrome.fileManagerPrivate.FileTaskDescriptor} */ this.descriptor = null; throw new Error('Designed to decorate elements'); } /** * Decorates the element. * @param {!Element} element Element to be decorated. * @return {!FilesMenuItem} Decorated element. */ static decorate(element) { element.__proto__ = FilesMenuItem.prototype; element = /** @type {!FilesMenuItem} */ (element); element.decorate(); return element; } /** * @override */ decorate() { this.animating_ = false; // Custom menu item can have sophisticated content (elements). if (!this.children.length) { this.label_ = assertInstanceof(document.createElement('span'), HTMLElement); this.label_.textContent = this.textContent; this.iconStart_ = assertInstanceof(document.createElement('div'), HTMLElement); this.iconStart_.classList.add('icon', 'start'); this.iconManaged_ = assertInstanceof(document.createElement('div'), HTMLElement); this.iconManaged_.classList.add('icon', 'managed'); this.iconEnd_ = assertInstanceof(document.createElement('div'), HTMLElement); this.iconEnd_.classList.add('icon', 'end'); /** * This is hidden by default because most of the menu items require * neither the end icon nor the managed icon, so the component that * plans to use either end icon should explicitly make it visible. */ this.setIconEndHidden(true); this.toggleManagedIcon(/*visible=*/ false); // Override with standard menu item elements. this.textContent = ''; this.appendChild(this.iconStart_); this.appendChild(this.label_); this.appendChild(this.iconManaged_); this.appendChild(this.iconEnd_); } this.ripple_ = assertInstanceof(document.createElement('paper-ripple'), HTMLElement); this.appendChild(this.ripple_); this.addEventListener('activate', this.onActivated_.bind(this)); } /** * Handles activate event. * @param {Event} event * @private */ onActivated_(event) { // Perform ripple animation if it's activated by keyboard. if (event.originalEvent instanceof KeyboardEvent) { this.ripple_.simulatedRipple(); } // Perform fade out animation. const menu = assertInstanceof(this.parentNode, Menu); // If activation was on a menu-item that hosts a sub-menu, don't animate const subMenuId = event.target.getAttribute('sub-menu'); if (subMenuId !== null) { if (document.querySelector(subMenuId) !== null) { return; } } this.setMenuAsAnimating_(menu, true /* animating */); const player = menu.animate( [ { opacity: 1, offset: 0, }, { opacity: 0, offset: 1, }, ], 300); player.addEventListener( 'finish', this.setMenuAsAnimating_.bind(this, menu, false /* not animating */)); } /** * Sets menu as animating. * @param {!Menu} menu * @param {boolean} value True to set it as animating. * @private */ setMenuAsAnimating_(menu, value) { menu.classList.toggle('animating', value); for (let i = 0; i < menu.menuItems.length; i++) { const menuItem = menu.menuItems[i]; if (menuItem instanceof FilesMenuItem) { menuItem.setAnimating_(value); } } if (!value) { menu.classList.remove('toolbar-menu'); } } /** * Sets the menu item as animating. * @param {boolean} value True to set this as animating. * @private */ setAnimating_(value) { this.animating_ = value; if (this.animating_) { return; } // Update hidden property if there is a pending change. if (this.hidden_ !== undefined) { this.hidden = this.hidden_; this.hidden_ = undefined; } } /** * @return {boolean} */ get hidden() { if (this.hidden_ !== undefined) { return this.hidden_; } return Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'hidden') .get.call(this); } /** * Overrides hidden property to block the change of hidden property while * menu is animating. * @param {boolean} value */ set hidden(value) { if (this.animating_) { this.hidden_ = value; return; } Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'hidden') .set.call(this, value); } /** * @return {string} */ get label() { return this.label_.textContent; } /** * @param {string} value */ set label(value) { this.label_.textContent = value; } /** * @return {string} */ get iconStartImage() { return this.iconStart_.style.backgroundImage; } /** * @param {string} value */ set iconStartImage(value) { this.iconStart_.setAttribute('style', 'background-image: ' + value); } /** * @return {string} */ get iconStartFileType() { return this.iconStart_.getAttribute('file-type-icon'); } /** * @param {string} value */ set iconStartFileType(value) { this.iconStart_.setAttribute('file-type-icon', value); } /** * Sets or removes the `is-managed` attribute. * @param {boolean} isManaged */ toggleIsManagedAttribute(isManaged) { this.toggleAttribute('is-managed', isManaged); } /** * Sets the `is-default` attribute. */ setIsDefaultAttribute() { this.toggleAttribute('is-default', true); } /** * Toggles visibility of the `Managed by Policy` icon. * @param {boolean} visible */ toggleManagedIcon(visible) { this.iconManaged_.toggleAttribute('hidden', !visible); this.toggleIsManagedAttribute(visible); } /** * @return {string} */ get iconEndImage() { return this.iconEnd_.style.backgroundImage; } /** * @param {string} value */ set iconEndImage(value) { this.iconEnd_.setAttribute('style', 'background-image: ' + value); } /** * @return {string} */ get iconEndFileType() { return this.iconEnd_.getAttribute('file-type-icon'); } /** * @param {string} value */ set iconEndFileType(value) { this.iconEnd_.setAttribute('file-type-icon', value); } removeIconEndFileType() { this.iconEnd_.removeAttribute('file-type-icon'); } /** * * @param {boolean} isHidden */ setIconEndHidden(isHidden) { this.iconEnd_.toggleAttribute('hidden', isHidden); } }
{ "content_hash": "f4619cecb76abaafc04a5080e271e5bc", "timestamp": "", "source": "github", "line_count": 312, "max_line_length": 78, "avg_line_length": 23.66346153846154, "alnum_prop": 0.6111336854937017, "repo_name": "chromium/chromium", "id": "e81534d2d77d02cbf47b9a4186bed05c4cbbaf09", "size": "7383", "binary": false, "copies": "6", "ref": "refs/heads/main", "path": "ui/file_manager/file_manager/foreground/js/ui/files_menu.js", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
#include <Array.hpp> #include <common/half.hpp> #include <kernel/random_engine.hpp> #include <af/dim4.hpp> using common::half; namespace opencl { void initMersenneState(Array<uint> &state, const uintl seed, const Array<uint> &tbl) { kernel::initMersenneState(*state.get(), *tbl.get(), seed); } template<typename T> Array<T> uniformDistribution(const af::dim4 &dims, const af_random_engine_type type, const uintl &seed, uintl &counter) { Array<T> out = createEmptyArray<T>(dims); kernel::uniformDistributionCBRNG<T>(*out.get(), out.elements(), type, seed, counter); return out; } template<typename T> Array<T> normalDistribution(const af::dim4 &dims, const af_random_engine_type type, const uintl &seed, uintl &counter) { Array<T> out = createEmptyArray<T>(dims); kernel::normalDistributionCBRNG<T>(*out.get(), out.elements(), type, seed, counter); return out; } template<typename T> Array<T> uniformDistribution(const af::dim4 &dims, Array<uint> pos, Array<uint> sh1, Array<uint> sh2, uint mask, Array<uint> recursion_table, Array<uint> temper_table, Array<uint> state) { Array<T> out = createEmptyArray<T>(dims); kernel::uniformDistributionMT<T>( *out.get(), out.elements(), *state.get(), *pos.get(), *sh1.get(), *sh2.get(), mask, *recursion_table.get(), *temper_table.get()); return out; } template<typename T> Array<T> normalDistribution(const af::dim4 &dims, Array<uint> pos, Array<uint> sh1, Array<uint> sh2, uint mask, Array<uint> recursion_table, Array<uint> temper_table, Array<uint> state) { Array<T> out = createEmptyArray<T>(dims); kernel::normalDistributionMT<T>( *out.get(), out.elements(), *state.get(), *pos.get(), *sh1.get(), *sh2.get(), mask, *recursion_table.get(), *temper_table.get()); return out; } #define INSTANTIATE_UNIFORM(T) \ template Array<T> uniformDistribution<T>( \ const af::dim4 &dims, const af_random_engine_type type, \ const uintl &seed, uintl &counter); \ template Array<T> uniformDistribution<T>( \ const af::dim4 &dims, Array<uint> pos, Array<uint> sh1, \ Array<uint> sh2, uint mask, Array<uint> recursion_table, \ Array<uint> temper_table, Array<uint> state); #define INSTANTIATE_NORMAL(T) \ template Array<T> normalDistribution<T>( \ const af::dim4 &dims, const af_random_engine_type type, \ const uintl &seed, uintl &counter); \ template Array<T> normalDistribution<T>( \ const af::dim4 &dims, Array<uint> pos, Array<uint> sh1, \ Array<uint> sh2, uint mask, Array<uint> recursion_table, \ Array<uint> temper_table, Array<uint> state); #define COMPLEX_UNIFORM_DISTRIBUTION(T, TR) \ template<> \ Array<T> uniformDistribution<T>(const af::dim4 &dims, \ const af_random_engine_type type, \ const uintl &seed, uintl &counter) { \ Array<T> out = createEmptyArray<T>(dims); \ size_t elements = out.elements() * 2; \ kernel::uniformDistributionCBRNG<TR>(*out.get(), elements, type, seed, \ counter); \ return out; \ } \ template<> \ Array<T> uniformDistribution<T>( \ const af::dim4 &dims, Array<uint> pos, Array<uint> sh1, \ Array<uint> sh2, uint mask, Array<uint> recursion_table, \ Array<uint> temper_table, Array<uint> state) { \ Array<T> out = createEmptyArray<T>(dims); \ size_t elements = out.elements() * 2; \ kernel::uniformDistributionMT<TR>( \ *out.get(), elements, *state.get(), *pos.get(), *sh1.get(), \ *sh2.get(), mask, *recursion_table.get(), *temper_table.get()); \ return out; \ } #define COMPLEX_NORMAL_DISTRIBUTION(T, TR) \ template<> \ Array<T> normalDistribution<T>(const af::dim4 &dims, \ const af_random_engine_type type, \ const uintl &seed, uintl &counter) { \ Array<T> out = createEmptyArray<T>(dims); \ size_t elements = out.elements() * 2; \ kernel::normalDistributionCBRNG<TR>(*out.get(), elements, type, seed, \ counter); \ return out; \ } \ template<> \ Array<T> normalDistribution<T>( \ const af::dim4 &dims, Array<uint> pos, Array<uint> sh1, \ Array<uint> sh2, uint mask, Array<uint> recursion_table, \ Array<uint> temper_table, Array<uint> state) { \ Array<T> out = createEmptyArray<T>(dims); \ size_t elements = out.elements() * 2; \ kernel::normalDistributionMT<TR>( \ *out.get(), elements, *state.get(), *pos.get(), *sh1.get(), \ *sh2.get(), mask, *recursion_table.get(), *temper_table.get()); \ return out; \ } INSTANTIATE_UNIFORM(float) INSTANTIATE_UNIFORM(double) INSTANTIATE_UNIFORM(int) INSTANTIATE_UNIFORM(uint) INSTANTIATE_UNIFORM(intl) INSTANTIATE_UNIFORM(uintl) INSTANTIATE_UNIFORM(char) INSTANTIATE_UNIFORM(uchar) INSTANTIATE_UNIFORM(short) INSTANTIATE_UNIFORM(ushort) INSTANTIATE_UNIFORM(half) INSTANTIATE_NORMAL(float) INSTANTIATE_NORMAL(double) INSTANTIATE_NORMAL(half) COMPLEX_UNIFORM_DISTRIBUTION(cdouble, double) COMPLEX_UNIFORM_DISTRIBUTION(cfloat, float) COMPLEX_NORMAL_DISTRIBUTION(cdouble, double) COMPLEX_NORMAL_DISTRIBUTION(cfloat, float) } // namespace opencl
{ "content_hash": "8fff18b23f55047e9fbc42d7d20cba0b", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 80, "avg_line_length": 49.86486486486486, "alnum_prop": 0.4644986449864499, "repo_name": "umar456/arrayfire", "id": "c112df4196a90f47f41d1bce50e210abdcc939dd", "size": "7711", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/backend/opencl/random_engine.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "539568" }, { "name": "C++", "bytes": "7255097" }, { "name": "CMake", "bytes": "361695" }, { "name": "Cuda", "bytes": "365317" }, { "name": "Python", "bytes": "4852" }, { "name": "Shell", "bytes": "1120" } ], "symlink_target": "" }
import renderStaticStyles, { extractDynamicStyles } from '../../modules/core/renderer' import StyleContainer from '../../modules/api/StyleContainer' describe('Extracting dynamic styles', () => { it('should return a scoped stateful selector if a function is passed', () => { const input = props => ({ backgroundColor: 'red', width: 12 }) const output = { _statefulSelector: input } expect(extractDynamicStyles(input)).to.eql(output) }) it('should be empty if no dynamic styles are used', () => { const input = { backgroundColor: 'red', width: 12 } expect(extractDynamicStyles(input)).to.eql({ }) }) it('should extract flat dynamic style properties', () => { const colorFn = props => props.color const input = { backgroundColor: 'red', width: 12, color: colorFn } const output = { color: colorFn } expect(extractDynamicStyles(input)).to.eql(output) }) it('should remove a selector if containing only dynamic styles', () => { const styles = { 'isDynamic=true': { color: props => props.color } } extractDynamicStyles(styles) expect(styles).to.eql({ }) }) it('should remove a selector if it is an object', () => { const styles = { box: { color: 'red' } } extractDynamicStyles(styles) expect(styles).to.eql({ }) }) it('should also treat boolean values as dynamic', () => { const styles = { box: { color: true } } extractDynamicStyles(styles) expect(styles).to.eql({ }) }) }) describe('Rendering static styles', () => { it('should return a selector', () => { const styles = { 'isDynamic=true': { color: 'red' }, backgroundColor: 'blue' } const selector = renderStaticStyles(styles) expect(selector).to.eql('s0') }) it('should seperate dynamic styles', () => { const dynamicStyle = props => props.color const styles = { color: dynamicStyle } const selector = renderStaticStyles(styles) expect(selector).to.eql('s0') expect(StyleContainer.dynamics.get('s0').color).to.eql(dynamicStyle) }) })
{ "content_hash": "55805db88a3f7cdaab890f6c00a2adf2", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 86, "avg_line_length": 30.47826086956522, "alnum_prop": 0.6252971944840704, "repo_name": "dustin-H/react-look", "id": "8b862220177ee1453c11bdd196e2e0ea08fd9ef3", "size": "2103", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "packages/react-look-native/test/core/renderer-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "442" }, { "name": "JavaScript", "bytes": "104786" } ], "symlink_target": "" }
* Updated: Styles in the Builder and Customizer are now compatible with WordPress 4.4. * Improved: Range slider options in the Customizer now perform better. * Fixed: Some font family options didn't work correctly if the Global body font was not set to the default. * Fixed: Custom logo attachment ID couldn't be determined from its URL in some situations. * Fixed: The Button format wrapped awkwardly to the next line if too long. * Fixed: Builder script now requires WP's media views script as a dependency. ## 1.6.5 * Improved: Site title and tagline are now treated as screen reader text when hidden (instead of removed) for better accessibility. * Improved: Better handling of admin notices. * Updated: Larger theme screenshot. * Updated: The latest list of Google fonts. * Bug fix: Don't show Yoast SEO's breadcrumb on a static front page (since it is only "Home"). * Changed: Added a notice that Make will soon drop support for WP 4.0 and 4.1. ## 1.6.4 * New feature: Support for Yoast SEO's breadcrumb functionality. * Choose which views display the breadcrumb in the Customizer's Layout panel. * Improved: Better responsive layout for the WooCommerce product grid, as well as cart and checkout pages. * Bug fix: The Detail color option was not correctly setting the color for post categories and tags. ## 1.6.3 * Improved: Reduced the top margin on the Gallery Slider when it is displaying the navigation dots. * Improved: Better translation strings and notes in the EXIF template tag. * Updated: The latest list of Google fonts. Added Tamil and Thai font subset options. * Changed: The EXIF data markup no longer wraps each data label in a span. * Changed: Renamed the Menu locations to use the word "Navigation" instead of "Menu". * Changed: Removed the `ttfmake` prefix from most 3rd party script IDs when registering them. * Bug fix: FitVids was not successfully getting added as a script dependency. This caused some embedded videos to not scale correctly. * Bug fix: Builder sections receiving focus due to an anchor tag were outlined in blue in Webkit browsers. ## 1.6.2.1 * Bug fix: Undefined function fatal error. * Bug fix: Customizer control classes will now attempt to autoload if they have not been defined yet. ## 1.6.2 * Updated: Ensure compatibility with upcoming 4.3 version of WordPress: * Deprecate Make's Favicon and Apple Touch Icon options in favor of the new Site Icon option. * Adjust styling of Customizer sections. * Updated: Font Awesome icon library updated to version 4.4.0. * Updated: The latest list of Google fonts. * Improved: Pages using the Builder template can now set a featured image (though it will not render on the page by default). * Improved: Better handling of localization: * Parent and child themes have separate text domains. * Translation files for the parent theme can be stored in the child theme directory to prevent loss during updates. * Improved translator notes for some strings. * Ensure that all translated strings are escaped for security hardening. * Improved: The Format Builder now uses the Global color scheme for color defaults. * Bug fix: PHP fatal error in RSS feed when feed item contained embedded video. * Bux fix: The `make_sanitize_text_allowed_tags` filter was not applied correctly. * Bug fix: In rare cases, some WooCommerce pages were not rendering correctly if they used the Builder template. ## 1.6.1 * New feature: All default sections now have background image and background color options. * Improved: Cycle2 slider script only loads when content requires it. * Bug fix: H1 typography settings no longer affect the site title (which has its own typography settings). * Updated: Mobile navigation script now matches latest version in the _s theme. * New filter: `make_required_files` modifies the list of theme files to load. * Changed: Prevent Make from activating if WordPress version is less than 4.0. ## 1.6.0 * Improved: Video embeds can now be set to specific widths and alignments while still behaving responsively on narrow screens. * Improved: Make now enqueues the parent stylesheet if the child theme is version 1.1 or higher (instead of relying on a CSS @import statement). * Improved: Several minor Builder UI tweaks. * Fixed: Builder content preview panes sometimes weren't refreshing in Firefox. * Fixed: Google Maps embeds now only resize to specific dimensions when added in post content. * Fixed: Taxonomy icons now align with their lists properly in the post footer even when other meta elements are present. * New filter: `make_builder_js_templates` modifies the array of JS templates loaded on the Page Builder screen. * Updated: The latest list of Google fonts. * Changed: Make now only supports WordPress 4.0 and higher. * Changed: New theme screenshot. CC0 compatible. ## 1.5.2 * Added options for Arabic and Hebrew in Google Fonts character subsets. * Fixed url encoding issues with Google Fonts URL. * Fixed issue causing Format Builder's button URL to not update correctly. * Fixed some instances of default stylesheet overriding Customizer typography settings. * Fixed wrong version number for FontAwesome library in some places. * Fixed fatal error in Customizer for WP versions before 4.0. * Updated Google Fonts. * Updated Dutch translation. Props @LeoOosterloo. ## 1.5.1 * Added Customizer options to remove header and footer boundary padding. * Added style support for the new official Twitter plugin. * Fixed broken mailto link for email icon in header/footer social icons. * Fixed extra space added below footer in Chrome browsers. * Added a notice that Make will drop support for WP 3.9 soon. ## 1.5.0 * Customizer overhaul * Added new typography options: line height, font weight, font style, letter spacing, word spacing, link underlining. * Added new typography option elements: widget title (separate from widget body), footer widget title, footer widget body. * Added font weight option for links. * Added Chosen.js for improved font choice UI. * Improved UI for other typography choices. * Added new color options: global link hover/focus, header bar links, footer links, sidebar color options, main menu color options. * Improved background image positioning options to account for both horizontal and vertical positioning. * Added opacity dimension to background colors. * Added option to customize "Read more" link text. * Added new main menu options: font weight and background color for current item. * Added options to change social icon size in header and footer. * Reorganized files and functions in Make's customizer module. * Reorganized Customizer panels, sections, and controls. * Improved social profiles custom menu by enabling email and RSS icons. * Improved handling of long content in Gallery section's item descriptions. * Improved display of Banner section in narrow view. * Fixed differing container widths on narrow view in Boxed mode. * Deprecated function ttfmake_display_favicons. * Deprecated function ttfmake_body_layout_classes. * Added style support for Postmatic. * Fixed styling of WooCommerce coupon field. * Updated Cycle2 to 2.1.6. * Updated FontAwesome to 4.3.0. * Added Russian translation. * Updated Dutch translation. ## 1.4.9 * Fixed bug that displayed page duplication info on custom post type screens. * Fixed undefined function error in WP versions less than 4.0. * Fixed doubled content in document title tag. * Added formal system for showing/hiding admin notices. * Added a notice when Make is installed on a site running a WordPress version older than 3.9. * Added notices for when an older version of Make Plus is installed. ## 1.4.8 * Fixed bug preventing Builder section duplication in some cases * Fixed line breaks in post comment count in Webkit browsers * Fixed content editor in Builder overlay resizable * Deprecated unused Builder functions * Added new filter hook: `make_content_width` * Added theme support for title tag * Added Russian translation ## 1.4.7 * Fixed bug where Customizer's font-family options weren't showing correct selected choice * Fixed issue with the custom logo not appearing correctly in some server environments * Added additional inline documentation for some action and filter hooks * Added Estonian translation ## 1.4.6 * Fixed several small compatibility issues in WordPress 4.1 * Fixed error thrown by Format Builder on some admin screens * Fixed entry date layout issue in Chrome caused by excess whitespace in HTML ## 1.4.5 * Fixed raw CSS appearing in rich snippet content in some situations * Fixed post meta alignment issues * Fixed blurry Page Builder overlays in Safari * Updated Google Fonts list * Updated documentation links * Updated Dutch translation ## 1.4.4 * Fixed inaccessible Attachment Display Settings panel when editing pages * Added Dutch translation ## 1.4.3 * Improved text sanitization in some instances to allow more HTML tags and attributes * Fixed incorrect text color being applied to Header Bar menu items * Other minor code improvements ## 1.4.2 * Fixed Column configuration data not saving correctly in the Page Builder ## 1.4.1 * Added the Format Builder tool to the Visual Editor * Added the Insert Icon button to the Visual Editor * Removed old button, alert, and list formatting options in favor of the Format Builder * Fixed minor issues with the Page Builder * Updated German translations ## 1.4.0 * Updated Page Builder interface to improve performance, reduce clutter and better match WordPress' flat design ## 1.3.2 * Fixed fatal error in PHP 5.2. ## 1.3.1 * Fixed fatal error in PHP 5.2. ## 1.3.0 * Added support for WordPress 4.0 and Customizer panels * Updated organization of Customizer options to utilize panels * Added individual font family and size options for each header level (H1 - H6) * Added other new font options: Tagline family, Sub-menu family and size, Widget family * Added lots of new filter and action hooks for developers, along with inline documentation * Updated FontAwesome library to 4.2. Includes support for 5 new social profile icons: Angel List, Last.fm, Slideshare, Twitch, and Yelp * Fixed incorrect header font size defaults * Fixed post navigation arrow orientation * Fixed theme name in German translation ## 1.2.2 * Fixed a bug that caused some style and script assets to not load correctly on some web host configurations ## 1.2.1 * Fixed issue where Page Builder was hidden in certain situations when adding a new page * Updated theme screenshot with CC0-compatible image * Added missing text domain strings * Removed query string parameters from Make Plus links ## 1.2.0 * Added ability to override some auxiliary stylesheets and scripts in child theme * Added ability for CPTs to use the builder * Added a "Maintain aspect ratio" option for banner sections for better responsive control * Added IDs for individual text columns * Added menu in the header bar * Added filters to control font size * Added notice for users trying to install Make Plus as a theme * Fixed issue where captions on non-linked gallery items would not reveal on iOS * Fixed issue where HTML added to Header/Footer text fields appeared as plain text in the Customizer * Fixed alignment issues with submenus * Fixed issue that caused submenus to fall below some content * Fixed JS errors that occurred when rich text editor was turned off * Fixed issue with broken default background color * Improved the responsiveness of banner sections * Improved consistency of textdomain handling ## 1.1.1 * Added Japanese translations * Added license information file * Fixed an incorrect label in the Customizer * Fixed issue where footer text was double sanitized * Fixed issue with dropdown menus being unreachable on an iPad ## 1.1.0 * Added control for showing comment count * Added controls for positioning author, date, and comment count * Added control for aligning featured images ## 1.0.11 * Improved messaging about Make Plus * Improved sorting of footer links in builder sections * Fixed ID sanitization bugs where ID values were greater than the maximum allowed integer value * Fixed bug that did not allow anyone but Super Admins to save banner sections in Multisite * Fixed a bug that defaulted comments to being hidden on posts * Removed unnecessary class from banner sections * Added a notice about sidebars not being available on builder template pages * Added more social icons ## 1.0.10 * Improved consistency in styling between custom menus and default menus * Improved JetPack share button styling * Fixed an issue with dynamically added TinyMCE instances affecting already added instances * Added link to social menu support documentation ## 1.0.9 * Fixed PHP notice edge case when $post object is not set when saving post * Fixed issue of white font not showing on TinyMCE background * Updated Font Awesome to 4.1.0 ## 1.0.8 * Removed Make Plus information from the admin bar * Added Make Plus information to the Customizer * Improved aspects of the builder to prepare for additional premium features ## 1.0.7 * Fixed bug that prevented default font from showing in the editor styles * Fixed Photon conflict that rendered custom logo functionality unusable * Added filter builder section footer action links * Added builder API function for removing builder sections * Added information about Style Kits, Easy Digital Downloads, and Page Duplicator * Added German and Finnish translations ## 1.0.6 * Added Make Plus information * Fixed bug with images not displaying properly when aspect ratio was set to none in the Gallery section * Removed sanitization of Customizer description section as these never receive user input ## 1.0.5 * Improved styling of widgets * Improved whitespacing in the builder interface * Improved language in builder * Improved builder icons * Added styles to make sure empty text columns hold their width * Added functionality to disable header items in the font select lists * Added filter for showing/hiding footer credit * Added styling for WooCommerce product tag cloud ## 1.0.4 * Improved banner slide image position * Added underline for footer link * Added function to determine if companion plugin is installed * Added TinyMCE buttons from builder to other TinyMCE instances * Builder API improvements * Added ability for templates to exist outside of a parent or child theme * Added class for noting whether a builder page is displayed or not * Added wrapper functions for getting images used in the builder for easier filterability * Added actions for altering builder from 3rd party code * Added event for after section is removed * Removed save post actions when builder isn't being saved * Improved the abstraction of data saving functions for easier global use * Improved timing of events to prevent unfortunate code loading issues * Fixed bug with determining next/prev section that could cause a fatal error ## 1.0.3 * Improved tagline to be more readable * Improved CSS code styling without any functional changes ## 1.0.2 * Removed RTL stylesheet as it was just a placeholder * Improved testimonial display in the TinyMCE editor * Fixed bug with broken narrow menu when using default menu ## 1.0.1 * Improved builder section descriptions * Improved compatibility for JetPack "component" plugins * Improved margin below widgets in narrow view * Improved spacing of elements in the customizer * Fixed bug with overlay in gallery section * Fixed bug with secondary color being applied to responsive menus ## 1.0.0 * Initial release
{ "content_hash": "1dbdb619cb623467238ecac8087794dc", "timestamp": "", "source": "github", "line_count": 354, "max_line_length": 144, "avg_line_length": 44.04237288135593, "alnum_prop": 0.7832724007440189, "repo_name": "lamosty/lamosty.com", "id": "850583d6d5f5343cc8053c722b44c3a984c85726", "size": "15601", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "web/app/themes/make/changelog.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "147499" }, { "name": "JavaScript", "bytes": "295966" }, { "name": "PHP", "bytes": "711259" }, { "name": "Ruby", "bytes": "5043" } ], "symlink_target": "" }
using CoreGraphics; using UIKit; namespace Appearance { public class PlainView : UIView { private UIProgressView progress; private UIButton plainButton; private UISlider slider; public PlainView() { slider = new UISlider(); progress = new UIProgressView(); plainButton = UIButton.FromType(UIButtonType.RoundedRect); plainButton.SetTitle("Plain Button", UIControlState.Normal); plainButton.Frame = new CGRect(20, 150, 130, 40); slider.Frame = new CGRect(20, 190, 250, 20); progress.Frame = new CGRect(20, 230, 250, 20); slider.Value = 0.75f; progress.Progress = 0.35f; AddSubview(plainButton); AddSubview(slider); AddSubview(progress); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (plainButton != null) { plainButton.Dispose(); plainButton = null; } if (slider != null) { slider.Dispose(); slider = null; } if (progress != null) { progress.Dispose(); progress = null; } } } }
{ "content_hash": "a21f6945dbb9cfb2762f676f5ab76c45", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 72, "avg_line_length": 25.22222222222222, "alnum_prop": 0.4985315712187959, "repo_name": "xamarin/monotouch-samples", "id": "e09c5e8446fdb4c5fad67b516a77573d6be131f8", "size": "1362", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Appearance/Appearance/PlainView.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "5568672" }, { "name": "F#", "bytes": "11402" }, { "name": "GLSL", "bytes": "13657" }, { "name": "HTML", "bytes": "9912" }, { "name": "Makefile", "bytes": "16378" }, { "name": "Metal", "bytes": "4299" }, { "name": "Objective-C", "bytes": "106014" }, { "name": "Shell", "bytes": "6235" } ], "symlink_target": "" }
<resources> <string name="app_name">酷欧天气</string> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> </resources>
{ "content_hash": "3835542b9f4efccd92800e69f332919b", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 70, "avg_line_length": 35.25, "alnum_prop": 0.6477541371158393, "repo_name": "yhx95/yhxcoolweather", "id": "a4f9410a0c6deed63ae42552d8e42ed525f02d3f", "size": "431", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/values/styles.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "33319" } ], "symlink_target": "" }
module UnittestJS module Builder module HtmlHelper def script_tag(filename) "<script src=\"#{filename}?#{cache_buster}\" type=\"text/javascript\" charset=\"utf-8\"></script>" end # for backwards compatibility: alias :to_script_tag :script_tag def link_tag(filename) "<link rel=\"stylesheet\" href=\"#{filename}?#{cache_buster}\" type=\"text/css\" />" end # for backwards compatibility: alias :to_link_tag :link_tag def cache_buster @cache_buster ||= Time.now.to_i.to_s end end end end
{ "content_hash": "90a86d04c7239cff0efa03db9c3f8dbb", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 106, "avg_line_length": 28.333333333333332, "alnum_prop": 0.5865546218487395, "repo_name": "tobie/unittest_js", "id": "13d550de82a6753780cc3882c7585f7e27f89779", "size": "595", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/unittest_js/builder/html_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "771" }, { "name": "JavaScript", "bytes": "21894" }, { "name": "Ruby", "bytes": "31470" } ], "symlink_target": "" }
import { merge, find } from 'lodash' const defaultConfig = { envs: { local: { serverUrl: 'http://localhost:4000', logLevel: 'trace' }, dev: { serverUrl: 'http://tessellate-stage.elasticbeanstalk.com', logLevel: 'debug' }, stage: { serverUrl: 'http://tessellate-stage.elasticbeanstalk.com', logLevel: 'info' }, prod: { serverUrl: 'http://tessellate.elasticbeanstalk.com', logLevel: 'error' } }, tokenName: 'tessellate', tokenDataName: 'tessellate-tokenData', tokenUserDataName: 'tessellate-currentUser', oauthioKey: 'sxwuB9Gci8-4pBH7xjD0V_jooNU', oauthioCDN: 'https://s3.amazonaws.com/kyper-cdn/js/libs/oauthio-web/v0.5.0/oauth.min.js' } let instance = null let envName = 'prod' let level = null class Config { constructor () { if (!instance) { merge(this, defaultConfig) instance = this } return instance } get serverUrl () { if (typeof window !== 'undefined' && window.location && window.location.host && window.location.host !== '') { const matchingEnv = find(defaultConfig.envs, env => { return env.serverUrl === window.location.host }) if (matchingEnv) { return '' } } return defaultConfig.envs[this.envName].serverUrl } set logLevel (setLevel) { level = setLevel } get logLevel () { if (level) { return level } return defaultConfig.envs[this.envName].logLevel } set envName (newEnv) { envName = newEnv } get envName () { return envName } get env () { if (defaultConfig.envs[this.envName]) { return defaultConfig.envs[this.envName] } } applySettings (settings) { if (settings) { merge(this, settings) } } } let config = new Config() export default config
{ "content_hash": "3ebfeae0f160906c125754c87a5c9aa3", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 114, "avg_line_length": 20.806818181818183, "alnum_prop": 0.6127799016930638, "repo_name": "KyperTech/matter-library", "id": "1c0172db0105ac38535cf73b947f9866840a7c90", "size": "1831", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/config.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2075" }, { "name": "JavaScript", "bytes": "369152" } ], "symlink_target": "" }
@interface PodsDummy_Pods_TLTools_Tests : NSObject @end @implementation PodsDummy_Pods_TLTools_Tests @end
{ "content_hash": "a07ff61c49ba2f74cd14e4059b0b005a", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 50, "avg_line_length": 26.5, "alnum_prop": 0.8207547169811321, "repo_name": "tang335976123/TLTools", "id": "cbaf810133b579e51858c0be6895c975cb1d7965", "size": "140", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Example/Pods/Target Support Files/Pods-TLTools_Tests/Pods-TLTools_Tests-dummy.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "301498" }, { "name": "Ruby", "bytes": "1493" }, { "name": "Shell", "bytes": "20872" }, { "name": "Swift", "bytes": "6166" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>statsmodels.tsa.statespace.mlemodel.MLEModel.update &#8212; statsmodels v0.10.2 documentation</title> <link rel="stylesheet" href="../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/language_data.js"></script> <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.tsa.statespace.mlemodel.MLEResults" href="statsmodels.tsa.statespace.mlemodel.MLEResults.html" /> <link rel="prev" title="statsmodels.tsa.statespace.mlemodel.MLEModel.untransform_params" href="statsmodels.tsa.statespace.mlemodel.MLEModel.untransform_params.html" /> <link rel="stylesheet" href="../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../_static/scripts.js"> </script> <script type="text/javascript" src="../_static/facebox.js"> </script> <script type="text/javascript"> $.facebox.settings.closeImage = "../_static/closelabel.png" $.facebox.settings.loadingImage = "../_static/loading.gif" </script> <script> $(document).ready(function() { $.getJSON("../../versions.json", function(versions) { var dropdown = document.createElement("div"); dropdown.className = "dropdown"; var button = document.createElement("button"); button.className = "dropbtn"; button.innerHTML = "Other Versions"; var content = document.createElement("div"); content.className = "dropdown-content"; dropdown.appendChild(button); dropdown.appendChild(content); $(".header").prepend(dropdown); for (var i = 0; i < versions.length; i++) { if (versions[i].substring(0, 1) == "v") { versions[i] = [versions[i], versions[i].substring(1)]; } else { versions[i] = [versions[i], versions[i]]; }; }; for (var i = 0; i < versions.length; i++) { var a = document.createElement("a"); a.innerHTML = versions[i][1]; a.href = "../../" + versions[i][0] + "/index.html"; a.title = versions[i][1]; $(".dropdown-content").append(a); }; }); }); </script> </head><body> <div class="headerwrap"> <div class = "header"> <a href = "../index.html"> <img src="../_static/statsmodels_hybi_banner.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="statsmodels.tsa.statespace.mlemodel.MLEResults.html" title="statsmodels.tsa.statespace.mlemodel.MLEResults" accesskey="N">next</a> |</li> <li class="right" > <a href="statsmodels.tsa.statespace.mlemodel.MLEModel.untransform_params.html" title="statsmodels.tsa.statespace.mlemodel.MLEModel.untransform_params" accesskey="P">previous</a> |</li> <li><a href ="../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../dev/index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../faq.html">FAQ</a></li> &nbsp;|&nbsp; <li class="nav-item nav-item-1"><a href="../statespace.html" >Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a> |</li> <li class="nav-item nav-item-2"><a href="statsmodels.tsa.statespace.mlemodel.MLEModel.html" accesskey="U">statsmodels.tsa.statespace.mlemodel.MLEModel</a> |</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="statsmodels-tsa-statespace-mlemodel-mlemodel-update"> <h1>statsmodels.tsa.statespace.mlemodel.MLEModel.update<a class="headerlink" href="#statsmodels-tsa-statespace-mlemodel-mlemodel-update" title="Permalink to this headline">¶</a></h1> <p>method</p> <dl class="method"> <dt id="statsmodels.tsa.statespace.mlemodel.MLEModel.update"> <code class="sig-prename descclassname">MLEModel.</code><code class="sig-name descname">update</code><span class="sig-paren">(</span><em class="sig-param">params</em>, <em class="sig-param">transformed=True</em>, <em class="sig-param">complex_step=False</em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/tsa/statespace/mlemodel.html#MLEModel.update"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.tsa.statespace.mlemodel.MLEModel.update" title="Permalink to this definition">¶</a></dt> <dd><p>Update the parameters of the model</p> <dl class="field-list simple"> <dt class="field-odd">Parameters</dt> <dd class="field-odd"><dl class="simple"> <dt><strong>params</strong><span class="classifier">array_like</span></dt><dd><p>Array of new parameters.</p> </dd> <dt><strong>transformed</strong><span class="classifier">boolean, optional</span></dt><dd><p>Whether or not <cite>params</cite> is already transformed. If set to False, <cite>transform_params</cite> is called. Default is True.</p> </dd> </dl> </dd> <dt class="field-even">Returns</dt> <dd class="field-even"><dl class="simple"> <dt><strong>params</strong><span class="classifier">array_like</span></dt><dd><p>Array of parameters.</p> </dd> </dl> </dd> </dl> <p class="rubric">Notes</p> <p>Since Model is a base class, this method should be overridden by subclasses to perform actual updating steps.</p> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="statsmodels.tsa.statespace.mlemodel.MLEModel.untransform_params.html" title="previous chapter">statsmodels.tsa.statespace.mlemodel.MLEModel.untransform_params</a></p> <h4>Next topic</h4> <p class="topless"><a href="statsmodels.tsa.statespace.mlemodel.MLEResults.html" title="next chapter">statsmodels.tsa.statespace.mlemodel.MLEResults</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/generated/statsmodels.tsa.statespace.mlemodel.MLEModel.update.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3 id="searchlabel">Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" aria-labelledby="searchlabel" /> <input type="submit" value="Go" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.2.1. </div> </body> </html>
{ "content_hash": "392c6736409c78037625846f8b5d68da", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 572, "avg_line_length": 47.01086956521739, "alnum_prop": 0.653179190751445, "repo_name": "statsmodels/statsmodels.github.io", "id": "c8be50c2825ac4e98c3f43f7f7c00f21711c6972", "size": "8654", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v0.10.2/generated/statsmodels.tsa.statespace.mlemodel.MLEModel.update.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
require 'spec_helper' describe InstanceManager::InstanceFormatter do context "with a single ec2 instance" do subject { InstanceManager::InstanceFormatter.new(@staging) } it "should output the information we care about" do output=<<EOF #{@staging.id} => #{@staging.tags["Name"]} ip: #{@staging.public_ip_address} private hostname: #{@staging.private_dns_name} EOF subject.format_output.should == output end end context "with an array of ec2 instances" do subject { InstanceManager::InstanceFormatter.new([@staging,@staging]) } it "should output the information of every server we care about" do output=<<-EOF.gsub(/^[^\n]\s{1,8}/,"") #{@staging.id} => #{@staging.tags["Name"]} ip: #{@staging.public_ip_address} private hostname: #{@staging.private_dns_name} #{@staging.id} => #{@staging.tags["Name"]} ip: #{@staging.public_ip_address} private hostname: #{@staging.private_dns_name} EOF subject.format_output.should == output end end context "with no instances" do subject { InstanceManager::InstanceFormatter.new } it "should output that nothing matched" do subject.format_output.should == "No Instances Matched" end end context "with an instance that has no tags or no name tag" do before(:each) do @instance = @conn.servers.new @instance_with_tags = @conn.servers.new("tags" => {"test" => "test"}) end subject { InstanceManager::InstanceFormatter.new(@instance) } it "should not raise an error" do expect{ subject.format_output }.to_not raise_error expect{ InstanceManager::InstanceFormatter.new(@instance_with_tags).format_output }.to_not raise_error end end context "with a single rds instance" do before do @production_rds.reload end subject { InstanceManager::InstanceFormatter.new(@production_rds) } it "should format correctly" do output =<<-EOF.gsub(/^\s{8}/,"") #{@production_rds.id} Endpoint: #{@production_rds.endpoint["Address"]} Type: Master EOF subject.format_output.should == output end end end
{ "content_hash": "8f2b42a1c8a03580939cd1cf223b9f20", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 108, "avg_line_length": 33.03030303030303, "alnum_prop": 0.6522935779816513, "repo_name": "akatz/instance_manager", "id": "9423ff7b67ad4f0a6df91dda10668104639b867d", "size": "2180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/sk/instance_formatter_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "33359" }, { "name": "Shell", "bytes": "74" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/context_menu_view" android:title="@string/context_menu_view" /> </menu>
{ "content_hash": "cd7877793619372496e4cbacd0dfad1e", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 65, "avg_line_length": 36.5, "alnum_prop": 0.6438356164383562, "repo_name": "datanets/otashu", "id": "9f0e50b57ebacb8ab73ce3e80fb75cb57fa81b4c", "size": "219", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "kanjoto-android/res/menu/context_menu_path.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "959942" } ], "symlink_target": "" }
/** * org.apache.beam.sdk.nexmark.model.sql.adapter. */ /** * Model adapter which contains a mapping between specific Java model to a Row. */ package org.apache.beam.sdk.nexmark.model.sql.adapter;
{ "content_hash": "cf2ead6a6b8b377db9c4763bbc9e6a26", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 79, "avg_line_length": 20.4, "alnum_prop": 0.7156862745098039, "repo_name": "tgroh/beam", "id": "6c79ad3edbb200f8ffe76c11061de60d8f86700a", "size": "1009", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sdks/java/nexmark/src/main/java/org/apache/beam/sdk/nexmark/model/sql/adapter/package-info.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "5994" }, { "name": "Go", "bytes": "2167258" }, { "name": "Groovy", "bytes": "127719" }, { "name": "Java", "bytes": "17206671" }, { "name": "Python", "bytes": "3584300" }, { "name": "Shell", "bytes": "82600" } ], "symlink_target": "" }
using Alachisoft.NCache.Common.Stats; using Alachisoft.NCache.Common.Threading; using System; namespace Alachisoft.NCache.Client { class AsyncOperationCompletedEventTask : AsyncProcessor.IAsyncTask { private bool _notifyAsync; private CommandBase _command; private string _key; private object _asyncOpResult; private Broker _parent; private UsageStats _stats; public AsyncOperationCompletedEventTask(Broker parent, CommandBase command, string key, object asyncOpResult, bool notifyAsync) { this._parent = parent; this._key = key; this._command = command; this._asyncOpResult = asyncOpResult; this._notifyAsync = notifyAsync; } public void Process() { try { if (_parent != null && _parent._cache.AsyncEventHandler != null) { _stats = new UsageStats(); _stats.BeginSample(); if (_command is AddCommand) { _parent._cache.AsyncEventHandler.OnAsyncAddCompleted(_key, ((AddCommand)_command).AsycItemAddedOpComplete, _asyncOpResult, _notifyAsync); } else if (_command is InsertCommand) { _parent._cache.AsyncEventHandler.OnAsyncInsertCompleted(_key, ((InsertCommand)_command).AsycItemUpdatedOpComplete, _asyncOpResult, _notifyAsync); } else if (_command is RemoveCommand) { _parent._cache.AsyncEventHandler.OnAsyncRemoveCompleted(_key, ((RemoveCommand)_command).AsyncItemRemovedOpComplete, _asyncOpResult, _notifyAsync); } else if (_command is ClearCommand) { _parent._cache.AsyncEventHandler.OnAsyncClearCompleted(((ClearCommand)_command).AsyncCacheClearedOpComplete, _asyncOpResult, _notifyAsync); } } _stats.EndSample(); _parent._perfStatsColl.IncrementAvgEventProcessingSample(_stats.Current); } catch (Exception ex) { if (_parent.Logger.IsErrorLogsEnabled) _parent.Logger.NCacheLog.Error("Async Operation completed Event Task.Process", ex.ToString()); } } } }
{ "content_hash": "b22af306c06802c23c3a6db54ffd7e99", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 170, "avg_line_length": 40.57377049180328, "alnum_prop": 0.5628282828282828, "repo_name": "Alachisoft/NCache", "id": "4f8321d82c541110ad5f864df0cda7d3bac18ddc", "size": "3081", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Src/NCClient/Web/RemoteClient/AsyncTask/AsyncOperationCompletedEventTask.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "12283536" }, { "name": "CSS", "bytes": "707" }, { "name": "HTML", "bytes": "16825" }, { "name": "JavaScript", "bytes": "377" } ], "symlink_target": "" }
@interface ScrollViewAndAutolayoutTests : XCTestCase @end @implementation ScrollViewAndAutolayoutTests - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testExample { // This is an example of a functional test case. XCTAssert(YES, @"Pass"); } - (void)testPerformanceExample { // This is an example of a performance test case. [self measureBlock:^{ // Put the code you want to measure the time of here. }]; } @end
{ "content_hash": "6fe1f8b1a8d33d5b9409b2046f96083d", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 107, "avg_line_length": 24.137931034482758, "alnum_prop": 0.6914285714285714, "repo_name": "MarshalW/ScrollViewAndAutolayout", "id": "3255737d787761152929db9dd5c47654ffaefd31", "size": "927", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ScrollViewAndAutolayoutTests/ScrollViewAndAutolayoutTests.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Objective-C", "bytes": "8618" } ], "symlink_target": "" }