code stringlengths 3 1.01M | repo_name stringlengths 5 116 | path stringlengths 3 311 | language stringclasses 30 values | license stringclasses 15 values | size int64 3 1.01M |
|---|---|---|---|---|---|
// Copyright 2020 The Terraformer Authors.
//
// 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.
package launchdarkly
import (
"errors"
"os"
"github.com/GoogleCloudPlatform/terraformer/terraformutils"
)
type LaunchDarklyProvider struct { //nolint
terraformutils.Provider
apiKey string
}
const (
basePath = "https://app.launchdarkly.com/api/v2"
version = "0.0.1"
APIVersion = "20191212"
)
func (p *LaunchDarklyProvider) Init(args []string) error {
if os.Getenv("LAUNCHDARKLY_ACCESS_TOKEN") == "" {
return errors.New("set LAUNCHDARKLY_ACCESS_TOKEN env var")
}
p.apiKey = os.Getenv("LAUNCHDARKLY_ACCESS_TOKEN")
return nil
}
func (p *LaunchDarklyProvider) GetName() string {
return "launchdarkly"
}
func (p *LaunchDarklyProvider) GetProviderData(arg ...string) map[string]interface{} {
return map[string]interface{}{
"provider": map[string]interface{}{
"launchdarkly": map[string]interface{}{
"api_key": p.apiKey,
},
},
}
}
func (LaunchDarklyProvider) GetResourceConnections() map[string]map[string][]string {
return map[string]map[string][]string{}
}
func (p *LaunchDarklyProvider) GetSupportedService() map[string]terraformutils.ServiceGenerator {
return map[string]terraformutils.ServiceGenerator{
"project": &ProjectGenerator{},
}
}
func (p *LaunchDarklyProvider) InitService(serviceName string, verbose bool) error {
var isSupported bool
if _, isSupported = p.GetSupportedService()[serviceName]; !isSupported {
return errors.New("launchdarkly: " + serviceName + " not supported service")
}
p.Service = p.GetSupportedService()[serviceName]
p.Service.SetName(serviceName)
p.Service.SetVerbose(verbose)
p.Service.SetProviderName(p.GetName())
p.Service.SetArgs(map[string]interface{}{
"api_key": p.apiKey,
})
return nil
}
| GoogleCloudPlatform/terraformer | providers/launchdarkly/launchdarkly_provider.go | GO | apache-2.0 | 2,291 |
package org.renjin.primitives;
import org.renjin.eval.Context;
import org.renjin.eval.EvalException;
import org.renjin.primitives.annotations.processor.ArgumentException;
import org.renjin.primitives.annotations.processor.ArgumentIterator;
import org.renjin.primitives.annotations.processor.WrapperRuntime;
import org.renjin.sexp.BuiltinFunction;
import org.renjin.sexp.Environment;
import org.renjin.sexp.FunctionCall;
import org.renjin.sexp.ListVector;
import org.renjin.sexp.PairList;
import org.renjin.sexp.SEXP;
import org.renjin.sexp.Symbol;
public class R$primitive$$Fortran
extends BuiltinFunction
{
public R$primitive$$Fortran() {
super(".Fortran");
}
public SEXP apply(Context context, Environment environment, FunctionCall call, PairList args) {
try {
ArgumentIterator argIt = new ArgumentIterator(context, environment, args);
ListVector.NamedBuilder varArgs = new ListVector.NamedBuilder();
ListVector varArgList;
String pos2;
String flag0 = null;
boolean flag1 = false;
boolean flag2 = false;
boolean flag3 = false;
pos2 = WrapperRuntime.convertToString(argIt.evalNext());
while (argIt.hasNext()) {
PairList.Node node = argIt.nextNode();
SEXP value = node.getValue();
SEXP evaluated;
if (value == Symbol.MISSING_ARG) {
evaluated = value;
} else {
evaluated = context.evaluate(value, environment);
}
if (!node.hasName()) {
varArgs.add(evaluated);
} else {
String name = node.getName();
if ("ENCODING".equals(name)) {
flag3 = WrapperRuntime.convertToBooleanPrimitive(evaluated);
} else {
if ("PACKAGE".equals(name)) {
flag0 = WrapperRuntime.convertToString(evaluated);
} else {
if ("NAOK".equals(name)) {
flag1 = WrapperRuntime.convertToBooleanPrimitive(evaluated);
} else {
if ("DUP".equals(name)) {
flag2 = WrapperRuntime.convertToBooleanPrimitive(evaluated);
} else {
varArgs.add(name, evaluated);
}
}
}
}
}
}
varArgList = varArgs.build();
return Native.dotFortran(context, environment, pos2, varArgList, flag0, flag1, flag2, flag3);
} catch (ArgumentException e) {
throw new EvalException(context, "Invalid argument: %s. Expected:\n\t.Fortran(character(1), ..., character(1), logical(1), logical(1), logical(1))", e.getMessage());
} catch (EvalException e) {
e.initContext(context);
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new EvalException(e);
}
}
public static SEXP doApply(Context context, Environment environment, FunctionCall call, String[] argNames, SEXP[] args) {
try {
ListVector.NamedBuilder varArgs = new ListVector.NamedBuilder();
ListVector varArgList;
String pos2;
String flag0 = null;
boolean flag1 = false;
boolean flag2 = false;
boolean flag3 = false;
pos2 = WrapperRuntime.convertToString(args[ 0 ]);
for (int i = 1; (i<(args.length)); i ++) {
varArgs.add(argNames[i], args[i]);
}
varArgList = varArgs.build();
return Native.dotFortran(context, environment, pos2, varArgList, flag0, flag1, flag2, flag3);
} catch (EvalException e) {
e.initContext(context);
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new EvalException(e);
}
}
public SEXP apply(Context context, Environment environment, FunctionCall call, String[] argNames, SEXP[] args) {
return R$primitive$$Fortran.doApply(context, environment, call, argNames, args);
}
}
| bedatadriven/renjin-statet | org.renjin.core/src-gen/org/renjin/primitives/R$primitive$$Fortran.java | Java | apache-2.0 | 4,496 |
/**
* 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.
*/
package org.apache.heron.streamlet.scala
import org.apache.heron.streamlet.{
IStreamletBasicOperator,
IStreamletOperator,
IStreamletWindowOperator,
JoinType,
KeyValue,
KeyedWindow,
WindowConfig
}
/**
* A Streamlet is a (potentially unbounded) ordered collection of tuples.
* Streamlets originate from pub/sub systems(such Pulsar/Kafka), or from
* static data(such as csv files, HDFS files), or for that matter any other
* source. They are also created by transforming existing Streamlets using
* operations such as map/flatMap, etc.
* Besides the tuples, a Streamlet has the following properties associated with it
* a) name. User assigned or system generated name to refer the streamlet
* b) nPartitions. Number of partitions that the streamlet is composed of. Thus the
* ordering of the tuples in a Streamlet is wrt the tuples within a partition.
* This allows the system to distribute each partition to different nodes across the cluster.
* A bunch of transformations can be done on Streamlets(like map/flatMap, etc.). Each
* of these transformations operate on every tuple of the Streamlet and produce a new
* Streamlet. One can think of a transformation attaching itself to the stream and processing
* each tuple as they go by. Thus the parallelism of any operator is implicitly determined
* by the number of partitions of the stream that it is operating on. If a particular
* transformation wants to operate at a different parallelism, one can repartition the
* Streamlet before doing the transformation.
*/
trait Streamlet[R] {
/**
* Sets the name of the Streamlet.
*
* @param sName The name given by the user for this Streamlet
* @return Returns back the Streamlet with changed name
*/
def setName(sName: String): Streamlet[R]
/**
* Gets the name of the Streamlet.
*
* @return Returns the name of the Streamlet
*/
def getName: String
/**
* Sets the number of partitions of the streamlet
*
* @param numPartitions The user assigned number of partitions
* @return Returns back the Streamlet with changed number of partitions
*/
def setNumPartitions(numPartitions: Int): Streamlet[R]
/**
* Gets the number of partitions of this Streamlet.
*
* @return the number of partitions of this Streamlet
*/
def getNumPartitions: Int
/**
* Return a new Streamlet by applying mapFn to each element of this Streamlet
*
* @param mapFn The Map Function that should be applied to each element
*/
def map[T](mapFn: R => T): Streamlet[T]
/**
* Return a new Streamlet by applying flatMapFn to each element of this Streamlet and
* flattening the result
*
* @param flatMapFn The FlatMap Function that should be applied to each element
*/
def flatMap[T](flatMapFn: R => Iterable[_ <: T]): Streamlet[T]
/**
* Return a new Streamlet by applying the filterFn on each element of this streamlet
* and including only those elements that satisfy the filterFn
*
* @param filterFn The filter Function that should be applied to each element
*/
def filter(filterFn: R => Boolean): Streamlet[R]
/**
* Same as filter(filterFn).setNumPartitions(nPartitions) where filterFn is identity
*/
def repartition(numPartitions: Int): Streamlet[R]
/**
* A more generalized version of repartition where a user can determine which partitions
* any particular tuple should go to. For each element of the current streamlet, the user
* supplied partitionFn is invoked passing in the element as the first argument. The second
* argument is the number of partitions of the downstream streamlet. The partitionFn should
* return 0 or more unique numbers between 0 and npartitions to indicate which partitions
* this element should be routed to.
*/
def repartition(numPartitions: Int,
partitionFn: (R, Int) => Seq[Int]): Streamlet[R]
/**
* Clones the current Streamlet. It returns an array of numClones Streamlets where each
* Streamlet contains all the tuples of the current Streamlet
*
* @param numClones The number of clones to clone
*/
def clone(numClones: Int): Seq[Streamlet[R]]
/**
* Return a new Streamlet by inner joining 'this streamlet with ‘other’ streamlet.
* The join is done over elements accumulated over a time window defined by windowCfg.
* The elements are compared using the thisKeyExtractor for this streamlet with the
* otherKeyExtractor for the other streamlet. On each matching pair, the joinFunction is applied.
*
* @param other The Streamlet that we are joining with.
* @param thisKeyExtractor The function applied to a tuple of this streamlet to get the key
* @param otherKeyExtractor The function applied to a tuple of the other streamlet to get the key
* @param windowCfg This is a specification of what kind of windowing strategy you like to
* have. Typical windowing strategies are sliding windows and tumbling windows
* @param joinFunction The join function that needs to be applied
*/
def join[K, S, T](
other: Streamlet[S],
thisKeyExtractor: R => K,
otherKeyExtractor: S => K,
windowCfg: WindowConfig,
joinFunction: (R, S) => T): Streamlet[KeyValue[KeyedWindow[K], T]]
/**
* Return a new KVStreamlet by joining 'this streamlet with ‘other’ streamlet. The type of joining
* is declared by the joinType parameter.
* The join is done over elements accumulated over a time window defined by windowCfg.
* The elements are compared using the thisKeyExtractor for this streamlet with the
* otherKeyExtractor for the other streamlet. On each matching pair, the joinFunction is applied.
* Types of joins {@link JoinType}
*
* @param other The Streamlet that we are joining with.
* @param thisKeyExtractor The function applied to a tuple of this streamlet to get the key
* @param otherKeyExtractor The function applied to a tuple of the other streamlet to get the key
* @param windowCfg This is a specification of what kind of windowing strategy you like to
* have. Typical windowing strategies are sliding windows and tumbling windows
* @param joinType Type of Join. Options { @link JoinType}
* @param joinFunction The join function that needs to be applied
*/
def join[K, S, T](
other: Streamlet[S],
thisKeyExtractor: R => K,
otherKeyExtractor: S => K,
windowCfg: WindowConfig,
joinType: JoinType,
joinFunction: (R, S) => T): Streamlet[KeyValue[KeyedWindow[K], T]]
/**
* Return a new Streamlet accumulating tuples of this streamlet over a Window defined by
* windowCfg and applying reduceFn on those tuples.
*
* @param keyExtractor The function applied to a tuple of this streamlet to get the key
* @param valueExtractor The function applied to a tuple of this streamlet to extract the value
* to be reduced on
* @param windowCfg This is a specification of what kind of windowing strategy you like to have.
* Typical windowing strategies are sliding windows and tumbling windows
* @param reduceFn The reduce function that you want to apply to all the values of a key.
*/
def reduceByKeyAndWindow[K, V](
keyExtractor: R => K,
valueExtractor: R => V,
windowCfg: WindowConfig,
reduceFn: (V, V) => V): Streamlet[KeyValue[KeyedWindow[K], V]]
/**
* Return a new Streamlet accumulating tuples of this streamlet over a Window defined by
* windowCfg and applying reduceFn on those tuples. For each window, the value identity is used
* as a initial value. All the matching tuples are reduced using reduceFn startin from this
* initial value.
*
* @param keyExtractor The function applied to a tuple of this streamlet to get the key
* @param windowCfg This is a specification of what kind of windowing strategy you like to have.
* Typical windowing strategies are sliding windows and tumbling windows
* @param identity The identity element is both the initial value inside the reduction window
* and the default result if there are no elements in the window
* @param reduceFn The reduce function takes two parameters: a partial result of the reduction
* and the next element of the stream. It returns a new partial result.
*/
def reduceByKeyAndWindow[K, T](
keyExtractor: R => K,
windowCfg: WindowConfig,
identity: T,
reduceFn: (T, R) => T): Streamlet[KeyValue[KeyedWindow[K], T]]
/**
* Returns a new Streamlet that is the union of this and the ‘other’ streamlet. Essentially
* the new streamlet will contain tuples belonging to both Streamlets
*/
def union(other: Streamlet[_ <: R]): Streamlet[R]
/**
* Returns a new Streamlet by applying the transformFunction on each element of this streamlet.
* Before starting to cycle the transformFunction over the Streamlet, the open function is called.
* This allows the transform Function to do any kind of initialization/loading, etc.
*
* @param serializableTransformer The transformation function to be applied
* @param < T> The return type of the transform
* @return Streamlet containing the output of the transformFunction
*/
def transform[T](
serializableTransformer: SerializableTransformer[R, _ <: T]): Streamlet[T]
/**
* Returns a new Streamlet by applying the operator on each element of this streamlet.
* @param operator The operator to be applied
* @param <T> The return type of the transform
* @return Streamlet containing the output of the operation
*/
def applyOperator[T](operator: IStreamletOperator[R, T]): Streamlet[T]
/**
* Returns a new Streamlet by applying the operator on each element of this streamlet.
* @param operator The operator to be applied
* @param <T> The return type of the transform
* @return Streamlet containing the output of the operation
*/
def applyOperator[T](operator: IStreamletBasicOperator[R, T]): Streamlet[T]
/**
* Returns a new Streamlet by applying the operator on each element of this streamlet.
* @param operator The operator to be applied
* @param <T> The return type of the transform
* @return Streamlet containing the output of the operation
*/
def applyOperator[T](operator: IStreamletWindowOperator[R, T]): Streamlet[T]
/**
* Logs every element of the streamlet using String.valueOf function
* This is one of the sink functions in the sense that this operation returns void
*/
def log(): Unit
/**
* Applies the consumer function to every element of the stream
* This function does not return anything.
*
* @param consumer The user supplied consumer function that is invoked for each element
* of this streamlet.
*/
def consume(consumer: R => Unit): Unit
/**
* Applies the sink's put function to every element of the stream
* This function does not return anything.
*
* @param sink The Sink whose put method consumes each element
* of this streamlet.
*/
def toSink(sink: Sink[R]): Unit
}
| tomncooper/heron | heron/api/src/scala/org/apache/heron/streamlet/scala/Streamlet.scala | Scala | apache-2.0 | 12,236 |
<!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_24) on Mon May 16 13:35:20 BST 2011 -->
<TITLE>
TouchMUX (leJOS NXJ PC API documentation)
</TITLE>
<META NAME="date" CONTENT="2011-05-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="TouchMUX (leJOS NXJ PC API documentation)";
}
}
</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> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../lejos/nxt/addon/SensorSelectorException.html" title="class in lejos.nxt.addon"><B>PREV CLASS</B></A>
NEXT CLASS</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?lejos/nxt/addon/TouchMUX.html" target="_top"><B>FRAMES</B></A>
<A HREF="TouchMUX.html" target="_top"><B>NO FRAMES</B></A>
<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>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
lejos.nxt.addon</FONT>
<BR>
Class TouchMUX</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>lejos.nxt.addon.TouchMUX</B>
</PRE>
<HR>
<DL>
<DT><PRE>public class <B>TouchMUX</B><DT>extends java.lang.Object</DL>
</PRE>
<P>
Interface for the Mindsensors Touch Multiplexer.
This device allows up to three touch sensors to be attached to a single NXT
sensor port.
<P>
<P>
<DL>
<DT><B>Author:</B></DT>
<DD>Andy</DD>
</DL>
<HR>
<P>
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Field Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/addon/TouchMUX.html#ID_T1">ID_T1</A></B></CODE>
<BR>
Bit ID returned by readSensors when sensor T1 is pressed</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/addon/TouchMUX.html#ID_T2">ID_T2</A></B></CODE>
<BR>
Bit ID returned by readSensors when sensor T1 is pressed</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/addon/TouchMUX.html#ID_T3">ID_T3</A></B></CODE>
<BR>
Bit ID returned by readSensors when sensor T1 is pressed</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/addon/TouchMUX.html#NUMBER_OF_SENSORS">NUMBER_OF_SENSORS</A></B></CODE>
<BR>
number of touch sensors supported by this device</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../lejos/robotics/Touch.html" title="interface in lejos.robotics">Touch</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/addon/TouchMUX.html#T1">T1</A></B></CODE>
<BR>
Instance for the touch sensor connected to port T1</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../lejos/robotics/Touch.html" title="interface in lejos.robotics">Touch</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/addon/TouchMUX.html#T2">T2</A></B></CODE>
<BR>
Instance for the touch sensor connected to port T2</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../lejos/robotics/Touch.html" title="interface in lejos.robotics">Touch</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/addon/TouchMUX.html#T3">T3</A></B></CODE>
<BR>
Instance for the touch sensor connected to port T3</TD>
</TR>
</TABLE>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../lejos/nxt/addon/TouchMUX.html#TouchMUX(lejos.nxt.ADSensorPort)">TouchMUX</A></B>(<A HREF="../../../lejos/nxt/ADSensorPort.html" title="interface in lejos.nxt">ADSensorPort</A> port)</CODE>
<BR>
Create a object to provide access to a touch sensor multiplexer</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../lejos/robotics/Touch.html" title="interface in lejos.robotics">Touch</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/addon/TouchMUX.html#getInstance(int)">getInstance</A></B>(int id)</CODE>
<BR>
Return a Touch interface providing access to the sensor specified by the
given id.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/addon/TouchMUX.html#readSensors()">readSensors</A></B>()</CODE>
<BR>
Read the touch multiplexer and return a bit mask showing which sensors
are currently pressed.</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ FIELD DETAIL =========== -->
<A NAME="field_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Field Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="NUMBER_OF_SENSORS"><!-- --></A><H3>
NUMBER_OF_SENSORS</H3>
<PRE>
public static final int <B>NUMBER_OF_SENSORS</B></PRE>
<DL>
<DD>number of touch sensors supported by this device
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#lejos.nxt.addon.TouchMUX.NUMBER_OF_SENSORS">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="ID_T1"><!-- --></A><H3>
ID_T1</H3>
<PRE>
public static final int <B>ID_T1</B></PRE>
<DL>
<DD>Bit ID returned by readSensors when sensor T1 is pressed
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#lejos.nxt.addon.TouchMUX.ID_T1">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="ID_T2"><!-- --></A><H3>
ID_T2</H3>
<PRE>
public static final int <B>ID_T2</B></PRE>
<DL>
<DD>Bit ID returned by readSensors when sensor T1 is pressed
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#lejos.nxt.addon.TouchMUX.ID_T2">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="ID_T3"><!-- --></A><H3>
ID_T3</H3>
<PRE>
public static final int <B>ID_T3</B></PRE>
<DL>
<DD>Bit ID returned by readSensors when sensor T1 is pressed
<P>
<DL>
<DT><B>See Also:</B><DD><A HREF="../../../constant-values.html#lejos.nxt.addon.TouchMUX.ID_T3">Constant Field Values</A></DL>
</DL>
<HR>
<A NAME="T1"><!-- --></A><H3>
T1</H3>
<PRE>
public final <A HREF="../../../lejos/robotics/Touch.html" title="interface in lejos.robotics">Touch</A> <B>T1</B></PRE>
<DL>
<DD>Instance for the touch sensor connected to port T1
<P>
<DL>
</DL>
</DL>
<HR>
<A NAME="T2"><!-- --></A><H3>
T2</H3>
<PRE>
public final <A HREF="../../../lejos/robotics/Touch.html" title="interface in lejos.robotics">Touch</A> <B>T2</B></PRE>
<DL>
<DD>Instance for the touch sensor connected to port T2
<P>
<DL>
</DL>
</DL>
<HR>
<A NAME="T3"><!-- --></A><H3>
T3</H3>
<PRE>
public final <A HREF="../../../lejos/robotics/Touch.html" title="interface in lejos.robotics">Touch</A> <B>T3</B></PRE>
<DL>
<DD>Instance for the touch sensor connected to port T3
<P>
<DL>
</DL>
</DL>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="TouchMUX(lejos.nxt.ADSensorPort)"><!-- --></A><H3>
TouchMUX</H3>
<PRE>
public <B>TouchMUX</B>(<A HREF="../../../lejos/nxt/ADSensorPort.html" title="interface in lejos.nxt">ADSensorPort</A> port)</PRE>
<DL>
<DD>Create a object to provide access to a touch sensor multiplexer
<P>
<DL>
<DT><B>Parameters:</B><DD><CODE>port</CODE> - The NXT sensor port to which the multiplexer is attached</DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="getInstance(int)"><!-- --></A><H3>
getInstance</H3>
<PRE>
public <A HREF="../../../lejos/robotics/Touch.html" title="interface in lejos.robotics">Touch</A> <B>getInstance</B>(int id)</PRE>
<DL>
<DD>Return a Touch interface providing access to the sensor specified by the
given id.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>id</CODE> - a number between 0..<A HREF="../../../lejos/nxt/addon/TouchMUX.html#NUMBER_OF_SENSORS"><CODE>NUMBER_OF_SENSORS</CODE></A>-1
<DT><B>Returns:</B><DD>the requested Touch interface</DL>
</DD>
</DL>
<HR>
<A NAME="readSensors()"><!-- --></A><H3>
readSensors</H3>
<PRE>
public int <B>readSensors</B>()</PRE>
<DL>
<DD>Read the touch multiplexer and return a bit mask showing which sensors
are currently pressed. Returns ID_T1 if T1 is pressed, ID_T2 if T2 is
pressed and ID_T3 id T3 is pressed. If more then one sensor is pressed
the return will be an or of the values.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>bit mask showing which sensor buttons are pressed.</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<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> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../lejos/nxt/addon/SensorSelectorException.html" title="class in lejos.nxt.addon"><B>PREV CLASS</B></A>
NEXT CLASS</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?lejos/nxt/addon/TouchMUX.html" target="_top"><B>FRAMES</B></A>
<A HREF="TouchMUX.html" target="_top"><B>NO FRAMES</B></A>
<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>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| AndrewZurn/sju-compsci-archive | CS200s/CS217b/OriginalFiles/doc/lejos/nxt/addon/TouchMUX.html | HTML | apache-2.0 | 17,227 |
# Lotus balticus Miniaev SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Bot. Mater. Gerb. Bot. Inst. Komarova Akad. Nauk S. S. S. R. 18:129. 1957
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Lotus/Lotus corniculatus/ Syn. Lotus balticus/README.md | Markdown | apache-2.0 | 248 |
//===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// Modifications Copyright (c) 2019 Advanced Micro Devices, Inc. All rights reserved.
// Notified per clause 4(b) of the license.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// Custom DAG lowering for SI
//
//===----------------------------------------------------------------------===//
#if defined(_MSC_VER) || defined(__MINGW32__)
// Provide M_PI.
#define _USE_MATH_DEFINES
#endif
#include "SIISelLowering.h"
#include "AMDGPU.h"
#include "AMDGPUSubtarget.h"
#include "AMDGPUTargetMachine.h"
#include "SIDefines.h"
#include "SIInstrInfo.h"
#include "SIMachineFunctionInfo.h"
#include "SIRegisterInfo.h"
#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
#include "Utils/AMDGPUBaseInfo.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Twine.h"
#include "llvm/CodeGen/Analysis.h"
#include "llvm/CodeGen/CallingConvLower.h"
#include "llvm/CodeGen/DAGCombine.h"
#include "llvm/CodeGen/ISDOpcodes.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineMemOperand.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SelectionDAG.h"
#include "llvm/CodeGen/SelectionDAGNodes.h"
#include "llvm/CodeGen/TargetCallingConv.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CodeGen.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/KnownBits.h"
#include "llvm/Support/MachineValueType.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Target/TargetOptions.h"
#include <cassert>
#include <cmath>
#include <cstdint>
#include <iterator>
#include <tuple>
#include <utility>
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "si-lower"
STATISTIC(NumTailCalls, "Number of tail calls");
static cl::opt<bool> EnableVGPRIndexMode(
"amdgpu-vgpr-index-mode",
cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
cl::init(false));
static cl::opt<bool> DisableLoopAlignment(
"amdgpu-disable-loop-alignment",
cl::desc("Do not align and prefetch loops"),
cl::init(false));
static unsigned findFirstFreeSGPR(CCState &CCInfo) {
unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
return AMDGPU::SGPR0 + Reg;
}
}
llvm_unreachable("Cannot allocate sgpr");
}
SITargetLowering::SITargetLowering(const TargetMachine &TM,
const GCNSubtarget &STI)
: AMDGPUTargetLowering(TM, STI),
Subtarget(&STI) {
addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
if (Subtarget->has16BitInsts()) {
addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
// Unless there are also VOP3P operations, not operations are really legal.
addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
}
if (Subtarget->hasMAIInsts()) {
addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
}
computeRegisterProperties(Subtarget->getRegisterInfo());
// We need to custom lower vector stores from local memory
setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
setOperationAction(ISD::LOAD, MVT::i1, Custom);
setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
setOperationAction(ISD::STORE, MVT::v2i32, Custom);
setOperationAction(ISD::STORE, MVT::v3i32, Custom);
setOperationAction(ISD::STORE, MVT::v4i32, Custom);
setOperationAction(ISD::STORE, MVT::v5i32, Custom);
setOperationAction(ISD::STORE, MVT::v8i32, Custom);
setOperationAction(ISD::STORE, MVT::v16i32, Custom);
setOperationAction(ISD::STORE, MVT::i1, Custom);
setOperationAction(ISD::STORE, MVT::v32i32, Custom);
setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
setOperationAction(ISD::SELECT, MVT::i1, Promote);
setOperationAction(ISD::SELECT, MVT::i64, Custom);
setOperationAction(ISD::SELECT, MVT::f64, Promote);
AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
setOperationAction(ISD::SETCC, MVT::i1, Promote);
setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
setOperationAction(ISD::BRCOND, MVT::Other, Custom);
setOperationAction(ISD::BR_CC, MVT::i1, Expand);
setOperationAction(ISD::BR_CC, MVT::i32, Expand);
setOperationAction(ISD::BR_CC, MVT::i64, Expand);
setOperationAction(ISD::BR_CC, MVT::f32, Expand);
setOperationAction(ISD::BR_CC, MVT::f64, Expand);
setOperationAction(ISD::UADDO, MVT::i32, Legal);
setOperationAction(ISD::USUBO, MVT::i32, Legal);
setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
#if 0
setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
#endif
// We only support LOAD/STORE and vector manipulation ops for vectors
// with > 4 elements.
for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
MVT::v32i32, MVT::v32f32 }) {
for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
switch (Op) {
case ISD::LOAD:
case ISD::STORE:
case ISD::BUILD_VECTOR:
case ISD::BITCAST:
case ISD::EXTRACT_VECTOR_ELT:
case ISD::INSERT_VECTOR_ELT:
case ISD::INSERT_SUBVECTOR:
case ISD::EXTRACT_SUBVECTOR:
case ISD::SCALAR_TO_VECTOR:
break;
case ISD::CONCAT_VECTORS:
setOperationAction(Op, VT, Custom);
break;
default:
setOperationAction(Op, VT, Expand);
break;
}
}
}
setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
// TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
// is expanded to avoid having two separate loops in case the index is a VGPR.
// Most operations are naturally 32-bit vector operations. We only support
// load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
}
setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
// Avoid stack access for these.
// TODO: Generalize to more vector types.
setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
// Deal with vec3 vector operations when widened to vec4.
setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
// Deal with vec5 vector operations when widened to vec8.
setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
// BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
// and output demarshalling
setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
// We can't return success/failure, only the old value,
// let LLVM add the comparison
setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
if (Subtarget->hasFlatAddressSpace()) {
setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
}
setOperationAction(ISD::BSWAP, MVT::i32, Legal);
setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
// On SI this is s_memtime and s_memrealtime on VI.
setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
setOperationAction(ISD::TRAP, MVT::Other, Custom);
setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
if (Subtarget->has16BitInsts()) {
setOperationAction(ISD::FLOG, MVT::f16, Custom);
setOperationAction(ISD::FEXP, MVT::f16, Custom);
setOperationAction(ISD::FLOG10, MVT::f16, Custom);
}
// v_mad_f32 does not support denormals according to some sources.
if (!Subtarget->hasFP32Denormals())
setOperationAction(ISD::FMAD, MVT::f32, Legal);
if (!Subtarget->hasBFI()) {
// fcopysign can be done in a single instruction with BFI.
setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
}
if (!Subtarget->hasBCNT(32))
setOperationAction(ISD::CTPOP, MVT::i32, Expand);
if (!Subtarget->hasBCNT(64))
setOperationAction(ISD::CTPOP, MVT::i64, Expand);
if (Subtarget->hasFFBH())
setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
if (Subtarget->hasFFBL())
setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
// We only really have 32-bit BFE instructions (and 16-bit on VI).
//
// On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
// effort to match them now. We want this to be false for i64 cases when the
// extraction isn't restricted to the upper or lower half. Ideally we would
// have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
// span the midpoint are probably relatively rare, so don't worry about them
// for now.
if (Subtarget->hasBFE())
setHasExtractBitsInsn(true);
setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
// These are really only legal for ieee_mode functions. We should be avoiding
// them for functions that don't have ieee_mode enabled, so just say they are
// legal.
setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
if (Subtarget->haveRoundOpsF64()) {
setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
setOperationAction(ISD::FCEIL, MVT::f64, Legal);
setOperationAction(ISD::FRINT, MVT::f64, Legal);
} else {
setOperationAction(ISD::FCEIL, MVT::f64, Custom);
setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
setOperationAction(ISD::FRINT, MVT::f64, Custom);
setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
}
setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
setOperationAction(ISD::FSIN, MVT::f32, Custom);
setOperationAction(ISD::FCOS, MVT::f32, Custom);
setOperationAction(ISD::FDIV, MVT::f32, Custom);
setOperationAction(ISD::FDIV, MVT::f64, Custom);
if (Subtarget->has16BitInsts()) {
setOperationAction(ISD::Constant, MVT::i16, Legal);
setOperationAction(ISD::SMIN, MVT::i16, Legal);
setOperationAction(ISD::SMAX, MVT::i16, Legal);
setOperationAction(ISD::UMIN, MVT::i16, Legal);
setOperationAction(ISD::UMAX, MVT::i16, Legal);
setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
setOperationAction(ISD::ROTR, MVT::i16, Promote);
setOperationAction(ISD::ROTL, MVT::i16, Promote);
setOperationAction(ISD::SDIV, MVT::i16, Promote);
setOperationAction(ISD::UDIV, MVT::i16, Promote);
setOperationAction(ISD::SREM, MVT::i16, Promote);
setOperationAction(ISD::UREM, MVT::i16, Promote);
setOperationAction(ISD::BSWAP, MVT::i16, Promote);
setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
setOperationAction(ISD::CTTZ, MVT::i16, Promote);
setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
setOperationAction(ISD::CTLZ, MVT::i16, Promote);
setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
setOperationAction(ISD::CTPOP, MVT::i16, Promote);
setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
setOperationAction(ISD::BR_CC, MVT::i16, Expand);
setOperationAction(ISD::LOAD, MVT::i16, Custom);
setTruncStoreAction(MVT::i64, MVT::i16, Expand);
setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
// F16 - Constant Actions.
setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
// F16 - Load/Store Actions.
setOperationAction(ISD::LOAD, MVT::f16, Promote);
AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
setOperationAction(ISD::STORE, MVT::f16, Promote);
AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
// F16 - VOP1 Actions.
setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
setOperationAction(ISD::FCOS, MVT::f16, Promote);
setOperationAction(ISD::FSIN, MVT::f16, Promote);
setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
setOperationAction(ISD::FROUND, MVT::f16, Custom);
// F16 - VOP2 Actions.
setOperationAction(ISD::BR_CC, MVT::f16, Expand);
setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
setOperationAction(ISD::FDIV, MVT::f16, Custom);
// F16 - VOP3 Actions.
setOperationAction(ISD::FMA, MVT::f16, Legal);
if (!Subtarget->hasFP16Denormals() && STI.hasMadF16())
setOperationAction(ISD::FMAD, MVT::f16, Legal);
for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
switch (Op) {
case ISD::LOAD:
case ISD::STORE:
case ISD::BUILD_VECTOR:
case ISD::BITCAST:
case ISD::EXTRACT_VECTOR_ELT:
case ISD::INSERT_VECTOR_ELT:
case ISD::INSERT_SUBVECTOR:
case ISD::EXTRACT_SUBVECTOR:
case ISD::SCALAR_TO_VECTOR:
break;
case ISD::CONCAT_VECTORS:
setOperationAction(Op, VT, Custom);
break;
default:
setOperationAction(Op, VT, Expand);
break;
}
}
}
// XXX - Do these do anything? Vector constants turn into build_vector.
setOperationAction(ISD::Constant, MVT::v2i16, Legal);
setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
setOperationAction(ISD::STORE, MVT::v2i16, Promote);
AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
setOperationAction(ISD::STORE, MVT::v2f16, Promote);
AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
setOperationAction(ISD::AND, MVT::v2i16, Promote);
AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
setOperationAction(ISD::OR, MVT::v2i16, Promote);
AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
setOperationAction(ISD::XOR, MVT::v2i16, Promote);
AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
setOperationAction(ISD::STORE, MVT::v4i16, Promote);
AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
setOperationAction(ISD::STORE, MVT::v4f16, Promote);
AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
if (!Subtarget->hasVOP3PInsts()) {
setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
}
setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
// This isn't really legal, but this avoids the legalizer unrolling it (and
// allows matching fneg (fabs x) patterns)
setOperationAction(ISD::FABS, MVT::v2f16, Legal);
setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
}
if (Subtarget->hasVOP3PInsts()) {
setOperationAction(ISD::ADD, MVT::v2i16, Legal);
setOperationAction(ISD::SUB, MVT::v2i16, Legal);
setOperationAction(ISD::MUL, MVT::v2i16, Legal);
setOperationAction(ISD::SHL, MVT::v2i16, Legal);
setOperationAction(ISD::SRL, MVT::v2i16, Legal);
setOperationAction(ISD::SRA, MVT::v2i16, Legal);
setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
setOperationAction(ISD::FADD, MVT::v2f16, Legal);
setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
setOperationAction(ISD::FMA, MVT::v2f16, Legal);
setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
setOperationAction(ISD::SHL, MVT::v4i16, Custom);
setOperationAction(ISD::SRA, MVT::v4i16, Custom);
setOperationAction(ISD::SRL, MVT::v4i16, Custom);
setOperationAction(ISD::ADD, MVT::v4i16, Custom);
setOperationAction(ISD::SUB, MVT::v4i16, Custom);
setOperationAction(ISD::MUL, MVT::v4i16, Custom);
setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
setOperationAction(ISD::FADD, MVT::v4f16, Custom);
setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
setOperationAction(ISD::FMA, MVT::v4f16, Custom);
setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
}
setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
setOperationAction(ISD::FABS, MVT::v4f16, Custom);
if (Subtarget->has16BitInsts()) {
setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
} else {
// Legalization hack.
setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
setOperationAction(ISD::FABS, MVT::v2f16, Custom);
}
for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
setOperationAction(ISD::SELECT, VT, Custom);
}
setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
setTargetDAGCombine(ISD::ADD);
setTargetDAGCombine(ISD::ADDCARRY);
setTargetDAGCombine(ISD::SUB);
setTargetDAGCombine(ISD::SUBCARRY);
setTargetDAGCombine(ISD::FADD);
setTargetDAGCombine(ISD::FSUB);
setTargetDAGCombine(ISD::FMINNUM);
setTargetDAGCombine(ISD::FMAXNUM);
setTargetDAGCombine(ISD::FMINNUM_IEEE);
setTargetDAGCombine(ISD::FMAXNUM_IEEE);
setTargetDAGCombine(ISD::FMA);
setTargetDAGCombine(ISD::SMIN);
setTargetDAGCombine(ISD::SMAX);
setTargetDAGCombine(ISD::UMIN);
setTargetDAGCombine(ISD::UMAX);
setTargetDAGCombine(ISD::SETCC);
setTargetDAGCombine(ISD::AND);
setTargetDAGCombine(ISD::OR);
setTargetDAGCombine(ISD::XOR);
setTargetDAGCombine(ISD::SINT_TO_FP);
setTargetDAGCombine(ISD::UINT_TO_FP);
setTargetDAGCombine(ISD::FCANONICALIZE);
setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
setTargetDAGCombine(ISD::ZERO_EXTEND);
setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
// All memory operations. Some folding on the pointer operand is done to help
// matching the constant offsets in the addressing modes.
setTargetDAGCombine(ISD::LOAD);
setTargetDAGCombine(ISD::STORE);
setTargetDAGCombine(ISD::ATOMIC_LOAD);
setTargetDAGCombine(ISD::ATOMIC_STORE);
setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
setTargetDAGCombine(ISD::ATOMIC_SWAP);
setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
setSchedulingPreference(Sched::RegPressure);
}
const GCNSubtarget *SITargetLowering::getSubtarget() const {
return Subtarget;
}
//===----------------------------------------------------------------------===//
// TargetLowering queries
//===----------------------------------------------------------------------===//
// v_mad_mix* support a conversion from f16 to f32.
//
// There is only one special case when denormals are enabled we don't currently,
// where this is OK to use.
bool SITargetLowering::isFPExtFoldable(unsigned Opcode,
EVT DestVT, EVT SrcVT) const {
return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
(Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() &&
SrcVT.getScalarType() == MVT::f16;
}
bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
// SI has some legal vector types, but no legal vector operations. Say no
// shuffles are legal in order to prefer scalarizing some vector operations.
return false;
}
MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
CallingConv::ID CC,
EVT VT) const {
if (CC == CallingConv::AMDGPU_KERNEL)
return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
if (VT.isVector()) {
EVT ScalarVT = VT.getScalarType();
unsigned Size = ScalarVT.getSizeInBits();
if (Size == 32)
return ScalarVT.getSimpleVT();
if (Size > 32)
return MVT::i32;
if (Size == 16 && Subtarget->has16BitInsts())
return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
} else if (VT.getSizeInBits() > 32)
return MVT::i32;
return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
}
unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
CallingConv::ID CC,
EVT VT) const {
if (CC == CallingConv::AMDGPU_KERNEL)
return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
if (VT.isVector()) {
unsigned NumElts = VT.getVectorNumElements();
EVT ScalarVT = VT.getScalarType();
unsigned Size = ScalarVT.getSizeInBits();
if (Size == 32)
return NumElts;
if (Size > 32)
return NumElts * ((Size + 31) / 32);
if (Size == 16 && Subtarget->has16BitInsts())
return (NumElts + 1) / 2;
} else if (VT.getSizeInBits() > 32)
return (VT.getSizeInBits() + 31) / 32;
return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
}
unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
LLVMContext &Context, CallingConv::ID CC,
EVT VT, EVT &IntermediateVT,
unsigned &NumIntermediates, MVT &RegisterVT) const {
if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
unsigned NumElts = VT.getVectorNumElements();
EVT ScalarVT = VT.getScalarType();
unsigned Size = ScalarVT.getSizeInBits();
if (Size == 32) {
RegisterVT = ScalarVT.getSimpleVT();
IntermediateVT = RegisterVT;
NumIntermediates = NumElts;
return NumIntermediates;
}
if (Size > 32) {
RegisterVT = MVT::i32;
IntermediateVT = RegisterVT;
NumIntermediates = NumElts * ((Size + 31) / 32);
return NumIntermediates;
}
// FIXME: We should fix the ABI to be the same on targets without 16-bit
// support, but unless we can properly handle 3-vectors, it will be still be
// inconsistent.
if (Size == 16 && Subtarget->has16BitInsts()) {
RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
IntermediateVT = RegisterVT;
NumIntermediates = (NumElts + 1) / 2;
return NumIntermediates;
}
}
return TargetLowering::getVectorTypeBreakdownForCallingConv(
Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
}
static MVT memVTFromAggregate(Type *Ty) {
// Only limited forms of aggregate type currently expected.
assert(Ty->isStructTy() && "Expected struct type");
Type *ElementType = nullptr;
unsigned NumElts;
if (Ty->getContainedType(0)->isVectorTy()) {
VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0));
ElementType = VecComponent->getElementType();
NumElts = VecComponent->getNumElements();
} else {
ElementType = Ty->getContainedType(0);
NumElts = 1;
}
assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type");
// Calculate the size of the memVT type from the aggregate
unsigned Pow2Elts = 0;
unsigned ElementSize;
switch (ElementType->getTypeID()) {
default:
llvm_unreachable("Unknown type!");
case Type::IntegerTyID:
ElementSize = cast<IntegerType>(ElementType)->getBitWidth();
break;
case Type::HalfTyID:
ElementSize = 16;
break;
case Type::FloatTyID:
ElementSize = 32;
break;
}
unsigned AdditionalElts = ElementSize == 16 ? 2 : 1;
Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts);
return MVT::getVectorVT(MVT::getVT(ElementType, false),
Pow2Elts);
}
bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
const CallInst &CI,
MachineFunction &MF,
unsigned IntrID) const {
if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
AMDGPU::lookupRsrcIntrinsic(IntrID)) {
AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
(Intrinsic::ID)IntrID);
if (Attr.hasFnAttribute(Attribute::ReadNone))
return false;
SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
if (RsrcIntr->IsImage) {
Info.ptrVal = MFI->getImagePSV(
*MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
CI.getArgOperand(RsrcIntr->RsrcArg));
Info.align.reset();
} else {
Info.ptrVal = MFI->getBufferPSV(
*MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
CI.getArgOperand(RsrcIntr->RsrcArg));
}
Info.flags = MachineMemOperand::MODereferenceable;
if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
Info.opc = ISD::INTRINSIC_W_CHAIN;
Info.memVT = MVT::getVT(CI.getType(), true);
if (Info.memVT == MVT::Other) {
// Some intrinsics return an aggregate type - special case to work out
// the correct memVT
Info.memVT = memVTFromAggregate(CI.getType());
}
Info.flags |= MachineMemOperand::MOLoad;
} else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
Info.opc = ISD::INTRINSIC_VOID;
Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
Info.flags |= MachineMemOperand::MOStore;
} else {
// Atomic
Info.opc = ISD::INTRINSIC_W_CHAIN;
Info.memVT = MVT::getVT(CI.getType());
Info.flags = MachineMemOperand::MOLoad |
MachineMemOperand::MOStore |
MachineMemOperand::MODereferenceable;
// XXX - Should this be volatile without known ordering?
Info.flags |= MachineMemOperand::MOVolatile;
}
return true;
}
switch (IntrID) {
case Intrinsic::amdgcn_atomic_inc:
case Intrinsic::amdgcn_atomic_dec:
case Intrinsic::amdgcn_ds_ordered_add:
case Intrinsic::amdgcn_ds_ordered_swap:
case Intrinsic::amdgcn_ds_fadd:
case Intrinsic::amdgcn_ds_fmin:
case Intrinsic::amdgcn_ds_fmax: {
Info.opc = ISD::INTRINSIC_W_CHAIN;
Info.memVT = MVT::getVT(CI.getType());
Info.ptrVal = CI.getOperand(0);
Info.align.reset();
Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
if (!Vol->isZero())
Info.flags |= MachineMemOperand::MOVolatile;
return true;
}
case Intrinsic::amdgcn_buffer_atomic_fadd: {
SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
Info.opc = ISD::INTRINSIC_VOID;
Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
Info.ptrVal = MFI->getBufferPSV(
*MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
CI.getArgOperand(1));
Info.align.reset();
Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
if (!Vol || !Vol->isZero())
Info.flags |= MachineMemOperand::MOVolatile;
return true;
}
case Intrinsic::amdgcn_global_atomic_fadd: {
Info.opc = ISD::INTRINSIC_VOID;
Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
->getPointerElementType());
Info.ptrVal = CI.getOperand(0);
Info.align.reset();
Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
return true;
}
case Intrinsic::amdgcn_ds_append:
case Intrinsic::amdgcn_ds_consume: {
Info.opc = ISD::INTRINSIC_W_CHAIN;
Info.memVT = MVT::getVT(CI.getType());
Info.ptrVal = CI.getOperand(0);
Info.align.reset();
Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
if (!Vol->isZero())
Info.flags |= MachineMemOperand::MOVolatile;
return true;
}
case Intrinsic::amdgcn_ds_gws_init:
case Intrinsic::amdgcn_ds_gws_barrier:
case Intrinsic::amdgcn_ds_gws_sema_v:
case Intrinsic::amdgcn_ds_gws_sema_br:
case Intrinsic::amdgcn_ds_gws_sema_p:
case Intrinsic::amdgcn_ds_gws_sema_release_all: {
Info.opc = ISD::INTRINSIC_VOID;
SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
Info.ptrVal =
MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
// This is an abstract access, but we need to specify a type and size.
Info.memVT = MVT::i32;
Info.size = 4;
Info.align = Align(4);
Info.flags = MachineMemOperand::MOStore;
if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
Info.flags = MachineMemOperand::MOLoad;
return true;
}
default:
return false;
}
}
bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
SmallVectorImpl<Value*> &Ops,
Type *&AccessTy) const {
switch (II->getIntrinsicID()) {
case Intrinsic::amdgcn_atomic_inc:
case Intrinsic::amdgcn_atomic_dec:
case Intrinsic::amdgcn_ds_ordered_add:
case Intrinsic::amdgcn_ds_ordered_swap:
case Intrinsic::amdgcn_ds_fadd:
case Intrinsic::amdgcn_ds_fmin:
case Intrinsic::amdgcn_ds_fmax: {
Value *Ptr = II->getArgOperand(0);
AccessTy = II->getType();
Ops.push_back(Ptr);
return true;
}
default:
return false;
}
}
bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
if (!Subtarget->hasFlatInstOffsets()) {
// Flat instructions do not have offsets, and only have the register
// address.
return AM.BaseOffs == 0 && AM.Scale == 0;
}
// GFX9 added a 13-bit signed offset. When using regular flat instructions,
// the sign bit is ignored and is treated as a 12-bit unsigned offset.
// GFX10 shrinked signed offset to 12 bits. When using regular flat
// instructions, the sign bit is also ignored and is treated as 11-bit
// unsigned offset.
if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
return isUInt<11>(AM.BaseOffs) && AM.Scale == 0;
// Just r + i
return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
}
bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
if (Subtarget->hasFlatGlobalInsts())
return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
// Assume the we will use FLAT for all global memory accesses
// on VI.
// FIXME: This assumption is currently wrong. On VI we still use
// MUBUF instructions for the r + i addressing mode. As currently
// implemented, the MUBUF instructions only work on buffer < 4GB.
// It may be possible to support > 4GB buffers with MUBUF instructions,
// by setting the stride value in the resource descriptor which would
// increase the size limit to (stride * 4GB). However, this is risky,
// because it has never been validated.
return isLegalFlatAddressingMode(AM);
}
return isLegalMUBUFAddressingMode(AM);
}
bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
// MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
// additionally can do r + r + i with addr64. 32-bit has more addressing
// mode options. Depending on the resource constant, it can also do
// (i64 r0) + (i32 r1) * (i14 i).
//
// Private arrays end up using a scratch buffer most of the time, so also
// assume those use MUBUF instructions. Scratch loads / stores are currently
// implemented as mubuf instructions with offen bit set, so slightly
// different than the normal addr64.
if (!isUInt<12>(AM.BaseOffs))
return false;
// FIXME: Since we can split immediate into soffset and immediate offset,
// would it make sense to allow any immediate?
switch (AM.Scale) {
case 0: // r + i or just i, depending on HasBaseReg.
return true;
case 1:
return true; // We have r + r or r + i.
case 2:
if (AM.HasBaseReg) {
// Reject 2 * r + r.
return false;
}
// Allow 2 * r as r + r
// Or 2 * r + i is allowed as r + r + i.
return true;
default: // Don't allow n * r
return false;
}
}
bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
const AddrMode &AM, Type *Ty,
unsigned AS, Instruction *I) const {
// No global is ever allowed as a base.
if (AM.BaseGV)
return false;
if (AS == AMDGPUAS::GLOBAL_ADDRESS)
return isLegalGlobalAddressingMode(AM);
if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
AS == AMDGPUAS::BUFFER_FAT_POINTER) {
// If the offset isn't a multiple of 4, it probably isn't going to be
// correctly aligned.
// FIXME: Can we get the real alignment here?
if (AM.BaseOffs % 4 != 0)
return isLegalMUBUFAddressingMode(AM);
// There are no SMRD extloads, so if we have to do a small type access we
// will use a MUBUF load.
// FIXME?: We also need to do this if unaligned, but we don't know the
// alignment here.
if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
return isLegalGlobalAddressingMode(AM);
if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
// SMRD instructions have an 8-bit, dword offset on SI.
if (!isUInt<8>(AM.BaseOffs / 4))
return false;
} else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
// On CI+, this can also be a 32-bit literal constant offset. If it fits
// in 8-bits, it can use a smaller encoding.
if (!isUInt<32>(AM.BaseOffs / 4))
return false;
} else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
// On VI, these use the SMEM format and the offset is 20-bit in bytes.
if (!isUInt<20>(AM.BaseOffs))
return false;
} else
llvm_unreachable("unhandled generation");
if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
return true;
if (AM.Scale == 1 && AM.HasBaseReg)
return true;
return false;
} else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
return isLegalMUBUFAddressingMode(AM);
} else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
AS == AMDGPUAS::REGION_ADDRESS) {
// Basic, single offset DS instructions allow a 16-bit unsigned immediate
// field.
// XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
// an 8-bit dword offset but we don't know the alignment here.
if (!isUInt<16>(AM.BaseOffs))
return false;
if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
return true;
if (AM.Scale == 1 && AM.HasBaseReg)
return true;
return false;
} else if (AS == AMDGPUAS::FLAT_ADDRESS ||
AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
// For an unknown address space, this usually means that this is for some
// reason being used for pure arithmetic, and not based on some addressing
// computation. We don't have instructions that compute pointers with any
// addressing modes, so treat them as having no offset like flat
// instructions.
return isLegalFlatAddressingMode(AM);
} else {
llvm_unreachable("unhandled address space");
}
}
bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
const SelectionDAG &DAG) const {
if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
return (MemVT.getSizeInBits() <= 4 * 32);
} else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
return (MemVT.getSizeInBits() <= MaxPrivateBits);
} else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
return (MemVT.getSizeInBits() <= 2 * 32);
}
return true;
}
bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
unsigned Size, unsigned AddrSpace, unsigned Align,
MachineMemOperand::Flags Flags, bool *IsFast) const {
if (IsFast)
*IsFast = false;
if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
AddrSpace == AMDGPUAS::REGION_ADDRESS) {
// ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
// aligned, 8 byte access in a single operation using ds_read2/write2_b32
// with adjacent offsets.
bool AlignedBy4 = (Align % 4 == 0);
if (IsFast)
*IsFast = AlignedBy4;
return AlignedBy4;
}
// FIXME: We have to be conservative here and assume that flat operations
// will access scratch. If we had access to the IR function, then we
// could determine if any private memory was used in the function.
if (!Subtarget->hasUnalignedScratchAccess() &&
(AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
bool AlignedBy4 = Align >= 4;
if (IsFast)
*IsFast = AlignedBy4;
return AlignedBy4;
}
if (Subtarget->hasUnalignedBufferAccess()) {
// If we have an uniform constant load, it still requires using a slow
// buffer instruction if unaligned.
if (IsFast) {
*IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
(Align % 4 == 0) : true;
}
return true;
}
// Smaller than dword value must be aligned.
if (Size < 32)
return false;
// 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
// byte-address are ignored, thus forcing Dword alignment.
// This applies to private, global, and constant memory.
if (IsFast)
*IsFast = true;
return Size >= 32 && Align >= 4;
}
bool SITargetLowering::allowsMisalignedMemoryAccesses(
EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
bool *IsFast) const {
if (IsFast)
*IsFast = false;
// TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
// which isn't a simple VT.
// Until MVT is extended to handle this, simply check for the size and
// rely on the condition below: allow accesses if the size is a multiple of 4.
if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
VT.getStoreSize() > 16)) {
return false;
}
return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
Align, Flags, IsFast);
}
EVT SITargetLowering::getOptimalMemOpType(
uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
bool ZeroMemset, bool MemcpyStrSrc,
const AttributeList &FuncAttributes) const {
// FIXME: Should account for address space here.
// The default fallback uses the private pointer size as a guess for a type to
// use. Make sure we switch these to 64-bit accesses.
if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
return MVT::v4i32;
if (Size >= 8 && DstAlign >= 4)
return MVT::v2i32;
// Use the default.
return MVT::Other;
}
static bool isFlatGlobalAddrSpace(unsigned AS) {
return AS == AMDGPUAS::GLOBAL_ADDRESS ||
AS == AMDGPUAS::FLAT_ADDRESS ||
AS == AMDGPUAS::CONSTANT_ADDRESS ||
AS > AMDGPUAS::MAX_AMDGPU_ADDRESS;
}
bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
unsigned DestAS) const {
return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
}
bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
const MemSDNode *MemNode = cast<MemSDNode>(N);
const Value *Ptr = MemNode->getMemOperand()->getValue();
const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
return I && I->getMetadata("amdgpu.noclobber");
}
bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
unsigned DestAS) const {
// Flat -> private/local is a simple truncate.
// Flat -> global is no-op
if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
return true;
return isNoopAddrSpaceCast(SrcAS, DestAS);
}
bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
const MemSDNode *MemNode = cast<MemSDNode>(N);
return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
}
TargetLoweringBase::LegalizeTypeAction
SITargetLowering::getPreferredVectorAction(MVT VT) const {
int NumElts = VT.getVectorNumElements();
if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
return TargetLoweringBase::getPreferredVectorAction(VT);
}
bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
Type *Ty) const {
// FIXME: Could be smarter if called for vector constants.
return true;
}
bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
if (Subtarget->has16BitInsts() && VT == MVT::i16) {
switch (Op) {
case ISD::LOAD:
case ISD::STORE:
// These operations are done with 32-bit instructions anyway.
case ISD::AND:
case ISD::OR:
case ISD::XOR:
case ISD::SELECT:
// TODO: Extensions?
return true;
default:
return false;
}
}
// SimplifySetCC uses this function to determine whether or not it should
// create setcc with i1 operands. We don't have instructions for i1 setcc.
if (VT == MVT::i1 && Op == ISD::SETCC)
return false;
return TargetLowering::isTypeDesirableForOp(Op, VT);
}
SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
const SDLoc &SL,
SDValue Chain,
uint64_t Offset) const {
const DataLayout &DL = DAG.getDataLayout();
MachineFunction &MF = DAG.getMachineFunction();
const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
const ArgDescriptor *InputPtrReg;
const TargetRegisterClass *RC;
std::tie(InputPtrReg, RC)
= Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
}
SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
const SDLoc &SL) const {
uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
FIRST_IMPLICIT);
return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
}
SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
const SDLoc &SL, SDValue Val,
bool Signed,
const ISD::InputArg *Arg) const {
// First, if it is a widened vector, narrow it.
if (VT.isVector() &&
VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
EVT NarrowedVT =
EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
VT.getVectorNumElements());
Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
DAG.getConstant(0, SL, MVT::i32));
}
// Then convert the vector elements or scalar value.
if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
VT.bitsLT(MemVT)) {
unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
}
if (MemVT.isFloatingPoint())
Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
else if (Signed)
Val = DAG.getSExtOrTrunc(Val, SL, VT);
else
Val = DAG.getZExtOrTrunc(Val, SL, VT);
return Val;
}
SDValue SITargetLowering::lowerKernargMemParameter(
SelectionDAG &DAG, EVT VT, EVT MemVT,
const SDLoc &SL, SDValue Chain,
uint64_t Offset, unsigned Align, bool Signed,
const ISD::InputArg *Arg) const {
Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
// Try to avoid using an extload by loading earlier than the argument address,
// and extracting the relevant bits. The load should hopefully be merged with
// the previous argument.
if (MemVT.getStoreSize() < 4 && Align < 4) {
// TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
int64_t AlignDownOffset = alignDown(Offset, 4);
int64_t OffsetDiff = Offset - AlignDownOffset;
EVT IntVT = MemVT.changeTypeToInteger();
// TODO: If we passed in the base kernel offset we could have a better
// alignment than 4, but we don't really need it.
SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
MachineMemOperand::MODereferenceable |
MachineMemOperand::MOInvariant);
SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
}
SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
MachineMemOperand::MODereferenceable |
MachineMemOperand::MOInvariant);
SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
}
SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
const SDLoc &SL, SDValue Chain,
const ISD::InputArg &Arg) const {
MachineFunction &MF = DAG.getMachineFunction();
MachineFrameInfo &MFI = MF.getFrameInfo();
if (Arg.Flags.isByVal()) {
unsigned Size = Arg.Flags.getByValSize();
int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
return DAG.getFrameIndex(FrameIdx, MVT::i32);
}
unsigned ArgOffset = VA.getLocMemOffset();
unsigned ArgSize = VA.getValVT().getStoreSize();
int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
// Create load nodes to retrieve arguments from the stack.
SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
SDValue ArgValue;
// For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
MVT MemVT = VA.getValVT();
switch (VA.getLocInfo()) {
default:
break;
case CCValAssign::BCvt:
MemVT = VA.getLocVT();
break;
case CCValAssign::SExt:
ExtType = ISD::SEXTLOAD;
break;
case CCValAssign::ZExt:
ExtType = ISD::ZEXTLOAD;
break;
case CCValAssign::AExt:
ExtType = ISD::EXTLOAD;
break;
}
ArgValue = DAG.getExtLoad(
ExtType, SL, VA.getLocVT(), Chain, FIN,
MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
MemVT);
return ArgValue;
}
SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
const SIMachineFunctionInfo &MFI,
EVT VT,
AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
const ArgDescriptor *Reg;
const TargetRegisterClass *RC;
std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
}
static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
CallingConv::ID CallConv,
ArrayRef<ISD::InputArg> Ins,
BitVector &Skipped,
FunctionType *FType,
SIMachineFunctionInfo *Info) {
for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
const ISD::InputArg *Arg = &Ins[I];
assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
"vector type argument should have been split");
// First check if it's a PS input addr.
if (CallConv == CallingConv::AMDGPU_PS &&
!Arg->Flags.isInReg() && PSInputNum <= 15) {
bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
// Inconveniently only the first part of the split is marked as isSplit,
// so skip to the end. We only want to increment PSInputNum once for the
// entire split argument.
if (Arg->Flags.isSplit()) {
while (!Arg->Flags.isSplitEnd()) {
assert((!Arg->VT.isVector() ||
Arg->VT.getScalarSizeInBits() == 16) &&
"unexpected vector split in ps argument type");
if (!SkipArg)
Splits.push_back(*Arg);
Arg = &Ins[++I];
}
}
if (SkipArg) {
// We can safely skip PS inputs.
Skipped.set(Arg->getOrigArgIndex());
++PSInputNum;
continue;
}
Info->markPSInputAllocated(PSInputNum);
if (Arg->Used)
Info->markPSInputEnabled(PSInputNum);
++PSInputNum;
}
Splits.push_back(*Arg);
}
}
// Allocate special inputs passed in VGPRs.
void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
MachineFunction &MF,
const SIRegisterInfo &TRI,
SIMachineFunctionInfo &Info) const {
const LLT S32 = LLT::scalar(32);
MachineRegisterInfo &MRI = MF.getRegInfo();
if (Info.hasWorkItemIDX()) {
Register Reg = AMDGPU::VGPR0;
MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
CCInfo.AllocateReg(Reg);
Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
}
if (Info.hasWorkItemIDY()) {
Register Reg = AMDGPU::VGPR1;
MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
CCInfo.AllocateReg(Reg);
Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
}
if (Info.hasWorkItemIDZ()) {
Register Reg = AMDGPU::VGPR2;
MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
CCInfo.AllocateReg(Reg);
Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
}
}
// Try to allocate a VGPR at the end of the argument list, or if no argument
// VGPRs are left allocating a stack slot.
// If \p Mask is is given it indicates bitfield position in the register.
// If \p Arg is given use it with new ]p Mask instead of allocating new.
static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
ArgDescriptor Arg = ArgDescriptor()) {
if (Arg.isSet())
return ArgDescriptor::createArg(Arg, Mask);
ArrayRef<MCPhysReg> ArgVGPRs
= makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
if (RegIdx == ArgVGPRs.size()) {
// Spill to stack required.
int64_t Offset = CCInfo.AllocateStack(4, 4);
return ArgDescriptor::createStack(Offset, Mask);
}
unsigned Reg = ArgVGPRs[RegIdx];
Reg = CCInfo.AllocateReg(Reg);
assert(Reg != AMDGPU::NoRegister);
MachineFunction &MF = CCInfo.getMachineFunction();
Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
return ArgDescriptor::createRegister(Reg, Mask);
}
static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
const TargetRegisterClass *RC,
unsigned NumArgRegs) {
ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
if (RegIdx == ArgSGPRs.size())
report_fatal_error("ran out of SGPRs for arguments");
unsigned Reg = ArgSGPRs[RegIdx];
Reg = CCInfo.AllocateReg(Reg);
assert(Reg != AMDGPU::NoRegister);
MachineFunction &MF = CCInfo.getMachineFunction();
MF.addLiveIn(Reg, RC);
return ArgDescriptor::createRegister(Reg);
}
static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
}
static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
}
void SITargetLowering::allocateSpecialInputVGPRs(CCState &CCInfo,
MachineFunction &MF,
const SIRegisterInfo &TRI,
SIMachineFunctionInfo &Info) const {
const unsigned Mask = 0x3ff;
ArgDescriptor Arg;
if (Info.hasWorkItemIDX()) {
Arg = allocateVGPR32Input(CCInfo, Mask);
Info.setWorkItemIDX(Arg);
}
if (Info.hasWorkItemIDY()) {
Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
Info.setWorkItemIDY(Arg);
}
if (Info.hasWorkItemIDZ())
Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
}
void SITargetLowering::allocateSpecialInputSGPRs(
CCState &CCInfo,
MachineFunction &MF,
const SIRegisterInfo &TRI,
SIMachineFunctionInfo &Info) const {
auto &ArgInfo = Info.getArgInfo();
// TODO: Unify handling with private memory pointers.
if (Info.hasDispatchPtr())
ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
if (Info.hasQueuePtr())
ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
if (Info.hasKernargSegmentPtr())
ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
if (Info.hasDispatchID())
ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
// flat_scratch_init is not applicable for non-kernel functions.
if (Info.hasWorkGroupIDX())
ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
if (Info.hasWorkGroupIDY())
ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
if (Info.hasWorkGroupIDZ())
ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
if (Info.hasImplicitArgPtr())
ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
}
// Allocate special inputs passed in user SGPRs.
void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
MachineFunction &MF,
const SIRegisterInfo &TRI,
SIMachineFunctionInfo &Info) const {
if (Info.hasImplicitBufferPtr()) {
unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
CCInfo.AllocateReg(ImplicitBufferPtrReg);
}
// FIXME: How should these inputs interact with inreg / custom SGPR inputs?
if (Info.hasPrivateSegmentBuffer()) {
unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
CCInfo.AllocateReg(PrivateSegmentBufferReg);
}
if (Info.hasDispatchPtr()) {
unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
CCInfo.AllocateReg(DispatchPtrReg);
}
if (Info.hasQueuePtr()) {
unsigned QueuePtrReg = Info.addQueuePtr(TRI);
MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
CCInfo.AllocateReg(QueuePtrReg);
}
if (Info.hasKernargSegmentPtr()) {
MachineRegisterInfo &MRI = MF.getRegInfo();
Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
CCInfo.AllocateReg(InputPtrReg);
Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
}
if (Info.hasDispatchID()) {
unsigned DispatchIDReg = Info.addDispatchID(TRI);
MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
CCInfo.AllocateReg(DispatchIDReg);
}
if (Info.hasFlatScratchInit()) {
unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
CCInfo.AllocateReg(FlatScratchInitReg);
}
// TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
// these from the dispatch pointer.
}
// Allocate special input registers that are initialized per-wave.
void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
MachineFunction &MF,
SIMachineFunctionInfo &Info,
CallingConv::ID CallConv,
bool IsShader) const {
if (Info.hasWorkGroupIDX()) {
unsigned Reg = Info.addWorkGroupIDX();
MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
CCInfo.AllocateReg(Reg);
}
if (Info.hasWorkGroupIDY()) {
unsigned Reg = Info.addWorkGroupIDY();
MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
CCInfo.AllocateReg(Reg);
}
if (Info.hasWorkGroupIDZ()) {
unsigned Reg = Info.addWorkGroupIDZ();
MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
CCInfo.AllocateReg(Reg);
}
if (Info.hasWorkGroupInfo()) {
unsigned Reg = Info.addWorkGroupInfo();
MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
CCInfo.AllocateReg(Reg);
}
if (Info.hasPrivateSegmentWaveByteOffset()) {
// Scratch wave offset passed in system SGPR.
unsigned PrivateSegmentWaveByteOffsetReg;
if (IsShader) {
PrivateSegmentWaveByteOffsetReg =
Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
// This is true if the scratch wave byte offset doesn't have a fixed
// location.
if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
}
} else
PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
}
}
static void reservePrivateMemoryRegs(const TargetMachine &TM,
MachineFunction &MF,
const SIRegisterInfo &TRI,
SIMachineFunctionInfo &Info) {
// Now that we've figured out where the scratch register inputs are, see if
// should reserve the arguments and use them directly.
MachineFrameInfo &MFI = MF.getFrameInfo();
bool HasStackObjects = MFI.hasStackObjects();
const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
// Record that we know we have non-spill stack objects so we don't need to
// check all stack objects later.
if (HasStackObjects)
Info.setHasNonSpillStackObjects(true);
// Everything live out of a block is spilled with fast regalloc, so it's
// almost certain that spilling will be required.
if (TM.getOptLevel() == CodeGenOpt::None)
HasStackObjects = true;
// For now assume stack access is needed in any callee functions, so we need
// the scratch registers to pass in.
bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
// If we have stack objects, we unquestionably need the private buffer
// resource. For the Code Object V2 ABI, this will be the first 4 user
// SGPR inputs. We can reserve those and use them directly.
Register PrivateSegmentBufferReg =
Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
Info.setScratchRSrcReg(PrivateSegmentBufferReg);
} else {
unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
// We tentatively reserve the last registers (skipping the last registers
// which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
// we'll replace these with the ones immediately after those which were
// really allocated. In the prologue copies will be inserted from the
// argument to these reserved registers.
// Without HSA, relocations are used for the scratch pointer and the
// buffer resource setup is always inserted in the prologue. Scratch wave
// offset is still in an input SGPR.
Info.setScratchRSrcReg(ReservedBufferReg);
}
// hasFP should be accurate for kernels even before the frame is finalized.
if (ST.getFrameLowering()->hasFP(MF)) {
MachineRegisterInfo &MRI = MF.getRegInfo();
// Try to use s32 as the SP, but move it if it would interfere with input
// arguments. This won't work with calls though.
//
// FIXME: Move SP to avoid any possible inputs, or find a way to spill input
// registers.
if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
} else {
assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
if (MFI.hasCalls())
report_fatal_error("call in graphics shader with too many input SGPRs");
for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
if (!MRI.isLiveIn(Reg)) {
Info.setStackPtrOffsetReg(Reg);
break;
}
}
if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
report_fatal_error("failed to find register for SP");
}
if (MFI.hasCalls()) {
Info.setScratchWaveOffsetReg(AMDGPU::SGPR33);
Info.setFrameOffsetReg(AMDGPU::SGPR33);
} else {
unsigned ReservedOffsetReg =
TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
Info.setScratchWaveOffsetReg(ReservedOffsetReg);
Info.setFrameOffsetReg(ReservedOffsetReg);
}
} else if (RequiresStackAccess) {
assert(!MFI.hasCalls());
// We know there are accesses and they will be done relative to SP, so just
// pin it to the input.
//
// FIXME: Should not do this if inline asm is reading/writing these
// registers.
Register PreloadedSP = Info.getPreloadedReg(
AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
Info.setStackPtrOffsetReg(PreloadedSP);
Info.setScratchWaveOffsetReg(PreloadedSP);
Info.setFrameOffsetReg(PreloadedSP);
} else {
assert(!MFI.hasCalls());
// There may not be stack access at all. There may still be spills, or
// access of a constant pointer (in which cases an extra copy will be
// emitted in the prolog).
unsigned ReservedOffsetReg
= TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
Info.setStackPtrOffsetReg(ReservedOffsetReg);
Info.setScratchWaveOffsetReg(ReservedOffsetReg);
Info.setFrameOffsetReg(ReservedOffsetReg);
}
}
bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
return !Info->isEntryFunction();
}
void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
}
void SITargetLowering::insertCopiesSplitCSR(
MachineBasicBlock *Entry,
const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
if (!IStart)
return;
const TargetInstrInfo *TII = Subtarget->getInstrInfo();
MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
MachineBasicBlock::iterator MBBI = Entry->begin();
for (const MCPhysReg *I = IStart; *I; ++I) {
const TargetRegisterClass *RC = nullptr;
if (AMDGPU::SReg_64RegClass.contains(*I))
RC = &AMDGPU::SGPR_64RegClass;
else if (AMDGPU::SReg_32RegClass.contains(*I))
RC = &AMDGPU::SGPR_32RegClass;
else
llvm_unreachable("Unexpected register class in CSRsViaCopy!");
Register NewVR = MRI->createVirtualRegister(RC);
// Create copy from CSR to a virtual register.
Entry->addLiveIn(*I);
BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
.addReg(*I);
// Insert the copy-back instructions right before the terminator.
for (auto *Exit : Exits)
BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
TII->get(TargetOpcode::COPY), *I)
.addReg(NewVR);
}
}
SDValue SITargetLowering::LowerFormalArguments(
SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
MachineFunction &MF = DAG.getMachineFunction();
const Function &Fn = MF.getFunction();
FunctionType *FType = MF.getFunction().getFunctionType();
SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
DiagnosticInfoUnsupported NoGraphicsHSA(
Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
DAG.getContext()->diagnose(NoGraphicsHSA);
return DAG.getEntryNode();
}
SmallVector<ISD::InputArg, 16> Splits;
SmallVector<CCValAssign, 16> ArgLocs;
BitVector Skipped(Ins.size());
CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
*DAG.getContext());
bool IsShader = AMDGPU::isShader(CallConv);
bool IsKernel = AMDGPU::isKernel(CallConv);
bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
if (IsShader) {
processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
// At least one interpolation mode must be enabled or else the GPU will
// hang.
//
// Check PSInputAddr instead of PSInputEnable. The idea is that if the user
// set PSInputAddr, the user wants to enable some bits after the compilation
// based on run-time states. Since we can't know what the final PSInputEna
// will look like, so we shouldn't do anything here and the user should take
// responsibility for the correct programming.
//
// Otherwise, the following restrictions apply:
// - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
// - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
// enabled too.
if (CallConv == CallingConv::AMDGPU_PS) {
if ((Info->getPSInputAddr() & 0x7F) == 0 ||
((Info->getPSInputAddr() & 0xF) == 0 &&
Info->isPSInputAllocated(11))) {
CCInfo.AllocateReg(AMDGPU::VGPR0);
CCInfo.AllocateReg(AMDGPU::VGPR1);
Info->markPSInputAllocated(0);
Info->markPSInputEnabled(0);
}
if (Subtarget->isAmdPalOS()) {
// For isAmdPalOS, the user does not enable some bits after compilation
// based on run-time states; the register values being generated here are
// the final ones set in hardware. Therefore we need to apply the
// workaround to PSInputAddr and PSInputEnable together. (The case where
// a bit is set in PSInputAddr but not PSInputEnable is where the
// frontend set up an input arg for a particular interpolation mode, but
// nothing uses that input arg. Really we should have an earlier pass
// that removes such an arg.)
unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
if ((PsInputBits & 0x7F) == 0 ||
((PsInputBits & 0xF) == 0 &&
(PsInputBits >> 11 & 1)))
Info->markPSInputEnabled(
countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
}
}
assert(!Info->hasDispatchPtr() &&
!Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
!Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
!Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
!Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
!Info->hasWorkItemIDZ());
} else if (IsKernel) {
assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
} else {
Splits.append(Ins.begin(), Ins.end());
}
if (IsEntryFunc) {
allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
}
if (IsKernel) {
analyzeFormalArgumentsCompute(CCInfo, Ins);
} else {
CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
}
SmallVector<SDValue, 16> Chains;
// FIXME: This is the minimum kernel argument alignment. We should improve
// this to the maximum alignment of the arguments.
//
// FIXME: Alignment of explicit arguments totally broken with non-0 explicit
// kern arg offset.
const unsigned KernelArgBaseAlign = 16;
for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
const ISD::InputArg &Arg = Ins[i];
if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
InVals.push_back(DAG.getUNDEF(Arg.VT));
continue;
}
CCValAssign &VA = ArgLocs[ArgIdx++];
MVT VT = VA.getLocVT();
if (IsEntryFunc && VA.isMemLoc()) {
VT = Ins[i].VT;
EVT MemVT = VA.getLocVT();
const uint64_t Offset = VA.getLocMemOffset();
unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
SDValue Arg = lowerKernargMemParameter(
DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
Chains.push_back(Arg.getValue(1));
auto *ParamTy =
dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
// On SI local pointers are just offsets into LDS, so they are always
// less than 16-bits. On CI and newer they could potentially be
// real pointers, so we can't guarantee their size.
Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
DAG.getValueType(MVT::i16));
}
InVals.push_back(Arg);
continue;
} else if (!IsEntryFunc && VA.isMemLoc()) {
SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
InVals.push_back(Val);
if (!Arg.Flags.isByVal())
Chains.push_back(Val.getValue(1));
continue;
}
assert(VA.isRegLoc() && "Parameter must be in a register!");
Register Reg = VA.getLocReg();
const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
EVT ValVT = VA.getValVT();
Reg = MF.addLiveIn(Reg, RC);
SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
if (Arg.Flags.isSRet()) {
// The return object should be reasonably addressable.
// FIXME: This helps when the return is a real sret. If it is a
// automatically inserted sret (i.e. CanLowerReturn returns false), an
// extra copy is inserted in SelectionDAGBuilder which obscures this.
unsigned NumBits
= 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
}
// If this is an 8 or 16-bit value, it is really passed promoted
// to 32 bits. Insert an assert[sz]ext to capture this, then
// truncate to the right size.
switch (VA.getLocInfo()) {
case CCValAssign::Full:
break;
case CCValAssign::BCvt:
Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
break;
case CCValAssign::SExt:
Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
DAG.getValueType(ValVT));
Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
break;
case CCValAssign::ZExt:
Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
DAG.getValueType(ValVT));
Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
break;
case CCValAssign::AExt:
Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
break;
default:
llvm_unreachable("Unknown loc info!");
}
InVals.push_back(Val);
}
if (!IsEntryFunc) {
// Special inputs come after user arguments.
allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
}
// Start adding system SGPRs.
if (IsEntryFunc) {
allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
} else {
CCInfo.AllocateReg(Info->getScratchRSrcReg());
CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
CCInfo.AllocateReg(Info->getFrameOffsetReg());
allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
}
auto &ArgUsageInfo =
DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
unsigned StackArgSize = CCInfo.getNextStackOffset();
Info->setBytesInStackArgArea(StackArgSize);
return Chains.empty() ? Chain :
DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
}
// TODO: If return values can't fit in registers, we should return as many as
// possible in registers before passing on stack.
bool SITargetLowering::CanLowerReturn(
CallingConv::ID CallConv,
MachineFunction &MF, bool IsVarArg,
const SmallVectorImpl<ISD::OutputArg> &Outs,
LLVMContext &Context) const {
// Replacing returns with sret/stack usage doesn't make sense for shaders.
// FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
// for shaders. Vector types should be explicitly handled by CC.
if (AMDGPU::isEntryFunctionCC(CallConv))
return true;
SmallVector<CCValAssign, 16> RVLocs;
CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
}
SDValue
SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
bool isVarArg,
const SmallVectorImpl<ISD::OutputArg> &Outs,
const SmallVectorImpl<SDValue> &OutVals,
const SDLoc &DL, SelectionDAG &DAG) const {
MachineFunction &MF = DAG.getMachineFunction();
SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
if (AMDGPU::isKernel(CallConv)) {
return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
OutVals, DL, DAG);
}
bool IsShader = AMDGPU::isShader(CallConv);
Info->setIfReturnsVoid(Outs.empty());
bool IsWaveEnd = Info->returnsVoid() && IsShader;
// CCValAssign - represent the assignment of the return value to a location.
SmallVector<CCValAssign, 48> RVLocs;
SmallVector<ISD::OutputArg, 48> Splits;
// CCState - Info about the registers and stack slots.
CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
*DAG.getContext());
// Analyze outgoing return values.
CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
SDValue Flag;
SmallVector<SDValue, 48> RetOps;
RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
// Add return address for callable functions.
if (!Info->isEntryFunction()) {
const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
SDValue ReturnAddrReg = CreateLiveInRegister(
DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
SDValue ReturnAddrVirtualReg = DAG.getRegister(
MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
MVT::i64);
Chain =
DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
Flag = Chain.getValue(1);
RetOps.push_back(ReturnAddrVirtualReg);
}
// Copy the result values into the output registers.
for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
++I, ++RealRVLocIdx) {
CCValAssign &VA = RVLocs[I];
assert(VA.isRegLoc() && "Can only return in registers!");
// TODO: Partially return in registers if return values don't fit.
SDValue Arg = OutVals[RealRVLocIdx];
// Copied from other backends.
switch (VA.getLocInfo()) {
case CCValAssign::Full:
break;
case CCValAssign::BCvt:
Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
break;
case CCValAssign::SExt:
Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
break;
case CCValAssign::ZExt:
Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
break;
case CCValAssign::AExt:
Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
break;
default:
llvm_unreachable("Unknown loc info!");
}
Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
Flag = Chain.getValue(1);
RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
}
// FIXME: Does sret work properly?
if (!Info->isEntryFunction()) {
const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
const MCPhysReg *I =
TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
if (I) {
for (; *I; ++I) {
if (AMDGPU::SReg_64RegClass.contains(*I))
RetOps.push_back(DAG.getRegister(*I, MVT::i64));
else if (AMDGPU::SReg_32RegClass.contains(*I))
RetOps.push_back(DAG.getRegister(*I, MVT::i32));
else
llvm_unreachable("Unexpected register class in CSRsViaCopy!");
}
}
}
// Update chain and glue.
RetOps[0] = Chain;
if (Flag.getNode())
RetOps.push_back(Flag);
unsigned Opc = AMDGPUISD::ENDPGM;
if (!IsWaveEnd)
Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
return DAG.getNode(Opc, DL, MVT::Other, RetOps);
}
SDValue SITargetLowering::LowerCallResult(
SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
SDValue ThisVal) const {
CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
// Assign locations to each value returned by this call.
SmallVector<CCValAssign, 16> RVLocs;
CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
*DAG.getContext());
CCInfo.AnalyzeCallResult(Ins, RetCC);
// Copy all of the result registers out of their specified physreg.
for (unsigned i = 0; i != RVLocs.size(); ++i) {
CCValAssign VA = RVLocs[i];
SDValue Val;
if (VA.isRegLoc()) {
Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
Chain = Val.getValue(1);
InFlag = Val.getValue(2);
} else if (VA.isMemLoc()) {
report_fatal_error("TODO: return values in memory");
} else
llvm_unreachable("unknown argument location type");
switch (VA.getLocInfo()) {
case CCValAssign::Full:
break;
case CCValAssign::BCvt:
Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
break;
case CCValAssign::ZExt:
Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
DAG.getValueType(VA.getValVT()));
Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
break;
case CCValAssign::SExt:
Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
DAG.getValueType(VA.getValVT()));
Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
break;
case CCValAssign::AExt:
Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
break;
default:
llvm_unreachable("Unknown loc info!");
}
InVals.push_back(Val);
}
return Chain;
}
// Add code to pass special inputs required depending on used features separate
// from the explicit user arguments present in the IR.
void SITargetLowering::passSpecialInputs(
CallLoweringInfo &CLI,
CCState &CCInfo,
const SIMachineFunctionInfo &Info,
SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
SmallVectorImpl<SDValue> &MemOpChains,
SDValue Chain) const {
// If we don't have a call site, this was a call inserted by
// legalization. These can never use special inputs.
if (!CLI.CS)
return;
const Function *CalleeFunc = CLI.CS.getCalledFunction();
assert(CalleeFunc);
SelectionDAG &DAG = CLI.DAG;
const SDLoc &DL = CLI.DL;
const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
auto &ArgUsageInfo =
DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
const AMDGPUFunctionArgInfo &CalleeArgInfo
= ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
// TODO: Unify with private memory register handling. This is complicated by
// the fact that at least in kernels, the input argument is not necessarily
// in the same location as the input.
AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
AMDGPUFunctionArgInfo::DISPATCH_PTR,
AMDGPUFunctionArgInfo::QUEUE_PTR,
AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
AMDGPUFunctionArgInfo::DISPATCH_ID,
AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
};
for (auto InputID : InputRegs) {
const ArgDescriptor *OutgoingArg;
const TargetRegisterClass *ArgRC;
std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
if (!OutgoingArg)
continue;
const ArgDescriptor *IncomingArg;
const TargetRegisterClass *IncomingArgRC;
std::tie(IncomingArg, IncomingArgRC)
= CallerArgInfo.getPreloadedValue(InputID);
assert(IncomingArgRC == ArgRC);
// All special arguments are ints for now.
EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
SDValue InputReg;
if (IncomingArg) {
InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
} else {
// The implicit arg ptr is special because it doesn't have a corresponding
// input for kernels, and is computed from the kernarg segment pointer.
assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
InputReg = getImplicitArgPtr(DAG, DL);
}
if (OutgoingArg->isRegister()) {
RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
} else {
unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
SpecialArgOffset);
MemOpChains.push_back(ArgStore);
}
}
// Pack workitem IDs into a single register or pass it as is if already
// packed.
const ArgDescriptor *OutgoingArg;
const TargetRegisterClass *ArgRC;
std::tie(OutgoingArg, ArgRC) =
CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
if (!OutgoingArg)
std::tie(OutgoingArg, ArgRC) =
CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
if (!OutgoingArg)
std::tie(OutgoingArg, ArgRC) =
CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
if (!OutgoingArg)
return;
const ArgDescriptor *IncomingArgX
= CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
const ArgDescriptor *IncomingArgY
= CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
const ArgDescriptor *IncomingArgZ
= CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
SDValue InputReg;
SDLoc SL;
// If incoming ids are not packed we need to pack them.
if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX)
InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) {
SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
DAG.getShiftAmountConstant(10, MVT::i32, SL));
InputReg = InputReg.getNode() ?
DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
}
if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) {
SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
DAG.getShiftAmountConstant(20, MVT::i32, SL));
InputReg = InputReg.getNode() ?
DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
}
if (!InputReg.getNode()) {
// Workitem ids are already packed, any of present incoming arguments
// will carry all required fields.
ArgDescriptor IncomingArg = ArgDescriptor::createArg(
IncomingArgX ? *IncomingArgX :
IncomingArgY ? *IncomingArgY :
*IncomingArgZ, ~0u);
InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
}
if (OutgoingArg->isRegister()) {
RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
} else {
unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
SpecialArgOffset);
MemOpChains.push_back(ArgStore);
}
}
static bool canGuaranteeTCO(CallingConv::ID CC) {
return CC == CallingConv::Fast;
}
/// Return true if we might ever do TCO for calls with this calling convention.
static bool mayTailCallThisCC(CallingConv::ID CC) {
switch (CC) {
case CallingConv::C:
return true;
default:
return canGuaranteeTCO(CC);
}
}
bool SITargetLowering::isEligibleForTailCallOptimization(
SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
const SmallVectorImpl<ISD::OutputArg> &Outs,
const SmallVectorImpl<SDValue> &OutVals,
const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
if (!mayTailCallThisCC(CalleeCC))
return false;
MachineFunction &MF = DAG.getMachineFunction();
const Function &CallerF = MF.getFunction();
CallingConv::ID CallerCC = CallerF.getCallingConv();
const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
// Kernels aren't callable, and don't have a live in return address so it
// doesn't make sense to do a tail call with entry functions.
if (!CallerPreserved)
return false;
bool CCMatch = CallerCC == CalleeCC;
if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
if (canGuaranteeTCO(CalleeCC) && CCMatch)
return true;
return false;
}
// TODO: Can we handle var args?
if (IsVarArg)
return false;
for (const Argument &Arg : CallerF.args()) {
if (Arg.hasByValAttr())
return false;
}
LLVMContext &Ctx = *DAG.getContext();
// Check that the call results are passed in the same way.
if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
CCAssignFnForCall(CalleeCC, IsVarArg),
CCAssignFnForCall(CallerCC, IsVarArg)))
return false;
// The callee has to preserve all registers the caller needs to preserve.
if (!CCMatch) {
const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
return false;
}
// Nothing more to check if the callee is taking no arguments.
if (Outs.empty())
return true;
SmallVector<CCValAssign, 16> ArgLocs;
CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
// If the stack arguments for this call do not fit into our own save area then
// the call cannot be made tail.
// TODO: Is this really necessary?
if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
return false;
const MachineRegisterInfo &MRI = MF.getRegInfo();
return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
}
bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
if (!CI->isTailCall())
return false;
const Function *ParentFn = CI->getParent()->getParent();
if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
return false;
auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
return (Attr.getValueAsString() != "true");
}
// The wave scratch offset register is used as the global base pointer.
SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
SmallVectorImpl<SDValue> &InVals) const {
SelectionDAG &DAG = CLI.DAG;
const SDLoc &DL = CLI.DL;
SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
SDValue Chain = CLI.Chain;
SDValue Callee = CLI.Callee;
bool &IsTailCall = CLI.IsTailCall;
CallingConv::ID CallConv = CLI.CallConv;
bool IsVarArg = CLI.IsVarArg;
bool IsSibCall = false;
bool IsThisReturn = false;
MachineFunction &MF = DAG.getMachineFunction();
if (IsVarArg) {
return lowerUnhandledCall(CLI, InVals,
"unsupported call to variadic function ");
}
if (!CLI.CS.getInstruction())
report_fatal_error("unsupported libcall legalization");
if (!CLI.CS.getCalledFunction()) {
return lowerUnhandledCall(CLI, InVals,
"unsupported indirect call to function ");
}
if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
return lowerUnhandledCall(CLI, InVals,
"unsupported required tail call to function ");
}
if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
// Note the issue is with the CC of the calling function, not of the call
// itself.
return lowerUnhandledCall(CLI, InVals,
"unsupported call from graphics shader of function ");
}
if (IsTailCall) {
IsTailCall = isEligibleForTailCallOptimization(
Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
report_fatal_error("failed to perform tail call elimination on a call "
"site marked musttail");
}
bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
// A sibling call is one where we're under the usual C ABI and not planning
// to change that but can still do a tail call:
if (!TailCallOpt && IsTailCall)
IsSibCall = true;
if (IsTailCall)
++NumTailCalls;
}
const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
// Analyze operands of the call, assigning locations to each operand.
SmallVector<CCValAssign, 16> ArgLocs;
CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
CCInfo.AnalyzeCallOperands(Outs, AssignFn);
// Get a count of how many bytes are to be pushed on the stack.
unsigned NumBytes = CCInfo.getNextStackOffset();
if (IsSibCall) {
// Since we're not changing the ABI to make this a tail call, the memory
// operands are already available in the caller's incoming argument space.
NumBytes = 0;
}
// FPDiff is the byte offset of the call's argument area from the callee's.
// Stores to callee stack arguments will be placed in FixedStackSlots offset
// by this amount for a tail call. In a sibling call it must be 0 because the
// caller will deallocate the entire stack and the callee still expects its
// arguments to begin at SP+0. Completely unused for non-tail calls.
int32_t FPDiff = 0;
MachineFrameInfo &MFI = MF.getFrameInfo();
SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
// Adjust the stack pointer for the new arguments...
// These operations are automatically eliminated by the prolog/epilog pass
if (!IsSibCall) {
Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
SmallVector<SDValue, 4> CopyFromChains;
// In the HSA case, this should be an identity copy.
SDValue ScratchRSrcReg
= DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
Chain = DAG.getTokenFactor(DL, CopyFromChains);
}
SmallVector<SDValue, 8> MemOpChains;
MVT PtrVT = MVT::i32;
// Walk the register/memloc assignments, inserting copies/loads.
for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
++i, ++realArgIdx) {
CCValAssign &VA = ArgLocs[i];
SDValue Arg = OutVals[realArgIdx];
// Promote the value if needed.
switch (VA.getLocInfo()) {
case CCValAssign::Full:
break;
case CCValAssign::BCvt:
Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
break;
case CCValAssign::ZExt:
Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
break;
case CCValAssign::SExt:
Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
break;
case CCValAssign::AExt:
Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
break;
case CCValAssign::FPExt:
Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
break;
default:
llvm_unreachable("Unknown loc info!");
}
if (VA.isRegLoc()) {
RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
} else {
assert(VA.isMemLoc());
SDValue DstAddr;
MachinePointerInfo DstInfo;
unsigned LocMemOffset = VA.getLocMemOffset();
int32_t Offset = LocMemOffset;
SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
unsigned Align = 0;
if (IsTailCall) {
ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
unsigned OpSize = Flags.isByVal() ?
Flags.getByValSize() : VA.getValVT().getStoreSize();
// FIXME: We can have better than the minimum byval required alignment.
Align = Flags.isByVal() ? Flags.getByValAlign() :
MinAlign(Subtarget->getStackAlignment(), Offset);
Offset = Offset + FPDiff;
int FI = MFI.CreateFixedObject(OpSize, Offset, true);
DstAddr = DAG.getFrameIndex(FI, PtrVT);
DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
// Make sure any stack arguments overlapping with where we're storing
// are loaded before this eventual operation. Otherwise they'll be
// clobbered.
// FIXME: Why is this really necessary? This seems to just result in a
// lot of code to copy the stack and write them back to the same
// locations, which are supposed to be immutable?
Chain = addTokenForArgument(Chain, DAG, MFI, FI);
} else {
DstAddr = PtrOff;
DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
Align = MinAlign(Subtarget->getStackAlignment(), LocMemOffset);
}
if (Outs[i].Flags.isByVal()) {
SDValue SizeNode =
DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
SDValue Cpy = DAG.getMemcpy(
Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
/*isVol = */ false, /*AlwaysInline = */ true,
/*isTailCall = */ false, DstInfo,
MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
*DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS))));
MemOpChains.push_back(Cpy);
} else {
SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Align);
MemOpChains.push_back(Store);
}
}
}
// Copy special input registers after user input arguments.
passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
if (!MemOpChains.empty())
Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
// Build a sequence of copy-to-reg nodes chained together with token chain
// and flag operands which copy the outgoing args into the appropriate regs.
SDValue InFlag;
for (auto &RegToPass : RegsToPass) {
Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
RegToPass.second, InFlag);
InFlag = Chain.getValue(1);
}
SDValue PhysReturnAddrReg;
if (IsTailCall) {
// Since the return is being combined with the call, we need to pass on the
// return address.
const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
SDValue ReturnAddrReg = CreateLiveInRegister(
DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
MVT::i64);
Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
InFlag = Chain.getValue(1);
}
// We don't usually want to end the call-sequence here because we would tidy
// the frame up *after* the call, however in the ABI-changing tail-call case
// we've carefully laid out the parameters so that when sp is reset they'll be
// in the correct location.
if (IsTailCall && !IsSibCall) {
Chain = DAG.getCALLSEQ_END(Chain,
DAG.getTargetConstant(NumBytes, DL, MVT::i32),
DAG.getTargetConstant(0, DL, MVT::i32),
InFlag, DL);
InFlag = Chain.getValue(1);
}
std::vector<SDValue> Ops;
Ops.push_back(Chain);
Ops.push_back(Callee);
// Add a redundant copy of the callee global which will not be legalized, as
// we need direct access to the callee later.
GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee);
const GlobalValue *GV = GSD->getGlobal();
Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
if (IsTailCall) {
// Each tail call may have to adjust the stack by a different amount, so
// this information must travel along with the operation for eventual
// consumption by emitEpilogue.
Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Ops.push_back(PhysReturnAddrReg);
}
// Add argument registers to the end of the list so that they are known live
// into the call.
for (auto &RegToPass : RegsToPass) {
Ops.push_back(DAG.getRegister(RegToPass.first,
RegToPass.second.getValueType()));
}
// Add a register mask operand representing the call-preserved registers.
auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
assert(Mask && "Missing call preserved mask for calling convention");
Ops.push_back(DAG.getRegisterMask(Mask));
if (InFlag.getNode())
Ops.push_back(InFlag);
SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
// If we're doing a tall call, use a TC_RETURN here rather than an
// actual call instruction.
if (IsTailCall) {
MFI.setHasTailCall();
return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
}
// Returns a chain and a flag for retval copy to use.
SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
Chain = Call.getValue(0);
InFlag = Call.getValue(1);
uint64_t CalleePopBytes = NumBytes;
Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
InFlag, DL);
if (!Ins.empty())
InFlag = Chain.getValue(1);
// Handle result values, copying them out of physregs into vregs that we
// return.
return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
InVals, IsThisReturn,
IsThisReturn ? OutVals[0] : SDValue());
}
Register SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
const MachineFunction &MF) const {
Register Reg = StringSwitch<Register>(RegName)
.Case("m0", AMDGPU::M0)
.Case("exec", AMDGPU::EXEC)
.Case("exec_lo", AMDGPU::EXEC_LO)
.Case("exec_hi", AMDGPU::EXEC_HI)
.Case("flat_scratch", AMDGPU::FLAT_SCR)
.Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
.Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
.Default(Register());
if (Reg == AMDGPU::NoRegister) {
report_fatal_error(Twine("invalid register name \""
+ StringRef(RegName) + "\"."));
}
if (!Subtarget->hasFlatScrRegister() &&
Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
report_fatal_error(Twine("invalid register \""
+ StringRef(RegName) + "\" for subtarget."));
}
switch (Reg) {
case AMDGPU::M0:
case AMDGPU::EXEC_LO:
case AMDGPU::EXEC_HI:
case AMDGPU::FLAT_SCR_LO:
case AMDGPU::FLAT_SCR_HI:
if (VT.getSizeInBits() == 32)
return Reg;
break;
case AMDGPU::EXEC:
case AMDGPU::FLAT_SCR:
if (VT.getSizeInBits() == 64)
return Reg;
break;
default:
llvm_unreachable("missing register type checking");
}
report_fatal_error(Twine("invalid type for register \""
+ StringRef(RegName) + "\"."));
}
// If kill is not the last instruction, split the block so kill is always a
// proper terminator.
MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
MachineBasicBlock *BB) const {
const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
MachineBasicBlock::iterator SplitPoint(&MI);
++SplitPoint;
if (SplitPoint == BB->end()) {
// Don't bother with a new block.
MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
return BB;
}
MachineFunction *MF = BB->getParent();
MachineBasicBlock *SplitBB
= MF->CreateMachineBasicBlock(BB->getBasicBlock());
MF->insert(++MachineFunction::iterator(BB), SplitBB);
SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
SplitBB->transferSuccessorsAndUpdatePHIs(BB);
BB->addSuccessor(SplitBB);
MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
return SplitBB;
}
// Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
// \p MI will be the only instruction in the loop body block. Otherwise, it will
// be the first instruction in the remainder block.
//
/// \returns { LoopBody, Remainder }
static std::pair<MachineBasicBlock *, MachineBasicBlock *>
splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
MachineFunction *MF = MBB.getParent();
MachineBasicBlock::iterator I(&MI);
// To insert the loop we need to split the block. Move everything after this
// point to a new block, and insert a new empty block between the two.
MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
MachineFunction::iterator MBBI(MBB);
++MBBI;
MF->insert(MBBI, LoopBB);
MF->insert(MBBI, RemainderBB);
LoopBB->addSuccessor(LoopBB);
LoopBB->addSuccessor(RemainderBB);
// Move the rest of the block into a new block.
RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
if (InstInLoop) {
auto Next = std::next(I);
// Move instruction to loop body.
LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
// Move the rest of the block.
RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
} else {
RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
}
MBB.addSuccessor(LoopBB);
return std::make_pair(LoopBB, RemainderBB);
}
/// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
MachineBasicBlock *MBB = MI.getParent();
const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
auto I = MI.getIterator();
auto E = std::next(I);
BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
.addImm(0);
MIBundleBuilder Bundler(*MBB, I, E);
finalizeBundle(*MBB, Bundler.begin());
}
MachineBasicBlock *
SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
MachineBasicBlock *BB) const {
const DebugLoc &DL = MI.getDebugLoc();
MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
MachineBasicBlock *LoopBB;
MachineBasicBlock *RemainderBB;
const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
// Apparently kill flags are only valid if the def is in the same block?
if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
Src->setIsKill(false);
std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
MachineBasicBlock::iterator I = LoopBB->end();
const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
// Clear TRAP_STS.MEM_VIOL
BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
.addImm(0)
.addImm(EncodedReg);
bundleInstWithWaitcnt(MI);
Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
// Load and check TRAP_STS.MEM_VIOL
BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
.addImm(EncodedReg);
// FIXME: Do we need to use an isel pseudo that may clobber scc?
BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
.addReg(Reg, RegState::Kill)
.addImm(0);
BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
.addMBB(LoopBB);
return RemainderBB;
}
// Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
// wavefront. If the value is uniform and just happens to be in a VGPR, this
// will only do one iteration. In the worst case, this will loop 64 times.
//
// TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
const SIInstrInfo *TII,
MachineRegisterInfo &MRI,
MachineBasicBlock &OrigBB,
MachineBasicBlock &LoopBB,
const DebugLoc &DL,
const MachineOperand &IdxReg,
unsigned InitReg,
unsigned ResultReg,
unsigned PhiReg,
unsigned InitSaveExecReg,
int Offset,
bool UseGPRIdxMode,
bool IsIndirectSrc) {
MachineFunction *MF = OrigBB.getParent();
const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
const SIRegisterInfo *TRI = ST.getRegisterInfo();
MachineBasicBlock::iterator I = LoopBB.begin();
const TargetRegisterClass *BoolRC = TRI->getBoolRC();
Register PhiExec = MRI.createVirtualRegister(BoolRC);
Register NewExec = MRI.createVirtualRegister(BoolRC);
Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
Register CondReg = MRI.createVirtualRegister(BoolRC);
BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
.addReg(InitReg)
.addMBB(&OrigBB)
.addReg(ResultReg)
.addMBB(&LoopBB);
BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
.addReg(InitSaveExecReg)
.addMBB(&OrigBB)
.addReg(NewExec)
.addMBB(&LoopBB);
// Read the next variant <- also loop target.
BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
.addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
// Compare the just read M0 value to all possible Idx values.
BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
.addReg(CurrentIdxReg)
.addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
// Update EXEC, save the original EXEC value to VCC.
BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
: AMDGPU::S_AND_SAVEEXEC_B64),
NewExec)
.addReg(CondReg, RegState::Kill);
MRI.setSimpleHint(NewExec, CondReg);
if (UseGPRIdxMode) {
unsigned IdxReg;
if (Offset == 0) {
IdxReg = CurrentIdxReg;
} else {
IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
.addReg(CurrentIdxReg, RegState::Kill)
.addImm(Offset);
}
unsigned IdxMode = IsIndirectSrc ?
AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
MachineInstr *SetOn =
BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
.addReg(IdxReg, RegState::Kill)
.addImm(IdxMode);
SetOn->getOperand(3).setIsUndef();
} else {
// Move index from VCC into M0
if (Offset == 0) {
BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
.addReg(CurrentIdxReg, RegState::Kill);
} else {
BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
.addReg(CurrentIdxReg, RegState::Kill)
.addImm(Offset);
}
}
// Update EXEC, switch all done bits to 0 and all todo bits to 1.
unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
MachineInstr *InsertPt =
BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
: AMDGPU::S_XOR_B64_term), Exec)
.addReg(Exec)
.addReg(NewExec);
// XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
// s_cbranch_scc0?
// Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
.addMBB(&LoopBB);
return InsertPt->getIterator();
}
// This has slightly sub-optimal regalloc when the source vector is killed by
// the read. The register allocator does not understand that the kill is
// per-workitem, so is kept alive for the whole loop so we end up not re-using a
// subregister from it, using 1 more VGPR than necessary. This was saved when
// this was expanded after register allocation.
static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
MachineBasicBlock &MBB,
MachineInstr &MI,
unsigned InitResultReg,
unsigned PhiReg,
int Offset,
bool UseGPRIdxMode,
bool IsIndirectSrc) {
MachineFunction *MF = MBB.getParent();
const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
const SIRegisterInfo *TRI = ST.getRegisterInfo();
MachineRegisterInfo &MRI = MF->getRegInfo();
const DebugLoc &DL = MI.getDebugLoc();
MachineBasicBlock::iterator I(&MI);
const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
Register DstReg = MI.getOperand(0).getReg();
Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
// Save the EXEC mask
BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
.addReg(Exec);
MachineBasicBlock *LoopBB;
MachineBasicBlock *RemainderBB;
std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
InitResultReg, DstReg, PhiReg, TmpExec,
Offset, UseGPRIdxMode, IsIndirectSrc);
MachineBasicBlock::iterator First = RemainderBB->begin();
BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec)
.addReg(SaveExec);
return InsPt;
}
// Returns subreg index, offset
static std::pair<unsigned, int>
computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
const TargetRegisterClass *SuperRC,
unsigned VecReg,
int Offset) {
int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
// Skip out of bounds offsets, or else we would end up using an undefined
// register.
if (Offset >= NumElts || Offset < 0)
return std::make_pair(AMDGPU::sub0, Offset);
return std::make_pair(AMDGPU::sub0 + Offset, 0);
}
// Return true if the index is an SGPR and was set.
static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
MachineRegisterInfo &MRI,
MachineInstr &MI,
int Offset,
bool UseGPRIdxMode,
bool IsIndirectSrc) {
MachineBasicBlock *MBB = MI.getParent();
const DebugLoc &DL = MI.getDebugLoc();
MachineBasicBlock::iterator I(&MI);
const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
assert(Idx->getReg() != AMDGPU::NoRegister);
if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
return false;
if (UseGPRIdxMode) {
unsigned IdxMode = IsIndirectSrc ?
AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
if (Offset == 0) {
MachineInstr *SetOn =
BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
.add(*Idx)
.addImm(IdxMode);
SetOn->getOperand(3).setIsUndef();
} else {
Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
.add(*Idx)
.addImm(Offset);
MachineInstr *SetOn =
BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
.addReg(Tmp, RegState::Kill)
.addImm(IdxMode);
SetOn->getOperand(3).setIsUndef();
}
return true;
}
if (Offset == 0) {
BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
.add(*Idx);
} else {
BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
.add(*Idx)
.addImm(Offset);
}
return true;
}
// Control flow needs to be inserted if indexing with a VGPR.
static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
MachineBasicBlock &MBB,
const GCNSubtarget &ST) {
const SIInstrInfo *TII = ST.getInstrInfo();
const SIRegisterInfo &TRI = TII->getRegisterInfo();
MachineFunction *MF = MBB.getParent();
MachineRegisterInfo &MRI = MF->getRegInfo();
Register Dst = MI.getOperand(0).getReg();
Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
unsigned SubReg;
std::tie(SubReg, Offset)
= computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
MachineBasicBlock::iterator I(&MI);
const DebugLoc &DL = MI.getDebugLoc();
if (UseGPRIdxMode) {
// TODO: Look at the uses to avoid the copy. This may require rescheduling
// to avoid interfering with other uses, so probably requires a new
// optimization pass.
BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
.addReg(SrcReg, RegState::Undef, SubReg)
.addReg(SrcReg, RegState::Implicit)
.addReg(AMDGPU::M0, RegState::Implicit);
BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
} else {
BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
.addReg(SrcReg, RegState::Undef, SubReg)
.addReg(SrcReg, RegState::Implicit);
}
MI.eraseFromParent();
return &MBB;
}
const DebugLoc &DL = MI.getDebugLoc();
MachineBasicBlock::iterator I(&MI);
Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
Offset, UseGPRIdxMode, true);
MachineBasicBlock *LoopBB = InsPt->getParent();
if (UseGPRIdxMode) {
BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
.addReg(SrcReg, RegState::Undef, SubReg)
.addReg(SrcReg, RegState::Implicit)
.addReg(AMDGPU::M0, RegState::Implicit);
BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
} else {
BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
.addReg(SrcReg, RegState::Undef, SubReg)
.addReg(SrcReg, RegState::Implicit);
}
MI.eraseFromParent();
return LoopBB;
}
static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
const TargetRegisterClass *VecRC) {
switch (TRI.getRegSizeInBits(*VecRC)) {
case 32: // 4 bytes
return AMDGPU::V_MOVRELD_B32_V1;
case 64: // 8 bytes
return AMDGPU::V_MOVRELD_B32_V2;
case 128: // 16 bytes
return AMDGPU::V_MOVRELD_B32_V4;
case 256: // 32 bytes
return AMDGPU::V_MOVRELD_B32_V8;
case 512: // 64 bytes
return AMDGPU::V_MOVRELD_B32_V16;
default:
llvm_unreachable("unsupported size for MOVRELD pseudos");
}
}
static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
MachineBasicBlock &MBB,
const GCNSubtarget &ST) {
const SIInstrInfo *TII = ST.getInstrInfo();
const SIRegisterInfo &TRI = TII->getRegisterInfo();
MachineFunction *MF = MBB.getParent();
MachineRegisterInfo &MRI = MF->getRegInfo();
Register Dst = MI.getOperand(0).getReg();
const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
// This can be an immediate, but will be folded later.
assert(Val->getReg());
unsigned SubReg;
std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
SrcVec->getReg(),
Offset);
bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
if (Idx->getReg() == AMDGPU::NoRegister) {
MachineBasicBlock::iterator I(&MI);
const DebugLoc &DL = MI.getDebugLoc();
assert(Offset == 0);
BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
.add(*SrcVec)
.add(*Val)
.addImm(SubReg);
MI.eraseFromParent();
return &MBB;
}
if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
MachineBasicBlock::iterator I(&MI);
const DebugLoc &DL = MI.getDebugLoc();
if (UseGPRIdxMode) {
BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
.addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
.add(*Val)
.addReg(Dst, RegState::ImplicitDefine)
.addReg(SrcVec->getReg(), RegState::Implicit)
.addReg(AMDGPU::M0, RegState::Implicit);
BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
} else {
const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
BuildMI(MBB, I, DL, MovRelDesc)
.addReg(Dst, RegState::Define)
.addReg(SrcVec->getReg())
.add(*Val)
.addImm(SubReg - AMDGPU::sub0);
}
MI.eraseFromParent();
return &MBB;
}
if (Val->isReg())
MRI.clearKillFlags(Val->getReg());
const DebugLoc &DL = MI.getDebugLoc();
Register PhiReg = MRI.createVirtualRegister(VecRC);
auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
Offset, UseGPRIdxMode, false);
MachineBasicBlock *LoopBB = InsPt->getParent();
if (UseGPRIdxMode) {
BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
.addReg(PhiReg, RegState::Undef, SubReg) // vdst
.add(*Val) // src0
.addReg(Dst, RegState::ImplicitDefine)
.addReg(PhiReg, RegState::Implicit)
.addReg(AMDGPU::M0, RegState::Implicit);
BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
} else {
const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
.addReg(Dst, RegState::Define)
.addReg(PhiReg)
.add(*Val)
.addImm(SubReg - AMDGPU::sub0);
}
MI.eraseFromParent();
return LoopBB;
}
MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
MachineInstr &MI, MachineBasicBlock *BB) const {
const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
MachineFunction *MF = BB->getParent();
SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
if (TII->isMIMG(MI)) {
if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
report_fatal_error("missing mem operand from MIMG instruction");
}
// Add a memoperand for mimg instructions so that they aren't assumed to
// be ordered memory instuctions.
return BB;
}
switch (MI.getOpcode()) {
case AMDGPU::S_ADD_U64_PSEUDO:
case AMDGPU::S_SUB_U64_PSEUDO: {
MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
const SIRegisterInfo *TRI = ST.getRegisterInfo();
const TargetRegisterClass *BoolRC = TRI->getBoolRC();
const DebugLoc &DL = MI.getDebugLoc();
MachineOperand &Dest = MI.getOperand(0);
MachineOperand &Src0 = MI.getOperand(1);
MachineOperand &Src1 = MI.getOperand(2);
Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
Src0, BoolRC, AMDGPU::sub0,
&AMDGPU::SReg_32_XM0RegClass);
MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
Src0, BoolRC, AMDGPU::sub1,
&AMDGPU::SReg_32_XM0RegClass);
MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
Src1, BoolRC, AMDGPU::sub0,
&AMDGPU::SReg_32_XM0RegClass);
MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
Src1, BoolRC, AMDGPU::sub1,
&AMDGPU::SReg_32_XM0RegClass);
bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
.add(Src0Sub0)
.add(Src1Sub0);
BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
.add(Src0Sub1)
.add(Src1Sub1);
BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
.addReg(DestSub0)
.addImm(AMDGPU::sub0)
.addReg(DestSub1)
.addImm(AMDGPU::sub1);
MI.eraseFromParent();
return BB;
}
case AMDGPU::SI_INIT_M0: {
BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
.add(MI.getOperand(0));
MI.eraseFromParent();
return BB;
}
case AMDGPU::SI_INIT_EXEC:
// This should be before all vector instructions.
BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
AMDGPU::EXEC)
.addImm(MI.getOperand(0).getImm());
MI.eraseFromParent();
return BB;
case AMDGPU::SI_INIT_EXEC_LO:
// This should be before all vector instructions.
BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
AMDGPU::EXEC_LO)
.addImm(MI.getOperand(0).getImm());
MI.eraseFromParent();
return BB;
case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
// Extract the thread count from an SGPR input and set EXEC accordingly.
// Since BFM can't shift by 64, handle that case with CMP + CMOV.
//
// S_BFE_U32 count, input, {shift, 7}
// S_BFM_B64 exec, count, 0
// S_CMP_EQ_U32 count, 64
// S_CMOV_B64 exec, -1
MachineInstr *FirstMI = &*BB->begin();
MachineRegisterInfo &MRI = MF->getRegInfo();
Register InputReg = MI.getOperand(0).getReg();
Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
bool Found = false;
// Move the COPY of the input reg to the beginning, so that we can use it.
for (auto I = BB->begin(); I != &MI; I++) {
if (I->getOpcode() != TargetOpcode::COPY ||
I->getOperand(0).getReg() != InputReg)
continue;
if (I == FirstMI) {
FirstMI = &*++BB->begin();
} else {
I->removeFromParent();
BB->insert(FirstMI, &*I);
}
Found = true;
break;
}
assert(Found);
(void)Found;
// This should be before all vector instructions.
unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
bool isWave32 = getSubtarget()->isWave32();
unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
.addReg(InputReg)
.addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
BuildMI(*BB, FirstMI, DebugLoc(),
TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
Exec)
.addReg(CountReg)
.addImm(0);
BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
.addReg(CountReg, RegState::Kill)
.addImm(getSubtarget()->getWavefrontSize());
BuildMI(*BB, FirstMI, DebugLoc(),
TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
Exec)
.addImm(-1);
MI.eraseFromParent();
return BB;
}
case AMDGPU::GET_GROUPSTATICSIZE: {
assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
DebugLoc DL = MI.getDebugLoc();
BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
.add(MI.getOperand(0))
.addImm(MFI->getLDSSize());
MI.eraseFromParent();
return BB;
}
case AMDGPU::SI_INDIRECT_SRC_V1:
case AMDGPU::SI_INDIRECT_SRC_V2:
case AMDGPU::SI_INDIRECT_SRC_V4:
case AMDGPU::SI_INDIRECT_SRC_V8:
case AMDGPU::SI_INDIRECT_SRC_V16:
return emitIndirectSrc(MI, *BB, *getSubtarget());
case AMDGPU::SI_INDIRECT_DST_V1:
case AMDGPU::SI_INDIRECT_DST_V2:
case AMDGPU::SI_INDIRECT_DST_V4:
case AMDGPU::SI_INDIRECT_DST_V8:
case AMDGPU::SI_INDIRECT_DST_V16:
return emitIndirectDst(MI, *BB, *getSubtarget());
case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
case AMDGPU::SI_KILL_I1_PSEUDO:
return splitKillBlock(MI, BB);
case AMDGPU::V_CNDMASK_B64_PSEUDO: {
MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
const SIRegisterInfo *TRI = ST.getRegisterInfo();
Register Dst = MI.getOperand(0).getReg();
Register Src0 = MI.getOperand(1).getReg();
Register Src1 = MI.getOperand(2).getReg();
const DebugLoc &DL = MI.getDebugLoc();
Register SrcCond = MI.getOperand(3).getReg();
Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
.addReg(SrcCond);
BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
.addImm(0)
.addReg(Src0, 0, AMDGPU::sub0)
.addImm(0)
.addReg(Src1, 0, AMDGPU::sub0)
.addReg(SrcCondCopy);
BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
.addImm(0)
.addReg(Src0, 0, AMDGPU::sub1)
.addImm(0)
.addReg(Src1, 0, AMDGPU::sub1)
.addReg(SrcCondCopy);
BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
.addReg(DstLo)
.addImm(AMDGPU::sub0)
.addReg(DstHi)
.addImm(AMDGPU::sub1);
MI.eraseFromParent();
return BB;
}
case AMDGPU::SI_BR_UNDEF: {
const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
const DebugLoc &DL = MI.getDebugLoc();
MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
.add(MI.getOperand(0));
Br->getOperand(1).setIsUndef(true); // read undef SCC
MI.eraseFromParent();
return BB;
}
case AMDGPU::ADJCALLSTACKUP:
case AMDGPU::ADJCALLSTACKDOWN: {
const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
MachineInstrBuilder MIB(*MF, &MI);
// Add an implicit use of the frame offset reg to prevent the restore copy
// inserted after the call from being reorderd after stack operations in the
// the caller's frame.
MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
.addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
.addReg(Info->getFrameOffsetReg(), RegState::Implicit);
return BB;
}
case AMDGPU::SI_CALL_ISEL: {
const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
const DebugLoc &DL = MI.getDebugLoc();
unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
MachineInstrBuilder MIB;
MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
MIB.add(MI.getOperand(I));
MIB.cloneMemRefs(MI);
MI.eraseFromParent();
return BB;
}
case AMDGPU::V_ADD_I32_e32:
case AMDGPU::V_SUB_I32_e32:
case AMDGPU::V_SUBREV_I32_e32: {
// TODO: Define distinct V_*_I32_Pseudo instructions instead.
const DebugLoc &DL = MI.getDebugLoc();
unsigned Opc = MI.getOpcode();
bool NeedClampOperand = false;
if (TII->pseudoToMCOpcode(Opc) == -1) {
Opc = AMDGPU::getVOPe64(Opc);
NeedClampOperand = true;
}
auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
if (TII->isVOP3(*I)) {
const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
const SIRegisterInfo *TRI = ST.getRegisterInfo();
I.addReg(TRI->getVCC(), RegState::Define);
}
I.add(MI.getOperand(1))
.add(MI.getOperand(2));
if (NeedClampOperand)
I.addImm(0); // clamp bit for e64 encoding
SmallSetVector<MachineInstr *, 32> Worklist;
TII->legalizeOperands(*I, Worklist);
MI.eraseFromParent();
return BB;
}
case AMDGPU::DS_GWS_INIT:
case AMDGPU::DS_GWS_SEMA_V:
case AMDGPU::DS_GWS_SEMA_BR:
case AMDGPU::DS_GWS_SEMA_P:
case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
case AMDGPU::DS_GWS_BARRIER:
// A s_waitcnt 0 is required to be the instruction immediately following.
if (getSubtarget()->hasGWSAutoReplay()) {
bundleInstWithWaitcnt(MI);
return BB;
}
return emitGWSMemViolTestLoop(MI, BB);
default:
return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
}
}
bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
return isTypeLegal(VT.getScalarType());
}
bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
// This currently forces unfolding various combinations of fsub into fma with
// free fneg'd operands. As long as we have fast FMA (controlled by
// isFMAFasterThanFMulAndFAdd), we should perform these.
// When fma is quarter rate, for f64 where add / sub are at best half rate,
// most of these combines appear to be cycle neutral but save on instruction
// count / code size.
return true;
}
EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
EVT VT) const {
if (!VT.isVector()) {
return MVT::i1;
}
return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
}
MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
// TODO: Should i16 be used always if legal? For now it would force VALU
// shifts.
return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
}
// Answering this is somewhat tricky and depends on the specific device which
// have different rates for fma or all f64 operations.
//
// v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
// regardless of which device (although the number of cycles differs between
// devices), so it is always profitable for f64.
//
// v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
// only on full rate devices. Normally, we should prefer selecting v_mad_f32
// which we can always do even without fused FP ops since it returns the same
// result as the separate operations and since it is always full
// rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
// however does not support denormals, so we do report fma as faster if we have
// a fast fma device and require denormals.
//
bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
VT = VT.getScalarType();
switch (VT.getSimpleVT().SimpleTy) {
case MVT::f32: {
// This is as fast on some subtargets. However, we always have full rate f32
// mad available which returns the same result as the separate operations
// which we should prefer over fma. We can't use this if we want to support
// denormals, so only report this in these cases.
if (Subtarget->hasFP32Denormals())
return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
// If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
}
case MVT::f64:
return true;
case MVT::f16:
return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
default:
break;
}
return false;
}
//===----------------------------------------------------------------------===//
// Custom DAG Lowering Operations
//===----------------------------------------------------------------------===//
// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
// wider vector type is legal.
SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
SelectionDAG &DAG) const {
unsigned Opc = Op.getOpcode();
EVT VT = Op.getValueType();
assert(VT == MVT::v4f16);
SDValue Lo, Hi;
std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
SDLoc SL(Op);
SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
Op->getFlags());
SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
Op->getFlags());
return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
}
// Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
// wider vector type is legal.
SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
SelectionDAG &DAG) const {
unsigned Opc = Op.getOpcode();
EVT VT = Op.getValueType();
assert(VT == MVT::v4i16 || VT == MVT::v4f16);
SDValue Lo0, Hi0;
std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
SDValue Lo1, Hi1;
std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
SDLoc SL(Op);
SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
Op->getFlags());
SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
Op->getFlags());
return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
}
SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
SelectionDAG &DAG) const {
unsigned Opc = Op.getOpcode();
EVT VT = Op.getValueType();
assert(VT == MVT::v4i16 || VT == MVT::v4f16);
SDValue Lo0, Hi0;
std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
SDValue Lo1, Hi1;
std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
SDValue Lo2, Hi2;
std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
SDLoc SL(Op);
SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
Op->getFlags());
SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
Op->getFlags());
return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
}
SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
switch (Op.getOpcode()) {
default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
case ISD::BRCOND: return LowerBRCOND(Op, DAG);
case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
case ISD::LOAD: {
SDValue Result = LowerLOAD(Op, DAG);
assert((!Result.getNode() ||
Result.getNode()->getNumValues() == 2) &&
"Load should return a value and a chain");
return Result;
}
case ISD::FSIN:
case ISD::FCOS:
return LowerTrig(Op, DAG);
case ISD::SELECT: return LowerSELECT(Op, DAG);
case ISD::FDIV: return LowerFDIV(Op, DAG);
case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
case ISD::STORE: return LowerSTORE(Op, DAG);
case ISD::GlobalAddress: {
MachineFunction &MF = DAG.getMachineFunction();
SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
return LowerGlobalAddress(MFI, Op, DAG);
}
case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
case ISD::INSERT_SUBVECTOR:
return lowerINSERT_SUBVECTOR(Op, DAG);
case ISD::INSERT_VECTOR_ELT:
return lowerINSERT_VECTOR_ELT(Op, DAG);
case ISD::EXTRACT_VECTOR_ELT:
return lowerEXTRACT_VECTOR_ELT(Op, DAG);
case ISD::VECTOR_SHUFFLE:
return lowerVECTOR_SHUFFLE(Op, DAG);
case ISD::BUILD_VECTOR:
return lowerBUILD_VECTOR(Op, DAG);
case ISD::FP_ROUND:
return lowerFP_ROUND(Op, DAG);
case ISD::TRAP:
return lowerTRAP(Op, DAG);
case ISD::DEBUGTRAP:
return lowerDEBUGTRAP(Op, DAG);
case ISD::FABS:
case ISD::FNEG:
case ISD::FCANONICALIZE:
return splitUnaryVectorOp(Op, DAG);
case ISD::FMINNUM:
case ISD::FMAXNUM:
return lowerFMINNUM_FMAXNUM(Op, DAG);
case ISD::FMA:
return splitTernaryVectorOp(Op, DAG);
case ISD::SHL:
case ISD::SRA:
case ISD::SRL:
case ISD::ADD:
case ISD::SUB:
case ISD::MUL:
case ISD::SMIN:
case ISD::SMAX:
case ISD::UMIN:
case ISD::UMAX:
case ISD::FADD:
case ISD::FMUL:
case ISD::FMINNUM_IEEE:
case ISD::FMAXNUM_IEEE:
return splitBinaryVectorOp(Op, DAG);
}
return SDValue();
}
static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
const SDLoc &DL,
SelectionDAG &DAG, bool Unpacked) {
if (!LoadVT.isVector())
return Result;
if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
// Truncate to v2i16/v4i16.
EVT IntLoadVT = LoadVT.changeTypeToInteger();
// Workaround legalizer not scalarizing truncate after vector op
// legalization byt not creating intermediate vector trunc.
SmallVector<SDValue, 4> Elts;
DAG.ExtractVectorElements(Result, Elts);
for (SDValue &Elt : Elts)
Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
// Bitcast to original type (v2f16/v4f16).
return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
}
// Cast back to the original packed type.
return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
}
SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
MemSDNode *M,
SelectionDAG &DAG,
ArrayRef<SDValue> Ops,
bool IsIntrinsic) const {
SDLoc DL(M);
bool Unpacked = Subtarget->hasUnpackedD16VMem();
EVT LoadVT = M->getValueType(0);
EVT EquivLoadVT = LoadVT;
if (Unpacked && LoadVT.isVector()) {
EquivLoadVT = LoadVT.isVector() ?
EVT::getVectorVT(*DAG.getContext(), MVT::i32,
LoadVT.getVectorNumElements()) : LoadVT;
}
// Change from v4f16/v2f16 to EquivLoadVT.
SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
SDValue Load
= DAG.getMemIntrinsicNode(
IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
VTList, Ops, M->getMemoryVT(),
M->getMemOperand());
if (!Unpacked) // Just adjusted the opcode.
return Load;
SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
}
SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
SelectionDAG &DAG,
ArrayRef<SDValue> Ops) const {
SDLoc DL(M);
EVT LoadVT = M->getValueType(0);
EVT EltType = LoadVT.getScalarType();
EVT IntVT = LoadVT.changeTypeToInteger();
bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
unsigned Opc =
IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
if (IsD16) {
return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
}
// Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
if (isTypeLegal(LoadVT)) {
return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
M->getMemOperand(), DAG);
}
EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
M->getMemOperand(), DAG);
return DAG.getMergeValues(
{DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
DL);
}
static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
SDNode *N, SelectionDAG &DAG) {
EVT VT = N->getValueType(0);
const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
int CondCode = CD->getSExtValue();
if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
return DAG.getUNDEF(VT);
ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
SDValue LHS = N->getOperand(1);
SDValue RHS = N->getOperand(2);
SDLoc DL(N);
EVT CmpVT = LHS.getValueType();
if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
}
ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
DAG.getCondCode(CCOpcode));
if (VT.bitsEq(CCVT))
return SetCC;
return DAG.getZExtOrTrunc(SetCC, DL, VT);
}
static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
SDNode *N, SelectionDAG &DAG) {
EVT VT = N->getValueType(0);
const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
int CondCode = CD->getSExtValue();
if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
return DAG.getUNDEF(VT);
}
SDValue Src0 = N->getOperand(1);
SDValue Src1 = N->getOperand(2);
EVT CmpVT = Src0.getValueType();
SDLoc SL(N);
if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
}
FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
Src1, DAG.getCondCode(CCOpcode));
if (VT.bitsEq(CCVT))
return SetCC;
return DAG.getZExtOrTrunc(SetCC, SL, VT);
}
void SITargetLowering::ReplaceNodeResults(SDNode *N,
SmallVectorImpl<SDValue> &Results,
SelectionDAG &DAG) const {
switch (N->getOpcode()) {
case ISD::INSERT_VECTOR_ELT: {
if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
Results.push_back(Res);
return;
}
case ISD::EXTRACT_VECTOR_ELT: {
if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
Results.push_back(Res);
return;
}
case ISD::INTRINSIC_WO_CHAIN: {
unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
switch (IID) {
case Intrinsic::amdgcn_cvt_pkrtz: {
SDValue Src0 = N->getOperand(1);
SDValue Src1 = N->getOperand(2);
SDLoc SL(N);
SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
Src0, Src1);
Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
return;
}
case Intrinsic::amdgcn_cvt_pknorm_i16:
case Intrinsic::amdgcn_cvt_pknorm_u16:
case Intrinsic::amdgcn_cvt_pk_i16:
case Intrinsic::amdgcn_cvt_pk_u16: {
SDValue Src0 = N->getOperand(1);
SDValue Src1 = N->getOperand(2);
SDLoc SL(N);
unsigned Opcode;
if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
Opcode = AMDGPUISD::CVT_PK_I16_I32;
else
Opcode = AMDGPUISD::CVT_PK_U16_U32;
EVT VT = N->getValueType(0);
if (isTypeLegal(VT))
Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
else {
SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
}
return;
}
}
break;
}
case ISD::INTRINSIC_W_CHAIN: {
if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
if (Res.getOpcode() == ISD::MERGE_VALUES) {
// FIXME: Hacky
Results.push_back(Res.getOperand(0));
Results.push_back(Res.getOperand(1));
} else {
Results.push_back(Res);
Results.push_back(Res.getValue(1));
}
return;
}
break;
}
case ISD::SELECT: {
SDLoc SL(N);
EVT VT = N->getValueType(0);
EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
EVT SelectVT = NewVT;
if (NewVT.bitsLT(MVT::i32)) {
LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
SelectVT = MVT::i32;
}
SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
N->getOperand(0), LHS, RHS);
if (NewVT != SelectVT)
NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
return;
}
case ISD::FNEG: {
if (N->getValueType(0) != MVT::v2f16)
break;
SDLoc SL(N);
SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
BC,
DAG.getConstant(0x80008000, SL, MVT::i32));
Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
return;
}
case ISD::FABS: {
if (N->getValueType(0) != MVT::v2f16)
break;
SDLoc SL(N);
SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
BC,
DAG.getConstant(0x7fff7fff, SL, MVT::i32));
Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
return;
}
default:
break;
}
}
/// Helper function for LowerBRCOND
static SDNode *findUser(SDValue Value, unsigned Opcode) {
SDNode *Parent = Value.getNode();
for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
I != E; ++I) {
if (I.getUse().get() != Value)
continue;
if (I->getOpcode() == Opcode)
return *I;
}
return nullptr;
}
unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
case Intrinsic::amdgcn_if:
return AMDGPUISD::IF;
case Intrinsic::amdgcn_else:
return AMDGPUISD::ELSE;
case Intrinsic::amdgcn_loop:
return AMDGPUISD::LOOP;
case Intrinsic::amdgcn_end_cf:
llvm_unreachable("should not occur");
default:
return 0;
}
}
// break, if_break, else_break are all only used as inputs to loop, not
// directly as branch conditions.
return 0;
}
bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
const Triple &TT = getTargetMachine().getTargetTriple();
return (GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
AMDGPU::shouldEmitConstantsToTextSection(TT);
}
bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
// FIXME: Either avoid relying on address space here or change the default
// address space for functions to avoid the explicit check.
return (GV->getValueType()->isFunctionTy() ||
GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
!shouldEmitFixup(GV) &&
!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
}
bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
}
/// This transforms the control flow intrinsics to get the branch destination as
/// last parameter, also switches branch target with BR if the need arise
SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
SelectionDAG &DAG) const {
SDLoc DL(BRCOND);
SDNode *Intr = BRCOND.getOperand(1).getNode();
SDValue Target = BRCOND.getOperand(2);
SDNode *BR = nullptr;
SDNode *SetCC = nullptr;
if (Intr->getOpcode() == ISD::SETCC) {
// As long as we negate the condition everything is fine
SetCC = Intr;
Intr = SetCC->getOperand(0).getNode();
} else {
// Get the target from BR if we don't negate the condition
BR = findUser(BRCOND, ISD::BR);
Target = BR->getOperand(1);
}
// FIXME: This changes the types of the intrinsics instead of introducing new
// nodes with the correct types.
// e.g. llvm.amdgcn.loop
// eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
// => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
unsigned CFNode = isCFIntrinsic(Intr);
if (CFNode == 0) {
// This is a uniform branch so we don't need to legalize.
return BRCOND;
}
bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
assert(!SetCC ||
(SetCC->getConstantOperandVal(1) == 1 &&
cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
ISD::SETNE));
// operands of the new intrinsic call
SmallVector<SDValue, 4> Ops;
if (HaveChain)
Ops.push_back(BRCOND.getOperand(0));
Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end());
Ops.push_back(Target);
ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
// build the new intrinsic call
SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
if (!HaveChain) {
SDValue Ops[] = {
SDValue(Result, 0),
BRCOND.getOperand(0)
};
Result = DAG.getMergeValues(Ops, DL).getNode();
}
if (BR) {
// Give the branch instruction our target
SDValue Ops[] = {
BR->getOperand(0),
BRCOND.getOperand(2)
};
SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
BR = NewBR.getNode();
}
SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
// Copy the intrinsic results to registers
for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
if (!CopyToReg)
continue;
Chain = DAG.getCopyToReg(
Chain, DL,
CopyToReg->getOperand(1),
SDValue(Result, i - 1),
SDValue());
DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
}
// Remove the old intrinsic from the chain
DAG.ReplaceAllUsesOfValueWith(
SDValue(Intr, Intr->getNumValues() - 1),
Intr->getOperand(0));
return Chain;
}
SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
SelectionDAG &DAG) const {
MVT VT = Op.getSimpleValueType();
SDLoc DL(Op);
// Checking the depth
if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
return DAG.getConstant(0, DL, VT);
MachineFunction &MF = DAG.getMachineFunction();
const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
// Check for kernel and shader functions
if (Info->isEntryFunction())
return DAG.getConstant(0, DL, VT);
MachineFrameInfo &MFI = MF.getFrameInfo();
// There is a call to @llvm.returnaddress in this function
MFI.setReturnAddressIsTaken(true);
const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
// Get the return address reg and mark it as an implicit live-in
unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
}
SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
SDValue Op,
const SDLoc &DL,
EVT VT) const {
return Op.getValueType().bitsLE(VT) ?
DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
DAG.getNode(ISD::FTRUNC, DL, VT, Op);
}
SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
assert(Op.getValueType() == MVT::f16 &&
"Do not know how to custom lower FP_ROUND for non-f16 type");
SDValue Src = Op.getOperand(0);
EVT SrcVT = Src.getValueType();
if (SrcVT != MVT::f64)
return Op;
SDLoc DL(Op);
SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
}
SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
SelectionDAG &DAG) const {
EVT VT = Op.getValueType();
const MachineFunction &MF = DAG.getMachineFunction();
const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
bool IsIEEEMode = Info->getMode().IEEE;
// FIXME: Assert during eslection that this is only selected for
// ieee_mode. Currently a combine can produce the ieee version for non-ieee
// mode functions, but this happens to be OK since it's only done in cases
// where there is known no sNaN.
if (IsIEEEMode)
return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
if (VT == MVT::v4f16)
return splitBinaryVectorOp(Op, DAG);
return Op;
}
SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
SDLoc SL(Op);
SDValue Chain = Op.getOperand(0);
if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
!Subtarget->isTrapHandlerEnabled())
return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
MachineFunction &MF = DAG.getMachineFunction();
SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
unsigned UserSGPR = Info->getQueuePtrUserSGPR();
assert(UserSGPR != AMDGPU::NoRegister);
SDValue QueuePtr = CreateLiveInRegister(
DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
QueuePtr, SDValue());
SDValue Ops[] = {
ToReg,
DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
SGPR01,
ToReg.getValue(1)
};
return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
}
SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
SDLoc SL(Op);
SDValue Chain = Op.getOperand(0);
MachineFunction &MF = DAG.getMachineFunction();
if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
!Subtarget->isTrapHandlerEnabled()) {
DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
"debugtrap handler not supported",
Op.getDebugLoc(),
DS_Warning);
LLVMContext &Ctx = MF.getFunction().getContext();
Ctx.diagnose(NoTrap);
return Chain;
}
SDValue Ops[] = {
Chain,
DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
};
return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
}
SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
SelectionDAG &DAG) const {
// FIXME: Use inline constants (src_{shared, private}_base) instead.
if (Subtarget->hasApertureRegs()) {
unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
unsigned Encoding =
AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
SDValue ApertureReg = SDValue(
DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
}
MachineFunction &MF = DAG.getMachineFunction();
SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
unsigned UserSGPR = Info->getQueuePtrUserSGPR();
assert(UserSGPR != AMDGPU::NoRegister);
SDValue QueuePtr = CreateLiveInRegister(
DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
// Offset into amd_queue_t for group_segment_aperture_base_hi /
// private_segment_aperture_base_hi.
uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
// TODO: Use custom target PseudoSourceValue.
// TODO: We should use the value from the IR intrinsic call, but it might not
// be available and how do we get it?
Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
AMDGPUAS::CONSTANT_ADDRESS));
MachinePointerInfo PtrInfo(V, StructOffset);
return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
MinAlign(64, StructOffset),
MachineMemOperand::MODereferenceable |
MachineMemOperand::MOInvariant);
}
SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
SelectionDAG &DAG) const {
SDLoc SL(Op);
const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
SDValue Src = ASC->getOperand(0);
SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
const AMDGPUTargetMachine &TM =
static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
// flat -> local/private
if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
unsigned DestAS = ASC->getDestAddressSpace();
if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
unsigned NullVal = TM.getNullPointerValue(DestAS);
SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
return DAG.getNode(ISD::SELECT, SL, MVT::i32,
NonNull, Ptr, SegmentNullPtr);
}
}
// local/private -> flat
if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
unsigned SrcAS = ASC->getSrcAddressSpace();
if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
unsigned NullVal = TM.getNullPointerValue(SrcAS);
SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
SDValue NonNull
= DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
SDValue CvtPtr
= DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
FlatNullPtr);
}
}
// global <-> flat are no-ops and never emitted.
const MachineFunction &MF = DAG.getMachineFunction();
DiagnosticInfoUnsupported InvalidAddrSpaceCast(
MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
DAG.getContext()->diagnose(InvalidAddrSpaceCast);
return DAG.getUNDEF(ASC->getValueType(0));
}
// This lowers an INSERT_SUBVECTOR by extracting the individual elements from
// the small vector and inserting them into the big vector. That is better than
// the default expansion of doing it via a stack slot. Even though the use of
// the stack slot would be optimized away afterwards, the stack slot itself
// remains.
SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
SelectionDAG &DAG) const {
SDValue Vec = Op.getOperand(0);
SDValue Ins = Op.getOperand(1);
SDValue Idx = Op.getOperand(2);
EVT VecVT = Vec.getValueType();
EVT InsVT = Ins.getValueType();
EVT EltVT = VecVT.getVectorElementType();
unsigned InsNumElts = InsVT.getVectorNumElements();
unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
SDLoc SL(Op);
for (unsigned I = 0; I != InsNumElts; ++I) {
SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
DAG.getConstant(I, SL, MVT::i32));
Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
DAG.getConstant(IdxVal + I, SL, MVT::i32));
}
return Vec;
}
SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
SelectionDAG &DAG) const {
SDValue Vec = Op.getOperand(0);
SDValue InsVal = Op.getOperand(1);
SDValue Idx = Op.getOperand(2);
EVT VecVT = Vec.getValueType();
EVT EltVT = VecVT.getVectorElementType();
unsigned VecSize = VecVT.getSizeInBits();
unsigned EltSize = EltVT.getSizeInBits();
assert(VecSize <= 64);
unsigned NumElts = VecVT.getVectorNumElements();
SDLoc SL(Op);
auto KIdx = dyn_cast<ConstantSDNode>(Idx);
if (NumElts == 4 && EltSize == 16 && KIdx) {
SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
DAG.getConstant(0, SL, MVT::i32));
SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
DAG.getConstant(1, SL, MVT::i32));
SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
unsigned Idx = KIdx->getZExtValue();
bool InsertLo = Idx < 2;
SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
InsertLo ? LoVec : HiVec,
DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
SDValue Concat = InsertLo ?
DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
}
if (isa<ConstantSDNode>(Idx))
return SDValue();
MVT IntVT = MVT::getIntegerVT(VecSize);
// Avoid stack access for dynamic indexing.
// v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
// Create a congruent vector with the target value in each element so that
// the required element can be masked and ORed into the target vector.
SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
DAG.getSplatBuildVector(VecVT, SL, InsVal));
assert(isPowerOf2_32(EltSize));
SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
// Convert vector index to bit-index.
SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
DAG.getConstant(0xffff, SL, IntVT),
ScaledIdx);
SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
DAG.getNOT(SL, BFM, IntVT), BCVec);
SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
}
SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
SelectionDAG &DAG) const {
SDLoc SL(Op);
EVT ResultVT = Op.getValueType();
SDValue Vec = Op.getOperand(0);
SDValue Idx = Op.getOperand(1);
EVT VecVT = Vec.getValueType();
unsigned VecSize = VecVT.getSizeInBits();
EVT EltVT = VecVT.getVectorElementType();
assert(VecSize <= 64);
DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
// Make sure we do any optimizations that will make it easier to fold
// source modifiers before obscuring it with bit operations.
// XXX - Why doesn't this get called when vector_shuffle is expanded?
if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
return Combined;
unsigned EltSize = EltVT.getSizeInBits();
assert(isPowerOf2_32(EltSize));
MVT IntVT = MVT::getIntegerVT(VecSize);
SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
// Convert vector index to bit-index (* EltSize)
SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
if (ResultVT == MVT::f16) {
SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
}
return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
}
static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
assert(Elt % 2 == 0);
return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
}
SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
SelectionDAG &DAG) const {
SDLoc SL(Op);
EVT ResultVT = Op.getValueType();
ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
EVT EltVT = PackVT.getVectorElementType();
int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
// vector_shuffle <0,1,6,7> lhs, rhs
// -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
//
// vector_shuffle <6,7,2,3> lhs, rhs
// -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
//
// vector_shuffle <6,7,0,1> lhs, rhs
// -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
// Avoid scalarizing when both halves are reading from consecutive elements.
SmallVector<SDValue, 4> Pieces;
for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
if (elementPairIsContiguous(SVN->getMask(), I)) {
const int Idx = SVN->getMaskElt(I);
int VecIdx = Idx < SrcNumElts ? 0 : 1;
int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
PackVT, SVN->getOperand(VecIdx),
DAG.getConstant(EltIdx, SL, MVT::i32));
Pieces.push_back(SubVec);
} else {
const int Idx0 = SVN->getMaskElt(I);
const int Idx1 = SVN->getMaskElt(I + 1);
int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
SDValue Vec0 = SVN->getOperand(VecIdx0);
SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
SDValue Vec1 = SVN->getOperand(VecIdx1);
SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
}
}
return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
}
SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
SelectionDAG &DAG) const {
SDLoc SL(Op);
EVT VT = Op.getValueType();
if (VT == MVT::v4i16 || VT == MVT::v4f16) {
EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
// Turn into pair of packed build_vectors.
// TODO: Special case for constants that can be materialized with s_mov_b64.
SDValue Lo = DAG.getBuildVector(HalfVT, SL,
{ Op.getOperand(0), Op.getOperand(1) });
SDValue Hi = DAG.getBuildVector(HalfVT, SL,
{ Op.getOperand(2), Op.getOperand(3) });
SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
}
assert(VT == MVT::v2f16 || VT == MVT::v2i16);
assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
SDValue Lo = Op.getOperand(0);
SDValue Hi = Op.getOperand(1);
// Avoid adding defined bits with the zero_extend.
if (Hi.isUndef()) {
Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
}
Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
DAG.getConstant(16, SL, MVT::i32));
if (Lo.isUndef())
return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
return DAG.getNode(ISD::BITCAST, SL, VT, Or);
}
bool
SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
// We can fold offsets for anything that doesn't require a GOT relocation.
return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
!shouldEmitGOTReloc(GA->getGlobal());
}
static SDValue
buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
const SDLoc &DL, unsigned Offset, EVT PtrVT,
unsigned GAFlags = SIInstrInfo::MO_NONE) {
// In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
// lowered to the following code sequence:
//
// For constant address space:
// s_getpc_b64 s[0:1]
// s_add_u32 s0, s0, $symbol
// s_addc_u32 s1, s1, 0
//
// s_getpc_b64 returns the address of the s_add_u32 instruction and then
// a fixup or relocation is emitted to replace $symbol with a literal
// constant, which is a pc-relative offset from the encoding of the $symbol
// operand to the global variable.
//
// For global address space:
// s_getpc_b64 s[0:1]
// s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
// s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
//
// s_getpc_b64 returns the address of the s_add_u32 instruction and then
// fixups or relocations are emitted to replace $symbol@*@lo and
// $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
// which is a 64-bit pc-relative offset from the encoding of the $symbol
// operand to the global variable.
//
// What we want here is an offset from the value returned by s_getpc
// (which is the address of the s_add_u32 instruction) to the global
// variable, but since the encoding of $symbol starts 4 bytes after the start
// of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
// small. This requires us to add 4 to the global variable offset in order to
// compute the correct address.
SDValue PtrLo =
DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
SDValue PtrHi;
if (GAFlags == SIInstrInfo::MO_NONE) {
PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
} else {
PtrHi =
DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
}
return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
}
SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
SDValue Op,
SelectionDAG &DAG) const {
GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
const GlobalValue *GV = GSD->getGlobal();
if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
(!GV->hasExternalLinkage() ||
getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)) ||
GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
SDLoc DL(GSD);
EVT PtrVT = Op.getValueType();
if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
SIInstrInfo::MO_ABS32_LO);
return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
}
if (shouldEmitFixup(GV))
return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
else if (shouldEmitPCReloc(GV))
return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
SIInstrInfo::MO_REL32);
SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
SIInstrInfo::MO_GOTPCREL32);
Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
const DataLayout &DataLayout = DAG.getDataLayout();
unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
MachinePointerInfo PtrInfo
= MachinePointerInfo::getGOT(DAG.getMachineFunction());
return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
MachineMemOperand::MODereferenceable |
MachineMemOperand::MOInvariant);
}
SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
const SDLoc &DL, SDValue V) const {
// We can't use S_MOV_B32 directly, because there is no way to specify m0 as
// the destination register.
//
// We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
// so we will end up with redundant moves to m0.
//
// We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
// A Null SDValue creates a glue result.
SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
V, Chain);
return SDValue(M0, 0);
}
SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
SDValue Op,
MVT VT,
unsigned Offset) const {
SDLoc SL(Op);
SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
DAG.getEntryNode(), Offset, 4, false);
// The local size values will have the hi 16-bits as zero.
return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
DAG.getValueType(VT));
}
static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
EVT VT) {
DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
"non-hsa intrinsic with hsa target",
DL.getDebugLoc());
DAG.getContext()->diagnose(BadIntrin);
return DAG.getUNDEF(VT);
}
static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
EVT VT) {
DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
"intrinsic not supported on subtarget",
DL.getDebugLoc());
DAG.getContext()->diagnose(BadIntrin);
return DAG.getUNDEF(VT);
}
static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
ArrayRef<SDValue> Elts) {
assert(!Elts.empty());
MVT Type;
unsigned NumElts;
if (Elts.size() == 1) {
Type = MVT::f32;
NumElts = 1;
} else if (Elts.size() == 2) {
Type = MVT::v2f32;
NumElts = 2;
} else if (Elts.size() <= 4) {
Type = MVT::v4f32;
NumElts = 4;
} else if (Elts.size() <= 8) {
Type = MVT::v8f32;
NumElts = 8;
} else {
assert(Elts.size() <= 16);
Type = MVT::v16f32;
NumElts = 16;
}
SmallVector<SDValue, 16> VecElts(NumElts);
for (unsigned i = 0; i < Elts.size(); ++i) {
SDValue Elt = Elts[i];
if (Elt.getValueType() != MVT::f32)
Elt = DAG.getBitcast(MVT::f32, Elt);
VecElts[i] = Elt;
}
for (unsigned i = Elts.size(); i < NumElts; ++i)
VecElts[i] = DAG.getUNDEF(MVT::f32);
if (NumElts == 1)
return VecElts[0];
return DAG.getBuildVector(Type, DL, VecElts);
}
static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
SDValue *GLC, SDValue *SLC, SDValue *DLC) {
auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
uint64_t Value = CachePolicyConst->getZExtValue();
SDLoc DL(CachePolicy);
if (GLC) {
*GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
Value &= ~(uint64_t)0x1;
}
if (SLC) {
*SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
Value &= ~(uint64_t)0x2;
}
if (DLC) {
*DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
Value &= ~(uint64_t)0x4;
}
return Value == 0;
}
// Re-construct the required return value for a image load intrinsic.
// This is more complicated due to the optional use TexFailCtrl which means the required
// return type is an aggregate
static SDValue constructRetValue(SelectionDAG &DAG,
MachineSDNode *Result,
ArrayRef<EVT> ResultTypes,
bool IsTexFail, bool Unpacked, bool IsD16,
int DMaskPop, int NumVDataDwords,
const SDLoc &DL, LLVMContext &Context) {
// Determine the required return type. This is the same regardless of IsTexFail flag
EVT ReqRetVT = ResultTypes[0];
EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT;
int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT;
EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts)
: AdjEltVT
: ReqRetVT;
// Extract data part of the result
// Bitcast the result to the same type as the required return type
int NumElts;
if (IsD16 && !Unpacked)
NumElts = NumVDataDwords << 1;
else
NumElts = NumVDataDwords;
EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts)
: AdjEltVT;
// Special case for v6f16. Rather than add support for this, use v3i32 to
// extract the data elements
bool V6F16Special = false;
if (NumElts == 6) {
CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2);
DMaskPop >>= 1;
ReqRetNumElts >>= 1;
V6F16Special = true;
AdjVT = MVT::v2i32;
}
SDValue N = SDValue(Result, 0);
SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N);
// Iterate over the result
SmallVector<SDValue, 4> BVElts;
if (CastVT.isVector()) {
DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop);
} else {
BVElts.push_back(CastRes);
}
int ExtraElts = ReqRetNumElts - DMaskPop;
while(ExtraElts--)
BVElts.push_back(DAG.getUNDEF(AdjEltVT));
SDValue PreTFCRes;
if (ReqRetNumElts > 1) {
SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts);
if (IsD16 && Unpacked)
PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked);
else
PreTFCRes = NewVec;
} else {
PreTFCRes = BVElts[0];
}
if (V6F16Special)
PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes);
if (!IsTexFail) {
if (Result->getNumValues() > 1)
return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL);
else
return PreTFCRes;
}
// Extract the TexFail result and insert into aggregate return
SmallVector<SDValue, 1> TFCElt;
DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1);
SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]);
return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL);
}
static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
SDValue *LWE, bool &IsTexFail) {
auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
uint64_t Value = TexFailCtrlConst->getZExtValue();
if (Value) {
IsTexFail = true;
}
SDLoc DL(TexFailCtrlConst);
*TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
Value &= ~(uint64_t)0x1;
*LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
Value &= ~(uint64_t)0x2;
return Value == 0;
}
SDValue SITargetLowering::lowerImage(SDValue Op,
const AMDGPU::ImageDimIntrinsicInfo *Intr,
SelectionDAG &DAG) const {
SDLoc DL(Op);
MachineFunction &MF = DAG.getMachineFunction();
const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
unsigned IntrOpcode = Intr->BaseOpcode;
bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
bool IsD16 = false;
bool IsA16 = false;
SDValue VData;
int NumVDataDwords;
bool AdjustRetType = false;
unsigned AddrIdx; // Index of first address argument
unsigned DMask;
unsigned DMaskLanes = 0;
if (BaseOpcode->Atomic) {
VData = Op.getOperand(2);
bool Is64Bit = VData.getValueType() == MVT::i64;
if (BaseOpcode->AtomicX2) {
SDValue VData2 = Op.getOperand(3);
VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
{VData, VData2});
if (Is64Bit)
VData = DAG.getBitcast(MVT::v4i32, VData);
ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
DMask = Is64Bit ? 0xf : 0x3;
NumVDataDwords = Is64Bit ? 4 : 2;
AddrIdx = 4;
} else {
DMask = Is64Bit ? 0x3 : 0x1;
NumVDataDwords = Is64Bit ? 2 : 1;
AddrIdx = 3;
}
} else {
unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
DMask = DMaskConst->getZExtValue();
DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
if (BaseOpcode->Store) {
VData = Op.getOperand(2);
MVT StoreVT = VData.getSimpleValueType();
if (StoreVT.getScalarType() == MVT::f16) {
if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
return Op; // D16 is unsupported for this instruction
IsD16 = true;
VData = handleD16VData(VData, DAG);
}
NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
} else {
// Work out the num dwords based on the dmask popcount and underlying type
// and whether packing is supported.
MVT LoadVT = ResultTypes[0].getSimpleVT();
if (LoadVT.getScalarType() == MVT::f16) {
if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
return Op; // D16 is unsupported for this instruction
IsD16 = true;
}
// Confirm that the return type is large enough for the dmask specified
if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
(!LoadVT.isVector() && DMaskLanes > 1))
return Op;
if (IsD16 && !Subtarget->hasUnpackedD16VMem())
NumVDataDwords = (DMaskLanes + 1) / 2;
else
NumVDataDwords = DMaskLanes;
AdjustRetType = true;
}
AddrIdx = DMaskIdx + 1;
}
unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
NumCoords + NumLCM;
unsigned NumMIVAddrs = NumVAddrs;
SmallVector<SDValue, 4> VAddrs;
// Optimize _L to _LZ when _L is zero
if (LZMappingInfo) {
if (auto ConstantLod =
dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
if (ConstantLod->isZero() || ConstantLod->isNegative()) {
IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l
NumMIVAddrs--; // remove 'lod'
}
}
}
// Optimize _mip away, when 'lod' is zero
if (MIPMappingInfo) {
if (auto ConstantLod =
dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
if (ConstantLod->isNullValue()) {
IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip
NumMIVAddrs--; // remove 'lod'
}
}
}
// Check for 16 bit addresses and pack if true.
unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
const MVT VAddrScalarVT = VAddrVT.getScalarType();
if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) &&
ST->hasFeature(AMDGPU::FeatureR128A16)) {
IsA16 = true;
const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
SDValue AddrLo, AddrHi;
// Push back extra arguments.
if (i < DimIdx) {
AddrLo = Op.getOperand(i);
} else {
AddrLo = Op.getOperand(i);
// Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
// in 1D, derivatives dx/dh and dx/dv are packed with undef.
if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
((NumGradients / 2) % 2 == 1 &&
(i == DimIdx + (NumGradients / 2) - 1 ||
i == DimIdx + NumGradients - 1))) {
AddrHi = DAG.getUNDEF(MVT::f16);
} else {
AddrHi = Op.getOperand(i + 1);
i++;
}
AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT,
{AddrLo, AddrHi});
AddrLo = DAG.getBitcast(MVT::i32, AddrLo);
}
VAddrs.push_back(AddrLo);
}
} else {
for (unsigned i = 0; i < NumMIVAddrs; ++i)
VAddrs.push_back(Op.getOperand(AddrIdx + i));
}
// If the register allocator cannot place the address registers contiguously
// without introducing moves, then using the non-sequential address encoding
// is always preferable, since it saves VALU instructions and is usually a
// wash in terms of code size or even better.
//
// However, we currently have no way of hinting to the register allocator that
// MIMG addresses should be placed contiguously when it is possible to do so,
// so force non-NSA for the common 2-address case as a heuristic.
//
// SIShrinkInstructions will convert NSA encodings to non-NSA after register
// allocation when possible.
bool UseNSA =
ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
SDValue VAddr;
if (!UseNSA)
VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
unsigned CtrlIdx; // Index of texfailctrl argument
SDValue Unorm;
if (!BaseOpcode->Sampler) {
Unorm = True;
CtrlIdx = AddrIdx + NumVAddrs + 1;
} else {
auto UnormConst =
cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
Unorm = UnormConst->getZExtValue() ? True : False;
CtrlIdx = AddrIdx + NumVAddrs + 3;
}
SDValue TFE;
SDValue LWE;
SDValue TexFail = Op.getOperand(CtrlIdx);
bool IsTexFail = false;
if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
return Op;
if (IsTexFail) {
if (!DMaskLanes) {
// Expecting to get an error flag since TFC is on - and dmask is 0
// Force dmask to be at least 1 otherwise the instruction will fail
DMask = 0x1;
DMaskLanes = 1;
NumVDataDwords = 1;
}
NumVDataDwords += 1;
AdjustRetType = true;
}
// Has something earlier tagged that the return type needs adjusting
// This happens if the instruction is a load or has set TexFailCtrl flags
if (AdjustRetType) {
// NumVDataDwords reflects the true number of dwords required in the return type
if (DMaskLanes == 0 && !BaseOpcode->Store) {
// This is a no-op load. This can be eliminated
SDValue Undef = DAG.getUNDEF(Op.getValueType());
if (isa<MemSDNode>(Op))
return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
return Undef;
}
EVT NewVT = NumVDataDwords > 1 ?
EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords)
: MVT::f32;
ResultTypes[0] = NewVT;
if (ResultTypes.size() == 3) {
// Original result was aggregate type used for TexFailCtrl results
// The actual instruction returns as a vector type which has now been
// created. Remove the aggregate result.
ResultTypes.erase(&ResultTypes[1]);
}
}
SDValue GLC;
SDValue SLC;
SDValue DLC;
if (BaseOpcode->Atomic) {
GLC = True; // TODO no-return optimization
if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
IsGFX10 ? &DLC : nullptr))
return Op;
} else {
if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
IsGFX10 ? &DLC : nullptr))
return Op;
}
SmallVector<SDValue, 26> Ops;
if (BaseOpcode->Store || BaseOpcode->Atomic)
Ops.push_back(VData); // vdata
if (UseNSA) {
for (const SDValue &Addr : VAddrs)
Ops.push_back(Addr);
} else {
Ops.push_back(VAddr);
}
Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
if (BaseOpcode->Sampler)
Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
if (IsGFX10)
Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
Ops.push_back(Unorm);
if (IsGFX10)
Ops.push_back(DLC);
Ops.push_back(GLC);
Ops.push_back(SLC);
Ops.push_back(IsA16 && // a16 or r128
ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
Ops.push_back(TFE); // tfe
Ops.push_back(LWE); // lwe
if (!IsGFX10)
Ops.push_back(DimInfo->DA ? True : False);
if (BaseOpcode->HasD16)
Ops.push_back(IsD16 ? True : False);
if (isa<MemSDNode>(Op))
Ops.push_back(Op.getOperand(0)); // chain
int NumVAddrDwords =
UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
int Opcode = -1;
if (IsGFX10) {
Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
UseNSA ? AMDGPU::MIMGEncGfx10NSA
: AMDGPU::MIMGEncGfx10Default,
NumVDataDwords, NumVAddrDwords);
} else {
if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
NumVDataDwords, NumVAddrDwords);
if (Opcode == -1)
Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
NumVDataDwords, NumVAddrDwords);
}
assert(Opcode != -1);
MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
MachineMemOperand *MemRef = MemOp->getMemOperand();
DAG.setNodeMemRefs(NewNode, {MemRef});
}
if (BaseOpcode->AtomicX2) {
SmallVector<SDValue, 1> Elt;
DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
} else if (!BaseOpcode->Store) {
return constructRetValue(DAG, NewNode,
OrigResultTypes, IsTexFail,
Subtarget->hasUnpackedD16VMem(), IsD16,
DMaskLanes, NumVDataDwords, DL,
*DAG.getContext());
}
return SDValue(NewNode, 0);
}
SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
SDValue Offset, SDValue GLC, SDValue DLC,
SelectionDAG &DAG) const {
MachineFunction &MF = DAG.getMachineFunction();
MachineMemOperand *MMO = MF.getMachineMemOperand(
MachinePointerInfo(),
MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
MachineMemOperand::MOInvariant,
VT.getStoreSize(), VT.getStoreSize());
if (!Offset->isDivergent()) {
SDValue Ops[] = {
Rsrc,
Offset, // Offset
GLC,
DLC,
};
return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
DAG.getVTList(VT), Ops, VT, MMO);
}
// We have a divergent offset. Emit a MUBUF buffer load instead. We can
// assume that the buffer is unswizzled.
SmallVector<SDValue, 4> Loads;
unsigned NumLoads = 1;
MVT LoadVT = VT.getSimpleVT();
unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
assert((LoadVT.getScalarType() == MVT::i32 ||
LoadVT.getScalarType() == MVT::f32) &&
isPowerOf2_32(NumElts));
if (NumElts == 8 || NumElts == 16) {
NumLoads = NumElts == 16 ? 4 : 2;
LoadVT = MVT::v4i32;
}
SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue();
SDValue Ops[] = {
DAG.getEntryNode(), // Chain
Rsrc, // rsrc
DAG.getConstant(0, DL, MVT::i32), // vindex
{}, // voffset
{}, // soffset
{}, // offset
DAG.getTargetConstant(CachePolicy, DL, MVT::i32), // cachepolicy
DAG.getTargetConstant(0, DL, MVT::i1), // idxen
};
// Use the alignment to ensure that the required offsets will fit into the
// immediate offsets.
setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
for (unsigned i = 0; i < NumLoads; ++i) {
Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList,
Ops, LoadVT, MMO));
}
if (VT == MVT::v8i32 || VT == MVT::v16i32)
return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
return Loads[0];
}
SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
SelectionDAG &DAG) const {
MachineFunction &MF = DAG.getMachineFunction();
auto MFI = MF.getInfo<SIMachineFunctionInfo>();
EVT VT = Op.getValueType();
SDLoc DL(Op);
unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
// TODO: Should this propagate fast-math-flags?
switch (IntrinsicID) {
case Intrinsic::amdgcn_implicit_buffer_ptr: {
if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
return emitNonHSAIntrinsicError(DAG, DL, VT);
return getPreloadedValue(DAG, *MFI, VT,
AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
}
case Intrinsic::amdgcn_dispatch_ptr:
case Intrinsic::amdgcn_queue_ptr: {
if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
DiagnosticInfoUnsupported BadIntrin(
MF.getFunction(), "unsupported hsa intrinsic without hsa target",
DL.getDebugLoc());
DAG.getContext()->diagnose(BadIntrin);
return DAG.getUNDEF(VT);
}
auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
return getPreloadedValue(DAG, *MFI, VT, RegID);
}
case Intrinsic::amdgcn_implicitarg_ptr: {
if (MFI->isEntryFunction())
return getImplicitArgPtr(DAG, DL);
return getPreloadedValue(DAG, *MFI, VT,
AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
}
case Intrinsic::amdgcn_kernarg_segment_ptr: {
return getPreloadedValue(DAG, *MFI, VT,
AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
}
case Intrinsic::amdgcn_dispatch_id: {
return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
}
case Intrinsic::amdgcn_rcp:
return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
case Intrinsic::amdgcn_rsq:
return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
case Intrinsic::amdgcn_rsq_legacy:
if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
return emitRemovedIntrinsicError(DAG, DL, VT);
return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
case Intrinsic::amdgcn_rcp_legacy:
if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
return emitRemovedIntrinsicError(DAG, DL, VT);
return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
case Intrinsic::amdgcn_rsq_clamp: {
if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
Type *Type = VT.getTypeForEVT(*DAG.getContext());
APFloat Max = APFloat::getLargest(Type->getFltSemantics());
APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
DAG.getConstantFP(Max, DL, VT));
return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
DAG.getConstantFP(Min, DL, VT));
}
case Intrinsic::r600_read_ngroups_x:
if (Subtarget->isAmdHsaOS())
return emitNonHSAIntrinsicError(DAG, DL, VT);
return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
SI::KernelInputOffsets::NGROUPS_X, 4, false);
case Intrinsic::r600_read_ngroups_y:
if (Subtarget->isAmdHsaOS())
return emitNonHSAIntrinsicError(DAG, DL, VT);
return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
SI::KernelInputOffsets::NGROUPS_Y, 4, false);
case Intrinsic::r600_read_ngroups_z:
if (Subtarget->isAmdHsaOS())
return emitNonHSAIntrinsicError(DAG, DL, VT);
return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
SI::KernelInputOffsets::NGROUPS_Z, 4, false);
case Intrinsic::r600_read_global_size_x:
if (Subtarget->isAmdHsaOS())
return emitNonHSAIntrinsicError(DAG, DL, VT);
return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
case Intrinsic::r600_read_global_size_y:
if (Subtarget->isAmdHsaOS())
return emitNonHSAIntrinsicError(DAG, DL, VT);
return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
case Intrinsic::r600_read_global_size_z:
if (Subtarget->isAmdHsaOS())
return emitNonHSAIntrinsicError(DAG, DL, VT);
return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
case Intrinsic::r600_read_local_size_x:
if (Subtarget->isAmdHsaOS())
return emitNonHSAIntrinsicError(DAG, DL, VT);
return lowerImplicitZextParam(DAG, Op, MVT::i16,
SI::KernelInputOffsets::LOCAL_SIZE_X);
case Intrinsic::r600_read_local_size_y:
if (Subtarget->isAmdHsaOS())
return emitNonHSAIntrinsicError(DAG, DL, VT);
return lowerImplicitZextParam(DAG, Op, MVT::i16,
SI::KernelInputOffsets::LOCAL_SIZE_Y);
case Intrinsic::r600_read_local_size_z:
if (Subtarget->isAmdHsaOS())
return emitNonHSAIntrinsicError(DAG, DL, VT);
return lowerImplicitZextParam(DAG, Op, MVT::i16,
SI::KernelInputOffsets::LOCAL_SIZE_Z);
case Intrinsic::amdgcn_workgroup_id_x:
case Intrinsic::r600_read_tgid_x:
return getPreloadedValue(DAG, *MFI, VT,
AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
case Intrinsic::amdgcn_workgroup_id_y:
case Intrinsic::r600_read_tgid_y:
return getPreloadedValue(DAG, *MFI, VT,
AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
case Intrinsic::amdgcn_workgroup_id_z:
case Intrinsic::r600_read_tgid_z:
return getPreloadedValue(DAG, *MFI, VT,
AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
case Intrinsic::amdgcn_workitem_id_x:
case Intrinsic::r600_read_tidig_x:
return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
SDLoc(DAG.getEntryNode()),
MFI->getArgInfo().WorkItemIDX);
case Intrinsic::amdgcn_workitem_id_y:
case Intrinsic::r600_read_tidig_y:
return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
SDLoc(DAG.getEntryNode()),
MFI->getArgInfo().WorkItemIDY);
case Intrinsic::amdgcn_workitem_id_z:
case Intrinsic::r600_read_tidig_z:
return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
SDLoc(DAG.getEntryNode()),
MFI->getArgInfo().WorkItemIDZ);
case Intrinsic::amdgcn_wavefrontsize:
return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
SDLoc(Op), MVT::i32);
case Intrinsic::amdgcn_s_buffer_load: {
bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
SDValue GLC;
SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
IsGFX10 ? &DLC : nullptr))
return Op;
return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC,
DAG);
}
case Intrinsic::amdgcn_fdiv_fast:
return lowerFDIV_FAST(Op, DAG);
case Intrinsic::amdgcn_interp_mov: {
SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
SDValue Glue = M0.getValue(1);
return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
Op.getOperand(2), Op.getOperand(3), Glue);
}
case Intrinsic::amdgcn_interp_p1: {
SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
SDValue Glue = M0.getValue(1);
return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
Op.getOperand(2), Op.getOperand(3), Glue);
}
case Intrinsic::amdgcn_interp_p2: {
SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
SDValue Glue = SDValue(M0.getNode(), 1);
return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
Glue);
}
case Intrinsic::amdgcn_interp_p1_f16: {
SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
SDValue Glue = M0.getValue(1);
if (getSubtarget()->getLDSBankCount() == 16) {
// 16 bank LDS
SDValue S = DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
DAG.getConstant(2, DL, MVT::i32), // P0
Op.getOperand(2), // Attrchan
Op.getOperand(3), // Attr
Glue);
SDValue Ops[] = {
Op.getOperand(1), // Src0
Op.getOperand(2), // Attrchan
Op.getOperand(3), // Attr
DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers
S, // Src2 - holds two f16 values selected by high
DAG.getTargetConstant(0, DL, MVT::i32), // $src2_modifiers
Op.getOperand(4), // high
DAG.getTargetConstant(0, DL, MVT::i1), // $clamp
DAG.getTargetConstant(0, DL, MVT::i32) // $omod
};
return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops);
} else {
// 32 bank LDS
SDValue Ops[] = {
Op.getOperand(1), // Src0
Op.getOperand(2), // Attrchan
Op.getOperand(3), // Attr
DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers
Op.getOperand(4), // high
DAG.getTargetConstant(0, DL, MVT::i1), // $clamp
DAG.getTargetConstant(0, DL, MVT::i32), // $omod
Glue
};
return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops);
}
}
case Intrinsic::amdgcn_interp_p2_f16: {
SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(6));
SDValue Glue = SDValue(M0.getNode(), 1);
SDValue Ops[] = {
Op.getOperand(2), // Src0
Op.getOperand(3), // Attrchan
Op.getOperand(4), // Attr
DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers
Op.getOperand(1), // Src2
DAG.getTargetConstant(0, DL, MVT::i32), // $src2_modifiers
Op.getOperand(5), // high
DAG.getTargetConstant(0, DL, MVT::i1), // $clamp
Glue
};
return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops);
}
case Intrinsic::amdgcn_sin:
return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
case Intrinsic::amdgcn_cos:
return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
case Intrinsic::amdgcn_mul_u24:
return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
case Intrinsic::amdgcn_mul_i24:
return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
case Intrinsic::amdgcn_log_clamp: {
if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
return SDValue();
DiagnosticInfoUnsupported BadIntrin(
MF.getFunction(), "intrinsic not supported on subtarget",
DL.getDebugLoc());
DAG.getContext()->diagnose(BadIntrin);
return DAG.getUNDEF(VT);
}
case Intrinsic::amdgcn_ldexp:
return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
Op.getOperand(1), Op.getOperand(2));
case Intrinsic::amdgcn_fract:
return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
case Intrinsic::amdgcn_class:
return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
Op.getOperand(1), Op.getOperand(2));
case Intrinsic::amdgcn_div_fmas:
return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
Op.getOperand(4));
case Intrinsic::amdgcn_div_fixup:
return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
case Intrinsic::amdgcn_trig_preop:
return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
Op.getOperand(1), Op.getOperand(2));
case Intrinsic::amdgcn_div_scale: {
const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
// Translate to the operands expected by the machine instruction. The
// first parameter must be the same as the first instruction.
SDValue Numerator = Op.getOperand(1);
SDValue Denominator = Op.getOperand(2);
// Note this order is opposite of the machine instruction's operations,
// which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
// intrinsic has the numerator as the first operand to match a normal
// division operation.
SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
Denominator, Numerator);
}
case Intrinsic::amdgcn_icmp: {
// There is a Pat that handles this variant, so return it as-is.
if (Op.getOperand(1).getValueType() == MVT::i1 &&
Op.getConstantOperandVal(2) == 0 &&
Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
return Op;
return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
}
case Intrinsic::amdgcn_fcmp: {
return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
}
case Intrinsic::amdgcn_fmed3:
return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
case Intrinsic::amdgcn_fdot2:
return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
Op.getOperand(4));
case Intrinsic::amdgcn_fmul_legacy:
return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
Op.getOperand(1), Op.getOperand(2));
case Intrinsic::amdgcn_sffbh:
return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
case Intrinsic::amdgcn_sbfe:
return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
case Intrinsic::amdgcn_ubfe:
return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
case Intrinsic::amdgcn_cvt_pkrtz:
case Intrinsic::amdgcn_cvt_pknorm_i16:
case Intrinsic::amdgcn_cvt_pknorm_u16:
case Intrinsic::amdgcn_cvt_pk_i16:
case Intrinsic::amdgcn_cvt_pk_u16: {
// FIXME: Stop adding cast if v2f16/v2i16 are legal.
EVT VT = Op.getValueType();
unsigned Opcode;
if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
Opcode = AMDGPUISD::CVT_PK_I16_I32;
else
Opcode = AMDGPUISD::CVT_PK_U16_U32;
if (isTypeLegal(VT))
return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
Op.getOperand(1), Op.getOperand(2));
return DAG.getNode(ISD::BITCAST, DL, VT, Node);
}
case Intrinsic::amdgcn_fmad_ftz:
return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
Op.getOperand(2), Op.getOperand(3));
case Intrinsic::amdgcn_if_break:
return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
Op->getOperand(1), Op->getOperand(2)), 0);
case Intrinsic::amdgcn_groupstaticsize: {
Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
return Op;
const Module *M = MF.getFunction().getParent();
const GlobalValue *GV =
M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
SIInstrInfo::MO_ABS32_LO);
return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
}
case Intrinsic::amdgcn_is_shared:
case Intrinsic::amdgcn_is_private: {
SDLoc SL(Op);
unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
SDValue Aperture = getSegmentAperture(AS, SL, DAG);
SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
Op.getOperand(1));
SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
DAG.getConstant(1, SL, MVT::i32));
return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
}
default:
if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
return lowerImage(Op, ImageDimIntr, DAG);
return Op;
}
}
SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
SelectionDAG &DAG) const {
unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
SDLoc DL(Op);
switch (IntrID) {
case Intrinsic::amdgcn_ds_ordered_add:
case Intrinsic::amdgcn_ds_ordered_swap: {
MemSDNode *M = cast<MemSDNode>(Op);
SDValue Chain = M->getOperand(0);
SDValue M0 = M->getOperand(2);
SDValue Value = M->getOperand(3);
unsigned IndexOperand = M->getConstantOperandVal(7);
unsigned WaveRelease = M->getConstantOperandVal(8);
unsigned WaveDone = M->getConstantOperandVal(9);
unsigned ShaderType;
unsigned Instruction;
unsigned OrderedCountIndex = IndexOperand & 0x3f;
IndexOperand &= ~0x3f;
unsigned CountDw = 0;
if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
CountDw = (IndexOperand >> 24) & 0xf;
IndexOperand &= ~(0xf << 24);
if (CountDw < 1 || CountDw > 4) {
report_fatal_error(
"ds_ordered_count: dword count must be between 1 and 4");
}
}
if (IndexOperand)
report_fatal_error("ds_ordered_count: bad index operand");
switch (IntrID) {
case Intrinsic::amdgcn_ds_ordered_add:
Instruction = 0;
break;
case Intrinsic::amdgcn_ds_ordered_swap:
Instruction = 1;
break;
}
if (WaveDone && !WaveRelease)
report_fatal_error("ds_ordered_count: wave_done requires wave_release");
switch (DAG.getMachineFunction().getFunction().getCallingConv()) {
case CallingConv::AMDGPU_CS:
case CallingConv::AMDGPU_KERNEL:
ShaderType = 0;
break;
case CallingConv::AMDGPU_PS:
ShaderType = 1;
break;
case CallingConv::AMDGPU_VS:
ShaderType = 2;
break;
case CallingConv::AMDGPU_GS:
ShaderType = 3;
break;
default:
report_fatal_error("ds_ordered_count unsupported for this calling conv");
}
unsigned Offset0 = OrderedCountIndex << 2;
unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
(Instruction << 4);
if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
Offset1 |= (CountDw - 1) << 6;
unsigned Offset = Offset0 | (Offset1 << 8);
SDValue Ops[] = {
Chain,
Value,
DAG.getTargetConstant(Offset, DL, MVT::i16),
copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
};
return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
M->getVTList(), Ops, M->getMemoryVT(),
M->getMemOperand());
}
case Intrinsic::amdgcn_ds_fadd: {
MemSDNode *M = cast<MemSDNode>(Op);
unsigned Opc;
switch (IntrID) {
case Intrinsic::amdgcn_ds_fadd:
Opc = ISD::ATOMIC_LOAD_FADD;
break;
}
return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
M->getOperand(0), M->getOperand(2), M->getOperand(3),
M->getMemOperand());
}
case Intrinsic::amdgcn_atomic_inc:
case Intrinsic::amdgcn_atomic_dec:
case Intrinsic::amdgcn_ds_fmin:
case Intrinsic::amdgcn_ds_fmax: {
MemSDNode *M = cast<MemSDNode>(Op);
unsigned Opc;
switch (IntrID) {
case Intrinsic::amdgcn_atomic_inc:
Opc = AMDGPUISD::ATOMIC_INC;
break;
case Intrinsic::amdgcn_atomic_dec:
Opc = AMDGPUISD::ATOMIC_DEC;
break;
case Intrinsic::amdgcn_ds_fmin:
Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
break;
case Intrinsic::amdgcn_ds_fmax:
Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
break;
default:
llvm_unreachable("Unknown intrinsic!");
}
SDValue Ops[] = {
M->getOperand(0), // Chain
M->getOperand(2), // Ptr
M->getOperand(3) // Value
};
return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
M->getMemoryVT(), M->getMemOperand());
}
case Intrinsic::amdgcn_buffer_load:
case Intrinsic::amdgcn_buffer_load_ubyte:
case Intrinsic::amdgcn_buffer_load_ushort:
case Intrinsic::amdgcn_buffer_load_format: {
unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
unsigned IdxEn = 1;
if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
IdxEn = Idx->getZExtValue() != 0;
SDValue Ops[] = {
Op.getOperand(0), // Chain
Op.getOperand(2), // rsrc
Op.getOperand(3), // vindex
SDValue(), // voffset -- will be set by setBufferOffsets
SDValue(), // soffset -- will be set by setBufferOffsets
SDValue(), // offset -- will be set by setBufferOffsets
DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
};
setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
unsigned Opc = 0;
switch (IntrID) {
case Intrinsic::amdgcn_buffer_load: Opc = AMDGPUISD::BUFFER_LOAD; break;
case Intrinsic::amdgcn_buffer_load_ubyte: Opc = AMDGPUISD::BUFFER_LOAD_UBYTE; break;
case Intrinsic::amdgcn_buffer_load_ushort: Opc = AMDGPUISD::BUFFER_LOAD_USHORT; break;
case Intrinsic::amdgcn_buffer_load_format: Opc = AMDGPUISD::BUFFER_LOAD_FORMAT; break;
default: llvm_unreachable("Unexpected IntrinsicID");
}
EVT VT = Op.getValueType();
EVT IntVT = VT.changeTypeToInteger();
auto *M = cast<MemSDNode>(Op);
EVT LoadVT = Op.getValueType();
if (LoadVT.getScalarType() == MVT::f16)
return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
M, DAG, Ops);
// Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
if (LoadVT.getScalarType() == MVT::i8 ||
LoadVT.getScalarType() == MVT::i16)
return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
M->getMemOperand(), DAG);
}
case Intrinsic::amdgcn_raw_buffer_load:
case Intrinsic::amdgcn_raw_buffer_load_format: {
const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
SDValue Ops[] = {
Op.getOperand(0), // Chain
Op.getOperand(2), // rsrc
DAG.getConstant(0, DL, MVT::i32), // vindex
Offsets.first, // voffset
Op.getOperand(4), // soffset
Offsets.second, // offset
Op.getOperand(5), // cachepolicy
DAG.getTargetConstant(0, DL, MVT::i1), // idxen
};
return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
}
case Intrinsic::amdgcn_struct_buffer_load:
case Intrinsic::amdgcn_struct_buffer_load_format: {
const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
SDValue Ops[] = {
Op.getOperand(0), // Chain
Op.getOperand(2), // rsrc
Op.getOperand(3), // vindex
Offsets.first, // voffset
Op.getOperand(5), // soffset
Offsets.second, // offset
Op.getOperand(6), // cachepolicy
DAG.getTargetConstant(1, DL, MVT::i1), // idxen
};
return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
}
case Intrinsic::amdgcn_tbuffer_load: {
MemSDNode *M = cast<MemSDNode>(Op);
EVT LoadVT = Op.getValueType();
unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
unsigned IdxEn = 1;
if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
IdxEn = Idx->getZExtValue() != 0;
SDValue Ops[] = {
Op.getOperand(0), // Chain
Op.getOperand(2), // rsrc
Op.getOperand(3), // vindex
Op.getOperand(4), // voffset
Op.getOperand(5), // soffset
Op.getOperand(6), // offset
DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
};
if (LoadVT.getScalarType() == MVT::f16)
return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
M, DAG, Ops);
return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
DAG);
}
case Intrinsic::amdgcn_raw_tbuffer_load: {
MemSDNode *M = cast<MemSDNode>(Op);
EVT LoadVT = Op.getValueType();
auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
SDValue Ops[] = {
Op.getOperand(0), // Chain
Op.getOperand(2), // rsrc
DAG.getConstant(0, DL, MVT::i32), // vindex
Offsets.first, // voffset
Op.getOperand(4), // soffset
Offsets.second, // offset
Op.getOperand(5), // format
Op.getOperand(6), // cachepolicy
DAG.getTargetConstant(0, DL, MVT::i1), // idxen
};
if (LoadVT.getScalarType() == MVT::f16)
return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
M, DAG, Ops);
return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
DAG);
}
case Intrinsic::amdgcn_struct_tbuffer_load: {
MemSDNode *M = cast<MemSDNode>(Op);
EVT LoadVT = Op.getValueType();
auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
SDValue Ops[] = {
Op.getOperand(0), // Chain
Op.getOperand(2), // rsrc
Op.getOperand(3), // vindex
Offsets.first, // voffset
Op.getOperand(5), // soffset
Offsets.second, // offset
Op.getOperand(6), // format
Op.getOperand(7), // cachepolicy
DAG.getTargetConstant(1, DL, MVT::i1), // idxen
};
if (LoadVT.getScalarType() == MVT::f16)
return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
M, DAG, Ops);
return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
DAG);
}
case Intrinsic::amdgcn_buffer_atomic_swap:
case Intrinsic::amdgcn_buffer_atomic_add:
case Intrinsic::amdgcn_buffer_atomic_sub:
case Intrinsic::amdgcn_buffer_atomic_smin:
case Intrinsic::amdgcn_buffer_atomic_umin:
case Intrinsic::amdgcn_buffer_atomic_smax:
case Intrinsic::amdgcn_buffer_atomic_umax:
case Intrinsic::amdgcn_buffer_atomic_and:
case Intrinsic::amdgcn_buffer_atomic_or:
case Intrinsic::amdgcn_buffer_atomic_xor: {
unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
unsigned IdxEn = 1;
if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
IdxEn = Idx->getZExtValue() != 0;
SDValue Ops[] = {
Op.getOperand(0), // Chain
Op.getOperand(2), // vdata
Op.getOperand(3), // rsrc
Op.getOperand(4), // vindex
SDValue(), // voffset -- will be set by setBufferOffsets
SDValue(), // soffset -- will be set by setBufferOffsets
SDValue(), // offset -- will be set by setBufferOffsets
DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
};
setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
EVT VT = Op.getValueType();
auto *M = cast<MemSDNode>(Op);
unsigned Opcode = 0;
switch (IntrID) {
case Intrinsic::amdgcn_buffer_atomic_swap:
Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
break;
case Intrinsic::amdgcn_buffer_atomic_add:
Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
break;
case Intrinsic::amdgcn_buffer_atomic_sub:
Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
break;
case Intrinsic::amdgcn_buffer_atomic_smin:
Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
break;
case Intrinsic::amdgcn_buffer_atomic_umin:
Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
break;
case Intrinsic::amdgcn_buffer_atomic_smax:
Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
break;
case Intrinsic::amdgcn_buffer_atomic_umax:
Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
break;
case Intrinsic::amdgcn_buffer_atomic_and:
Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
break;
case Intrinsic::amdgcn_buffer_atomic_or:
Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
break;
case Intrinsic::amdgcn_buffer_atomic_xor:
Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
break;
default:
llvm_unreachable("unhandled atomic opcode");
}
return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
M->getMemOperand());
}
case Intrinsic::amdgcn_raw_buffer_atomic_swap:
case Intrinsic::amdgcn_raw_buffer_atomic_add:
case Intrinsic::amdgcn_raw_buffer_atomic_sub:
case Intrinsic::amdgcn_raw_buffer_atomic_smin:
case Intrinsic::amdgcn_raw_buffer_atomic_umin:
case Intrinsic::amdgcn_raw_buffer_atomic_smax:
case Intrinsic::amdgcn_raw_buffer_atomic_umax:
case Intrinsic::amdgcn_raw_buffer_atomic_and:
case Intrinsic::amdgcn_raw_buffer_atomic_or:
case Intrinsic::amdgcn_raw_buffer_atomic_xor:
case Intrinsic::amdgcn_raw_buffer_atomic_inc:
case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
SDValue Ops[] = {
Op.getOperand(0), // Chain
Op.getOperand(2), // vdata
Op.getOperand(3), // rsrc
DAG.getConstant(0, DL, MVT::i32), // vindex
Offsets.first, // voffset
Op.getOperand(5), // soffset
Offsets.second, // offset
Op.getOperand(6), // cachepolicy
DAG.getTargetConstant(0, DL, MVT::i1), // idxen
};
EVT VT = Op.getValueType();
auto *M = cast<MemSDNode>(Op);
unsigned Opcode = 0;
switch (IntrID) {
case Intrinsic::amdgcn_raw_buffer_atomic_swap:
Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
break;
case Intrinsic::amdgcn_raw_buffer_atomic_add:
Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
break;
case Intrinsic::amdgcn_raw_buffer_atomic_sub:
Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
break;
case Intrinsic::amdgcn_raw_buffer_atomic_smin:
Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
break;
case Intrinsic::amdgcn_raw_buffer_atomic_umin:
Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
break;
case Intrinsic::amdgcn_raw_buffer_atomic_smax:
Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
break;
case Intrinsic::amdgcn_raw_buffer_atomic_umax:
Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
break;
case Intrinsic::amdgcn_raw_buffer_atomic_and:
Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
break;
case Intrinsic::amdgcn_raw_buffer_atomic_or:
Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
break;
case Intrinsic::amdgcn_raw_buffer_atomic_xor:
Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
break;
case Intrinsic::amdgcn_raw_buffer_atomic_inc:
Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
break;
case Intrinsic::amdgcn_raw_buffer_atomic_dec:
Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
break;
default:
llvm_unreachable("unhandled atomic opcode");
}
return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
M->getMemOperand());
}
case Intrinsic::amdgcn_struct_buffer_atomic_swap:
case Intrinsic::amdgcn_struct_buffer_atomic_add:
case Intrinsic::amdgcn_struct_buffer_atomic_sub:
case Intrinsic::amdgcn_struct_buffer_atomic_smin:
case Intrinsic::amdgcn_struct_buffer_atomic_umin:
case Intrinsic::amdgcn_struct_buffer_atomic_smax:
case Intrinsic::amdgcn_struct_buffer_atomic_umax:
case Intrinsic::amdgcn_struct_buffer_atomic_and:
case Intrinsic::amdgcn_struct_buffer_atomic_or:
case Intrinsic::amdgcn_struct_buffer_atomic_xor:
case Intrinsic::amdgcn_struct_buffer_atomic_inc:
case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
SDValue Ops[] = {
Op.getOperand(0), // Chain
Op.getOperand(2), // vdata
Op.getOperand(3), // rsrc
Op.getOperand(4), // vindex
Offsets.first, // voffset
Op.getOperand(6), // soffset
Offsets.second, // offset
Op.getOperand(7), // cachepolicy
DAG.getTargetConstant(1, DL, MVT::i1), // idxen
};
EVT VT = Op.getValueType();
auto *M = cast<MemSDNode>(Op);
unsigned Opcode = 0;
switch (IntrID) {
case Intrinsic::amdgcn_struct_buffer_atomic_swap:
Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
break;
case Intrinsic::amdgcn_struct_buffer_atomic_add:
Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
break;
case Intrinsic::amdgcn_struct_buffer_atomic_sub:
Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
break;
case Intrinsic::amdgcn_struct_buffer_atomic_smin:
Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
break;
case Intrinsic::amdgcn_struct_buffer_atomic_umin:
Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
break;
case Intrinsic::amdgcn_struct_buffer_atomic_smax:
Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
break;
case Intrinsic::amdgcn_struct_buffer_atomic_umax:
Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
break;
case Intrinsic::amdgcn_struct_buffer_atomic_and:
Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
break;
case Intrinsic::amdgcn_struct_buffer_atomic_or:
Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
break;
case Intrinsic::amdgcn_struct_buffer_atomic_xor:
Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
break;
case Intrinsic::amdgcn_struct_buffer_atomic_inc:
Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
break;
case Intrinsic::amdgcn_struct_buffer_atomic_dec:
Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
break;
default:
llvm_unreachable("unhandled atomic opcode");
}
return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
M->getMemOperand());
}
case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
unsigned IdxEn = 1;
if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
IdxEn = Idx->getZExtValue() != 0;
SDValue Ops[] = {
Op.getOperand(0), // Chain
Op.getOperand(2), // src
Op.getOperand(3), // cmp
Op.getOperand(4), // rsrc
Op.getOperand(5), // vindex
SDValue(), // voffset -- will be set by setBufferOffsets
SDValue(), // soffset -- will be set by setBufferOffsets
SDValue(), // offset -- will be set by setBufferOffsets
DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
};
setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
EVT VT = Op.getValueType();
auto *M = cast<MemSDNode>(Op);
return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
Op->getVTList(), Ops, VT, M->getMemOperand());
}
case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
SDValue Ops[] = {
Op.getOperand(0), // Chain
Op.getOperand(2), // src
Op.getOperand(3), // cmp
Op.getOperand(4), // rsrc
DAG.getConstant(0, DL, MVT::i32), // vindex
Offsets.first, // voffset
Op.getOperand(6), // soffset
Offsets.second, // offset
Op.getOperand(7), // cachepolicy
DAG.getTargetConstant(0, DL, MVT::i1), // idxen
};
EVT VT = Op.getValueType();
auto *M = cast<MemSDNode>(Op);
return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
Op->getVTList(), Ops, VT, M->getMemOperand());
}
case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
SDValue Ops[] = {
Op.getOperand(0), // Chain
Op.getOperand(2), // src
Op.getOperand(3), // cmp
Op.getOperand(4), // rsrc
Op.getOperand(5), // vindex
Offsets.first, // voffset
Op.getOperand(7), // soffset
Offsets.second, // offset
Op.getOperand(8), // cachepolicy
DAG.getTargetConstant(1, DL, MVT::i1), // idxen
};
EVT VT = Op.getValueType();
auto *M = cast<MemSDNode>(Op);
return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
Op->getVTList(), Ops, VT, M->getMemOperand());
}
default:
if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
AMDGPU::getImageDimIntrinsicInfo(IntrID))
return lowerImage(Op, ImageDimIntr, DAG);
return SDValue();
}
}
// Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
// dwordx4 if on SI.
SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
SDVTList VTList,
ArrayRef<SDValue> Ops, EVT MemVT,
MachineMemOperand *MMO,
SelectionDAG &DAG) const {
EVT VT = VTList.VTs[0];
EVT WidenedVT = VT;
EVT WidenedMemVT = MemVT;
if (!Subtarget->hasDwordx3LoadStores() &&
(WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
WidenedVT = EVT::getVectorVT(*DAG.getContext(),
WidenedVT.getVectorElementType(), 4);
WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
WidenedMemVT.getVectorElementType(), 4);
MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
}
assert(VTList.NumVTs == 2);
SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
WidenedMemVT, MMO);
if (WidenedVT != VT) {
auto Extract = DAG.getNode(
ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout())));
NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
}
return NewOp;
}
SDValue SITargetLowering::handleD16VData(SDValue VData,
SelectionDAG &DAG) const {
EVT StoreVT = VData.getValueType();
// No change for f16 and legal vector D16 types.
if (!StoreVT.isVector())
return VData;
SDLoc DL(VData);
assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
if (Subtarget->hasUnpackedD16VMem()) {
// We need to unpack the packed data to store.
EVT IntStoreVT = StoreVT.changeTypeToInteger();
SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
StoreVT.getVectorNumElements());
SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
return DAG.UnrollVectorOp(ZExt.getNode());
}
assert(isTypeLegal(StoreVT));
return VData;
}
SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
SelectionDAG &DAG) const {
SDLoc DL(Op);
SDValue Chain = Op.getOperand(0);
unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
MachineFunction &MF = DAG.getMachineFunction();
switch (IntrinsicID) {
case Intrinsic::amdgcn_exp: {
const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
const SDValue Ops[] = {
Chain,
DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
Op.getOperand(4), // src0
Op.getOperand(5), // src1
Op.getOperand(6), // src2
Op.getOperand(7), // src3
DAG.getTargetConstant(0, DL, MVT::i1), // compr
DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
};
unsigned Opc = Done->isNullValue() ?
AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
}
case Intrinsic::amdgcn_exp_compr: {
const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
SDValue Src0 = Op.getOperand(4);
SDValue Src1 = Op.getOperand(5);
const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
SDValue Undef = DAG.getUNDEF(MVT::f32);
const SDValue Ops[] = {
Chain,
DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en
DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
Undef, // src2
Undef, // src3
DAG.getTargetConstant(1, DL, MVT::i1), // compr
DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
};
unsigned Opc = Done->isNullValue() ?
AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
}
case Intrinsic::amdgcn_s_barrier: {
if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
if (WGSize <= ST.getWavefrontSize())
return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
Op.getOperand(0)), 0);
}
return SDValue();
};
case Intrinsic::amdgcn_tbuffer_store: {
SDValue VData = Op.getOperand(2);
bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
if (IsD16)
VData = handleD16VData(VData, DAG);
unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
unsigned IdxEn = 1;
if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
IdxEn = Idx->getZExtValue() != 0;
SDValue Ops[] = {
Chain,
VData, // vdata
Op.getOperand(3), // rsrc
Op.getOperand(4), // vindex
Op.getOperand(5), // voffset
Op.getOperand(6), // soffset
Op.getOperand(7), // offset
DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
};
unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
AMDGPUISD::TBUFFER_STORE_FORMAT;
MemSDNode *M = cast<MemSDNode>(Op);
return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
M->getMemoryVT(), M->getMemOperand());
}
case Intrinsic::amdgcn_struct_tbuffer_store: {
SDValue VData = Op.getOperand(2);
bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
if (IsD16)
VData = handleD16VData(VData, DAG);
auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
SDValue Ops[] = {
Chain,
VData, // vdata
Op.getOperand(3), // rsrc
Op.getOperand(4), // vindex
Offsets.first, // voffset
Op.getOperand(6), // soffset
Offsets.second, // offset
Op.getOperand(7), // format
Op.getOperand(8), // cachepolicy
DAG.getTargetConstant(1, DL, MVT::i1), // idexen
};
unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
AMDGPUISD::TBUFFER_STORE_FORMAT;
MemSDNode *M = cast<MemSDNode>(Op);
return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
M->getMemoryVT(), M->getMemOperand());
}
case Intrinsic::amdgcn_raw_tbuffer_store: {
SDValue VData = Op.getOperand(2);
bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
if (IsD16)
VData = handleD16VData(VData, DAG);
auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
SDValue Ops[] = {
Chain,
VData, // vdata
Op.getOperand(3), // rsrc
DAG.getConstant(0, DL, MVT::i32), // vindex
Offsets.first, // voffset
Op.getOperand(5), // soffset
Offsets.second, // offset
Op.getOperand(6), // format
Op.getOperand(7), // cachepolicy
DAG.getTargetConstant(0, DL, MVT::i1), // idexen
};
unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
AMDGPUISD::TBUFFER_STORE_FORMAT;
MemSDNode *M = cast<MemSDNode>(Op);
return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
M->getMemoryVT(), M->getMemOperand());
}
case Intrinsic::amdgcn_buffer_store:
case Intrinsic::amdgcn_buffer_store_byte:
case Intrinsic::amdgcn_buffer_store_short:
case Intrinsic::amdgcn_buffer_store_format: {
SDValue VData = Op.getOperand(2);
bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
if (IsD16)
VData = handleD16VData(VData, DAG);
unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
unsigned IdxEn = 1;
if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
IdxEn = Idx->getZExtValue() != 0;
SDValue Ops[] = {
Chain,
VData,
Op.getOperand(3), // rsrc
Op.getOperand(4), // vindex
SDValue(), // voffset -- will be set by setBufferOffsets
SDValue(), // soffset -- will be set by setBufferOffsets
SDValue(), // offset -- will be set by setBufferOffsets
DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
};
setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
unsigned Opc = 0;
switch (IntrinsicID) {
case Intrinsic::amdgcn_buffer_store: Opc = AMDGPUISD::BUFFER_STORE; break;
case Intrinsic::amdgcn_buffer_store_byte: Opc = AMDGPUISD::BUFFER_STORE_BYTE; break;
case Intrinsic::amdgcn_buffer_store_short: Opc = AMDGPUISD::BUFFER_STORE_SHORT; break;
case Intrinsic::amdgcn_buffer_store_format: Opc = AMDGPUISD::BUFFER_STORE_FORMAT; break;
default: llvm_unreachable("Unexpected IntrinsicID");
}
Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
MemSDNode *M = cast<MemSDNode>(Op);
// Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
EVT VDataType = VData.getValueType().getScalarType();
if (VDataType == MVT::i8 || VDataType == MVT::i16)
return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
M->getMemoryVT(), M->getMemOperand());
}
case Intrinsic::amdgcn_raw_buffer_store:
case Intrinsic::amdgcn_raw_buffer_store_format: {
const bool IsFormat =
IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
SDValue VData = Op.getOperand(2);
EVT VDataVT = VData.getValueType();
EVT EltType = VDataVT.getScalarType();
bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
if (IsD16)
VData = handleD16VData(VData, DAG);
if (!isTypeLegal(VDataVT)) {
VData =
DAG.getNode(ISD::BITCAST, DL,
getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
}
auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
SDValue Ops[] = {
Chain,
VData,
Op.getOperand(3), // rsrc
DAG.getConstant(0, DL, MVT::i32), // vindex
Offsets.first, // voffset
Op.getOperand(5), // soffset
Offsets.second, // offset
Op.getOperand(6), // cachepolicy
DAG.getTargetConstant(0, DL, MVT::i1), // idxen
};
unsigned Opc =
IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
MemSDNode *M = cast<MemSDNode>(Op);
// Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
M->getMemoryVT(), M->getMemOperand());
}
case Intrinsic::amdgcn_struct_buffer_store:
case Intrinsic::amdgcn_struct_buffer_store_format: {
const bool IsFormat =
IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
SDValue VData = Op.getOperand(2);
EVT VDataVT = VData.getValueType();
EVT EltType = VDataVT.getScalarType();
bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
if (IsD16)
VData = handleD16VData(VData, DAG);
if (!isTypeLegal(VDataVT)) {
VData =
DAG.getNode(ISD::BITCAST, DL,
getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
}
auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
SDValue Ops[] = {
Chain,
VData,
Op.getOperand(3), // rsrc
Op.getOperand(4), // vindex
Offsets.first, // voffset
Op.getOperand(6), // soffset
Offsets.second, // offset
Op.getOperand(7), // cachepolicy
DAG.getTargetConstant(1, DL, MVT::i1), // idxen
};
unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
MemSDNode *M = cast<MemSDNode>(Op);
// Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
EVT VDataType = VData.getValueType().getScalarType();
if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
M->getMemoryVT(), M->getMemOperand());
}
case Intrinsic::amdgcn_buffer_atomic_fadd: {
unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
unsigned IdxEn = 1;
if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
IdxEn = Idx->getZExtValue() != 0;
SDValue Ops[] = {
Chain,
Op.getOperand(2), // vdata
Op.getOperand(3), // rsrc
Op.getOperand(4), // vindex
SDValue(), // voffset -- will be set by setBufferOffsets
SDValue(), // soffset -- will be set by setBufferOffsets
SDValue(), // offset -- will be set by setBufferOffsets
DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
};
setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
EVT VT = Op.getOperand(2).getValueType();
auto *M = cast<MemSDNode>(Op);
unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
: AMDGPUISD::BUFFER_ATOMIC_FADD;
return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
M->getMemOperand());
}
case Intrinsic::amdgcn_global_atomic_fadd: {
SDValue Ops[] = {
Chain,
Op.getOperand(2), // ptr
Op.getOperand(3) // vdata
};
EVT VT = Op.getOperand(3).getValueType();
auto *M = cast<MemSDNode>(Op);
unsigned Opcode = VT.isVector() ? AMDGPUISD::ATOMIC_PK_FADD
: AMDGPUISD::ATOMIC_FADD;
return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
M->getMemOperand());
}
case Intrinsic::amdgcn_end_cf:
return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
Op->getOperand(2), Chain), 0);
default: {
if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
return lowerImage(Op, ImageDimIntr, DAG);
return Op;
}
}
}
// The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
// offset (the offset that is included in bounds checking and swizzling, to be
// split between the instruction's voffset and immoffset fields) and soffset
// (the offset that is excluded from bounds checking and swizzling, to go in
// the instruction's soffset field). This function takes the first kind of
// offset and figures out how to split it between voffset and immoffset.
std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
SDValue Offset, SelectionDAG &DAG) const {
SDLoc DL(Offset);
const unsigned MaxImm = 4095;
SDValue N0 = Offset;
ConstantSDNode *C1 = nullptr;
if ((C1 = dyn_cast<ConstantSDNode>(N0)))
N0 = SDValue();
else if (DAG.isBaseWithConstantOffset(N0)) {
C1 = cast<ConstantSDNode>(N0.getOperand(1));
N0 = N0.getOperand(0);
}
if (C1) {
unsigned ImmOffset = C1->getZExtValue();
// If the immediate value is too big for the immoffset field, put the value
// and -4096 into the immoffset field so that the value that is copied/added
// for the voffset field is a multiple of 4096, and it stands more chance
// of being CSEd with the copy/add for another similar load/store.
// However, do not do that rounding down to a multiple of 4096 if that is a
// negative number, as it appears to be illegal to have a negative offset
// in the vgpr, even if adding the immediate offset makes it positive.
unsigned Overflow = ImmOffset & ~MaxImm;
ImmOffset -= Overflow;
if ((int32_t)Overflow < 0) {
Overflow += ImmOffset;
ImmOffset = 0;
}
C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
if (Overflow) {
auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
if (!N0)
N0 = OverflowVal;
else {
SDValue Ops[] = { N0, OverflowVal };
N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
}
}
}
if (!N0)
N0 = DAG.getConstant(0, DL, MVT::i32);
if (!C1)
C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
return {N0, SDValue(C1, 0)};
}
// Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
// three offsets (voffset, soffset and instoffset) into the SDValue[3] array
// pointed to by Offsets.
void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
SelectionDAG &DAG, SDValue *Offsets,
unsigned Align) const {
SDLoc DL(CombinedOffset);
if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
uint32_t Imm = C->getZExtValue();
uint32_t SOffset, ImmOffset;
if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
return;
}
}
if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
SDValue N0 = CombinedOffset.getOperand(0);
SDValue N1 = CombinedOffset.getOperand(1);
uint32_t SOffset, ImmOffset;
int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
Subtarget, Align)) {
Offsets[0] = N0;
Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
return;
}
}
Offsets[0] = CombinedOffset;
Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
}
// Handle 8 bit and 16 bit buffer loads
SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
EVT LoadVT, SDLoc DL,
ArrayRef<SDValue> Ops,
MemSDNode *M) const {
EVT IntVT = LoadVT.changeTypeToInteger();
unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
Ops, IntVT,
M->getMemOperand());
SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
}
// Handle 8 bit and 16 bit buffer stores
SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
EVT VDataType, SDLoc DL,
SDValue Ops[],
MemSDNode *M) const {
if (VDataType == MVT::f16)
Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
Ops[1] = BufferStoreExt;
unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
AMDGPUISD::BUFFER_STORE_SHORT;
ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
M->getMemOperand());
}
static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
ISD::LoadExtType ExtType, SDValue Op,
const SDLoc &SL, EVT VT) {
if (VT.bitsLT(Op.getValueType()))
return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
switch (ExtType) {
case ISD::SEXTLOAD:
return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
case ISD::ZEXTLOAD:
return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
case ISD::EXTLOAD:
return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
case ISD::NON_EXTLOAD:
return Op;
}
llvm_unreachable("invalid ext type");
}
SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
SelectionDAG &DAG = DCI.DAG;
if (Ld->getAlignment() < 4 || Ld->isDivergent())
return SDValue();
// FIXME: Constant loads should all be marked invariant.
unsigned AS = Ld->getAddressSpace();
if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
(AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
return SDValue();
// Don't do this early, since it may interfere with adjacent load merging for
// illegal types. We can avoid losing alignment information for exotic types
// pre-legalize.
EVT MemVT = Ld->getMemoryVT();
if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
MemVT.getSizeInBits() >= 32)
return SDValue();
SDLoc SL(Ld);
assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
"unexpected vector extload");
// TODO: Drop only high part of range.
SDValue Ptr = Ld->getBasePtr();
SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
MVT::i32, SL, Ld->getChain(), Ptr,
Ld->getOffset(),
Ld->getPointerInfo(), MVT::i32,
Ld->getAlignment(),
Ld->getMemOperand()->getFlags(),
Ld->getAAInfo(),
nullptr); // Drop ranges
EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
if (MemVT.isFloatingPoint()) {
assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
"unexpected fp extload");
TruncVT = MemVT.changeTypeToInteger();
}
SDValue Cvt = NewLoad;
if (Ld->getExtensionType() == ISD::SEXTLOAD) {
Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
DAG.getValueType(TruncVT));
} else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
Ld->getExtensionType() == ISD::NON_EXTLOAD) {
Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
} else {
assert(Ld->getExtensionType() == ISD::EXTLOAD);
}
EVT VT = Ld->getValueType(0);
EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
DCI.AddToWorklist(Cvt.getNode());
// We may need to handle exotic cases, such as i16->i64 extloads, so insert
// the appropriate extension from the 32-bit load.
Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
DCI.AddToWorklist(Cvt.getNode());
// Handle conversion back to floating point if necessary.
Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
}
SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
SDLoc DL(Op);
LoadSDNode *Load = cast<LoadSDNode>(Op);
ISD::LoadExtType ExtType = Load->getExtensionType();
EVT MemVT = Load->getMemoryVT();
if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
return SDValue();
// FIXME: Copied from PPC
// First, load into 32 bits, then truncate to 1 bit.
SDValue Chain = Load->getChain();
SDValue BasePtr = Load->getBasePtr();
MachineMemOperand *MMO = Load->getMemOperand();
EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
BasePtr, RealMemVT, MMO);
if (!MemVT.isVector()) {
SDValue Ops[] = {
DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
NewLD.getValue(1)
};
return DAG.getMergeValues(Ops, DL);
}
SmallVector<SDValue, 3> Elts;
for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
DAG.getConstant(I, DL, MVT::i32));
Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
}
SDValue Ops[] = {
DAG.getBuildVector(MemVT, DL, Elts),
NewLD.getValue(1)
};
return DAG.getMergeValues(Ops, DL);
}
if (!MemVT.isVector())
return SDValue();
assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
"Custom lowering for non-i32 vectors hasn't been implemented.");
if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
MemVT, *Load->getMemOperand())) {
SDValue Ops[2];
std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
return DAG.getMergeValues(Ops, DL);
}
unsigned Alignment = Load->getAlignment();
unsigned AS = Load->getAddressSpace();
if (Subtarget->hasLDSMisalignedBug() &&
AS == AMDGPUAS::FLAT_ADDRESS &&
Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
return SplitVectorLoad(Op, DAG);
}
MachineFunction &MF = DAG.getMachineFunction();
SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
// If there is a possibilty that flat instruction access scratch memory
// then we need to use the same legalization rules we use for private.
if (AS == AMDGPUAS::FLAT_ADDRESS)
AS = MFI->hasFlatScratchInit() ?
AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
unsigned NumElements = MemVT.getVectorNumElements();
if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
if (MemVT.isPow2VectorType())
return SDValue();
if (NumElements == 3)
return WidenVectorLoad(Op, DAG);
return SplitVectorLoad(Op, DAG);
}
// Non-uniform loads will be selected to MUBUF instructions, so they
// have the same legalization requirements as global and private
// loads.
//
}
if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
AS == AMDGPUAS::GLOBAL_ADDRESS) {
if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
!Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
Alignment >= 4 && NumElements < 32) {
if (MemVT.isPow2VectorType())
return SDValue();
if (NumElements == 3)
return WidenVectorLoad(Op, DAG);
return SplitVectorLoad(Op, DAG);
}
// Non-uniform loads will be selected to MUBUF instructions, so they
// have the same legalization requirements as global and private
// loads.
//
}
if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
AS == AMDGPUAS::GLOBAL_ADDRESS ||
AS == AMDGPUAS::FLAT_ADDRESS) {
if (NumElements > 4)
return SplitVectorLoad(Op, DAG);
// v3 loads not supported on SI.
if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
return WidenVectorLoad(Op, DAG);
// v3 and v4 loads are supported for private and global memory.
return SDValue();
}
if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
// Depending on the setting of the private_element_size field in the
// resource descriptor, we can only make private accesses up to a certain
// size.
switch (Subtarget->getMaxPrivateElementSize()) {
case 4:
return scalarizeVectorLoad(Load, DAG);
case 8:
if (NumElements > 2)
return SplitVectorLoad(Op, DAG);
return SDValue();
case 16:
// Same as global/flat
if (NumElements > 4)
return SplitVectorLoad(Op, DAG);
// v3 loads not supported on SI.
if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
return WidenVectorLoad(Op, DAG);
return SDValue();
default:
llvm_unreachable("unsupported private_element_size");
}
} else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
// Use ds_read_b128 if possible.
if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
MemVT.getStoreSize() == 16)
return SDValue();
if (NumElements > 2)
return SplitVectorLoad(Op, DAG);
// SI has a hardware bug in the LDS / GDS boounds checking: if the base
// address is negative, then the instruction is incorrectly treated as
// out-of-bounds even if base + offsets is in bounds. Split vectorized
// loads here to avoid emitting ds_read2_b32. We may re-combine the
// load later in the SILoadStoreOptimizer.
if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
NumElements == 2 && MemVT.getStoreSize() == 8 &&
Load->getAlignment() < 8) {
return SplitVectorLoad(Op, DAG);
}
}
return SDValue();
}
SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
EVT VT = Op.getValueType();
assert(VT.getSizeInBits() == 64);
SDLoc DL(Op);
SDValue Cond = Op.getOperand(0);
SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
SDValue One = DAG.getConstant(1, DL, MVT::i32);
SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
return DAG.getNode(ISD::BITCAST, DL, VT, Res);
}
// Catch division cases where we can use shortcuts with rcp and rsq
// instructions.
SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
SelectionDAG &DAG) const {
SDLoc SL(Op);
SDValue LHS = Op.getOperand(0);
SDValue RHS = Op.getOperand(1);
EVT VT = Op.getValueType();
const SDNodeFlags Flags = Op->getFlags();
bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal();
if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
return SDValue();
if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
if (CLHS->isExactlyValue(1.0)) {
// v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
// the CI documentation has a worst case error of 1 ulp.
// OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
// use it as long as we aren't trying to use denormals.
//
// v_rcp_f16 and v_rsq_f16 DO support denormals.
// 1.0 / sqrt(x) -> rsq(x)
// XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
// error seems really high at 2^29 ULP.
if (RHS.getOpcode() == ISD::FSQRT)
return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
// 1.0 / x -> rcp(x)
return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
}
// Same as for 1.0, but expand the sign out of the constant.
if (CLHS->isExactlyValue(-1.0)) {
// -1.0 / x -> rcp (fneg x)
SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
}
}
}
if (Unsafe) {
// Turn into multiply by the reciprocal.
// x / y -> x * (1.0 / y)
SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
}
return SDValue();
}
static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
if (GlueChain->getNumValues() <= 1) {
return DAG.getNode(Opcode, SL, VT, A, B);
}
assert(GlueChain->getNumValues() == 3);
SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
switch (Opcode) {
default: llvm_unreachable("no chain equivalent for opcode");
case ISD::FMUL:
Opcode = AMDGPUISD::FMUL_W_CHAIN;
break;
}
return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
GlueChain.getValue(2));
}
static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
EVT VT, SDValue A, SDValue B, SDValue C,
SDValue GlueChain) {
if (GlueChain->getNumValues() <= 1) {
return DAG.getNode(Opcode, SL, VT, A, B, C);
}
assert(GlueChain->getNumValues() == 3);
SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
switch (Opcode) {
default: llvm_unreachable("no chain equivalent for opcode");
case ISD::FMA:
Opcode = AMDGPUISD::FMA_W_CHAIN;
break;
}
return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
GlueChain.getValue(2));
}
SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
return FastLowered;
SDLoc SL(Op);
SDValue Src0 = Op.getOperand(0);
SDValue Src1 = Op.getOperand(1);
SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
}
// Faster 2.5 ULP division that does not support denormals.
SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
SDLoc SL(Op);
SDValue LHS = Op.getOperand(1);
SDValue RHS = Op.getOperand(2);
SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
const APFloat K0Val(BitsToFloat(0x6f800000));
const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
const APFloat K1Val(BitsToFloat(0x2f800000));
const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
EVT SetCCVT =
getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
// TODO: Should this propagate fast-math-flags?
r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
// rcp does not support denormals.
SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
}
// Returns immediate value for setting the F32 denorm mode when using the
// S_DENORM_MODE instruction.
static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
const SDLoc &SL, const GCNSubtarget *ST) {
assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
int DPDenormModeDefault = ST->hasFP64Denormals()
? FP_DENORM_FLUSH_NONE
: FP_DENORM_FLUSH_IN_FLUSH_OUT;
int Mode = SPDenormMode | (DPDenormModeDefault << 2);
return DAG.getTargetConstant(Mode, SL, MVT::i32);
}
SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
return FastLowered;
SDLoc SL(Op);
SDValue LHS = Op.getOperand(0);
SDValue RHS = Op.getOperand(1);
const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
RHS, RHS, LHS);
SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
LHS, RHS, LHS);
// Denominator is scaled to not be denormal, so using rcp is ok.
SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
DenominatorScaled);
SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
DenominatorScaled);
const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
(4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
(1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
if (!Subtarget->hasFP32Denormals()) {
SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
SDValue EnableDenorm;
if (Subtarget->hasDenormModeInst()) {
const SDValue EnableDenormValue =
getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
DAG.getEntryNode(), EnableDenormValue);
} else {
const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
SL, MVT::i32);
EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
DAG.getEntryNode(), EnableDenormValue,
BitField);
}
SDValue Ops[3] = {
NegDivScale0,
EnableDenorm.getValue(0),
EnableDenorm.getValue(1)
};
NegDivScale0 = DAG.getMergeValues(Ops, SL);
}
SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
ApproxRcp, One, NegDivScale0);
SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
ApproxRcp, Fma0);
SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
Fma1, Fma1);
SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
NumeratorScaled, Mul);
SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
NumeratorScaled, Fma3);
if (!Subtarget->hasFP32Denormals()) {
SDValue DisableDenorm;
if (Subtarget->hasDenormModeInst()) {
const SDValue DisableDenormValue =
getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
Fma4.getValue(1), DisableDenormValue,
Fma4.getValue(2));
} else {
const SDValue DisableDenormValue =
DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
Fma4.getValue(1), DisableDenormValue,
BitField, Fma4.getValue(2));
}
SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
DisableDenorm, DAG.getRoot());
DAG.setRoot(OutputChain);
}
SDValue Scale = NumeratorScaled.getValue(1);
SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
Fma4, Fma1, Fma3, Scale);
return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
}
SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
if (DAG.getTarget().Options.UnsafeFPMath)
return lowerFastUnsafeFDIV(Op, DAG);
SDLoc SL(Op);
SDValue X = Op.getOperand(0);
SDValue Y = Op.getOperand(1);
const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
NegDivScale0, Mul, DivScale1);
SDValue Scale;
if (!Subtarget->hasUsableDivScaleConditionOutput()) {
// Workaround a hardware bug on SI where the condition output from div_scale
// is not usable.
const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
// Figure out if the scale to use for div_fmas.
SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
SDValue Scale0Hi
= DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
SDValue Scale1Hi
= DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
} else {
Scale = DivScale1.getValue(1);
}
SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
Fma4, Fma3, Mul, Scale);
return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
}
SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
EVT VT = Op.getValueType();
if (VT == MVT::f32)
return LowerFDIV32(Op, DAG);
if (VT == MVT::f64)
return LowerFDIV64(Op, DAG);
if (VT == MVT::f16)
return LowerFDIV16(Op, DAG);
llvm_unreachable("Unexpected type for fdiv");
}
SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
SDLoc DL(Op);
StoreSDNode *Store = cast<StoreSDNode>(Op);
EVT VT = Store->getMemoryVT();
if (VT == MVT::i1) {
return DAG.getTruncStore(Store->getChain(), DL,
DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
Store->getBasePtr(), MVT::i1, Store->getMemOperand());
}
assert(VT.isVector() &&
Store->getValue().getValueType().getScalarType() == MVT::i32);
if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
VT, *Store->getMemOperand())) {
return expandUnalignedStore(Store, DAG);
}
unsigned AS = Store->getAddressSpace();
if (Subtarget->hasLDSMisalignedBug() &&
AS == AMDGPUAS::FLAT_ADDRESS &&
Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
return SplitVectorStore(Op, DAG);
}
MachineFunction &MF = DAG.getMachineFunction();
SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
// If there is a possibilty that flat instruction access scratch memory
// then we need to use the same legalization rules we use for private.
if (AS == AMDGPUAS::FLAT_ADDRESS)
AS = MFI->hasFlatScratchInit() ?
AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
unsigned NumElements = VT.getVectorNumElements();
if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
AS == AMDGPUAS::FLAT_ADDRESS) {
if (NumElements > 4)
return SplitVectorStore(Op, DAG);
// v3 stores not supported on SI.
if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
return SplitVectorStore(Op, DAG);
return SDValue();
} else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
switch (Subtarget->getMaxPrivateElementSize()) {
case 4:
return scalarizeVectorStore(Store, DAG);
case 8:
if (NumElements > 2)
return SplitVectorStore(Op, DAG);
return SDValue();
case 16:
if (NumElements > 4 || NumElements == 3)
return SplitVectorStore(Op, DAG);
return SDValue();
default:
llvm_unreachable("unsupported private_element_size");
}
} else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
// Use ds_write_b128 if possible.
if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
VT.getStoreSize() == 16 && NumElements != 3)
return SDValue();
if (NumElements > 2)
return SplitVectorStore(Op, DAG);
// SI has a hardware bug in the LDS / GDS boounds checking: if the base
// address is negative, then the instruction is incorrectly treated as
// out-of-bounds even if base + offsets is in bounds. Split vectorized
// stores here to avoid emitting ds_write2_b32. We may re-combine the
// store later in the SILoadStoreOptimizer.
if (!Subtarget->hasUsableDSOffset() &&
NumElements == 2 && VT.getStoreSize() == 8 &&
Store->getAlignment() < 8) {
return SplitVectorStore(Op, DAG);
}
return SDValue();
} else {
llvm_unreachable("unhandled address space");
}
}
SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
SDLoc DL(Op);
EVT VT = Op.getValueType();
SDValue Arg = Op.getOperand(0);
SDValue TrigVal;
// TODO: Should this propagate fast-math-flags?
SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
if (Subtarget->hasTrigReducedRange()) {
SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
} else {
TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
}
switch (Op.getOpcode()) {
case ISD::FCOS:
return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
case ISD::FSIN:
return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
default:
llvm_unreachable("Wrong trig opcode");
}
}
SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
assert(AtomicNode->isCompareAndSwap());
unsigned AS = AtomicNode->getAddressSpace();
// No custom lowering required for local address space
if (!isFlatGlobalAddrSpace(AS))
return Op;
// Non-local address space requires custom lowering for atomic compare
// and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
SDLoc DL(Op);
SDValue ChainIn = Op.getOperand(0);
SDValue Addr = Op.getOperand(1);
SDValue Old = Op.getOperand(2);
SDValue New = Op.getOperand(3);
EVT VT = Op.getValueType();
MVT SimpleVT = VT.getSimpleVT();
MVT VecType = MVT::getVectorVT(SimpleVT, 2);
SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
SDValue Ops[] = { ChainIn, Addr, NewOld };
return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
Ops, VT, AtomicNode->getMemOperand());
}
//===----------------------------------------------------------------------===//
// Custom DAG optimizations
//===----------------------------------------------------------------------===//
SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
EVT VT = N->getValueType(0);
EVT ScalarVT = VT.getScalarType();
if (ScalarVT != MVT::f32)
return SDValue();
SelectionDAG &DAG = DCI.DAG;
SDLoc DL(N);
SDValue Src = N->getOperand(0);
EVT SrcVT = Src.getValueType();
// TODO: We could try to match extracting the higher bytes, which would be
// easier if i8 vectors weren't promoted to i32 vectors, particularly after
// types are legalized. v4i8 -> v4f32 is probably the only case to worry
// about in practice.
if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
DCI.AddToWorklist(Cvt.getNode());
return Cvt;
}
}
return SDValue();
}
// (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
// This is a variant of
// (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
//
// The normal DAG combiner will do this, but only if the add has one use since
// that would increase the number of instructions.
//
// This prevents us from seeing a constant offset that can be folded into a
// memory instruction's addressing mode. If we know the resulting add offset of
// a pointer can be folded into an addressing offset, we can replace the pointer
// operand with the add of new constant offset. This eliminates one of the uses,
// and may allow the remaining use to also be simplified.
//
SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
unsigned AddrSpace,
EVT MemVT,
DAGCombinerInfo &DCI) const {
SDValue N0 = N->getOperand(0);
SDValue N1 = N->getOperand(1);
// We only do this to handle cases where it's profitable when there are
// multiple uses of the add, so defer to the standard combine.
if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
N0->hasOneUse())
return SDValue();
const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
if (!CN1)
return SDValue();
const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
if (!CAdd)
return SDValue();
// If the resulting offset is too large, we can't fold it into the addressing
// mode offset.
APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
AddrMode AM;
AM.HasBaseReg = true;
AM.BaseOffs = Offset.getSExtValue();
if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
return SDValue();
SelectionDAG &DAG = DCI.DAG;
SDLoc SL(N);
EVT VT = N->getValueType(0);
SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
SDNodeFlags Flags;
Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
(N0.getOpcode() == ISD::OR ||
N0->getFlags().hasNoUnsignedWrap()));
return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
}
SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
DAGCombinerInfo &DCI) const {
SDValue Ptr = N->getBasePtr();
SelectionDAG &DAG = DCI.DAG;
SDLoc SL(N);
// TODO: We could also do this for multiplies.
if (Ptr.getOpcode() == ISD::SHL) {
SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(),
N->getMemoryVT(), DCI);
if (NewPtr) {
SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
}
}
return SDValue();
}
static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
(Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
(Opc == ISD::XOR && Val == 0);
}
// Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
// will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
// integer combine opportunities since most 64-bit operations are decomposed
// this way. TODO: We won't want this for SALU especially if it is an inline
// immediate.
SDValue SITargetLowering::splitBinaryBitConstantOp(
DAGCombinerInfo &DCI,
const SDLoc &SL,
unsigned Opc, SDValue LHS,
const ConstantSDNode *CRHS) const {
uint64_t Val = CRHS->getZExtValue();
uint32_t ValLo = Lo_32(Val);
uint32_t ValHi = Hi_32(Val);
const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
bitOpWithConstantIsReducible(Opc, ValHi)) ||
(CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
// If we need to materialize a 64-bit immediate, it will be split up later
// anyway. Avoid creating the harder to understand 64-bit immediate
// materialization.
return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
}
return SDValue();
}
// Returns true if argument is a boolean value which is not serialized into
// memory or argument and does not require v_cmdmask_b32 to be deserialized.
static bool isBoolSGPR(SDValue V) {
if (V.getValueType() != MVT::i1)
return false;
switch (V.getOpcode()) {
default: break;
case ISD::SETCC:
case ISD::AND:
case ISD::OR:
case ISD::XOR:
case AMDGPUISD::FP_CLASS:
return true;
}
return false;
}
// If a constant has all zeroes or all ones within each byte return it.
// Otherwise return 0.
static uint32_t getConstantPermuteMask(uint32_t C) {
// 0xff for any zero byte in the mask
uint32_t ZeroByteMask = 0;
if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
if ((NonZeroByteMask & C) != NonZeroByteMask)
return 0; // Partial bytes selected.
return C;
}
// Check if a node selects whole bytes from its operand 0 starting at a byte
// boundary while masking the rest. Returns select mask as in the v_perm_b32
// or -1 if not succeeded.
// Note byte select encoding:
// value 0-3 selects corresponding source byte;
// value 0xc selects zero;
// value 0xff selects 0xff.
static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
assert(V.getValueSizeInBits() == 32);
if (V.getNumOperands() != 2)
return ~0;
ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
if (!N1)
return ~0;
uint32_t C = N1->getZExtValue();
switch (V.getOpcode()) {
default:
break;
case ISD::AND:
if (uint32_t ConstMask = getConstantPermuteMask(C)) {
return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
}
break;
case ISD::OR:
if (uint32_t ConstMask = getConstantPermuteMask(C)) {
return (0x03020100 & ~ConstMask) | ConstMask;
}
break;
case ISD::SHL:
if (C % 8)
return ~0;
return uint32_t((0x030201000c0c0c0cull << C) >> 32);
case ISD::SRL:
if (C % 8)
return ~0;
return uint32_t(0x0c0c0c0c03020100ull >> C);
}
return ~0;
}
SDValue SITargetLowering::performAndCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
if (DCI.isBeforeLegalize())
return SDValue();
SelectionDAG &DAG = DCI.DAG;
EVT VT = N->getValueType(0);
SDValue LHS = N->getOperand(0);
SDValue RHS = N->getOperand(1);
const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
if (VT == MVT::i64 && CRHS) {
if (SDValue Split
= splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
return Split;
}
if (CRHS && VT == MVT::i32) {
// and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
// nb = number of trailing zeroes in mask
// It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
// given that we are selecting 8 or 16 bit fields starting at byte boundary.
uint64_t Mask = CRHS->getZExtValue();
unsigned Bits = countPopulation(Mask);
if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
(Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
unsigned Shift = CShift->getZExtValue();
unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
unsigned Offset = NB + Shift;
if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
SDLoc SL(N);
SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
LHS->getOperand(0),
DAG.getConstant(Offset, SL, MVT::i32),
DAG.getConstant(Bits, SL, MVT::i32));
EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
DAG.getValueType(NarrowVT));
SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
return Shl;
}
}
}
// and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
isa<ConstantSDNode>(LHS.getOperand(2))) {
uint32_t Sel = getConstantPermuteMask(Mask);
if (!Sel)
return SDValue();
// Select 0xc for all zero bytes
Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
SDLoc DL(N);
return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
}
}
// (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
// fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
SDValue X = LHS.getOperand(0);
SDValue Y = RHS.getOperand(0);
if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
return SDValue();
if (LCC == ISD::SETO) {
if (X != LHS.getOperand(1))
return SDValue();
if (RCC == ISD::SETUNE) {
const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
if (!C1 || !C1->isInfinity() || C1->isNegative())
return SDValue();
const uint32_t Mask = SIInstrFlags::N_NORMAL |
SIInstrFlags::N_SUBNORMAL |
SIInstrFlags::N_ZERO |
SIInstrFlags::P_ZERO |
SIInstrFlags::P_SUBNORMAL |
SIInstrFlags::P_NORMAL;
static_assert(((~(SIInstrFlags::S_NAN |
SIInstrFlags::Q_NAN |
SIInstrFlags::N_INFINITY |
SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
"mask not equal");
SDLoc DL(N);
return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
X, DAG.getConstant(Mask, DL, MVT::i32));
}
}
}
if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
std::swap(LHS, RHS);
if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
RHS.hasOneUse()) {
ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
// and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
// and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
(RHS.getOperand(0) == LHS.getOperand(0) &&
LHS.getOperand(0) == LHS.getOperand(1))) {
const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
unsigned NewMask = LCC == ISD::SETO ?
Mask->getZExtValue() & ~OrdMask :
Mask->getZExtValue() & OrdMask;
SDLoc DL(N);
return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
DAG.getConstant(NewMask, DL, MVT::i32));
}
}
if (VT == MVT::i32 &&
(RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
// and x, (sext cc from i1) => select cc, x, 0
if (RHS.getOpcode() != ISD::SIGN_EXTEND)
std::swap(LHS, RHS);
if (isBoolSGPR(RHS.getOperand(0)))
return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
}
// and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
uint32_t LHSMask = getPermuteMask(DAG, LHS);
uint32_t RHSMask = getPermuteMask(DAG, RHS);
if (LHSMask != ~0u && RHSMask != ~0u) {
// Canonicalize the expression in an attempt to have fewer unique masks
// and therefore fewer registers used to hold the masks.
if (LHSMask > RHSMask) {
std::swap(LHSMask, RHSMask);
std::swap(LHS, RHS);
}
// Select 0xc for each lane used from source operand. Zero has 0xc mask
// set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
// Check of we need to combine values from two sources within a byte.
if (!(LHSUsedLanes & RHSUsedLanes) &&
// If we select high and lower word keep it for SDWA.
// TODO: teach SDWA to work with v_perm_b32 and remove the check.
!(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
// Each byte in each mask is either selector mask 0-3, or has higher
// bits set in either of masks, which can be 0xff for 0xff or 0x0c for
// zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
// mask which is not 0xff wins. By anding both masks we have a correct
// result except that 0x0c shall be corrected to give 0x0c only.
uint32_t Mask = LHSMask & RHSMask;
for (unsigned I = 0; I < 32; I += 8) {
uint32_t ByteSel = 0xff << I;
if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
Mask &= (0x0c << I) & 0xffffffff;
}
// Add 4 to each active LHS lane. It will not affect any existing 0xff
// or 0x0c.
uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
SDLoc DL(N);
return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
LHS.getOperand(0), RHS.getOperand(0),
DAG.getConstant(Sel, DL, MVT::i32));
}
}
}
return SDValue();
}
SDValue SITargetLowering::performOrCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
SelectionDAG &DAG = DCI.DAG;
SDValue LHS = N->getOperand(0);
SDValue RHS = N->getOperand(1);
EVT VT = N->getValueType(0);
if (VT == MVT::i1) {
// or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
SDValue Src = LHS.getOperand(0);
if (Src != RHS.getOperand(0))
return SDValue();
const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
if (!CLHS || !CRHS)
return SDValue();
// Only 10 bits are used.
static const uint32_t MaxMask = 0x3ff;
uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
SDLoc DL(N);
return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
Src, DAG.getConstant(NewMask, DL, MVT::i32));
}
return SDValue();
}
// or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
LHS.getOpcode() == AMDGPUISD::PERM &&
isa<ConstantSDNode>(LHS.getOperand(2))) {
uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
if (!Sel)
return SDValue();
Sel |= LHS.getConstantOperandVal(2);
SDLoc DL(N);
return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
}
// or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
uint32_t LHSMask = getPermuteMask(DAG, LHS);
uint32_t RHSMask = getPermuteMask(DAG, RHS);
if (LHSMask != ~0u && RHSMask != ~0u) {
// Canonicalize the expression in an attempt to have fewer unique masks
// and therefore fewer registers used to hold the masks.
if (LHSMask > RHSMask) {
std::swap(LHSMask, RHSMask);
std::swap(LHS, RHS);
}
// Select 0xc for each lane used from source operand. Zero has 0xc mask
// set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
// Check of we need to combine values from two sources within a byte.
if (!(LHSUsedLanes & RHSUsedLanes) &&
// If we select high and lower word keep it for SDWA.
// TODO: teach SDWA to work with v_perm_b32 and remove the check.
!(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
// Kill zero bytes selected by other mask. Zero value is 0xc.
LHSMask &= ~RHSUsedLanes;
RHSMask &= ~LHSUsedLanes;
// Add 4 to each active LHS lane
LHSMask |= LHSUsedLanes & 0x04040404;
// Combine masks
uint32_t Sel = LHSMask | RHSMask;
SDLoc DL(N);
return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
LHS.getOperand(0), RHS.getOperand(0),
DAG.getConstant(Sel, DL, MVT::i32));
}
}
}
if (VT != MVT::i64)
return SDValue();
// TODO: This could be a generic combine with a predicate for extracting the
// high half of an integer being free.
// (or i64:x, (zero_extend i32:y)) ->
// i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
RHS.getOpcode() != ISD::ZERO_EXTEND)
std::swap(LHS, RHS);
if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
SDValue ExtSrc = RHS.getOperand(0);
EVT SrcVT = ExtSrc.getValueType();
if (SrcVT == MVT::i32) {
SDLoc SL(N);
SDValue LowLHS, HiBits;
std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
DCI.AddToWorklist(LowOr.getNode());
DCI.AddToWorklist(HiBits.getNode());
SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
LowOr, HiBits);
return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
}
}
const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
if (CRHS) {
if (SDValue Split
= splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
return Split;
}
return SDValue();
}
SDValue SITargetLowering::performXorCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
EVT VT = N->getValueType(0);
if (VT != MVT::i64)
return SDValue();
SDValue LHS = N->getOperand(0);
SDValue RHS = N->getOperand(1);
const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
if (CRHS) {
if (SDValue Split
= splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
return Split;
}
return SDValue();
}
// Instructions that will be lowered with a final instruction that zeros the
// high result bits.
// XXX - probably only need to list legal operations.
static bool fp16SrcZerosHighBits(unsigned Opc) {
switch (Opc) {
case ISD::FADD:
case ISD::FSUB:
case ISD::FMUL:
case ISD::FDIV:
case ISD::FREM:
case ISD::FMA:
case ISD::FMAD:
case ISD::FCANONICALIZE:
case ISD::FP_ROUND:
case ISD::UINT_TO_FP:
case ISD::SINT_TO_FP:
case ISD::FABS:
// Fabs is lowered to a bit operation, but it's an and which will clear the
// high bits anyway.
case ISD::FSQRT:
case ISD::FSIN:
case ISD::FCOS:
case ISD::FPOWI:
case ISD::FPOW:
case ISD::FLOG:
case ISD::FLOG2:
case ISD::FLOG10:
case ISD::FEXP:
case ISD::FEXP2:
case ISD::FCEIL:
case ISD::FTRUNC:
case ISD::FRINT:
case ISD::FNEARBYINT:
case ISD::FROUND:
case ISD::FFLOOR:
case ISD::FMINNUM:
case ISD::FMAXNUM:
case AMDGPUISD::FRACT:
case AMDGPUISD::CLAMP:
case AMDGPUISD::COS_HW:
case AMDGPUISD::SIN_HW:
case AMDGPUISD::FMIN3:
case AMDGPUISD::FMAX3:
case AMDGPUISD::FMED3:
case AMDGPUISD::FMAD_FTZ:
case AMDGPUISD::RCP:
case AMDGPUISD::RSQ:
case AMDGPUISD::RCP_IFLAG:
case AMDGPUISD::LDEXP:
return true;
default:
// fcopysign, select and others may be lowered to 32-bit bit operations
// which don't zero the high bits.
return false;
}
}
SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
if (!Subtarget->has16BitInsts() ||
DCI.getDAGCombineLevel() < AfterLegalizeDAG)
return SDValue();
EVT VT = N->getValueType(0);
if (VT != MVT::i32)
return SDValue();
SDValue Src = N->getOperand(0);
if (Src.getValueType() != MVT::i16)
return SDValue();
// (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
// FIXME: It is not universally true that the high bits are zeroed on gfx9.
if (Src.getOpcode() == ISD::BITCAST) {
SDValue BCSrc = Src.getOperand(0);
if (BCSrc.getValueType() == MVT::f16 &&
fp16SrcZerosHighBits(BCSrc.getOpcode()))
return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
}
return SDValue();
}
SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
DAGCombinerInfo &DCI)
const {
SDValue Src = N->getOperand(0);
auto *VTSign = cast<VTSDNode>(N->getOperand(1));
if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
VTSign->getVT() == MVT::i8) ||
(Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
VTSign->getVT() == MVT::i16)) &&
Src.hasOneUse()) {
auto *M = cast<MemSDNode>(Src);
SDValue Ops[] = {
Src.getOperand(0), // Chain
Src.getOperand(1), // rsrc
Src.getOperand(2), // vindex
Src.getOperand(3), // voffset
Src.getOperand(4), // soffset
Src.getOperand(5), // offset
Src.getOperand(6),
Src.getOperand(7)
};
// replace with BUFFER_LOAD_BYTE/SHORT
SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
Src.getOperand(0).getValueType());
unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
ResList,
Ops, M->getMemoryVT(),
M->getMemOperand());
return DCI.DAG.getMergeValues({BufferLoadSignExt,
BufferLoadSignExt.getValue(1)}, SDLoc(N));
}
return SDValue();
}
SDValue SITargetLowering::performClassCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
SelectionDAG &DAG = DCI.DAG;
SDValue Mask = N->getOperand(1);
// fp_class x, 0 -> false
if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
if (CMask->isNullValue())
return DAG.getConstant(0, SDLoc(N), MVT::i1);
}
if (N->getOperand(0).isUndef())
return DAG.getUNDEF(MVT::i1);
return SDValue();
}
SDValue SITargetLowering::performRcpCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
EVT VT = N->getValueType(0);
SDValue N0 = N->getOperand(0);
if (N0.isUndef())
return N0;
if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
N0.getOpcode() == ISD::SINT_TO_FP)) {
return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
N->getFlags());
}
return AMDGPUTargetLowering::performRcpCombine(N, DCI);
}
bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
unsigned MaxDepth) const {
unsigned Opcode = Op.getOpcode();
if (Opcode == ISD::FCANONICALIZE)
return true;
if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
auto F = CFP->getValueAPF();
if (F.isNaN() && F.isSignaling())
return false;
return !F.isDenormal() || denormalsEnabledForType(Op.getValueType());
}
// If source is a result of another standard FP operation it is already in
// canonical form.
if (MaxDepth == 0)
return false;
switch (Opcode) {
// These will flush denorms if required.
case ISD::FADD:
case ISD::FSUB:
case ISD::FMUL:
case ISD::FCEIL:
case ISD::FFLOOR:
case ISD::FMA:
case ISD::FMAD:
case ISD::FSQRT:
case ISD::FDIV:
case ISD::FREM:
case ISD::FP_ROUND:
case ISD::FP_EXTEND:
case AMDGPUISD::FMUL_LEGACY:
case AMDGPUISD::FMAD_FTZ:
case AMDGPUISD::RCP:
case AMDGPUISD::RSQ:
case AMDGPUISD::RSQ_CLAMP:
case AMDGPUISD::RCP_LEGACY:
case AMDGPUISD::RSQ_LEGACY:
case AMDGPUISD::RCP_IFLAG:
case AMDGPUISD::TRIG_PREOP:
case AMDGPUISD::DIV_SCALE:
case AMDGPUISD::DIV_FMAS:
case AMDGPUISD::DIV_FIXUP:
case AMDGPUISD::FRACT:
case AMDGPUISD::LDEXP:
case AMDGPUISD::CVT_PKRTZ_F16_F32:
case AMDGPUISD::CVT_F32_UBYTE0:
case AMDGPUISD::CVT_F32_UBYTE1:
case AMDGPUISD::CVT_F32_UBYTE2:
case AMDGPUISD::CVT_F32_UBYTE3:
return true;
// It can/will be lowered or combined as a bit operation.
// Need to check their input recursively to handle.
case ISD::FNEG:
case ISD::FABS:
case ISD::FCOPYSIGN:
return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
case ISD::FSIN:
case ISD::FCOS:
case ISD::FSINCOS:
return Op.getValueType().getScalarType() != MVT::f16;
case ISD::FMINNUM:
case ISD::FMAXNUM:
case ISD::FMINNUM_IEEE:
case ISD::FMAXNUM_IEEE:
case AMDGPUISD::CLAMP:
case AMDGPUISD::FMED3:
case AMDGPUISD::FMAX3:
case AMDGPUISD::FMIN3: {
// FIXME: Shouldn't treat the generic operations different based these.
// However, we aren't really required to flush the result from
// minnum/maxnum..
// snans will be quieted, so we only need to worry about denormals.
if (Subtarget->supportsMinMaxDenormModes() ||
denormalsEnabledForType(Op.getValueType()))
return true;
// Flushing may be required.
// In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
// targets need to check their input recursively.
// FIXME: Does this apply with clamp? It's implemented with max.
for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
return false;
}
return true;
}
case ISD::SELECT: {
return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
}
case ISD::BUILD_VECTOR: {
for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
SDValue SrcOp = Op.getOperand(i);
if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
return false;
}
return true;
}
case ISD::EXTRACT_VECTOR_ELT:
case ISD::EXTRACT_SUBVECTOR: {
return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
}
case ISD::INSERT_VECTOR_ELT: {
return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
}
case ISD::UNDEF:
// Could be anything.
return false;
case ISD::BITCAST: {
// Hack round the mess we make when legalizing extract_vector_elt
SDValue Src = Op.getOperand(0);
if (Src.getValueType() == MVT::i16 &&
Src.getOpcode() == ISD::TRUNCATE) {
SDValue TruncSrc = Src.getOperand(0);
if (TruncSrc.getValueType() == MVT::i32 &&
TruncSrc.getOpcode() == ISD::BITCAST &&
TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
}
}
return false;
}
case ISD::INTRINSIC_WO_CHAIN: {
unsigned IntrinsicID
= cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
// TODO: Handle more intrinsics
switch (IntrinsicID) {
case Intrinsic::amdgcn_cvt_pkrtz:
case Intrinsic::amdgcn_cubeid:
case Intrinsic::amdgcn_frexp_mant:
case Intrinsic::amdgcn_fdot2:
return true;
default:
break;
}
LLVM_FALLTHROUGH;
}
default:
return denormalsEnabledForType(Op.getValueType()) &&
DAG.isKnownNeverSNaN(Op);
}
llvm_unreachable("invalid operation");
}
// Constant fold canonicalize.
SDValue SITargetLowering::getCanonicalConstantFP(
SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
// Flush denormals to 0 if not enabled.
if (C.isDenormal() && !denormalsEnabledForType(VT))
return DAG.getConstantFP(0.0, SL, VT);
if (C.isNaN()) {
APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
if (C.isSignaling()) {
// Quiet a signaling NaN.
// FIXME: Is this supposed to preserve payload bits?
return DAG.getConstantFP(CanonicalQNaN, SL, VT);
}
// Make sure it is the canonical NaN bitpattern.
//
// TODO: Can we use -1 as the canonical NaN value since it's an inline
// immediate?
if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
return DAG.getConstantFP(CanonicalQNaN, SL, VT);
}
// Already canonical.
return DAG.getConstantFP(C, SL, VT);
}
static bool vectorEltWillFoldAway(SDValue Op) {
return Op.isUndef() || isa<ConstantFPSDNode>(Op);
}
SDValue SITargetLowering::performFCanonicalizeCombine(
SDNode *N,
DAGCombinerInfo &DCI) const {
SelectionDAG &DAG = DCI.DAG;
SDValue N0 = N->getOperand(0);
EVT VT = N->getValueType(0);
// fcanonicalize undef -> qnan
if (N0.isUndef()) {
APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
return DAG.getConstantFP(QNaN, SDLoc(N), VT);
}
if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
EVT VT = N->getValueType(0);
return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
}
// fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
// (fcanonicalize k)
//
// fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
// TODO: This could be better with wider vectors that will be split to v2f16,
// and to consider uses since there aren't that many packed operations.
if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
isTypeLegal(MVT::v2f16)) {
SDLoc SL(N);
SDValue NewElts[2];
SDValue Lo = N0.getOperand(0);
SDValue Hi = N0.getOperand(1);
EVT EltVT = Lo.getValueType();
if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
for (unsigned I = 0; I != 2; ++I) {
SDValue Op = N0.getOperand(I);
if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
CFP->getValueAPF());
} else if (Op.isUndef()) {
// Handled below based on what the other operand is.
NewElts[I] = Op;
} else {
NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
}
}
// If one half is undef, and one is constant, perfer a splat vector rather
// than the normal qNaN. If it's a register, prefer 0.0 since that's
// cheaper to use and may be free with a packed operation.
if (NewElts[0].isUndef()) {
if (isa<ConstantFPSDNode>(NewElts[1]))
NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
}
if (NewElts[1].isUndef()) {
NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
}
return DAG.getBuildVector(VT, SL, NewElts);
}
}
unsigned SrcOpc = N0.getOpcode();
// If it's free to do so, push canonicalizes further up the source, which may
// find a canonical source.
//
// TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
// sNaNs.
if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
if (CRHS && N0.hasOneUse()) {
SDLoc SL(N);
SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
N0.getOperand(0));
SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
DCI.AddToWorklist(Canon0.getNode());
return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
}
}
return isCanonicalized(DAG, N0) ? N0 : SDValue();
}
static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
switch (Opc) {
case ISD::FMAXNUM:
case ISD::FMAXNUM_IEEE:
return AMDGPUISD::FMAX3;
case ISD::SMAX:
return AMDGPUISD::SMAX3;
case ISD::UMAX:
return AMDGPUISD::UMAX3;
case ISD::FMINNUM:
case ISD::FMINNUM_IEEE:
return AMDGPUISD::FMIN3;
case ISD::SMIN:
return AMDGPUISD::SMIN3;
case ISD::UMIN:
return AMDGPUISD::UMIN3;
default:
llvm_unreachable("Not a min/max opcode");
}
}
SDValue SITargetLowering::performIntMed3ImmCombine(
SelectionDAG &DAG, const SDLoc &SL,
SDValue Op0, SDValue Op1, bool Signed) const {
ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
if (!K1)
return SDValue();
ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
if (!K0)
return SDValue();
if (Signed) {
if (K0->getAPIntValue().sge(K1->getAPIntValue()))
return SDValue();
} else {
if (K0->getAPIntValue().uge(K1->getAPIntValue()))
return SDValue();
}
EVT VT = K0->getValueType(0);
unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
return DAG.getNode(Med3Opc, SL, VT,
Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
}
// If there isn't a 16-bit med3 operation, convert to 32-bit.
MVT NVT = MVT::i32;
unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
}
static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
return C;
if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
return C;
}
return nullptr;
}
SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
const SDLoc &SL,
SDValue Op0,
SDValue Op1) const {
ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
if (!K1)
return SDValue();
ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
if (!K0)
return SDValue();
// Ordered >= (although NaN inputs should have folded away by now).
APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
if (Cmp == APFloat::cmpGreaterThan)
return SDValue();
const MachineFunction &MF = DAG.getMachineFunction();
const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
// TODO: Check IEEE bit enabled?
EVT VT = Op0.getValueType();
if (Info->getMode().DX10Clamp) {
// If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
// hardware fmed3 behavior converting to a min.
// FIXME: Should this be allowing -0.0?
if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
}
// med3 for f16 is only available on gfx9+, and not available for v2f16.
if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
// This isn't safe with signaling NaNs because in IEEE mode, min/max on a
// signaling NaN gives a quiet NaN. The quiet NaN input to the min would
// then give the other result, which is different from med3 with a NaN
// input.
SDValue Var = Op0.getOperand(0);
if (!DAG.isKnownNeverSNaN(Var))
return SDValue();
const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
if ((!K0->hasOneUse() ||
TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
(!K1->hasOneUse() ||
TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
Var, SDValue(K0, 0), SDValue(K1, 0));
}
}
return SDValue();
}
SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
SelectionDAG &DAG = DCI.DAG;
EVT VT = N->getValueType(0);
unsigned Opc = N->getOpcode();
SDValue Op0 = N->getOperand(0);
SDValue Op1 = N->getOperand(1);
// Only do this if the inner op has one use since this will just increases
// register pressure for no benefit.
if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
!VT.isVector() &&
(VT == MVT::i32 || VT == MVT::f32 ||
((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
// max(max(a, b), c) -> max3(a, b, c)
// min(min(a, b), c) -> min3(a, b, c)
if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
SDLoc DL(N);
return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
DL,
N->getValueType(0),
Op0.getOperand(0),
Op0.getOperand(1),
Op1);
}
// Try commuted.
// max(a, max(b, c)) -> max3(a, b, c)
// min(a, min(b, c)) -> min3(a, b, c)
if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
SDLoc DL(N);
return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
DL,
N->getValueType(0),
Op0,
Op1.getOperand(0),
Op1.getOperand(1));
}
}
// min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
return Med3;
}
if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
return Med3;
}
// fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
(Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
(Opc == AMDGPUISD::FMIN_LEGACY &&
Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
(VT == MVT::f32 || VT == MVT::f64 ||
(VT == MVT::f16 && Subtarget->has16BitInsts()) ||
(VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
Op0.hasOneUse()) {
if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
return Res;
}
return SDValue();
}
static bool isClampZeroToOne(SDValue A, SDValue B) {
if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
// FIXME: Should this be allowing -0.0?
return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
(CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
}
}
return false;
}
// FIXME: Should only worry about snans for version with chain.
SDValue SITargetLowering::performFMed3Combine(SDNode *N,
DAGCombinerInfo &DCI) const {
EVT VT = N->getValueType(0);
// v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
// NaNs. With a NaN input, the order of the operands may change the result.
SelectionDAG &DAG = DCI.DAG;
SDLoc SL(N);
SDValue Src0 = N->getOperand(0);
SDValue Src1 = N->getOperand(1);
SDValue Src2 = N->getOperand(2);
if (isClampZeroToOne(Src0, Src1)) {
// const_a, const_b, x -> clamp is safe in all cases including signaling
// nans.
// FIXME: Should this be allowing -0.0?
return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
}
const MachineFunction &MF = DAG.getMachineFunction();
const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
// FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
// handling no dx10-clamp?
if (Info->getMode().DX10Clamp) {
// If NaNs is clamped to 0, we are free to reorder the inputs.
if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
std::swap(Src0, Src1);
if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
std::swap(Src1, Src2);
if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
std::swap(Src0, Src1);
if (isClampZeroToOne(Src1, Src2))
return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
}
return SDValue();
}
SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
SDValue Src0 = N->getOperand(0);
SDValue Src1 = N->getOperand(1);
if (Src0.isUndef() && Src1.isUndef())
return DCI.DAG.getUNDEF(N->getValueType(0));
return SDValue();
}
SDValue SITargetLowering::performExtractVectorEltCombine(
SDNode *N, DAGCombinerInfo &DCI) const {
SDValue Vec = N->getOperand(0);
SelectionDAG &DAG = DCI.DAG;
EVT VecVT = Vec.getValueType();
EVT EltVT = VecVT.getVectorElementType();
if ((Vec.getOpcode() == ISD::FNEG ||
Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
SDLoc SL(N);
EVT EltVT = N->getValueType(0);
SDValue Idx = N->getOperand(1);
SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
Vec.getOperand(0), Idx);
return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
}
// ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
// =>
// Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
// Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
// ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
SDLoc SL(N);
EVT EltVT = N->getValueType(0);
SDValue Idx = N->getOperand(1);
unsigned Opc = Vec.getOpcode();
switch(Opc) {
default:
break;
// TODO: Support other binary operations.
case ISD::FADD:
case ISD::FSUB:
case ISD::FMUL:
case ISD::ADD:
case ISD::UMIN:
case ISD::UMAX:
case ISD::SMIN:
case ISD::SMAX:
case ISD::FMAXNUM:
case ISD::FMINNUM:
case ISD::FMAXNUM_IEEE:
case ISD::FMINNUM_IEEE: {
SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
Vec.getOperand(0), Idx);
SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
Vec.getOperand(1), Idx);
DCI.AddToWorklist(Elt0.getNode());
DCI.AddToWorklist(Elt1.getNode());
return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
}
}
}
unsigned VecSize = VecVT.getSizeInBits();
unsigned EltSize = EltVT.getSizeInBits();
// EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
// This elminates non-constant index and subsequent movrel or scratch access.
// Sub-dword vectors of size 2 dword or less have better implementation.
// Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
// instructions.
if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
!isa<ConstantSDNode>(N->getOperand(1))) {
SDLoc SL(N);
SDValue Idx = N->getOperand(1);
EVT IdxVT = Idx.getValueType();
SDValue V;
for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
SDValue IC = DAG.getConstant(I, SL, IdxVT);
SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
if (I == 0)
V = Elt;
else
V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
}
return V;
}
if (!DCI.isBeforeLegalize())
return SDValue();
// Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
// elements. This exposes more load reduction opportunities by replacing
// multiple small extract_vector_elements with a single 32-bit extract.
auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
if (isa<MemSDNode>(Vec) &&
EltSize <= 16 &&
EltVT.isByteSized() &&
VecSize > 32 &&
VecSize % 32 == 0 &&
Idx) {
EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
unsigned BitIndex = Idx->getZExtValue() * EltSize;
unsigned EltIdx = BitIndex / 32;
unsigned LeftoverBitIdx = BitIndex % 32;
SDLoc SL(N);
SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
DCI.AddToWorklist(Cast.getNode());
SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
DAG.getConstant(EltIdx, SL, MVT::i32));
DCI.AddToWorklist(Elt.getNode());
SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
DCI.AddToWorklist(Srl.getNode());
SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
DCI.AddToWorklist(Trunc.getNode());
return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
}
return SDValue();
}
SDValue
SITargetLowering::performInsertVectorEltCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
SDValue Vec = N->getOperand(0);
SDValue Idx = N->getOperand(2);
EVT VecVT = Vec.getValueType();
EVT EltVT = VecVT.getVectorElementType();
unsigned VecSize = VecVT.getSizeInBits();
unsigned EltSize = EltVT.getSizeInBits();
// INSERT_VECTOR_ELT (<n x e>, var-idx)
// => BUILD_VECTOR n x select (e, const-idx)
// This elminates non-constant index and subsequent movrel or scratch access.
// Sub-dword vectors of size 2 dword or less have better implementation.
// Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
// instructions.
if (isa<ConstantSDNode>(Idx) ||
VecSize > 256 || (VecSize <= 64 && EltSize < 32))
return SDValue();
SelectionDAG &DAG = DCI.DAG;
SDLoc SL(N);
SDValue Ins = N->getOperand(1);
EVT IdxVT = Idx.getValueType();
SmallVector<SDValue, 16> Ops;
for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
SDValue IC = DAG.getConstant(I, SL, IdxVT);
SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
Ops.push_back(V);
}
return DAG.getBuildVector(VecVT, SL, Ops);
}
unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
const SDNode *N0,
const SDNode *N1) const {
EVT VT = N0->getValueType(0);
// Only do this if we are not trying to support denormals. v_mad_f32 does not
// support denormals ever.
if (((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
(VT == MVT::f16 && !Subtarget->hasFP16Denormals() &&
getSubtarget()->hasMadF16())) &&
isOperationLegal(ISD::FMAD, VT))
return ISD::FMAD;
const TargetOptions &Options = DAG.getTarget().Options;
if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
(N0->getFlags().hasAllowContract() &&
N1->getFlags().hasAllowContract())) &&
isFMAFasterThanFMulAndFAdd(VT)) {
return ISD::FMA;
}
return 0;
}
// For a reassociatable opcode perform:
// op x, (op y, z) -> op (op x, z), y, if x and z are uniform
SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
SelectionDAG &DAG) const {
EVT VT = N->getValueType(0);
if (VT != MVT::i32 && VT != MVT::i64)
return SDValue();
unsigned Opc = N->getOpcode();
SDValue Op0 = N->getOperand(0);
SDValue Op1 = N->getOperand(1);
if (!(Op0->isDivergent() ^ Op1->isDivergent()))
return SDValue();
if (Op0->isDivergent())
std::swap(Op0, Op1);
if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
return SDValue();
SDValue Op2 = Op1.getOperand(1);
Op1 = Op1.getOperand(0);
if (!(Op1->isDivergent() ^ Op2->isDivergent()))
return SDValue();
if (Op1->isDivergent())
std::swap(Op1, Op2);
// If either operand is constant this will conflict with
// DAGCombiner::ReassociateOps().
if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
DAG.isConstantIntBuildVectorOrConstantInt(Op1))
return SDValue();
SDLoc SL(N);
SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
return DAG.getNode(Opc, SL, VT, Add1, Op2);
}
static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
EVT VT,
SDValue N0, SDValue N1, SDValue N2,
bool Signed) {
unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
}
SDValue SITargetLowering::performAddCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
SelectionDAG &DAG = DCI.DAG;
EVT VT = N->getValueType(0);
SDLoc SL(N);
SDValue LHS = N->getOperand(0);
SDValue RHS = N->getOperand(1);
if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
&& Subtarget->hasMad64_32() &&
!VT.isVector() && VT.getScalarSizeInBits() > 32 &&
VT.getScalarSizeInBits() <= 64) {
if (LHS.getOpcode() != ISD::MUL)
std::swap(LHS, RHS);
SDValue MulLHS = LHS.getOperand(0);
SDValue MulRHS = LHS.getOperand(1);
SDValue AddRHS = RHS;
// TODO: Maybe restrict if SGPR inputs.
if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
numBitsUnsigned(MulRHS, DAG) <= 32) {
MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
}
if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
}
return SDValue();
}
if (SDValue V = reassociateScalarOps(N, DAG)) {
return V;
}
if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
return SDValue();
// add x, zext (setcc) => addcarry x, 0, setcc
// add x, sext (setcc) => subcarry x, 0, setcc
unsigned Opc = LHS.getOpcode();
if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
std::swap(RHS, LHS);
Opc = RHS.getOpcode();
switch (Opc) {
default: break;
case ISD::ZERO_EXTEND:
case ISD::SIGN_EXTEND:
case ISD::ANY_EXTEND: {
auto Cond = RHS.getOperand(0);
if (!isBoolSGPR(Cond))
break;
SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
return DAG.getNode(Opc, SL, VTList, Args);
}
case ISD::ADDCARRY: {
// add x, (addcarry y, 0, cc) => addcarry x, y, cc
auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
if (!C || C->getZExtValue() != 0) break;
SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
}
}
return SDValue();
}
SDValue SITargetLowering::performSubCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
SelectionDAG &DAG = DCI.DAG;
EVT VT = N->getValueType(0);
if (VT != MVT::i32)
return SDValue();
SDLoc SL(N);
SDValue LHS = N->getOperand(0);
SDValue RHS = N->getOperand(1);
if (LHS.getOpcode() == ISD::SUBCARRY) {
// sub (subcarry x, 0, cc), y => subcarry x, y, cc
auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
if (!C || !C->isNullValue())
return SDValue();
SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
}
return SDValue();
}
SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
if (N->getValueType(0) != MVT::i32)
return SDValue();
auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
if (!C || C->getZExtValue() != 0)
return SDValue();
SelectionDAG &DAG = DCI.DAG;
SDValue LHS = N->getOperand(0);
// addcarry (add x, y), 0, cc => addcarry x, y, cc
// subcarry (sub x, y), 0, cc => subcarry x, y, cc
unsigned LHSOpc = LHS.getOpcode();
unsigned Opc = N->getOpcode();
if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
(LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
}
return SDValue();
}
SDValue SITargetLowering::performFAddCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
return SDValue();
SelectionDAG &DAG = DCI.DAG;
EVT VT = N->getValueType(0);
SDLoc SL(N);
SDValue LHS = N->getOperand(0);
SDValue RHS = N->getOperand(1);
// These should really be instruction patterns, but writing patterns with
// source modiifiers is a pain.
// fadd (fadd (a, a), b) -> mad 2.0, a, b
if (LHS.getOpcode() == ISD::FADD) {
SDValue A = LHS.getOperand(0);
if (A == LHS.getOperand(1)) {
unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
if (FusedOp != 0) {
const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
}
}
}
// fadd (b, fadd (a, a)) -> mad 2.0, a, b
if (RHS.getOpcode() == ISD::FADD) {
SDValue A = RHS.getOperand(0);
if (A == RHS.getOperand(1)) {
unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
if (FusedOp != 0) {
const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
}
}
}
return SDValue();
}
SDValue SITargetLowering::performFSubCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
return SDValue();
SelectionDAG &DAG = DCI.DAG;
SDLoc SL(N);
EVT VT = N->getValueType(0);
assert(!VT.isVector());
// Try to get the fneg to fold into the source modifier. This undoes generic
// DAG combines and folds them into the mad.
//
// Only do this if we are not trying to support denormals. v_mad_f32 does
// not support denormals ever.
SDValue LHS = N->getOperand(0);
SDValue RHS = N->getOperand(1);
if (LHS.getOpcode() == ISD::FADD) {
// (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
SDValue A = LHS.getOperand(0);
if (A == LHS.getOperand(1)) {
unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
if (FusedOp != 0){
const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
}
}
}
if (RHS.getOpcode() == ISD::FADD) {
// (fsub c, (fadd a, a)) -> mad -2.0, a, c
SDValue A = RHS.getOperand(0);
if (A == RHS.getOperand(1)) {
unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
if (FusedOp != 0){
const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
}
}
}
return SDValue();
}
SDValue SITargetLowering::performFMACombine(SDNode *N,
DAGCombinerInfo &DCI) const {
SelectionDAG &DAG = DCI.DAG;
EVT VT = N->getValueType(0);
SDLoc SL(N);
if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
return SDValue();
// FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
// FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
SDValue Op1 = N->getOperand(0);
SDValue Op2 = N->getOperand(1);
SDValue FMA = N->getOperand(2);
if (FMA.getOpcode() != ISD::FMA ||
Op1.getOpcode() != ISD::FP_EXTEND ||
Op2.getOpcode() != ISD::FP_EXTEND)
return SDValue();
// fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
// regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
// is sufficient to allow generaing fdot2.
const TargetOptions &Options = DAG.getTarget().Options;
if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
(N->getFlags().hasAllowContract() &&
FMA->getFlags().hasAllowContract())) {
Op1 = Op1.getOperand(0);
Op2 = Op2.getOperand(0);
if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
return SDValue();
SDValue Vec1 = Op1.getOperand(0);
SDValue Idx1 = Op1.getOperand(1);
SDValue Vec2 = Op2.getOperand(0);
SDValue FMAOp1 = FMA.getOperand(0);
SDValue FMAOp2 = FMA.getOperand(1);
SDValue FMAAcc = FMA.getOperand(2);
if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
FMAOp2.getOpcode() != ISD::FP_EXTEND)
return SDValue();
FMAOp1 = FMAOp1.getOperand(0);
FMAOp2 = FMAOp2.getOperand(0);
if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
return SDValue();
SDValue Vec3 = FMAOp1.getOperand(0);
SDValue Vec4 = FMAOp2.getOperand(0);
SDValue Idx2 = FMAOp1.getOperand(1);
if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
// Idx1 and Idx2 cannot be the same.
Idx1 == Idx2)
return SDValue();
if (Vec1 == Vec2 || Vec3 == Vec4)
return SDValue();
if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
return SDValue();
if ((Vec1 == Vec3 && Vec2 == Vec4) ||
(Vec1 == Vec4 && Vec2 == Vec3)) {
return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
DAG.getTargetConstant(0, SL, MVT::i1));
}
}
return SDValue();
}
SDValue SITargetLowering::performSetCCCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
SelectionDAG &DAG = DCI.DAG;
SDLoc SL(N);
SDValue LHS = N->getOperand(0);
SDValue RHS = N->getOperand(1);
EVT VT = LHS.getValueType();
ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
auto CRHS = dyn_cast<ConstantSDNode>(RHS);
if (!CRHS) {
CRHS = dyn_cast<ConstantSDNode>(LHS);
if (CRHS) {
std::swap(LHS, RHS);
CC = getSetCCSwappedOperands(CC);
}
}
if (CRHS) {
if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
isBoolSGPR(LHS.getOperand(0))) {
// setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
// setcc (sext from i1 cc), -1, eq|sle|uge) => cc
// setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1
// setcc (sext from i1 cc), 0, ne|ugt|slt) => cc
if ((CRHS->isAllOnesValue() &&
(CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
(CRHS->isNullValue() &&
(CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
DAG.getConstant(-1, SL, MVT::i1));
if ((CRHS->isAllOnesValue() &&
(CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
(CRHS->isNullValue() &&
(CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
return LHS.getOperand(0);
}
uint64_t CRHSVal = CRHS->getZExtValue();
if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
LHS.getOpcode() == ISD::SELECT &&
isa<ConstantSDNode>(LHS.getOperand(1)) &&
isa<ConstantSDNode>(LHS.getOperand(2)) &&
LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
isBoolSGPR(LHS.getOperand(0))) {
// Given CT != FT:
// setcc (select cc, CT, CF), CF, eq => xor cc, -1
// setcc (select cc, CT, CF), CF, ne => cc
// setcc (select cc, CT, CF), CT, ne => xor cc, -1
// setcc (select cc, CT, CF), CT, eq => cc
uint64_t CT = LHS.getConstantOperandVal(1);
uint64_t CF = LHS.getConstantOperandVal(2);
if ((CF == CRHSVal && CC == ISD::SETEQ) ||
(CT == CRHSVal && CC == ISD::SETNE))
return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
DAG.getConstant(-1, SL, MVT::i1));
if ((CF == CRHSVal && CC == ISD::SETNE) ||
(CT == CRHSVal && CC == ISD::SETEQ))
return LHS.getOperand(0);
}
}
if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
VT != MVT::f16))
return SDValue();
// Match isinf/isfinite pattern
// (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
// (fcmp one (fabs x), inf) -> (fp_class x,
// (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
if (!CRHS)
return SDValue();
const APFloat &APF = CRHS->getValueAPF();
if (APF.isInfinity() && !APF.isNegative()) {
const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
SIInstrFlags::N_INFINITY;
const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
SIInstrFlags::P_ZERO |
SIInstrFlags::N_NORMAL |
SIInstrFlags::P_NORMAL |
SIInstrFlags::N_SUBNORMAL |
SIInstrFlags::P_SUBNORMAL;
unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
DAG.getConstant(Mask, SL, MVT::i32));
}
}
return SDValue();
}
SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
SelectionDAG &DAG = DCI.DAG;
SDLoc SL(N);
unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
SDValue Src = N->getOperand(0);
SDValue Srl = N->getOperand(0);
if (Srl.getOpcode() == ISD::ZERO_EXTEND)
Srl = Srl.getOperand(0);
// TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
if (Srl.getOpcode() == ISD::SRL) {
// cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
// cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
// cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
if (const ConstantSDNode *C =
dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
EVT(MVT::i32));
unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
if (SrcOffset < 32 && SrcOffset % 8 == 0) {
return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
MVT::f32, Srl);
}
}
}
APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
KnownBits Known;
TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
!DCI.isBeforeLegalizeOps());
const TargetLowering &TLI = DAG.getTargetLoweringInfo();
if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
DCI.CommitTargetLoweringOpt(TLO);
}
return SDValue();
}
SDValue SITargetLowering::performClampCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
if (!CSrc)
return SDValue();
const MachineFunction &MF = DCI.DAG.getMachineFunction();
const APFloat &F = CSrc->getValueAPF();
APFloat Zero = APFloat::getZero(F.getSemantics());
APFloat::cmpResult Cmp0 = F.compare(Zero);
if (Cmp0 == APFloat::cmpLessThan ||
(Cmp0 == APFloat::cmpUnordered &&
MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
}
APFloat One(F.getSemantics(), "1.0");
APFloat::cmpResult Cmp1 = F.compare(One);
if (Cmp1 == APFloat::cmpGreaterThan)
return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
return SDValue(CSrc, 0);
}
SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
DAGCombinerInfo &DCI) const {
if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
return SDValue();
switch (N->getOpcode()) {
default:
return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
case ISD::ADD:
return performAddCombine(N, DCI);
case ISD::SUB:
return performSubCombine(N, DCI);
case ISD::ADDCARRY:
case ISD::SUBCARRY:
return performAddCarrySubCarryCombine(N, DCI);
case ISD::FADD:
return performFAddCombine(N, DCI);
case ISD::FSUB:
return performFSubCombine(N, DCI);
case ISD::SETCC:
return performSetCCCombine(N, DCI);
case ISD::FMAXNUM:
case ISD::FMINNUM:
case ISD::FMAXNUM_IEEE:
case ISD::FMINNUM_IEEE:
case ISD::SMAX:
case ISD::SMIN:
case ISD::UMAX:
case ISD::UMIN:
case AMDGPUISD::FMIN_LEGACY:
case AMDGPUISD::FMAX_LEGACY:
return performMinMaxCombine(N, DCI);
case ISD::FMA:
return performFMACombine(N, DCI);
case ISD::LOAD: {
if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
return Widended;
LLVM_FALLTHROUGH;
}
case ISD::STORE:
case ISD::ATOMIC_LOAD:
case ISD::ATOMIC_STORE:
case ISD::ATOMIC_CMP_SWAP:
case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
case ISD::ATOMIC_SWAP:
case ISD::ATOMIC_LOAD_ADD:
case ISD::ATOMIC_LOAD_SUB:
case ISD::ATOMIC_LOAD_AND:
case ISD::ATOMIC_LOAD_OR:
case ISD::ATOMIC_LOAD_XOR:
case ISD::ATOMIC_LOAD_NAND:
case ISD::ATOMIC_LOAD_MIN:
case ISD::ATOMIC_LOAD_MAX:
case ISD::ATOMIC_LOAD_UMIN:
case ISD::ATOMIC_LOAD_UMAX:
case ISD::ATOMIC_LOAD_FADD:
case AMDGPUISD::ATOMIC_INC:
case AMDGPUISD::ATOMIC_DEC:
case AMDGPUISD::ATOMIC_LOAD_FMIN:
case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
if (DCI.isBeforeLegalize())
break;
return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
case ISD::AND:
return performAndCombine(N, DCI);
case ISD::OR:
return performOrCombine(N, DCI);
case ISD::XOR:
return performXorCombine(N, DCI);
case ISD::ZERO_EXTEND:
return performZeroExtendCombine(N, DCI);
case ISD::SIGN_EXTEND_INREG:
return performSignExtendInRegCombine(N , DCI);
case AMDGPUISD::FP_CLASS:
return performClassCombine(N, DCI);
case ISD::FCANONICALIZE:
return performFCanonicalizeCombine(N, DCI);
case AMDGPUISD::RCP:
return performRcpCombine(N, DCI);
case AMDGPUISD::FRACT:
case AMDGPUISD::RSQ:
case AMDGPUISD::RCP_LEGACY:
case AMDGPUISD::RSQ_LEGACY:
case AMDGPUISD::RCP_IFLAG:
case AMDGPUISD::RSQ_CLAMP:
case AMDGPUISD::LDEXP: {
SDValue Src = N->getOperand(0);
if (Src.isUndef())
return Src;
break;
}
case ISD::SINT_TO_FP:
case ISD::UINT_TO_FP:
return performUCharToFloatCombine(N, DCI);
case AMDGPUISD::CVT_F32_UBYTE0:
case AMDGPUISD::CVT_F32_UBYTE1:
case AMDGPUISD::CVT_F32_UBYTE2:
case AMDGPUISD::CVT_F32_UBYTE3:
return performCvtF32UByteNCombine(N, DCI);
case AMDGPUISD::FMED3:
return performFMed3Combine(N, DCI);
case AMDGPUISD::CVT_PKRTZ_F16_F32:
return performCvtPkRTZCombine(N, DCI);
case AMDGPUISD::CLAMP:
return performClampCombine(N, DCI);
case ISD::SCALAR_TO_VECTOR: {
SelectionDAG &DAG = DCI.DAG;
EVT VT = N->getValueType(0);
// v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
if (VT == MVT::v2i16 || VT == MVT::v2f16) {
SDLoc SL(N);
SDValue Src = N->getOperand(0);
EVT EltVT = Src.getValueType();
if (EltVT == MVT::f16)
Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
}
break;
}
case ISD::EXTRACT_VECTOR_ELT:
return performExtractVectorEltCombine(N, DCI);
case ISD::INSERT_VECTOR_ELT:
return performInsertVectorEltCombine(N, DCI);
}
return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
}
/// Helper function for adjustWritemask
static unsigned SubIdx2Lane(unsigned Idx) {
switch (Idx) {
default: return 0;
case AMDGPU::sub0: return 0;
case AMDGPU::sub1: return 1;
case AMDGPU::sub2: return 2;
case AMDGPU::sub3: return 3;
case AMDGPU::sub4: return 4; // Possible with TFE/LWE
}
}
/// Adjust the writemask of MIMG instructions
SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
SelectionDAG &DAG) const {
unsigned Opcode = Node->getMachineOpcode();
// Subtract 1 because the vdata output is not a MachineSDNode operand.
int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
return Node; // not implemented for D16
SDNode *Users[5] = { nullptr };
unsigned Lane = 0;
unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
unsigned NewDmask = 0;
unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
unsigned TFCLane = 0;
bool HasChain = Node->getNumValues() > 1;
if (OldDmask == 0) {
// These are folded out, but on the chance it happens don't assert.
return Node;
}
unsigned OldBitsSet = countPopulation(OldDmask);
// Work out which is the TFE/LWE lane if that is enabled.
if (UsesTFC) {
TFCLane = OldBitsSet;
}
// Try to figure out the used register components
for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
I != E; ++I) {
// Don't look at users of the chain.
if (I.getUse().getResNo() != 0)
continue;
// Abort if we can't understand the usage
if (!I->isMachineOpcode() ||
I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
return Node;
// Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
// Note that subregs are packed, i.e. Lane==0 is the first bit set
// in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
// set, etc.
Lane = SubIdx2Lane(I->getConstantOperandVal(1));
// Check if the use is for the TFE/LWE generated result at VGPRn+1.
if (UsesTFC && Lane == TFCLane) {
Users[Lane] = *I;
} else {
// Set which texture component corresponds to the lane.
unsigned Comp;
for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
Comp = countTrailingZeros(Dmask);
Dmask &= ~(1 << Comp);
}
// Abort if we have more than one user per component.
if (Users[Lane])
return Node;
Users[Lane] = *I;
NewDmask |= 1 << Comp;
}
}
// Don't allow 0 dmask, as hardware assumes one channel enabled.
bool NoChannels = !NewDmask;
if (NoChannels) {
if (!UsesTFC) {
// No uses of the result and not using TFC. Then do nothing.
return Node;
}
// If the original dmask has one channel - then nothing to do
if (OldBitsSet == 1)
return Node;
// Use an arbitrary dmask - required for the instruction to work
NewDmask = 1;
}
// Abort if there's no change
if (NewDmask == OldDmask)
return Node;
unsigned BitsSet = countPopulation(NewDmask);
// Check for TFE or LWE - increase the number of channels by one to account
// for the extra return value
// This will need adjustment for D16 if this is also included in
// adjustWriteMask (this function) but at present D16 are excluded.
unsigned NewChannels = BitsSet + UsesTFC;
int NewOpcode =
AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
assert(NewOpcode != -1 &&
NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
"failed to find equivalent MIMG op");
// Adjust the writemask in the node
SmallVector<SDValue, 12> Ops;
Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
MVT ResultVT = NewChannels == 1 ?
SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
NewChannels == 5 ? 8 : NewChannels);
SDVTList NewVTList = HasChain ?
DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
NewVTList, Ops);
if (HasChain) {
// Update chain.
DAG.setNodeMemRefs(NewNode, Node->memoperands());
DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
}
if (NewChannels == 1) {
assert(Node->hasNUsesOfValue(1, 0));
SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
SDLoc(Node), Users[Lane]->getValueType(0),
SDValue(NewNode, 0));
DAG.ReplaceAllUsesWith(Users[Lane], Copy);
return nullptr;
}
// Update the users of the node with the new indices
for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
SDNode *User = Users[i];
if (!User) {
// Handle the special case of NoChannels. We set NewDmask to 1 above, but
// Users[0] is still nullptr because channel 0 doesn't really have a use.
if (i || !NoChannels)
continue;
} else {
SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
}
switch (Idx) {
default: break;
case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
}
}
DAG.RemoveDeadNode(Node);
return nullptr;
}
static bool isFrameIndexOp(SDValue Op) {
if (Op.getOpcode() == ISD::AssertZext)
Op = Op.getOperand(0);
return isa<FrameIndexSDNode>(Op);
}
/// Legalize target independent instructions (e.g. INSERT_SUBREG)
/// with frame index operands.
/// LLVM assumes that inputs are to these instructions are registers.
SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
SelectionDAG &DAG) const {
if (Node->getOpcode() == ISD::CopyToReg) {
RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
SDValue SrcVal = Node->getOperand(2);
// Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
// to try understanding copies to physical registers.
if (SrcVal.getValueType() == MVT::i1 &&
Register::isPhysicalRegister(DestReg->getReg())) {
SDLoc SL(Node);
MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
SDValue VReg = DAG.getRegister(
MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
SDNode *Glued = Node->getGluedNode();
SDValue ToVReg
= DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
SDValue ToResultReg
= DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
VReg, ToVReg.getValue(1));
DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
DAG.RemoveDeadNode(Node);
return ToResultReg.getNode();
}
}
SmallVector<SDValue, 8> Ops;
for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
if (!isFrameIndexOp(Node->getOperand(i))) {
Ops.push_back(Node->getOperand(i));
continue;
}
SDLoc DL(Node);
Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
Node->getOperand(i).getValueType(),
Node->getOperand(i)), 0));
}
return DAG.UpdateNodeOperands(Node, Ops);
}
/// Fold the instructions after selecting them.
/// Returns null if users were already updated.
SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
SelectionDAG &DAG) const {
const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
unsigned Opcode = Node->getMachineOpcode();
if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
!TII->isGather4(Opcode)) {
return adjustWritemask(Node, DAG);
}
if (Opcode == AMDGPU::INSERT_SUBREG ||
Opcode == AMDGPU::REG_SEQUENCE) {
legalizeTargetIndependentNode(Node, DAG);
return Node;
}
switch (Opcode) {
case AMDGPU::V_DIV_SCALE_F32:
case AMDGPU::V_DIV_SCALE_F64: {
// Satisfy the operand register constraint when one of the inputs is
// undefined. Ordinarily each undef value will have its own implicit_def of
// a vreg, so force these to use a single register.
SDValue Src0 = Node->getOperand(0);
SDValue Src1 = Node->getOperand(1);
SDValue Src2 = Node->getOperand(2);
if ((Src0.isMachineOpcode() &&
Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
(Src0 == Src1 || Src0 == Src2))
break;
MVT VT = Src0.getValueType().getSimpleVT();
const TargetRegisterClass *RC =
getRegClassFor(VT, Src0.getNode()->isDivergent());
MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
UndefReg, Src0, SDValue());
// src0 must be the same register as src1 or src2, even if the value is
// undefined, so make sure we don't violate this constraint.
if (Src0.isMachineOpcode() &&
Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
if (Src1.isMachineOpcode() &&
Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
Src0 = Src1;
else if (Src2.isMachineOpcode() &&
Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
Src0 = Src2;
else {
assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
Src0 = UndefReg;
Src1 = UndefReg;
}
} else
break;
SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
Ops.push_back(Node->getOperand(I));
Ops.push_back(ImpDef.getValue(1));
return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
}
case AMDGPU::V_PERMLANE16_B32:
case AMDGPU::V_PERMLANEX16_B32: {
ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0));
ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2));
if (!FI->getZExtValue() && !BC->getZExtValue())
break;
SDValue VDstIn = Node->getOperand(6);
if (VDstIn.isMachineOpcode()
&& VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF)
break;
MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
SDLoc(Node), MVT::i32);
SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1),
SDValue(BC, 0), Node->getOperand(3),
Node->getOperand(4), Node->getOperand(5),
SDValue(ImpDef, 0), Node->getOperand(7) };
return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
}
default:
break;
}
return Node;
}
/// Assign the register class depending on the number of
/// bits set in the writemask
void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
SDNode *Node) const {
const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
if (TII->isVOP3(MI.getOpcode())) {
// Make sure constant bus requirements are respected.
TII->legalizeOperandsVOP3(MRI, MI);
// Prefer VGPRs over AGPRs in mAI instructions where possible.
// This saves a chain-copy of registers and better ballance register
// use between vgpr and agpr as agpr tuples tend to be big.
if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
unsigned Opc = MI.getOpcode();
const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
if (I == -1)
break;
MachineOperand &Op = MI.getOperand(I);
if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
!Register::isVirtualRegister(Op.getReg()) ||
!TRI->isAGPR(MRI, Op.getReg()))
continue;
auto *Src = MRI.getUniqueVRegDef(Op.getReg());
if (!Src || !Src->isCopy() ||
!TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
continue;
auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
auto *NewRC = TRI->getEquivalentVGPRClass(RC);
// All uses of agpr64 and agpr32 can also accept vgpr except for
// v_accvgpr_read, but we do not produce agpr reads during selection,
// so no use checks are needed.
MRI.setRegClass(Op.getReg(), NewRC);
}
}
return;
}
// Replace unused atomics with the no return version.
int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
if (NoRetAtomicOp != -1) {
if (!Node->hasAnyUseOfValue(0)) {
MI.setDesc(TII->get(NoRetAtomicOp));
MI.RemoveOperand(0);
return;
}
// For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
// instruction, because the return type of these instructions is a vec2 of
// the memory type, so it can be tied to the input operand.
// This means these instructions always have a use, so we need to add a
// special case to check if the atomic has only one extract_subreg use,
// which itself has no uses.
if ((Node->hasNUsesOfValue(1, 0) &&
Node->use_begin()->isMachineOpcode() &&
Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
!Node->use_begin()->hasAnyUseOfValue(0))) {
Register Def = MI.getOperand(0).getReg();
// Change this into a noret atomic.
MI.setDesc(TII->get(NoRetAtomicOp));
MI.RemoveOperand(0);
// If we only remove the def operand from the atomic instruction, the
// extract_subreg will be left with a use of a vreg without a def.
// So we need to insert an implicit_def to avoid machine verifier
// errors.
BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
TII->get(AMDGPU::IMPLICIT_DEF), Def);
}
return;
}
}
static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
uint64_t Val) {
SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
}
MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
const SDLoc &DL,
SDValue Ptr) const {
const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
// Build the half of the subregister with the constants before building the
// full 128-bit register. If we are building multiple resource descriptors,
// this will allow CSEing of the 2-component register.
const SDValue Ops0[] = {
DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
buildSMovImm32(DAG, DL, 0),
DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
};
SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
MVT::v2i32, Ops0), 0);
// Combine the constants and the pointer.
const SDValue Ops1[] = {
DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
Ptr,
DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
SubRegHi,
DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
};
return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
}
/// Return a resource descriptor with the 'Add TID' bit enabled
/// The TID (Thread ID) is multiplied by the stride value (bits [61:48]
/// of the resource descriptor) to create an offset, which is added to
/// the resource pointer.
MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
SDValue Ptr, uint32_t RsrcDword1,
uint64_t RsrcDword2And3) const {
SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
if (RsrcDword1) {
PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
DAG.getConstant(RsrcDword1, DL, MVT::i32)),
0);
}
SDValue DataLo = buildSMovImm32(DAG, DL,
RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
const SDValue Ops[] = {
DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
PtrLo,
DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
PtrHi,
DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
DataLo,
DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
DataHi,
DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
};
return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
}
//===----------------------------------------------------------------------===//
// SI Inline Assembly Support
//===----------------------------------------------------------------------===//
std::pair<unsigned, const TargetRegisterClass *>
SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
StringRef Constraint,
MVT VT) const {
const TargetRegisterClass *RC = nullptr;
if (Constraint.size() == 1) {
switch (Constraint[0]) {
default:
return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
case 's':
case 'r':
switch (VT.getSizeInBits()) {
default:
return std::make_pair(0U, nullptr);
case 32:
case 16:
RC = &AMDGPU::SReg_32_XM0RegClass;
break;
case 64:
RC = &AMDGPU::SGPR_64RegClass;
break;
case 96:
RC = &AMDGPU::SReg_96RegClass;
break;
case 128:
RC = &AMDGPU::SReg_128RegClass;
break;
case 160:
RC = &AMDGPU::SReg_160RegClass;
break;
case 256:
RC = &AMDGPU::SReg_256RegClass;
break;
case 512:
RC = &AMDGPU::SReg_512RegClass;
break;
}
break;
case 'v':
switch (VT.getSizeInBits()) {
default:
return std::make_pair(0U, nullptr);
case 32:
case 16:
RC = &AMDGPU::VGPR_32RegClass;
break;
case 64:
RC = &AMDGPU::VReg_64RegClass;
break;
case 96:
RC = &AMDGPU::VReg_96RegClass;
break;
case 128:
RC = &AMDGPU::VReg_128RegClass;
break;
case 160:
RC = &AMDGPU::VReg_160RegClass;
break;
case 256:
RC = &AMDGPU::VReg_256RegClass;
break;
case 512:
RC = &AMDGPU::VReg_512RegClass;
break;
}
break;
case 'a':
if (!Subtarget->hasMAIInsts())
break;
switch (VT.getSizeInBits()) {
default:
return std::make_pair(0U, nullptr);
case 32:
case 16:
RC = &AMDGPU::AGPR_32RegClass;
break;
case 64:
RC = &AMDGPU::AReg_64RegClass;
break;
case 128:
RC = &AMDGPU::AReg_128RegClass;
break;
case 512:
RC = &AMDGPU::AReg_512RegClass;
break;
case 1024:
RC = &AMDGPU::AReg_1024RegClass;
// v32 types are not legal but we support them here.
return std::make_pair(0U, RC);
}
break;
}
// We actually support i128, i16 and f16 as inline parameters
// even if they are not reported as legal
if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
return std::make_pair(0U, RC);
}
if (Constraint.size() > 1) {
if (Constraint[1] == 'v') {
RC = &AMDGPU::VGPR_32RegClass;
} else if (Constraint[1] == 's') {
RC = &AMDGPU::SGPR_32RegClass;
} else if (Constraint[1] == 'a') {
RC = &AMDGPU::AGPR_32RegClass;
}
if (RC) {
uint32_t Idx;
bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
if (!Failed && Idx < RC->getNumRegs())
return std::make_pair(RC->getRegister(Idx), RC);
}
}
return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
}
SITargetLowering::ConstraintType
SITargetLowering::getConstraintType(StringRef Constraint) const {
if (Constraint.size() == 1) {
switch (Constraint[0]) {
default: break;
case 's':
case 'v':
case 'a':
return C_RegisterClass;
}
}
return TargetLowering::getConstraintType(Constraint);
}
// Figure out which registers should be reserved for stack access. Only after
// the function is legalized do we know all of the non-spill stack objects or if
// calls are present.
void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
MachineRegisterInfo &MRI = MF.getRegInfo();
SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
if (Info->isEntryFunction()) {
// Callable functions have fixed registers used for stack access.
reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
}
assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
Info->getStackPtrOffsetReg()));
if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
// We need to worry about replacing the default register with itself in case
// of MIR testcases missing the MFI.
if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) {
MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
Info->getScratchWaveOffsetReg());
}
Info->limitOccupancy(MF);
if (ST.isWave32() && !MF.empty()) {
// Add VCC_HI def because many instructions marked as imp-use VCC where
// we may only define VCC_LO. If nothing defines VCC_HI we may end up
// having a use of undef.
const SIInstrInfo *TII = ST.getInstrInfo();
DebugLoc DL;
MachineBasicBlock &MBB = MF.front();
MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
for (auto &MBB : MF) {
for (auto &MI : MBB) {
TII->fixImplicitOperands(MI);
}
}
}
TargetLoweringBase::finalizeLowering(MF);
}
void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
KnownBits &Known,
const APInt &DemandedElts,
const SelectionDAG &DAG,
unsigned Depth) const {
TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
DAG, Depth);
// Set the high bits to zero based on the maximum allowed scratch size per
// wave. We can't use vaddr in MUBUF instructions if we don't know the address
// calculation won't overflow, so assume the sign bit is never set.
Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
}
Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
const Align CacheLineAlign = Align(64);
// Pre-GFX10 target did not benefit from loop alignment
if (!ML || DisableLoopAlignment ||
(getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
getSubtarget()->hasInstFwdPrefetchBug())
return PrefAlign;
// On GFX10 I$ is 4 x 64 bytes cache lines.
// By default prefetcher keeps one cache line behind and reads two ahead.
// We can modify it with S_INST_PREFETCH for larger loops to have two lines
// behind and one ahead.
// Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
// If loop fits 64 bytes it always spans no more than two cache lines and
// does not need an alignment.
// Else if loop is less or equal 128 bytes we do not need to modify prefetch,
// Else if loop is less or equal 192 bytes we need two lines behind.
const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
const MachineBasicBlock *Header = ML->getHeader();
if (Header->getAlignment() != PrefAlign)
return Header->getAlignment(); // Already processed.
unsigned LoopSize = 0;
for (const MachineBasicBlock *MBB : ML->blocks()) {
// If inner loop block is aligned assume in average half of the alignment
// size to be added as nops.
if (MBB != Header)
LoopSize += MBB->getAlignment().value() / 2;
for (const MachineInstr &MI : *MBB) {
LoopSize += TII->getInstSizeInBytes(MI);
if (LoopSize > 192)
return PrefAlign;
}
}
if (LoopSize <= 64)
return PrefAlign;
if (LoopSize <= 128)
return CacheLineAlign;
// If any of parent loops is surrounded by prefetch instructions do not
// insert new for inner loop, which would reset parent's settings.
for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
if (MachineBasicBlock *Exit = P->getExitBlock()) {
auto I = Exit->getFirstNonDebugInstr();
if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
return CacheLineAlign;
}
}
MachineBasicBlock *Pre = ML->getLoopPreheader();
MachineBasicBlock *Exit = ML->getExitBlock();
if (Pre && Exit) {
BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
TII->get(AMDGPU::S_INST_PREFETCH))
.addImm(1); // prefetch 2 lines behind PC
BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
TII->get(AMDGPU::S_INST_PREFETCH))
.addImm(2); // prefetch 1 line behind PC
}
return CacheLineAlign;
}
LLVM_ATTRIBUTE_UNUSED
static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
assert(N->getOpcode() == ISD::CopyFromReg);
do {
// Follow the chain until we find an INLINEASM node.
N = N->getOperand(0).getNode();
if (N->getOpcode() == ISD::INLINEASM ||
N->getOpcode() == ISD::INLINEASM_BR)
return true;
} while (N->getOpcode() == ISD::CopyFromReg);
return false;
}
bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
{
switch (N->getOpcode()) {
case ISD::CopyFromReg:
{
const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
const MachineFunction * MF = FLI->MF;
const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
const MachineRegisterInfo &MRI = MF->getRegInfo();
const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
unsigned Reg = R->getReg();
if (Register::isPhysicalRegister(Reg))
return !TRI.isSGPRReg(MRI, Reg);
if (MRI.isLiveIn(Reg)) {
// workitem.id.x workitem.id.y workitem.id.z
// Any VGPR formal argument is also considered divergent
if (!TRI.isSGPRReg(MRI, Reg))
return true;
// Formal arguments of non-entry functions
// are conservatively considered divergent
else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
return true;
return false;
}
const Value *V = FLI->getValueFromVirtualReg(Reg);
if (V)
return KDA->isDivergent(V);
assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
return !TRI.isSGPRReg(MRI, Reg);
}
break;
case ISD::LOAD: {
const LoadSDNode *L = cast<LoadSDNode>(N);
unsigned AS = L->getAddressSpace();
// A flat load may access private memory.
return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
} break;
case ISD::CALLSEQ_END:
return true;
break;
case ISD::INTRINSIC_WO_CHAIN:
{
}
return AMDGPU::isIntrinsicSourceOfDivergence(
cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
case ISD::INTRINSIC_W_CHAIN:
return AMDGPU::isIntrinsicSourceOfDivergence(
cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
// In some cases intrinsics that are a source of divergence have been
// lowered to AMDGPUISD so we also need to check those too.
case AMDGPUISD::INTERP_MOV:
case AMDGPUISD::INTERP_P1:
case AMDGPUISD::INTERP_P2:
return true;
}
return false;
}
bool SITargetLowering::denormalsEnabledForType(EVT VT) const {
switch (VT.getScalarType().getSimpleVT().SimpleTy) {
case MVT::f32:
return Subtarget->hasFP32Denormals();
case MVT::f64:
return Subtarget->hasFP64Denormals();
case MVT::f16:
return Subtarget->hasFP16Denormals();
default:
return false;
}
}
bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
const SelectionDAG &DAG,
bool SNaN,
unsigned Depth) const {
if (Op.getOpcode() == AMDGPUISD::CLAMP) {
const MachineFunction &MF = DAG.getMachineFunction();
const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
if (Info->getMode().DX10Clamp)
return true; // Clamped to 0.
return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
}
return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
SNaN, Depth);
}
TargetLowering::AtomicExpansionKind
SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
switch (RMW->getOperation()) {
case AtomicRMWInst::FAdd: {
Type *Ty = RMW->getType();
// We don't have a way to support 16-bit atomics now, so just leave them
// as-is.
if (Ty->isHalfTy())
return AtomicExpansionKind::None;
if (!Ty->isFloatTy())
return AtomicExpansionKind::CmpXChg;
// TODO: Do have these for flat. Older targets also had them for buffers.
unsigned AS = RMW->getPointerAddressSpace();
return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
}
default:
break;
}
return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
}
| GPUOpen-Drivers/llvm | lib/Target/AMDGPU/SIISelLowering.cpp | C++ | apache-2.0 | 401,927 |
// -----------------------------------------------------------------------
// <copyright file="OsharpBuilder.cs" company="OSharp开源团队">
// Copyright (c) 2014-2018 OSharp. All rights reserved.
// </copyright>
// <site>http://www.osharp.org</site>
// <last-editor>郭明锋</last-editor>
// <last-date>2018-06-23 15:40</last-date>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using OSharp.Collections;
using OSharp.Core.Options;
using OSharp.Core.Packs;
using OSharp.Data;
using OSharp.Exceptions;
namespace OSharp.Core.Builders
{
/// <summary>
/// OSharp构建器
/// </summary>
public class OsharpBuilder : IOsharpBuilder
{
private readonly List<OsharpPack> _source;
private List<OsharpPack> _packs;
/// <summary>
/// 初始化一个<see cref="OsharpBuilder"/>类型的新实例
/// </summary>
public OsharpBuilder(IServiceCollection services)
{
Services = services;
_packs = new List<OsharpPack>();
_source = GetAllPacks(services);
}
/// <summary>
/// 获取 服务集合
/// </summary>
public IServiceCollection Services { get; }
/// <summary>
/// 获取 加载的模块集合
/// </summary>
public IEnumerable<OsharpPack> Packs => _packs;
/// <summary>
/// 获取 OSharp选项配置委托
/// </summary>
public Action<OsharpOptions> OptionsAction { get; private set; }
/// <summary>
/// 添加指定模块
/// </summary>
/// <typeparam name="TPack">要添加的模块类型</typeparam>
public IOsharpBuilder AddPack<TPack>() where TPack : OsharpPack
{
Type type = typeof(TPack);
if (_packs.Any(m => m.GetType() == type))
{
return this;
}
OsharpPack[] tmpPacks = new OsharpPack[_packs.Count];
_packs.CopyTo(tmpPacks);
OsharpPack pack = _source.FirstOrDefault(m => m.GetType() == type);
if (pack == null)
{
throw new OsharpException($"类型为“{type.FullName}”的模块实例无法找到");
}
_packs.AddIfNotExist(pack);
// 添加依赖模块
Type[] dependTypes = pack.GetDependPackTypes();
foreach (Type dependType in dependTypes)
{
OsharpPack dependPack = _source.Find(m => m.GetType() == dependType);
if (dependPack == null)
{
throw new OsharpException($"加载模块{pack.GetType().FullName}时无法找到依赖模块{dependType.FullName}");
}
_packs.AddIfNotExist(dependPack);
}
// 按先层级后顺序的规则进行排序
_packs = _packs.OrderBy(m => m.Level).ThenBy(m => m.Order).ToList();
tmpPacks = _packs.Except(tmpPacks).ToArray();
foreach (OsharpPack tmpPack in tmpPacks)
{
AddPack(Services, tmpPack);
}
return this;
}
/// <summary>
/// 添加OSharp选项配置
/// </summary>
/// <param name="optionsAction">OSharp操作选项</param>
/// <returns>OSharp构建器</returns>
public IOsharpBuilder AddOptions(Action<OsharpOptions> optionsAction)
{
Check.NotNull(optionsAction, nameof(optionsAction));
OptionsAction = optionsAction;
return this;
}
private static List<OsharpPack> GetAllPacks(IServiceCollection services)
{
IOsharpPackTypeFinder packTypeFinder =
services.GetOrAddTypeFinder<IOsharpPackTypeFinder>(assemblyFinder => new OsharpPackTypeFinder(assemblyFinder));
Type[] packTypes = packTypeFinder.FindAll();
return packTypes.Select(m => (OsharpPack)Activator.CreateInstance(m)).ToList();
}
private static IServiceCollection AddPack(IServiceCollection services, OsharpPack pack)
{
Type type = pack.GetType();
Type serviceType = typeof(OsharpPack);
if (type.BaseType?.IsAbstract == false)
{
//移除多重继承的模块
ServiceDescriptor[] descriptors = services.Where(m =>
m.Lifetime == ServiceLifetime.Singleton && m.ServiceType == serviceType
&& m.ImplementationInstance?.GetType() == type.BaseType).ToArray();
foreach (var descriptor in descriptors)
{
services.Remove(descriptor);
}
}
if (!services.Any(m => m.Lifetime == ServiceLifetime.Singleton && m.ServiceType == serviceType && m.ImplementationInstance?.GetType() == type))
{
services.AddSingleton(typeof(OsharpPack), pack);
pack.AddServices(services);
}
return services;
}
}
} | i66soft/osharp | src/OSharp/Core/Builders/OSharpBuilder.cs | C# | apache-2.0 | 5,232 |
/*
* Ext JS Library 2.0.2
* Copyright(c) 2006-2008, Ext JS, LLC.
* licensing@extjs.com
*
* http://extjs.com/license
*/
Ext.layout.ColumnLayout=Ext.extend(Ext.layout.ContainerLayout,{monitorResize:true,extraCls:"x-column",scrollOffset:0,isValidParent:function(B,A){return B.getEl().dom.parentNode==this.innerCt.dom},onLayout:function(C,F){var D=C.items.items,E=D.length,G,A;if(!this.innerCt){F.addClass("x-column-layout-ct");this.innerCt=F.createChild({cls:"x-column-inner"});this.innerCt.createChild({cls:"x-clear"})}this.renderAll(C,this.innerCt);var J=F.getViewSize();if(J.width<1&&J.height<1){return }var H=J.width-F.getPadding("lr")-this.scrollOffset,B=J.height-F.getPadding("tb"),I=H;this.innerCt.setWidth(H);for(A=0;A<E;A++){G=D[A];if(!G.columnWidth){I-=(G.getSize().width+G.getEl().getMargins("lr"))}}I=I<0?0:I;for(A=0;A<E;A++){G=D[A];if(G.columnWidth){G.setSize(Math.floor(G.columnWidth*I)-G.getEl().getMargins("lr"))}}}});Ext.Container.LAYOUTS["column"]=Ext.layout.ColumnLayout; | grasscrm/gdesigner | editor/lib/sources/ext-2.0.2/build/widgets/layout/ColumnLayout-min.js | JavaScript | apache-2.0 | 995 |
package org.springframework.data.sample.entities.integration;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.springframework.data.annotation.Id;
import org.springframework.data.crate.core.mapping.annotations.Table;
@Table(name="sub_class", numberOfReplicas="0")
public class SimpleEntityWithId extends SimpleEntity {
@Id
public long id;
public static SimpleEntityWithId simpleEntityWithId() {
SimpleEntity simpleEntity = simpleEntity();
SimpleEntityWithId entity = new SimpleEntityWithId();
entity.id = 1;
entity.integerField = 2;
entity.boolField = simpleEntity.boolField;
entity.dateField = simpleEntity.dateField;
entity.localeField = simpleEntity.localeField;
entity.stringField= simpleEntity.stringField;
return entity;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SimpleEntityWithId)) {
return false;
}
if (this == obj) {
return true;
}
SimpleEntityWithId that = (SimpleEntityWithId) obj;
return new EqualsBuilder().append(this.id, that.id)
.append(this.stringField, that.stringField)
.append(this.integerField, that.integerField)
.append(this.dateField, that.dateField)
.append(this.boolField, that.boolField)
.append(this.localeField, that.localeField)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(7, 11).append(id)
.append(stringField)
.append(integerField)
.append(dateField)
.append(boolField)
.append(localeField)
.toHashCode();
}
} | KPTechnologyLab/spring-data-crate | src/test/java/org/springframework/data/sample/entities/integration/SimpleEntityWithId.java | Java | apache-2.0 | 1,818 |
package org.nd4j.linalg.learning.config;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.learning.GradientUpdater;
import org.nd4j.linalg.learning.SgdUpdater;
/**
* SGD updater applies a learning rate only
* @author Adam Gibson
*/
@AllArgsConstructor
@Data
@EqualsAndHashCode
@Builder(builderClassName = "Builder")
public class Sgd implements IUpdater {
public static final double DEFAULT_SGD_LR = 1e-3;
private double learningRate;
public Sgd(){
this(DEFAULT_SGD_LR);
}
@Override
public long stateSize(long numParams) {
return 0;
}
@Override
public void applySchedules(int iteration, double newLearningRate) {
this.learningRate = newLearningRate;
}
@Override
public GradientUpdater instantiate(INDArray viewArray, boolean initializeViewArray) {
if (viewArray != null) {
throw new IllegalStateException("View arrays are not supported/required for SGD updater");
}
return new SgdUpdater(this);
}
@Override
public Sgd clone() {
return new Sgd(learningRate);
}
public static class Builder {
private double learningRate = DEFAULT_SGD_LR;
public Builder() {
}
}
}
| huitseeker/nd4j | nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/learning/config/Sgd.java | Java | apache-2.0 | 1,366 |
"""Test the Balboa Spa Client config flow."""
from unittest.mock import patch
from homeassistant import config_entries, data_entry_flow
from homeassistant.components.balboa.const import CONF_SYNC_TIME, DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import (
RESULT_TYPE_ABORT,
RESULT_TYPE_CREATE_ENTRY,
RESULT_TYPE_FORM,
)
from . import BalboaMock
from tests.common import MockConfigEntry
TEST_DATA = {
CONF_HOST: "1.1.1.1",
}
TEST_ID = "FakeBalboa"
async def test_form(hass: HomeAssistant) -> None:
"""Test we get the form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == RESULT_TYPE_FORM
assert result["errors"] == {}
with patch(
"homeassistant.components.balboa.config_flow.BalboaSpaWifi.connect",
new=BalboaMock.connect,
), patch(
"homeassistant.components.balboa.config_flow.BalboaSpaWifi.disconnect",
new=BalboaMock.disconnect,
), patch(
"homeassistant.components.balboa.config_flow.BalboaSpaWifi.listen",
new=BalboaMock.listen,
), patch(
"homeassistant.components.balboa.config_flow.BalboaSpaWifi.send_mod_ident_req",
new=BalboaMock.send_mod_ident_req,
), patch(
"homeassistant.components.balboa.config_flow.BalboaSpaWifi.send_panel_req",
new=BalboaMock.send_panel_req,
), patch(
"homeassistant.components.balboa.config_flow.BalboaSpaWifi.spa_configured",
new=BalboaMock.spa_configured,
), patch(
"homeassistant.components.balboa.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_DATA,
)
await hass.async_block_till_done()
assert result2["type"] == RESULT_TYPE_CREATE_ENTRY
assert result2["data"] == TEST_DATA
assert len(mock_setup_entry.mock_calls) == 1
async def test_form_cannot_connect(hass: HomeAssistant) -> None:
"""Test we handle cannot connect error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.balboa.config_flow.BalboaSpaWifi.connect",
new=BalboaMock.broken_connect,
), patch(
"homeassistant.components.balboa.config_flow.BalboaSpaWifi.disconnect",
new=BalboaMock.disconnect,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_DATA,
)
assert result2["type"] == RESULT_TYPE_FORM
assert result2["errors"] == {"base": "cannot_connect"}
async def test_unknown_error(hass: HomeAssistant) -> None:
"""Test we handle unknown error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.balboa.config_flow.BalboaSpaWifi.connect",
side_effect=Exception,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_DATA,
)
assert result2["type"] == RESULT_TYPE_FORM
assert result2["errors"] == {"base": "unknown"}
async def test_already_configured(hass: HomeAssistant) -> None:
"""Test when provided credentials are already configured."""
MockConfigEntry(domain=DOMAIN, data=TEST_DATA, unique_id=TEST_ID).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == SOURCE_USER
with patch(
"homeassistant.components.balboa.config_flow.BalboaSpaWifi.connect",
new=BalboaMock.connect,
), patch(
"homeassistant.components.balboa.config_flow.BalboaSpaWifi.disconnect",
new=BalboaMock.disconnect,
), patch(
"homeassistant.components.balboa.async_setup_entry",
return_value=True,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_DATA,
)
await hass.async_block_till_done()
assert result2["type"] == RESULT_TYPE_ABORT
assert result2["reason"] == "already_configured"
async def test_options_flow(hass):
"""Test specifying non default settings using options flow."""
config_entry = MockConfigEntry(domain=DOMAIN, data=TEST_DATA, unique_id=TEST_ID)
config_entry.add_to_hass(hass)
# Rather than mocking out 15 or so functions, we just need to mock
# the entire library, otherwise it will get stuck in a listener and
# the various loops in pybalboa.
with patch(
"homeassistant.components.balboa.config_flow.BalboaSpaWifi",
new=BalboaMock,
), patch(
"homeassistant.components.balboa.BalboaSpaWifi",
new=BalboaMock,
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "init"
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={CONF_SYNC_TIME: True},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert config_entry.options == {CONF_SYNC_TIME: True}
| jawilson/home-assistant | tests/components/balboa/test_config_flow.py | Python | apache-2.0 | 5,737 |
package org.renyan.leveldb.util;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Ints;
import org.renyan.leveldb.impl.FileMetaData;
import org.renyan.leveldb.impl.InternalKey;
import org.renyan.leveldb.impl.SeekingIterator;
import org.renyan.leveldb.impl.TableCache;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
public final class Level0Iterator extends AbstractSeekingIterator<InternalKey, Slice> implements InternalIterator
{
private final List<InternalTableIterator> inputs;
private final PriorityQueue<ComparableIterator> priorityQueue;
private final Comparator<InternalKey> comparator;
public Level0Iterator(TableCache tableCache, List<FileMetaData> files, Comparator<InternalKey> comparator)
{
Builder<InternalTableIterator> builder = ImmutableList.builder();
for (FileMetaData file : files) {
builder.add(tableCache.newIterator(file));
}
this.inputs = builder.build();
this.comparator = comparator;
this.priorityQueue = new PriorityQueue<ComparableIterator>(Iterables.size(inputs) + 1);
resetPriorityQueue(comparator);
}
public Level0Iterator(List<InternalTableIterator> inputs, Comparator<InternalKey> comparator)
{
this.inputs = inputs;
this.comparator = comparator;
this.priorityQueue = new PriorityQueue<ComparableIterator>(Iterables.size(inputs));
resetPriorityQueue(comparator);
}
@Override
protected void seekToFirstInternal()
{
for (InternalTableIterator input : inputs) {
input.seekToFirst();
}
resetPriorityQueue(comparator);
}
@Override
protected void seekInternal(InternalKey targetKey)
{
for (InternalTableIterator input : inputs) {
input.seek(targetKey);
}
resetPriorityQueue(comparator);
}
private void resetPriorityQueue(Comparator<InternalKey> comparator)
{
int i = 0;
for (InternalTableIterator input : inputs) {
if (input.hasNext()) {
priorityQueue.add(new ComparableIterator(input, comparator, i++, input.next()));
}
}
}
@Override
protected Entry<InternalKey, Slice> getNextElement()
{
Entry<InternalKey, Slice> result = null;
ComparableIterator nextIterator = priorityQueue.poll();
if (nextIterator != null) {
result = nextIterator.next();
if (nextIterator.hasNext()) {
priorityQueue.add(nextIterator);
}
}
return result;
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("MergingIterator");
sb.append("{inputs=").append(Iterables.toString(inputs));
sb.append(", comparator=").append(comparator);
sb.append('}');
return sb.toString();
}
private static class ComparableIterator implements Iterator<Entry<InternalKey, Slice>>, Comparable<ComparableIterator> {
private final SeekingIterator<InternalKey, Slice> iterator;
private final Comparator<InternalKey> comparator;
private final int ordinal;
private Entry<InternalKey,Slice> nextElement;
private ComparableIterator(SeekingIterator<InternalKey, Slice> iterator, Comparator<InternalKey> comparator, int ordinal, Entry<InternalKey, Slice> nextElement)
{
this.iterator = iterator;
this.comparator = comparator;
this.ordinal = ordinal;
this.nextElement = nextElement;
}
@Override
public boolean hasNext()
{
return nextElement != null;
}
public Entry<InternalKey, Slice> next()
{
if (nextElement == null) {
throw new NoSuchElementException();
}
Entry<InternalKey, Slice> result = nextElement;
if (iterator.hasNext()) {
nextElement = iterator.next();
} else {
nextElement = null;
}
return result;
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ComparableIterator comparableIterator = (ComparableIterator) o;
if (ordinal != comparableIterator.ordinal) {
return false;
}
if (nextElement != null ? !nextElement.equals(comparableIterator.nextElement) : comparableIterator.nextElement != null) {
return false;
}
return true;
}
@Override
public int hashCode()
{
int result = ordinal;
result = 31 * result + (nextElement != null ? nextElement.hashCode() : 0);
return result;
}
@Override
public int compareTo(ComparableIterator that)
{
int result = comparator.compare(this.nextElement.getKey(), that.nextElement.getKey());
if (result == 0) {
result = Ints.compare(this.ordinal, that.ordinal);
}
return result;
}
}
}
| savechina/leveldb | leveldb/src/main/java/org/renyan/leveldb/util/Level0Iterator.java | Java | apache-2.0 | 5,901 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
package com.amazonaws.services.inspector.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* This data type is used in the <a>AssessmentRunFilter</a> data type.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/TimestampRange" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class TimestampRange implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The minimum value of the timestamp range.
* </p>
*/
private java.util.Date beginDate;
/**
* <p>
* The maximum value of the timestamp range.
* </p>
*/
private java.util.Date endDate;
/**
* <p>
* The minimum value of the timestamp range.
* </p>
*
* @param beginDate
* The minimum value of the timestamp range.
*/
public void setBeginDate(java.util.Date beginDate) {
this.beginDate = beginDate;
}
/**
* <p>
* The minimum value of the timestamp range.
* </p>
*
* @return The minimum value of the timestamp range.
*/
public java.util.Date getBeginDate() {
return this.beginDate;
}
/**
* <p>
* The minimum value of the timestamp range.
* </p>
*
* @param beginDate
* The minimum value of the timestamp range.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public TimestampRange withBeginDate(java.util.Date beginDate) {
setBeginDate(beginDate);
return this;
}
/**
* <p>
* The maximum value of the timestamp range.
* </p>
*
* @param endDate
* The maximum value of the timestamp range.
*/
public void setEndDate(java.util.Date endDate) {
this.endDate = endDate;
}
/**
* <p>
* The maximum value of the timestamp range.
* </p>
*
* @return The maximum value of the timestamp range.
*/
public java.util.Date getEndDate() {
return this.endDate;
}
/**
* <p>
* The maximum value of the timestamp range.
* </p>
*
* @param endDate
* The maximum value of the timestamp range.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public TimestampRange withEndDate(java.util.Date endDate) {
setEndDate(endDate);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getBeginDate() != null)
sb.append("BeginDate: ").append(getBeginDate()).append(",");
if (getEndDate() != null)
sb.append("EndDate: ").append(getEndDate());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof TimestampRange == false)
return false;
TimestampRange other = (TimestampRange) obj;
if (other.getBeginDate() == null ^ this.getBeginDate() == null)
return false;
if (other.getBeginDate() != null && other.getBeginDate().equals(this.getBeginDate()) == false)
return false;
if (other.getEndDate() == null ^ this.getEndDate() == null)
return false;
if (other.getEndDate() != null && other.getEndDate().equals(this.getEndDate()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getBeginDate() == null) ? 0 : getBeginDate().hashCode());
hashCode = prime * hashCode + ((getEndDate() == null) ? 0 : getEndDate().hashCode());
return hashCode;
}
@Override
public TimestampRange clone() {
try {
return (TimestampRange) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.inspector.model.transform.TimestampRangeMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| aws/aws-sdk-java | aws-java-sdk-inspector/src/main/java/com/amazonaws/services/inspector/model/TimestampRange.java | Java | apache-2.0 | 5,572 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Wed Jun 10 10:20:03 MST 2020 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LoginModuleSupplier (BOM: * : All 2.6.1.Final-SNAPSHOT API)</title>
<meta name="date" content="2020-06-10">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="LoginModuleSupplier (BOM: * : All 2.6.1.Final-SNAPSHOT API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/LoginModuleSupplier.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.6.1.Final-SNAPSHOT</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModuleStackSupplier.html" title="interface in org.wildfly.swarm.config.security.security_domain.authentication"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/security/security_domain/authentication/LoginModuleSupplier.html" target="_top">Frames</a></li>
<li><a href="LoginModuleSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.wildfly.swarm.config.security.security_domain.authentication</div>
<h2 title="Interface LoginModuleSupplier" class="title">Interface LoginModuleSupplier<T extends <a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a>></h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Functional Interface:</dt>
<dd>This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.</dd>
</dl>
<hr>
<br>
<pre><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html?is-external=true" title="class or interface in java.lang">@FunctionalInterface</a>
public interface <span class="typeNameLabel">LoginModuleSupplier<T extends <a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a>></span></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModuleSupplier.html#get--">get</a></span>()</code>
<div class="block">Constructed instance of LoginModule resource</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="get--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>get</h4>
<pre><a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModule.html" title="class in org.wildfly.swarm.config.security.security_domain.authentication">LoginModule</a> get()</pre>
<div class="block">Constructed instance of LoginModule resource</div>
<dl>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>The instance</dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/LoginModuleSupplier.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.6.1.Final-SNAPSHOT</div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../../org/wildfly/swarm/config/security/security_domain/authentication/LoginModuleStackSupplier.html" title="interface in org.wildfly.swarm.config.security.security_domain.authentication"><span class="typeNameLink">Prev Class</span></a></li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/security/security_domain/authentication/LoginModuleSupplier.html" target="_top">Frames</a></li>
<li><a href="LoginModuleSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2020 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| wildfly-swarm/wildfly-swarm-javadocs | 2.6.1.Final-SNAPSHOT/apidocs/org/wildfly/swarm/config/security/security_domain/authentication/LoginModuleSupplier.html | HTML | apache-2.0 | 9,573 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_112) on Tue Sep 12 14:31:26 MST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.wildfly.swarm.config.management.security_realm.PropertiesAuthenticationSupplier (BOM: * : All 2017.9.5 API)</title>
<meta name="date" content="2017-09-12">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.wildfly.swarm.config.management.security_realm.PropertiesAuthenticationSupplier (BOM: * : All 2017.9.5 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PropertiesAuthenticationSupplier.html" title="interface in org.wildfly.swarm.config.management.security_realm">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.9.5</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/security_realm/class-use/PropertiesAuthenticationSupplier.html" target="_top">Frames</a></li>
<li><a href="PropertiesAuthenticationSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface org.wildfly.swarm.config.management.security_realm.PropertiesAuthenticationSupplier" class="title">Uses of Interface<br>org.wildfly.swarm.config.management.security_realm.PropertiesAuthenticationSupplier</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PropertiesAuthenticationSupplier.html" title="interface in org.wildfly.swarm.config.management.security_realm">PropertiesAuthenticationSupplier</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.management">org.wildfly.swarm.config.management</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.management">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PropertiesAuthenticationSupplier.html" title="interface in org.wildfly.swarm.config.management.security_realm">PropertiesAuthenticationSupplier</a> in <a href="../../../../../../../org/wildfly/swarm/config/management/package-summary.html">org.wildfly.swarm.config.management</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/management/package-summary.html">org.wildfly.swarm.config.management</a> with parameters of type <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PropertiesAuthenticationSupplier.html" title="interface in org.wildfly.swarm.config.management.security_realm">PropertiesAuthenticationSupplier</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/management/SecurityRealm.html" title="type parameter in SecurityRealm">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">SecurityRealm.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/SecurityRealm.html#propertiesAuthentication-org.wildfly.swarm.config.management.security_realm.PropertiesAuthenticationSupplier-">propertiesAuthentication</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PropertiesAuthenticationSupplier.html" title="interface in org.wildfly.swarm.config.management.security_realm">PropertiesAuthenticationSupplier</a> supplier)</code>
<div class="block">Configuration to use a list users stored within a properties file as the
user repository.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/PropertiesAuthenticationSupplier.html" title="interface in org.wildfly.swarm.config.management.security_realm">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.9.5</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/security_realm/class-use/PropertiesAuthenticationSupplier.html" target="_top">Frames</a></li>
<li><a href="PropertiesAuthenticationSupplier.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| wildfly-swarm/wildfly-swarm-javadocs | 2017.9.5/apidocs/org/wildfly/swarm/config/management/security_realm/class-use/PropertiesAuthenticationSupplier.html | HTML | apache-2.0 | 8,298 |
/*
* BJAF - Beetle J2EE Application Framework
* 甲壳虫J2EE企业应用开发框架
* 版权所有2003-2015 余浩东 (www.beetlesoft.net)
*
* 这是一个免费开源的软件,您必须在
*<http://www.apache.org/licenses/LICENSE-2.0>
*协议下合法使用、修改或重新发布。
*
* 感谢您使用、推广本框架,若有建议或问题,欢迎您和我联系。
* 邮件: <yuhaodong@gmail.com/>.
*/
package com.beetle.framework.appsrv.monitor;
import com.beetle.framework.AppProperties;
import com.beetle.framework.log.AppLogger;
import com.beetle.framework.util.thread.ThreadImp;
/**
* 内存监控器,防止服务器由于内存过低而瘫痪
*
*
* @author HenryYu
*
*/
public class JVMWatcher extends ThreadImp {
public JVMWatcher(int interval) {
super("AppMemoryWatcher", interval);
init(interval);
}
private float gcRate;
private AppLogger logger;
private int counter;
private int gcTime;
private boolean gcFlag;
private void init(int interval) {
// this.gcRate =
// Float.parseFloat(ResourceReader.getParameter("mem-rate"));
this.gcRate = AppProperties.getAsFloat("routinespool_MEM_RATE", 0.8f);
this.logger = AppLogger.getInstance(JVMWatcher.class);
this.counter = 0;
int gcInterval = 1000 * 60 * 10;
this.gcTime = gcInterval / interval;
this.gcFlag = false;
}
protected void routine() {
float memused = memoryUsedRate();
if (memused >= gcRate) {
if (!gcFlag) {
gcFlag = true;
counter = 0;
Runtime.getRuntime().gc();
if (logger.isInfoEnabled()) {
logger.info("system jvm called gc()");
}
}
}
// logger.debug("gcRate=" + gcRate + ",memoryUsedRate=" + memused);
counter++;
if (counter >= gcTime) {
counter = 0;
gcFlag = false;
}
}
private static float memoryUsedRate() {
long free = Runtime.getRuntime().freeMemory();
long total = Runtime.getRuntime().totalMemory();
return (float) (total - free) / (float) total;
}
protected void end() {// 只有调用stopNow方法才触发
logger.info("[AppMemoryWatcher]" + "stopped.");
}
}
| jbeetle/BJAF3.x | src/main/com/beetle/framework/appsrv/monitor/JVMWatcher.java | Java | apache-2.0 | 2,161 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_80) on Thu Jun 18 14:08:32 EDT 2015 -->
<title>CQL3Type.Custom (apache-cassandra API)</title>
<meta name="date" content="2015-06-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="CQL3Type.Custom (apache-cassandra API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/CQL3Type.Custom.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/apache/cassandra/cql3/CQL3Type.Collection.html" title="class in org.apache.cassandra.cql3"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/cql3/CQL3Type.Native.html" title="enum in org.apache.cassandra.cql3"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/cql3/CQL3Type.Custom.html" target="_top">Frames</a></li>
<li><a href="CQL3Type.Custom.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.cassandra.cql3</div>
<h2 title="Class CQL3Type.Custom" class="title">Class CQL3Type.Custom</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.apache.cassandra.cql3.CQL3Type.Custom</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../org/apache/cassandra/cql3/CQL3Type.html" title="interface in org.apache.cassandra.cql3">CQL3Type</a></dd>
</dl>
<dl>
<dt>Enclosing interface:</dt>
<dd><a href="../../../../org/apache/cassandra/cql3/CQL3Type.html" title="interface in org.apache.cassandra.cql3">CQL3Type</a></dd>
</dl>
<hr>
<br>
<pre>public static class <span class="strong">CQL3Type.Custom</span>
extends java.lang.Object
implements <a href="../../../../org/apache/cassandra/cql3/CQL3Type.html" title="interface in org.apache.cassandra.cql3">CQL3Type</a></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested_class_summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="nested_classes_inherited_from_class_org.apache.cassandra.cql3.CQL3Type">
<!-- -->
</a>
<h3>Nested classes/interfaces inherited from interface org.apache.cassandra.cql3.<a href="../../../../org/apache/cassandra/cql3/CQL3Type.html" title="interface in org.apache.cassandra.cql3">CQL3Type</a></h3>
<code><a href="../../../../org/apache/cassandra/cql3/CQL3Type.Collection.html" title="class in org.apache.cassandra.cql3">CQL3Type.Collection</a>, <a href="../../../../org/apache/cassandra/cql3/CQL3Type.Custom.html" title="class in org.apache.cassandra.cql3">CQL3Type.Custom</a>, <a href="../../../../org/apache/cassandra/cql3/CQL3Type.Native.html" title="enum in org.apache.cassandra.cql3">CQL3Type.Native</a></code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/cql3/CQL3Type.Custom.html#CQL3Type.Custom(org.apache.cassandra.db.marshal.AbstractType)">CQL3Type.Custom</a></strong>(<a href="../../../../org/apache/cassandra/db/marshal/AbstractType.html" title="class in org.apache.cassandra.db.marshal">AbstractType</a><?> type)</code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../org/apache/cassandra/cql3/CQL3Type.Custom.html#CQL3Type.Custom(java.lang.String)">CQL3Type.Custom</a></strong>(java.lang.String className)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql3/CQL3Type.Custom.html#equals(java.lang.Object)">equals</a></strong>(java.lang.Object o)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../org/apache/cassandra/db/marshal/AbstractType.html" title="class in org.apache.cassandra.db.marshal">AbstractType</a><?></code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql3/CQL3Type.Custom.html#getType()">getType</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql3/CQL3Type.Custom.html#hashCode()">hashCode</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql3/CQL3Type.Custom.html#isCollection()">isCollection</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql3/CQL3Type.Custom.html#isCounter()">isCounter</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../org/apache/cassandra/cql3/CQL3Type.Custom.html#toString()">toString</a></strong>()</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, finalize, getClass, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="CQL3Type.Custom(org.apache.cassandra.db.marshal.AbstractType)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>CQL3Type.Custom</h4>
<pre>public CQL3Type.Custom(<a href="../../../../org/apache/cassandra/db/marshal/AbstractType.html" title="class in org.apache.cassandra.db.marshal">AbstractType</a><?> type)</pre>
</li>
</ul>
<a name="CQL3Type.Custom(java.lang.String)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>CQL3Type.Custom</h4>
<pre>public CQL3Type.Custom(java.lang.String className)
throws <a href="../../../../org/apache/cassandra/exceptions/SyntaxException.html" title="class in org.apache.cassandra.exceptions">SyntaxException</a>,
<a href="../../../../org/apache/cassandra/exceptions/ConfigurationException.html" title="class in org.apache.cassandra.exceptions">ConfigurationException</a></pre>
<dl><dt><span class="strong">Throws:</span></dt>
<dd><code><a href="../../../../org/apache/cassandra/exceptions/SyntaxException.html" title="class in org.apache.cassandra.exceptions">SyntaxException</a></code></dd>
<dd><code><a href="../../../../org/apache/cassandra/exceptions/ConfigurationException.html" title="class in org.apache.cassandra.exceptions">ConfigurationException</a></code></dd></dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="isCollection()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isCollection</h4>
<pre>public boolean isCollection()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../org/apache/cassandra/cql3/CQL3Type.html#isCollection()">isCollection</a></code> in interface <code><a href="../../../../org/apache/cassandra/cql3/CQL3Type.html" title="interface in org.apache.cassandra.cql3">CQL3Type</a></code></dd>
</dl>
</li>
</ul>
<a name="getType()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getType</h4>
<pre>public <a href="../../../../org/apache/cassandra/db/marshal/AbstractType.html" title="class in org.apache.cassandra.db.marshal">AbstractType</a><?> getType()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../org/apache/cassandra/cql3/CQL3Type.html#getType()">getType</a></code> in interface <code><a href="../../../../org/apache/cassandra/cql3/CQL3Type.html" title="interface in org.apache.cassandra.cql3">CQL3Type</a></code></dd>
</dl>
</li>
</ul>
<a name="isCounter()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>isCounter</h4>
<pre>public boolean isCounter()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../org/apache/cassandra/cql3/CQL3Type.html#isCounter()">isCounter</a></code> in interface <code><a href="../../../../org/apache/cassandra/cql3/CQL3Type.html" title="interface in org.apache.cassandra.cql3">CQL3Type</a></code></dd>
</dl>
</li>
</ul>
<a name="equals(java.lang.Object)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>equals</h4>
<pre>public final boolean equals(java.lang.Object o)</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>equals</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
<a name="hashCode()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>hashCode</h4>
<pre>public final int hashCode()</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>hashCode</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
<a name="toString()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>toString</h4>
<pre>public java.lang.String toString()</pre>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code>toString</code> in class <code>java.lang.Object</code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/CQL3Type.Custom.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/apache/cassandra/cql3/CQL3Type.Collection.html" title="class in org.apache.cassandra.cql3"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/apache/cassandra/cql3/CQL3Type.Native.html" title="enum in org.apache.cassandra.cql3"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/cassandra/cql3/CQL3Type.Custom.html" target="_top">Frames</a></li>
<li><a href="CQL3Type.Custom.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2015 The Apache Software Foundation</small></p>
</body>
</html>
| anuragkapur/cassandra-2.1.2-ak-skynet | apache-cassandra-2.0.16/javadoc/org/apache/cassandra/cql3/CQL3Type.Custom.html | HTML | apache-2.0 | 15,163 |
// Copyright © 2017 Chocolatey Software, Inc
// Copyright © 2011 - 2017 RealDimensions Software, LLC
//
// 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.
namespace chocolatey.infrastructure.licensing
{
using System;
using System.IO;
using app;
using Rhino.Licensing;
public sealed class LicenseValidation
{
private const string PUBLIC_KEY =
@"<RSAKeyValue><Modulus>rznyhs3OslLqL7A7qav9bSHYGQmgWVsP/L47dWU7yF3EHsiYZuJNLlq8tQkPql/LB1FfLihiGsOKKUF1tmxihcRUrDaYkK1IYY3A+uJWkBglDUOUjnoDboI1FgF3wmXSb07JC8JCVYWjchq+h6MV9aDZaigA5MqMKNj9FE14f68=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
public static ChocolateyLicense validate()
{
var chocolateyLicense = new ChocolateyLicense
{
LicenseType = ChocolateyLicenseType.Unknown
};
string licenseFile = ApplicationParameters.LicenseFileLocation;
var userLicenseFile = ApplicationParameters.UserLicenseFileLocation;
if (File.Exists(userLicenseFile)) licenseFile = userLicenseFile;
//no IFileSystem at this point
if (File.Exists(licenseFile))
{
var license = new LicenseValidator(PUBLIC_KEY, licenseFile);
try
{
license.AssertValidLicense();
chocolateyLicense.IsValid = true;
}
catch (LicenseFileNotFoundException e)
{
chocolateyLicense.IsValid = false;
chocolateyLicense.InvalidReason = e.Message;
"chocolatey".Log().Error("A license was not found for a licensed version of Chocolatey:{0} {1}{0} {2}".format_with(Environment.NewLine, e.Message,
"A license was also not found in the user profile: '{0}'.".format_with(ApplicationParameters.UserLicenseFileLocation)));
}
catch (Exception e)
{
//license may be invalid
chocolateyLicense.IsValid = false;
chocolateyLicense.InvalidReason = e.Message;
"chocolatey".Log().Error("A license was found for a licensed version of Chocolatey, but is invalid:{0} {1}".format_with(Environment.NewLine, e.Message));
}
var chocolateyLicenseType = ChocolateyLicenseType.Unknown;
try
{
Enum.TryParse(license.LicenseType.to_string(), true, out chocolateyLicenseType);
}
catch (Exception)
{
chocolateyLicenseType = ChocolateyLicenseType.Unknown;
}
if (license.LicenseType == LicenseType.Trial)
{
chocolateyLicenseType = ChocolateyLicenseType.BusinessTrial;
}
else if (license.LicenseType == LicenseType.Education)
{
chocolateyLicenseType = ChocolateyLicenseType.Educational;
}
chocolateyLicense.LicenseType = chocolateyLicenseType;
chocolateyLicense.ExpirationDate = license.ExpirationDate;
chocolateyLicense.Name = license.Name;
chocolateyLicense.Id = license.UserId.to_string();
//todo: if it is expired, provide a warning.
// one month after it should stop working
}
else
{
//free version
chocolateyLicense.LicenseType = ChocolateyLicenseType.Foss;
}
return chocolateyLicense;
}
}
}
| Apteryx0/choco | src/chocolatey/infrastructure/licensing/LicenseValidation.cs | C# | apache-2.0 | 4,323 |
/*
* NIST SP800-38D compliant GCM implementation
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
*
* See also:
* [MGV] http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf
*
* We use the algorithm described as Shoup's method with 4-bit tables in
* [MGV] 4.1, pp. 12-13, to enhance speed without using too much memory.
*/
#include "common.h"
#if defined(MBEDTLS_GCM_C)
#include "mbedtls/gcm.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
#include <string.h>
#if defined(MBEDTLS_AESNI_C)
#include "aesni.h"
#endif
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
#include "mbedtls/aes.h"
#include "mbedtls/platform.h"
#if !defined(MBEDTLS_PLATFORM_C)
#include <stdio.h>
#define mbedtls_printf printf
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
#if !defined(MBEDTLS_GCM_ALT)
/* Parameter validation macros */
#define GCM_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_GCM_BAD_INPUT )
#define GCM_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
/*
* Initialize a context
*/
void mbedtls_gcm_init( mbedtls_gcm_context *ctx )
{
GCM_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_gcm_context ) );
}
/*
* Precompute small multiples of H, that is set
* HH[i] || HL[i] = H times i,
* where i is seen as a field element as in [MGV], ie high-order bits
* correspond to low powers of P. The result is stored in the same way, that
* is the high-order bit of HH corresponds to P^0 and the low-order bit of HL
* corresponds to P^127.
*/
static int gcm_gen_table( mbedtls_gcm_context *ctx )
{
int ret, i, j;
uint64_t hi, lo;
uint64_t vl, vh;
unsigned char h[16];
size_t olen = 0;
memset( h, 0, 16 );
if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, h, 16, h, &olen ) ) != 0 )
return( ret );
/* pack h as two 64-bits ints, big-endian */
hi = MBEDTLS_GET_UINT32_BE( h, 0 );
lo = MBEDTLS_GET_UINT32_BE( h, 4 );
vh = (uint64_t) hi << 32 | lo;
hi = MBEDTLS_GET_UINT32_BE( h, 8 );
lo = MBEDTLS_GET_UINT32_BE( h, 12 );
vl = (uint64_t) hi << 32 | lo;
/* 8 = 1000 corresponds to 1 in GF(2^128) */
ctx->HL[8] = vl;
ctx->HH[8] = vh;
#if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64)
/* With CLMUL support, we need only h, not the rest of the table */
if( mbedtls_aesni_has_support( MBEDTLS_AESNI_CLMUL ) )
return( 0 );
#endif
/* 0 corresponds to 0 in GF(2^128) */
ctx->HH[0] = 0;
ctx->HL[0] = 0;
for( i = 4; i > 0; i >>= 1 )
{
uint32_t T = ( vl & 1 ) * 0xe1000000U;
vl = ( vh << 63 ) | ( vl >> 1 );
vh = ( vh >> 1 ) ^ ( (uint64_t) T << 32);
ctx->HL[i] = vl;
ctx->HH[i] = vh;
}
for( i = 2; i <= 8; i *= 2 )
{
uint64_t *HiL = ctx->HL + i, *HiH = ctx->HH + i;
vh = *HiH;
vl = *HiL;
for( j = 1; j < i; j++ )
{
HiH[j] = vh ^ ctx->HH[j];
HiL[j] = vl ^ ctx->HL[j];
}
}
return( 0 );
}
int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx,
mbedtls_cipher_id_t cipher,
const unsigned char *key,
unsigned int keybits )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
const mbedtls_cipher_info_t *cipher_info;
GCM_VALIDATE_RET( ctx != NULL );
GCM_VALIDATE_RET( key != NULL );
GCM_VALIDATE_RET( keybits == 128 || keybits == 192 || keybits == 256 );
cipher_info = mbedtls_cipher_info_from_values( cipher, keybits,
MBEDTLS_MODE_ECB );
if( cipher_info == NULL )
return( MBEDTLS_ERR_GCM_BAD_INPUT );
if( cipher_info->block_size != 16 )
return( MBEDTLS_ERR_GCM_BAD_INPUT );
mbedtls_cipher_free( &ctx->cipher_ctx );
if( ( ret = mbedtls_cipher_setup( &ctx->cipher_ctx, cipher_info ) ) != 0 )
return( ret );
if( ( ret = mbedtls_cipher_setkey( &ctx->cipher_ctx, key, keybits,
MBEDTLS_ENCRYPT ) ) != 0 )
{
return( ret );
}
if( ( ret = gcm_gen_table( ctx ) ) != 0 )
return( ret );
return( 0 );
}
/*
* Shoup's method for multiplication use this table with
* last4[x] = x times P^128
* where x and last4[x] are seen as elements of GF(2^128) as in [MGV]
*/
static const uint64_t last4[16] =
{
0x0000, 0x1c20, 0x3840, 0x2460,
0x7080, 0x6ca0, 0x48c0, 0x54e0,
0xe100, 0xfd20, 0xd940, 0xc560,
0x9180, 0x8da0, 0xa9c0, 0xb5e0
};
/*
* Sets output to x times H using the precomputed tables.
* x and output are seen as elements of GF(2^128) as in [MGV].
*/
static void gcm_mult( mbedtls_gcm_context *ctx, const unsigned char x[16],
unsigned char output[16] )
{
int i = 0;
unsigned char lo, hi, rem;
uint64_t zh, zl;
#if defined(MBEDTLS_AESNI_C) && defined(MBEDTLS_HAVE_X86_64)
if( mbedtls_aesni_has_support( MBEDTLS_AESNI_CLMUL ) ) {
unsigned char h[16];
MBEDTLS_PUT_UINT32_BE( ctx->HH[8] >> 32, h, 0 );
MBEDTLS_PUT_UINT32_BE( ctx->HH[8], h, 4 );
MBEDTLS_PUT_UINT32_BE( ctx->HL[8] >> 32, h, 8 );
MBEDTLS_PUT_UINT32_BE( ctx->HL[8], h, 12 );
mbedtls_aesni_gcm_mult( output, x, h );
return;
}
#endif /* MBEDTLS_AESNI_C && MBEDTLS_HAVE_X86_64 */
lo = x[15] & 0xf;
zh = ctx->HH[lo];
zl = ctx->HL[lo];
for( i = 15; i >= 0; i-- )
{
lo = x[i] & 0xf;
hi = ( x[i] >> 4 ) & 0xf;
if( i != 15 )
{
rem = (unsigned char) zl & 0xf;
zl = ( zh << 60 ) | ( zl >> 4 );
zh = ( zh >> 4 );
zh ^= (uint64_t) last4[rem] << 48;
zh ^= ctx->HH[lo];
zl ^= ctx->HL[lo];
}
rem = (unsigned char) zl & 0xf;
zl = ( zh << 60 ) | ( zl >> 4 );
zh = ( zh >> 4 );
zh ^= (uint64_t) last4[rem] << 48;
zh ^= ctx->HH[hi];
zl ^= ctx->HL[hi];
}
MBEDTLS_PUT_UINT32_BE( zh >> 32, output, 0 );
MBEDTLS_PUT_UINT32_BE( zh, output, 4 );
MBEDTLS_PUT_UINT32_BE( zl >> 32, output, 8 );
MBEDTLS_PUT_UINT32_BE( zl, output, 12 );
}
int mbedtls_gcm_starts( mbedtls_gcm_context *ctx,
int mode,
const unsigned char *iv, size_t iv_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char work_buf[16];
size_t i;
const unsigned char *p;
size_t use_len, olen = 0;
uint64_t iv_bits;
GCM_VALIDATE_RET( ctx != NULL );
GCM_VALIDATE_RET( iv != NULL );
/* IV is limited to 2^64 bits, so 2^61 bytes */
/* IV is not allowed to be zero length */
if( iv_len == 0 || (uint64_t) iv_len >> 61 != 0 )
return( MBEDTLS_ERR_GCM_BAD_INPUT );
memset( ctx->y, 0x00, sizeof(ctx->y) );
memset( ctx->buf, 0x00, sizeof(ctx->buf) );
ctx->mode = mode;
ctx->len = 0;
ctx->add_len = 0;
if( iv_len == 12 )
{
memcpy( ctx->y, iv, iv_len );
ctx->y[15] = 1;
}
else
{
memset( work_buf, 0x00, 16 );
iv_bits = (uint64_t)iv_len * 8;
MBEDTLS_PUT_UINT64_BE( iv_bits, work_buf, 8 );
p = iv;
while( iv_len > 0 )
{
use_len = ( iv_len < 16 ) ? iv_len : 16;
for( i = 0; i < use_len; i++ )
ctx->y[i] ^= p[i];
gcm_mult( ctx, ctx->y, ctx->y );
iv_len -= use_len;
p += use_len;
}
for( i = 0; i < 16; i++ )
ctx->y[i] ^= work_buf[i];
gcm_mult( ctx, ctx->y, ctx->y );
}
if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, ctx->y, 16,
ctx->base_ectr, &olen ) ) != 0 )
{
return( ret );
}
return( 0 );
}
/**
* mbedtls_gcm_context::buf contains the partial state of the computation of
* the authentication tag.
* mbedtls_gcm_context::add_len and mbedtls_gcm_context::len indicate
* different stages of the computation:
* * len == 0 && add_len == 0: initial state
* * len == 0 && add_len % 16 != 0: the first `add_len % 16` bytes have
* a partial block of AD that has been
* xored in but not yet multiplied in.
* * len == 0 && add_len % 16 == 0: the authentication tag is correct if
* the data ends now.
* * len % 16 != 0: the first `len % 16` bytes have
* a partial block of ciphertext that has
* been xored in but not yet multiplied in.
* * len > 0 && len % 16 == 0: the authentication tag is correct if
* the data ends now.
*/
int mbedtls_gcm_update_ad( mbedtls_gcm_context *ctx,
const unsigned char *add, size_t add_len )
{
const unsigned char *p;
size_t use_len, i, offset;
GCM_VALIDATE_RET( add_len == 0 || add != NULL );
/* IV is limited to 2^64 bits, so 2^61 bytes */
if( (uint64_t) add_len >> 61 != 0 )
return( MBEDTLS_ERR_GCM_BAD_INPUT );
offset = ctx->add_len % 16;
p = add;
if( offset != 0 )
{
use_len = 16 - offset;
if( use_len > add_len )
use_len = add_len;
for( i = 0; i < use_len; i++ )
ctx->buf[i+offset] ^= p[i];
if( offset + use_len == 16 )
gcm_mult( ctx, ctx->buf, ctx->buf );
ctx->add_len += use_len;
add_len -= use_len;
p += use_len;
}
ctx->add_len += add_len;
while( add_len >= 16 )
{
for( i = 0; i < 16; i++ )
ctx->buf[i] ^= p[i];
gcm_mult( ctx, ctx->buf, ctx->buf );
add_len -= 16;
p += 16;
}
if( add_len > 0 )
{
for( i = 0; i < add_len; i++ )
ctx->buf[i] ^= p[i];
}
return( 0 );
}
/* Increment the counter. */
static void gcm_incr( unsigned char y[16] )
{
size_t i;
for( i = 16; i > 12; i-- )
if( ++y[i - 1] != 0 )
break;
}
/* Calculate and apply the encryption mask. Process use_len bytes of data,
* starting at position offset in the mask block. */
static int gcm_mask( mbedtls_gcm_context *ctx,
unsigned char ectr[16],
size_t offset, size_t use_len,
const unsigned char *input,
unsigned char *output )
{
size_t i;
size_t olen = 0;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, ctx->y, 16, ectr,
&olen ) ) != 0 )
{
mbedtls_platform_zeroize( ectr, 16 );
return( ret );
}
for( i = 0; i < use_len; i++ )
{
if( ctx->mode == MBEDTLS_GCM_DECRYPT )
ctx->buf[offset + i] ^= input[i];
output[i] = ectr[offset + i] ^ input[i];
if( ctx->mode == MBEDTLS_GCM_ENCRYPT )
ctx->buf[offset + i] ^= output[i];
}
return( 0 );
}
int mbedtls_gcm_update( mbedtls_gcm_context *ctx,
const unsigned char *input, size_t input_length,
unsigned char *output, size_t output_size,
size_t *output_length )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
const unsigned char *p = input;
unsigned char *out_p = output;
size_t offset;
unsigned char ectr[16];
if( output_size < input_length )
return( MBEDTLS_ERR_GCM_BUFFER_TOO_SMALL );
GCM_VALIDATE_RET( output_length != NULL );
*output_length = input_length;
/* Exit early if input_length==0 so that we don't do any pointer arithmetic
* on a potentially null pointer.
* Returning early also means that the last partial block of AD remains
* untouched for mbedtls_gcm_finish */
if( input_length == 0 )
return( 0 );
GCM_VALIDATE_RET( ctx != NULL );
GCM_VALIDATE_RET( input != NULL );
GCM_VALIDATE_RET( output != NULL );
if( output > input && (size_t) ( output - input ) < input_length )
return( MBEDTLS_ERR_GCM_BAD_INPUT );
/* Total length is restricted to 2^39 - 256 bits, ie 2^36 - 2^5 bytes
* Also check for possible overflow */
if( ctx->len + input_length < ctx->len ||
(uint64_t) ctx->len + input_length > 0xFFFFFFFE0ull )
{
return( MBEDTLS_ERR_GCM_BAD_INPUT );
}
if( ctx->len == 0 && ctx->add_len % 16 != 0 )
{
gcm_mult( ctx, ctx->buf, ctx->buf );
}
offset = ctx->len % 16;
if( offset != 0 )
{
size_t use_len = 16 - offset;
if( use_len > input_length )
use_len = input_length;
if( ( ret = gcm_mask( ctx, ectr, offset, use_len, p, out_p ) ) != 0 )
return( ret );
if( offset + use_len == 16 )
gcm_mult( ctx, ctx->buf, ctx->buf );
ctx->len += use_len;
input_length -= use_len;
p += use_len;
out_p += use_len;
}
ctx->len += input_length;
while( input_length >= 16 )
{
gcm_incr( ctx->y );
if( ( ret = gcm_mask( ctx, ectr, 0, 16, p, out_p ) ) != 0 )
return( ret );
gcm_mult( ctx, ctx->buf, ctx->buf );
input_length -= 16;
p += 16;
out_p += 16;
}
if( input_length > 0 )
{
gcm_incr( ctx->y );
if( ( ret = gcm_mask( ctx, ectr, 0, input_length, p, out_p ) ) != 0 )
return( ret );
}
mbedtls_platform_zeroize( ectr, sizeof( ectr ) );
return( 0 );
}
int mbedtls_gcm_finish( mbedtls_gcm_context *ctx,
unsigned char *output, size_t output_size,
size_t *output_length,
unsigned char *tag, size_t tag_len )
{
unsigned char work_buf[16];
size_t i;
uint64_t orig_len;
uint64_t orig_add_len;
GCM_VALIDATE_RET( ctx != NULL );
GCM_VALIDATE_RET( tag != NULL );
/* We never pass any output in finish(). The output parameter exists only
* for the sake of alternative implementations. */
(void) output;
(void) output_size;
*output_length = 0;
orig_len = ctx->len * 8;
orig_add_len = ctx->add_len * 8;
if( ctx->len == 0 && ctx->add_len % 16 != 0 )
{
gcm_mult( ctx, ctx->buf, ctx->buf );
}
if( tag_len > 16 || tag_len < 4 )
return( MBEDTLS_ERR_GCM_BAD_INPUT );
if( ctx->len % 16 != 0 )
gcm_mult( ctx, ctx->buf, ctx->buf );
memcpy( tag, ctx->base_ectr, tag_len );
if( orig_len || orig_add_len )
{
memset( work_buf, 0x00, 16 );
MBEDTLS_PUT_UINT32_BE( ( orig_add_len >> 32 ), work_buf, 0 );
MBEDTLS_PUT_UINT32_BE( ( orig_add_len ), work_buf, 4 );
MBEDTLS_PUT_UINT32_BE( ( orig_len >> 32 ), work_buf, 8 );
MBEDTLS_PUT_UINT32_BE( ( orig_len ), work_buf, 12 );
for( i = 0; i < 16; i++ )
ctx->buf[i] ^= work_buf[i];
gcm_mult( ctx, ctx->buf, ctx->buf );
for( i = 0; i < tag_len; i++ )
tag[i] ^= ctx->buf[i];
}
return( 0 );
}
int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx,
int mode,
size_t length,
const unsigned char *iv,
size_t iv_len,
const unsigned char *add,
size_t add_len,
const unsigned char *input,
unsigned char *output,
size_t tag_len,
unsigned char *tag )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t olen;
GCM_VALIDATE_RET( ctx != NULL );
GCM_VALIDATE_RET( iv != NULL );
GCM_VALIDATE_RET( add_len == 0 || add != NULL );
GCM_VALIDATE_RET( length == 0 || input != NULL );
GCM_VALIDATE_RET( length == 0 || output != NULL );
GCM_VALIDATE_RET( tag != NULL );
if( ( ret = mbedtls_gcm_starts( ctx, mode, iv, iv_len ) ) != 0 )
return( ret );
if( ( ret = mbedtls_gcm_update_ad( ctx, add, add_len ) ) != 0 )
return( ret );
if( ( ret = mbedtls_gcm_update( ctx, input, length,
output, length, &olen ) ) != 0 )
return( ret );
if( ( ret = mbedtls_gcm_finish( ctx, NULL, 0, &olen, tag, tag_len ) ) != 0 )
return( ret );
return( 0 );
}
int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx,
size_t length,
const unsigned char *iv,
size_t iv_len,
const unsigned char *add,
size_t add_len,
const unsigned char *tag,
size_t tag_len,
const unsigned char *input,
unsigned char *output )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char check_tag[16];
size_t i;
int diff;
GCM_VALIDATE_RET( ctx != NULL );
GCM_VALIDATE_RET( iv != NULL );
GCM_VALIDATE_RET( add_len == 0 || add != NULL );
GCM_VALIDATE_RET( tag != NULL );
GCM_VALIDATE_RET( length == 0 || input != NULL );
GCM_VALIDATE_RET( length == 0 || output != NULL );
if( ( ret = mbedtls_gcm_crypt_and_tag( ctx, MBEDTLS_GCM_DECRYPT, length,
iv, iv_len, add, add_len,
input, output, tag_len, check_tag ) ) != 0 )
{
return( ret );
}
/* Check tag in "constant-time" */
for( diff = 0, i = 0; i < tag_len; i++ )
diff |= tag[i] ^ check_tag[i];
if( diff != 0 )
{
mbedtls_platform_zeroize( output, length );
return( MBEDTLS_ERR_GCM_AUTH_FAILED );
}
return( 0 );
}
void mbedtls_gcm_free( mbedtls_gcm_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_cipher_free( &ctx->cipher_ctx );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_gcm_context ) );
}
#endif /* !MBEDTLS_GCM_ALT */
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
/*
* AES-GCM test vectors from:
*
* http://csrc.nist.gov/groups/STM/cavp/documents/mac/gcmtestvectors.zip
*/
#define MAX_TESTS 6
static const int key_index_test_data[MAX_TESTS] =
{ 0, 0, 1, 1, 1, 1 };
static const unsigned char key_test_data[MAX_TESTS][32] =
{
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c,
0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08,
0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c,
0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08 },
};
static const size_t iv_len_test_data[MAX_TESTS] =
{ 12, 12, 12, 12, 8, 60 };
static const int iv_index_test_data[MAX_TESTS] =
{ 0, 0, 1, 1, 1, 2 };
static const unsigned char iv_test_data[MAX_TESTS][64] =
{
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00 },
{ 0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad,
0xde, 0xca, 0xf8, 0x88 },
{ 0x93, 0x13, 0x22, 0x5d, 0xf8, 0x84, 0x06, 0xe5,
0x55, 0x90, 0x9c, 0x5a, 0xff, 0x52, 0x69, 0xaa,
0x6a, 0x7a, 0x95, 0x38, 0x53, 0x4f, 0x7d, 0xa1,
0xe4, 0xc3, 0x03, 0xd2, 0xa3, 0x18, 0xa7, 0x28,
0xc3, 0xc0, 0xc9, 0x51, 0x56, 0x80, 0x95, 0x39,
0xfc, 0xf0, 0xe2, 0x42, 0x9a, 0x6b, 0x52, 0x54,
0x16, 0xae, 0xdb, 0xf5, 0xa0, 0xde, 0x6a, 0x57,
0xa6, 0x37, 0xb3, 0x9b },
};
static const size_t add_len_test_data[MAX_TESTS] =
{ 0, 0, 0, 20, 20, 20 };
static const int add_index_test_data[MAX_TESTS] =
{ 0, 0, 0, 1, 1, 1 };
static const unsigned char additional_test_data[MAX_TESTS][64] =
{
{ 0x00 },
{ 0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef,
0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe, 0xef,
0xab, 0xad, 0xda, 0xd2 },
};
static const size_t pt_len_test_data[MAX_TESTS] =
{ 0, 16, 64, 60, 60, 60 };
static const int pt_index_test_data[MAX_TESTS] =
{ 0, 0, 1, 1, 1, 1 };
static const unsigned char pt_test_data[MAX_TESTS][64] =
{
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5,
0xa5, 0x59, 0x09, 0xc5, 0xaf, 0xf5, 0x26, 0x9a,
0x86, 0xa7, 0xa9, 0x53, 0x15, 0x34, 0xf7, 0xda,
0x2e, 0x4c, 0x30, 0x3d, 0x8a, 0x31, 0x8a, 0x72,
0x1c, 0x3c, 0x0c, 0x95, 0x95, 0x68, 0x09, 0x53,
0x2f, 0xcf, 0x0e, 0x24, 0x49, 0xa6, 0xb5, 0x25,
0xb1, 0x6a, 0xed, 0xf5, 0xaa, 0x0d, 0xe6, 0x57,
0xba, 0x63, 0x7b, 0x39, 0x1a, 0xaf, 0xd2, 0x55 },
};
static const unsigned char ct_test_data[MAX_TESTS * 3][64] =
{
{ 0x00 },
{ 0x03, 0x88, 0xda, 0xce, 0x60, 0xb6, 0xa3, 0x92,
0xf3, 0x28, 0xc2, 0xb9, 0x71, 0xb2, 0xfe, 0x78 },
{ 0x42, 0x83, 0x1e, 0xc2, 0x21, 0x77, 0x74, 0x24,
0x4b, 0x72, 0x21, 0xb7, 0x84, 0xd0, 0xd4, 0x9c,
0xe3, 0xaa, 0x21, 0x2f, 0x2c, 0x02, 0xa4, 0xe0,
0x35, 0xc1, 0x7e, 0x23, 0x29, 0xac, 0xa1, 0x2e,
0x21, 0xd5, 0x14, 0xb2, 0x54, 0x66, 0x93, 0x1c,
0x7d, 0x8f, 0x6a, 0x5a, 0xac, 0x84, 0xaa, 0x05,
0x1b, 0xa3, 0x0b, 0x39, 0x6a, 0x0a, 0xac, 0x97,
0x3d, 0x58, 0xe0, 0x91, 0x47, 0x3f, 0x59, 0x85 },
{ 0x42, 0x83, 0x1e, 0xc2, 0x21, 0x77, 0x74, 0x24,
0x4b, 0x72, 0x21, 0xb7, 0x84, 0xd0, 0xd4, 0x9c,
0xe3, 0xaa, 0x21, 0x2f, 0x2c, 0x02, 0xa4, 0xe0,
0x35, 0xc1, 0x7e, 0x23, 0x29, 0xac, 0xa1, 0x2e,
0x21, 0xd5, 0x14, 0xb2, 0x54, 0x66, 0x93, 0x1c,
0x7d, 0x8f, 0x6a, 0x5a, 0xac, 0x84, 0xaa, 0x05,
0x1b, 0xa3, 0x0b, 0x39, 0x6a, 0x0a, 0xac, 0x97,
0x3d, 0x58, 0xe0, 0x91 },
{ 0x61, 0x35, 0x3b, 0x4c, 0x28, 0x06, 0x93, 0x4a,
0x77, 0x7f, 0xf5, 0x1f, 0xa2, 0x2a, 0x47, 0x55,
0x69, 0x9b, 0x2a, 0x71, 0x4f, 0xcd, 0xc6, 0xf8,
0x37, 0x66, 0xe5, 0xf9, 0x7b, 0x6c, 0x74, 0x23,
0x73, 0x80, 0x69, 0x00, 0xe4, 0x9f, 0x24, 0xb2,
0x2b, 0x09, 0x75, 0x44, 0xd4, 0x89, 0x6b, 0x42,
0x49, 0x89, 0xb5, 0xe1, 0xeb, 0xac, 0x0f, 0x07,
0xc2, 0x3f, 0x45, 0x98 },
{ 0x8c, 0xe2, 0x49, 0x98, 0x62, 0x56, 0x15, 0xb6,
0x03, 0xa0, 0x33, 0xac, 0xa1, 0x3f, 0xb8, 0x94,
0xbe, 0x91, 0x12, 0xa5, 0xc3, 0xa2, 0x11, 0xa8,
0xba, 0x26, 0x2a, 0x3c, 0xca, 0x7e, 0x2c, 0xa7,
0x01, 0xe4, 0xa9, 0xa4, 0xfb, 0xa4, 0x3c, 0x90,
0xcc, 0xdc, 0xb2, 0x81, 0xd4, 0x8c, 0x7c, 0x6f,
0xd6, 0x28, 0x75, 0xd2, 0xac, 0xa4, 0x17, 0x03,
0x4c, 0x34, 0xae, 0xe5 },
{ 0x00 },
{ 0x98, 0xe7, 0x24, 0x7c, 0x07, 0xf0, 0xfe, 0x41,
0x1c, 0x26, 0x7e, 0x43, 0x84, 0xb0, 0xf6, 0x00 },
{ 0x39, 0x80, 0xca, 0x0b, 0x3c, 0x00, 0xe8, 0x41,
0xeb, 0x06, 0xfa, 0xc4, 0x87, 0x2a, 0x27, 0x57,
0x85, 0x9e, 0x1c, 0xea, 0xa6, 0xef, 0xd9, 0x84,
0x62, 0x85, 0x93, 0xb4, 0x0c, 0xa1, 0xe1, 0x9c,
0x7d, 0x77, 0x3d, 0x00, 0xc1, 0x44, 0xc5, 0x25,
0xac, 0x61, 0x9d, 0x18, 0xc8, 0x4a, 0x3f, 0x47,
0x18, 0xe2, 0x44, 0x8b, 0x2f, 0xe3, 0x24, 0xd9,
0xcc, 0xda, 0x27, 0x10, 0xac, 0xad, 0xe2, 0x56 },
{ 0x39, 0x80, 0xca, 0x0b, 0x3c, 0x00, 0xe8, 0x41,
0xeb, 0x06, 0xfa, 0xc4, 0x87, 0x2a, 0x27, 0x57,
0x85, 0x9e, 0x1c, 0xea, 0xa6, 0xef, 0xd9, 0x84,
0x62, 0x85, 0x93, 0xb4, 0x0c, 0xa1, 0xe1, 0x9c,
0x7d, 0x77, 0x3d, 0x00, 0xc1, 0x44, 0xc5, 0x25,
0xac, 0x61, 0x9d, 0x18, 0xc8, 0x4a, 0x3f, 0x47,
0x18, 0xe2, 0x44, 0x8b, 0x2f, 0xe3, 0x24, 0xd9,
0xcc, 0xda, 0x27, 0x10 },
{ 0x0f, 0x10, 0xf5, 0x99, 0xae, 0x14, 0xa1, 0x54,
0xed, 0x24, 0xb3, 0x6e, 0x25, 0x32, 0x4d, 0xb8,
0xc5, 0x66, 0x63, 0x2e, 0xf2, 0xbb, 0xb3, 0x4f,
0x83, 0x47, 0x28, 0x0f, 0xc4, 0x50, 0x70, 0x57,
0xfd, 0xdc, 0x29, 0xdf, 0x9a, 0x47, 0x1f, 0x75,
0xc6, 0x65, 0x41, 0xd4, 0xd4, 0xda, 0xd1, 0xc9,
0xe9, 0x3a, 0x19, 0xa5, 0x8e, 0x8b, 0x47, 0x3f,
0xa0, 0xf0, 0x62, 0xf7 },
{ 0xd2, 0x7e, 0x88, 0x68, 0x1c, 0xe3, 0x24, 0x3c,
0x48, 0x30, 0x16, 0x5a, 0x8f, 0xdc, 0xf9, 0xff,
0x1d, 0xe9, 0xa1, 0xd8, 0xe6, 0xb4, 0x47, 0xef,
0x6e, 0xf7, 0xb7, 0x98, 0x28, 0x66, 0x6e, 0x45,
0x81, 0xe7, 0x90, 0x12, 0xaf, 0x34, 0xdd, 0xd9,
0xe2, 0xf0, 0x37, 0x58, 0x9b, 0x29, 0x2d, 0xb3,
0xe6, 0x7c, 0x03, 0x67, 0x45, 0xfa, 0x22, 0xe7,
0xe9, 0xb7, 0x37, 0x3b },
{ 0x00 },
{ 0xce, 0xa7, 0x40, 0x3d, 0x4d, 0x60, 0x6b, 0x6e,
0x07, 0x4e, 0xc5, 0xd3, 0xba, 0xf3, 0x9d, 0x18 },
{ 0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07,
0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, 0x42, 0x7d,
0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9,
0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa,
0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d,
0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38,
0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a,
0xbc, 0xc9, 0xf6, 0x62, 0x89, 0x80, 0x15, 0xad },
{ 0x52, 0x2d, 0xc1, 0xf0, 0x99, 0x56, 0x7d, 0x07,
0xf4, 0x7f, 0x37, 0xa3, 0x2a, 0x84, 0x42, 0x7d,
0x64, 0x3a, 0x8c, 0xdc, 0xbf, 0xe5, 0xc0, 0xc9,
0x75, 0x98, 0xa2, 0xbd, 0x25, 0x55, 0xd1, 0xaa,
0x8c, 0xb0, 0x8e, 0x48, 0x59, 0x0d, 0xbb, 0x3d,
0xa7, 0xb0, 0x8b, 0x10, 0x56, 0x82, 0x88, 0x38,
0xc5, 0xf6, 0x1e, 0x63, 0x93, 0xba, 0x7a, 0x0a,
0xbc, 0xc9, 0xf6, 0x62 },
{ 0xc3, 0x76, 0x2d, 0xf1, 0xca, 0x78, 0x7d, 0x32,
0xae, 0x47, 0xc1, 0x3b, 0xf1, 0x98, 0x44, 0xcb,
0xaf, 0x1a, 0xe1, 0x4d, 0x0b, 0x97, 0x6a, 0xfa,
0xc5, 0x2f, 0xf7, 0xd7, 0x9b, 0xba, 0x9d, 0xe0,
0xfe, 0xb5, 0x82, 0xd3, 0x39, 0x34, 0xa4, 0xf0,
0x95, 0x4c, 0xc2, 0x36, 0x3b, 0xc7, 0x3f, 0x78,
0x62, 0xac, 0x43, 0x0e, 0x64, 0xab, 0xe4, 0x99,
0xf4, 0x7c, 0x9b, 0x1f },
{ 0x5a, 0x8d, 0xef, 0x2f, 0x0c, 0x9e, 0x53, 0xf1,
0xf7, 0x5d, 0x78, 0x53, 0x65, 0x9e, 0x2a, 0x20,
0xee, 0xb2, 0xb2, 0x2a, 0xaf, 0xde, 0x64, 0x19,
0xa0, 0x58, 0xab, 0x4f, 0x6f, 0x74, 0x6b, 0xf4,
0x0f, 0xc0, 0xc3, 0xb7, 0x80, 0xf2, 0x44, 0x45,
0x2d, 0xa3, 0xeb, 0xf1, 0xc5, 0xd8, 0x2c, 0xde,
0xa2, 0x41, 0x89, 0x97, 0x20, 0x0e, 0xf8, 0x2e,
0x44, 0xae, 0x7e, 0x3f },
};
static const unsigned char tag_test_data[MAX_TESTS * 3][16] =
{
{ 0x58, 0xe2, 0xfc, 0xce, 0xfa, 0x7e, 0x30, 0x61,
0x36, 0x7f, 0x1d, 0x57, 0xa4, 0xe7, 0x45, 0x5a },
{ 0xab, 0x6e, 0x47, 0xd4, 0x2c, 0xec, 0x13, 0xbd,
0xf5, 0x3a, 0x67, 0xb2, 0x12, 0x57, 0xbd, 0xdf },
{ 0x4d, 0x5c, 0x2a, 0xf3, 0x27, 0xcd, 0x64, 0xa6,
0x2c, 0xf3, 0x5a, 0xbd, 0x2b, 0xa6, 0xfa, 0xb4 },
{ 0x5b, 0xc9, 0x4f, 0xbc, 0x32, 0x21, 0xa5, 0xdb,
0x94, 0xfa, 0xe9, 0x5a, 0xe7, 0x12, 0x1a, 0x47 },
{ 0x36, 0x12, 0xd2, 0xe7, 0x9e, 0x3b, 0x07, 0x85,
0x56, 0x1b, 0xe1, 0x4a, 0xac, 0xa2, 0xfc, 0xcb },
{ 0x61, 0x9c, 0xc5, 0xae, 0xff, 0xfe, 0x0b, 0xfa,
0x46, 0x2a, 0xf4, 0x3c, 0x16, 0x99, 0xd0, 0x50 },
{ 0xcd, 0x33, 0xb2, 0x8a, 0xc7, 0x73, 0xf7, 0x4b,
0xa0, 0x0e, 0xd1, 0xf3, 0x12, 0x57, 0x24, 0x35 },
{ 0x2f, 0xf5, 0x8d, 0x80, 0x03, 0x39, 0x27, 0xab,
0x8e, 0xf4, 0xd4, 0x58, 0x75, 0x14, 0xf0, 0xfb },
{ 0x99, 0x24, 0xa7, 0xc8, 0x58, 0x73, 0x36, 0xbf,
0xb1, 0x18, 0x02, 0x4d, 0xb8, 0x67, 0x4a, 0x14 },
{ 0x25, 0x19, 0x49, 0x8e, 0x80, 0xf1, 0x47, 0x8f,
0x37, 0xba, 0x55, 0xbd, 0x6d, 0x27, 0x61, 0x8c },
{ 0x65, 0xdc, 0xc5, 0x7f, 0xcf, 0x62, 0x3a, 0x24,
0x09, 0x4f, 0xcc, 0xa4, 0x0d, 0x35, 0x33, 0xf8 },
{ 0xdc, 0xf5, 0x66, 0xff, 0x29, 0x1c, 0x25, 0xbb,
0xb8, 0x56, 0x8f, 0xc3, 0xd3, 0x76, 0xa6, 0xd9 },
{ 0x53, 0x0f, 0x8a, 0xfb, 0xc7, 0x45, 0x36, 0xb9,
0xa9, 0x63, 0xb4, 0xf1, 0xc4, 0xcb, 0x73, 0x8b },
{ 0xd0, 0xd1, 0xc8, 0xa7, 0x99, 0x99, 0x6b, 0xf0,
0x26, 0x5b, 0x98, 0xb5, 0xd4, 0x8a, 0xb9, 0x19 },
{ 0xb0, 0x94, 0xda, 0xc5, 0xd9, 0x34, 0x71, 0xbd,
0xec, 0x1a, 0x50, 0x22, 0x70, 0xe3, 0xcc, 0x6c },
{ 0x76, 0xfc, 0x6e, 0xce, 0x0f, 0x4e, 0x17, 0x68,
0xcd, 0xdf, 0x88, 0x53, 0xbb, 0x2d, 0x55, 0x1b },
{ 0x3a, 0x33, 0x7d, 0xbf, 0x46, 0xa7, 0x92, 0xc4,
0x5e, 0x45, 0x49, 0x13, 0xfe, 0x2e, 0xa8, 0xf2 },
{ 0xa4, 0x4a, 0x82, 0x66, 0xee, 0x1c, 0x8e, 0xb0,
0xc8, 0xb5, 0xd4, 0xcf, 0x5a, 0xe9, 0xf1, 0x9a },
};
int mbedtls_gcm_self_test( int verbose )
{
mbedtls_gcm_context ctx;
unsigned char buf[64];
unsigned char tag_buf[16];
int i, j, ret;
mbedtls_cipher_id_t cipher = MBEDTLS_CIPHER_ID_AES;
size_t olen;
for( j = 0; j < 3; j++ )
{
int key_len = 128 + 64 * j;
for( i = 0; i < MAX_TESTS; i++ )
{
mbedtls_gcm_init( &ctx );
if( verbose != 0 )
mbedtls_printf( " AES-GCM-%3d #%d (%s): ",
key_len, i, "enc" );
ret = mbedtls_gcm_setkey( &ctx, cipher,
key_test_data[key_index_test_data[i]],
key_len );
/*
* AES-192 is an optional feature that may be unavailable when
* there is an alternative underlying implementation i.e. when
* MBEDTLS_AES_ALT is defined.
*/
if( ret == MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED && key_len == 192 )
{
mbedtls_printf( "skipped\n" );
break;
}
else if( ret != 0 )
{
goto exit;
}
ret = mbedtls_gcm_crypt_and_tag( &ctx, MBEDTLS_GCM_ENCRYPT,
pt_len_test_data[i],
iv_test_data[iv_index_test_data[i]],
iv_len_test_data[i],
additional_test_data[add_index_test_data[i]],
add_len_test_data[i],
pt_test_data[pt_index_test_data[i]],
buf, 16, tag_buf );
#if defined(MBEDTLS_GCM_ALT)
/* Allow alternative implementations to only support 12-byte nonces. */
if( ret == MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED &&
iv_len_test_data[i] != 12 )
{
mbedtls_printf( "skipped\n" );
break;
}
#endif /* defined(MBEDTLS_GCM_ALT) */
if( ret != 0 )
goto exit;
if ( memcmp( buf, ct_test_data[j * 6 + i],
pt_len_test_data[i] ) != 0 ||
memcmp( tag_buf, tag_test_data[j * 6 + i], 16 ) != 0 )
{
ret = 1;
goto exit;
}
mbedtls_gcm_free( &ctx );
if( verbose != 0 )
mbedtls_printf( "passed\n" );
mbedtls_gcm_init( &ctx );
if( verbose != 0 )
mbedtls_printf( " AES-GCM-%3d #%d (%s): ",
key_len, i, "dec" );
ret = mbedtls_gcm_setkey( &ctx, cipher,
key_test_data[key_index_test_data[i]],
key_len );
if( ret != 0 )
goto exit;
ret = mbedtls_gcm_crypt_and_tag( &ctx, MBEDTLS_GCM_DECRYPT,
pt_len_test_data[i],
iv_test_data[iv_index_test_data[i]],
iv_len_test_data[i],
additional_test_data[add_index_test_data[i]],
add_len_test_data[i],
ct_test_data[j * 6 + i], buf, 16, tag_buf );
if( ret != 0 )
goto exit;
if( memcmp( buf, pt_test_data[pt_index_test_data[i]],
pt_len_test_data[i] ) != 0 ||
memcmp( tag_buf, tag_test_data[j * 6 + i], 16 ) != 0 )
{
ret = 1;
goto exit;
}
mbedtls_gcm_free( &ctx );
if( verbose != 0 )
mbedtls_printf( "passed\n" );
mbedtls_gcm_init( &ctx );
if( verbose != 0 )
mbedtls_printf( " AES-GCM-%3d #%d split (%s): ",
key_len, i, "enc" );
ret = mbedtls_gcm_setkey( &ctx, cipher,
key_test_data[key_index_test_data[i]],
key_len );
if( ret != 0 )
goto exit;
ret = mbedtls_gcm_starts( &ctx, MBEDTLS_GCM_ENCRYPT,
iv_test_data[iv_index_test_data[i]],
iv_len_test_data[i] );
if( ret != 0 )
goto exit;
ret = mbedtls_gcm_update_ad( &ctx,
additional_test_data[add_index_test_data[i]],
add_len_test_data[i] );
if( ret != 0 )
goto exit;
if( pt_len_test_data[i] > 32 )
{
size_t rest_len = pt_len_test_data[i] - 32;
ret = mbedtls_gcm_update( &ctx,
pt_test_data[pt_index_test_data[i]],
32,
buf, sizeof( buf ), &olen );
if( ret != 0 )
goto exit;
if( olen != 32 )
goto exit;
ret = mbedtls_gcm_update( &ctx,
pt_test_data[pt_index_test_data[i]] + 32,
rest_len,
buf + 32, sizeof( buf ) - 32, &olen );
if( ret != 0 )
goto exit;
if( olen != rest_len )
goto exit;
}
else
{
ret = mbedtls_gcm_update( &ctx,
pt_test_data[pt_index_test_data[i]],
pt_len_test_data[i],
buf, sizeof( buf ), &olen );
if( ret != 0 )
goto exit;
if( olen != pt_len_test_data[i] )
goto exit;
}
ret = mbedtls_gcm_finish( &ctx, NULL, 0, &olen, tag_buf, 16 );
if( ret != 0 )
goto exit;
if( memcmp( buf, ct_test_data[j * 6 + i],
pt_len_test_data[i] ) != 0 ||
memcmp( tag_buf, tag_test_data[j * 6 + i], 16 ) != 0 )
{
ret = 1;
goto exit;
}
mbedtls_gcm_free( &ctx );
if( verbose != 0 )
mbedtls_printf( "passed\n" );
mbedtls_gcm_init( &ctx );
if( verbose != 0 )
mbedtls_printf( " AES-GCM-%3d #%d split (%s): ",
key_len, i, "dec" );
ret = mbedtls_gcm_setkey( &ctx, cipher,
key_test_data[key_index_test_data[i]],
key_len );
if( ret != 0 )
goto exit;
ret = mbedtls_gcm_starts( &ctx, MBEDTLS_GCM_DECRYPT,
iv_test_data[iv_index_test_data[i]],
iv_len_test_data[i] );
if( ret != 0 )
goto exit;
ret = mbedtls_gcm_update_ad( &ctx,
additional_test_data[add_index_test_data[i]],
add_len_test_data[i] );
if( ret != 0 )
goto exit;
if( pt_len_test_data[i] > 32 )
{
size_t rest_len = pt_len_test_data[i] - 32;
ret = mbedtls_gcm_update( &ctx,
ct_test_data[j * 6 + i], 32,
buf, sizeof( buf ), &olen );
if( ret != 0 )
goto exit;
if( olen != 32 )
goto exit;
ret = mbedtls_gcm_update( &ctx,
ct_test_data[j * 6 + i] + 32,
rest_len,
buf + 32, sizeof( buf ) - 32, &olen );
if( ret != 0 )
goto exit;
if( olen != rest_len )
goto exit;
}
else
{
ret = mbedtls_gcm_update( &ctx,
ct_test_data[j * 6 + i],
pt_len_test_data[i],
buf, sizeof( buf ), &olen );
if( ret != 0 )
goto exit;
if( olen != pt_len_test_data[i] )
goto exit;
}
ret = mbedtls_gcm_finish( &ctx, NULL, 0, &olen, tag_buf, 16 );
if( ret != 0 )
goto exit;
if( memcmp( buf, pt_test_data[pt_index_test_data[i]],
pt_len_test_data[i] ) != 0 ||
memcmp( tag_buf, tag_test_data[j * 6 + i], 16 ) != 0 )
{
ret = 1;
goto exit;
}
mbedtls_gcm_free( &ctx );
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
}
if( verbose != 0 )
mbedtls_printf( "\n" );
ret = 0;
exit:
if( ret != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
mbedtls_gcm_free( &ctx );
}
return( ret );
}
#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
#endif /* MBEDTLS_GCM_C */
| ARMmbed/mbedtls | library/gcm.c | C | apache-2.0 | 38,696 |
document.addEventListener("deviceready", function(){
pushNotification = window.plugins.pushNotification;
$("#app-status-ul").append('<li>registering ' + device.platform + '</li>');
pushNotification.register( successHandler, errorHandler, { 'senderID':'86663666263', 'ecb':'onNotification' } );
function successHandler (result) {
alert('result = ' + result);
}
function errorHandler (error) {
alert('error = ' + error);
}
// iOS
function onNotificationAPN (event) {
if ( event.alert )
{
navigator.notification.alert(event.alert);
}
if ( event.sound )
{
var snd = new Media(event.sound);
snd.play();
}
if ( event.badge )
{
pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);
}
}
// Android and Amazon Fire OS
function onNotification(e) {
//$("#app-status-ul").append('<li>EVENT -> RECEIVED:' + e.event + '</li>');
switch( e.event )
{
case 'registered':
if ( e.regid.length > 0 )
{
console.log("Regid " + e.regid);
alert('registration id = '+e.regid);
}
break;
case 'message':
// this is the actual push notification. its format depends on the data model from the push server
alert('message = '+e.message+' msgcnt = '+e.msgcnt);
break;
case 'error':
alert('GCM error = '+e.msg);
break;
default:
alert('An unknown GCM event has occurred');
break;
}
}
});
$(document).on('ready', function() {
$(window).on('load', function() {
domain = 'https://galan.ehu.eus/exerclick/';
$.ajaxSetup({ cache: false });
// Cross domain
$.support.cors = true;
// Needed to get all the height
$('#header').show();
var windowHeight = $(window).height();
var offsetTop = $('#main').offset().top;
var offsetBottom = $('#overfooter').height() + $('#footer').height();
// DYNAMIC RESIZINGS
$('#exercises-container').css('height', windowHeight - offsetTop - offsetBottom - 2 * Math.floor(parseFloat($('body').css('font-size'))));
$('#exercises-content').css('height', $('#exercises-container').height() - Math.floor(parseFloat($('body').css('font-size'))));
$('#container').append('<div class="darken"></div>');
$('.darken').css('height', windowHeight);
$('.darken').hide();
$('.darken').on('click', hideAll);
function loadData() {
$.ajax({
type: 'GET',
async: false,
url: domain + 'get-data.php',
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
/*var lang = data.data[9].language;
switch(lang) {
case 'es':
break;
case 'eu':
break;
}*/
$('.name').attr('data-id', data.data[0].id);
if(data.data[1].subject != null)
$('.subject').html(data.data[1].subject);
var surname1 = (data.data[6] !== undefined && data.data[5].surname1 !== undefined) ? data.data[6].surname1 : ' ';
var surname2 = (data.data[7] !== undefined && data.data[6].surname2 !== undefined) ? data.data[7].surname2 : ' ';
$('.name').html(data.data[5].username + ' ' + surname1 + ' ' + surname2);
showExercises();
}
});
return $.Deferred().resolve();
}
function hideAll() {
if($('#exercise-details').length) {
$('#exercise-details').slideUp("slow", function() {
$('#exercise-details').remove();
});
}
$('.darken').hide();
return $.Deferred().resolve();
}
function showExercises() {
$.ajax({
type: 'GET',
async: false,
url: domain + 'show-exercises.php',
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
data: { Type: 'Active' },
success: function(data) {
$('#exercises-content').html("");
if(data.exercises.length == 0) {
$('#exercises-content').html('<div id="screen-center">No hay ejercicios disponibles.</div>');
} else {
$.each(data.exercises, function(i, item) {
var state = item.exercise.state.toLowerCase();
if(state === 'nothing') {
var background = '';
} else {
var background = 'background-' + state;
}
$('#exercises-content').append(
'<div class=\"exercise\" data-id=\"' + item.exercise.id + '\">' +
'<div class=\"exercise-container col-xs-12 ' + background + '\">' +
'<div class=\"col-xs-4 col-sm-6 col-md-9 col-lg-9 exercise-name ' + background + '\">' +
'<div class=\"ellipsis padd1 bold\">' + item.exercise.description + '</div>' +
'<div class=\"exercise-name-icons padd3\">' + item.exercise.nofinished + '/' + item.exercise.num + ' <i class=\"fa fa-check-square-o fa-fw\"></i> ' + item.exercise.noquestions + '/' + item.exercise.num + ' <i class=\"fa fa-exclamation fa-fw\"></i></div>' +
'</div>' +
'<div class=\"col-xs-8 col-sm-6 col-md-3 col-lg-3 exercise-buttons ' + background + '\">' +
'<div class=\"exercise-buttons-icons\">' +
'<button class="' + ((state === 'finished' || (state != 'finished' && state != 'question')) ? '' : 'disabled') + ' btn btn-default btn-primary col-xs-offset-2 col-xs-4 ' +
'button-finished"><i class="fa fa-flag-checkered"></i></button>' +
'<button class="' + ((state === 'question' || (state != 'finished' && state != 'question')) ? '' : 'disabled') + ' btn btn-default btn-danger col-xs-offset-2 col-xs-4 ' +
'button-question"><i class="fa fa-exclamation"></i></button>' +
'</div>' +
'</div>' +
'</div>' +
'</div>'
);
});
}
loadStudentProgressBar();
}
});
return $.Deferred().resolve();
}
function showExerciseDetails(id) {
// Wait for everything to hide
hideAll().done(function() {
$.ajax({
type: 'GET',
async: false,
url: domain + 'get-exercise-details.php',
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
data: { Id: id },
success: function(data) {
$('.darken').show();
$('#container').append(
'<div id=\"exercise-details\">' +
'<div id=\"exercise-details-title\">' +
'<div class=\"tab-title col-xs-2 col-lg-1\"><i class=\"back fa fa-reply btn btn-default\"></i></div>' +
'<div class=\"tab-title col-xs-10 col-lg-11 ehuFontStyle\"><h4>' + data.exercise.description + '</h4></div>' +
'</div>' +
'<div class=\"clear\"></div>' +
'<div class=\"row separator\"></div>' +
'<div class=\"exercise-details-body\">' +
'<div class="exercise-details-title col-xs-12">Enunciado</div>' +
'<p class="col-xs-12">' + data.exercise.statement + '</p>' +
'<div class="exercise-details-title col-lg-2 col-xs-6 bottompad">Tema</div><div class="exercise-detail col-lg-2 col-xs-6">' + data.exercise.topic + '</div>' +
'<div class=\"hidden-lg clear\"></div>' +
'<div class="exercise-details-title col-lg-2 col-xs-6 bottompad">Página</div><div class="exercise-detail col-lg-2 col-xs-6">' + data.exercise.page + '</div>' +
'<div class=\"hidden-lg clear\"></div>' +
'<div class="exercise-details-title col-lg-2 col-xs-6 bottompad">Dificultad</div><div class="exercise-detail col-lg-2 col-xs-6">' + data.exercise.difficulty + '</div>' +
'</div>' +
'</div>'
);
$('#header').show();
$('#state-buttons').show();
var windowHeight = $(window).height();
var offsetTop = $('#main').offset().top;
var offsetBottom = $('#overfooter').height() + $('#footer').height();
$('#exercise-details').css('bottom', offsetBottom);
$('#exercise-details').css('height', $('#exercises-container').height() + 2 * $('#state-buttons').height());
$('#exercise-details').hide();
$('#exercise-details').addClass('top-shadow');
$('#exercise-details').slideDown("slow");
}
});
});
return $.Deferred().resolve();
}
$(document).on('vclick click tap', '.button-question', function(e) {
e.stopPropagation();
var id = $(this).parents('.exercise').attr('data-id');
// Both buttons are not selected
if(!$(this).hasClass('disabled') && !$(this).siblings('.button-finished').hasClass('disabled')) {
markExerciseAs(id, 'Question');
var parent = $(this).parents('.exercise-container');
parent.addClass('background-question');
parent.find('.exercise-name').addClass('background-question');
parent.find('.exercise-buttons').addClass('background-question');
$(this).siblings('.button-finished').addClass('disabled');
//parent.removeClass('background-question');
//parent.find('.exercise-name').removeClass('background-question');
//parent.find('.exercise-buttons').removeClass('background-question');
} else if(!$(this).hasClass('disabled') && $(this).siblings('.button-finished').hasClass('disabled')) {
markExerciseAs(id, 'Nothing');
var parent = $(this).parents('.exercise-container');
parent.removeClass('background-question');
parent.find('.exercise-name').removeClass('background-question');
parent.find('.exercise-buttons').removeClass('background-question');
$(this).siblings('.button-finished').removeClass('disabled');
$(this).removeClass('disabled');
}
});
$(document).on('vclick click tap', '.button-finished', function(e) {
e.stopPropagation();
var id = $(this).parents('.exercise').attr('data-id');
// Both buttons are not selected
if(!$(this).hasClass('disabled') && !$(this).siblings('.button-question').hasClass('disabled')) {
markExerciseAs(id, 'Finished');
var parent = $(this).parents('.exercise-container');
parent.addClass('background-finished');
parent.find('.exercise-name').addClass('background-finished');
parent.find('.exercise-buttons').addClass('background-finished');
$(this).siblings('.button-question').addClass('disabled');
//parent.removeClass('background-question');
//parent.find('.exercise-name').removeClass('background-question');
//parent.find('.exercise-buttons').removeClass('background-question');
} else if(!$(this).hasClass('disabled') && $(this).siblings('.button-question').hasClass('disabled')) {
markExerciseAs(id, 'Nothing');
var parent = $(this).parents('.exercise-container');
parent.removeClass('background-finished');
parent.find('.exercise-name').removeClass('background-finished');
parent.find('.exercise-buttons').removeClass('background-finished');
$(this).removeClass('disabled');
$(this).siblings('.button-question').removeClass('disabled');
}
});
function loadStudentProgressBar() {
$.ajax({
type: 'GET',
async: false,
url: domain + 'get-student-progress.php',
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
$('#overfooter').find('.progress-percentage').html(data.data[0].studentprogress);
$('#overfooter').find('.progress-bar').css('width', data.data[0].studentprogress + '%').attr('aria-valuenow', data.data[0].studentprogress);
if(data.data[0].studentprogress == 100) {
$('#overfooter').find('.progress-bar').removeClass('progress-bar-info');
$('#overfooter').find('.progress-bar').removeClass('progress-bar-warning');
$('#overfooter').find('.progress-bar').addClass('progress-bar-success');
} else if(data.data[0].studentprogress >= 75) {
$('#overfooter').find('.progress-bar').removeClass('progress-bar-info');
$('#overfooter').find('.progress-bar').addClass('progress-bar-warning');
$('#overfooter').find('.progress-bar').removeClass('progress-bar-success');
} else {
$('#overfooter').find('.progress-bar').addClass('progress-bar-info');
$('#overfooter').find('.progress-bar').removeClass('progress-bar-warning');
$('#overfooter').find('.progress-bar').removeClass('progress-bar-success');
}
$('#footer').find('.progress-percentage').html(data.data[1].classprogress);
$('#footer').find('.progress-bar').css('width', data.data[1].classprogress + '%').attr('aria-valuenow', data.data[1].classprogress);
if(data.data[1].classprogress == 100) {
$('#footer').find('.progress-bar').removeClass('progress-bar-info');
$('#footer').find('.progress-bar').removeClass('progress-bar-warning');
$('#footer').find('.progress-bar').addClass('progress-bar-success');
} else if(data.data[1].classprogress >= 75) {
$('#footer').find('.progress-bar').removeClass('progress-bar-info');
$('#footer').find('.progress-bar').addClass('progress-bar-warning');
$('#footer').find('.progress-bar').removeClass('progress-bar-success');
} else {
$('#footer').find('.progress-bar').addClass('progress-bar-info');
$('#footer').find('.progress-bar').removeClass('progress-bar-warning');
$('#footer').find('.progress-bar').removeClass('progress-bar-success');
}
}
});
return $.Deferred().resolve();
}
function markExerciseAs(id, markAs) {
var idstudent = $('.name').attr('data-id');
$.ajax({
type: 'GET',
async: false,
url: domain + 'mark-exercise.php',
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
data: { Idexercise: id, State: markAs },
success: function(data) {
showExercises();
}
});
return $.Deferred().resolve();
}
$(document).on('vclick click tap', '.exercise', function() {
var id = $(this).attr('data-id');
showExerciseDetails(id);
});
$(document).on('vclick click tap', '.back', hideAll);
$(window).on('resize', function() {
$('#header').show();
var offsetTop = $('#main').offset().top;
var offsetBottom = $('#overfooter').height() + $('#footer').height();
var windowHeight = $(window).height();
// DYNAMIC RESIZINGS
$('#exercises-container').css('height', windowHeight - offsetTop - offsetBottom - 2*Math.floor(parseFloat($('body').css('font-size'))));
$('#exercises-content').css('height', $('#exercises-container').height() - Math.floor(parseFloat($('body').css('font-size'))));
if($('#exercise-details').length != 0) {
$('#exercise-details').css('bottom', offsetBottom);
$('#exercise-details').css('height', $('#exercises-container').height() + 2 * $('#state-buttons').height());
}
});
loadData();
setInterval(refresh, 3000);
});
});
| AdrianNunez/exerClick | phone/platforms/android/assets/www/js/student.js | JavaScript | apache-2.0 | 14,691 |
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { EventEmitter } from 'events';
import { LocalDataService } from '../services/local-data.service';
import { ApplicationViewModel, ListBody, ListPageViewModel } from '../services/viewmodel.types';
import { DataService } from './data.service';
export class UnreadStats {
public changes: number = 0;
public messages: number = 0;
}
// "Unread" statuses for items and pages
@Injectable()
export class UnreadService {
private _storageKey = 'readViedId';
private _readStatusChangeEmitter = new EventEmitter();
constructor(private _localDataService: LocalDataService,
private _dataService: DataService) {
}
public async markPageRead(pageId: string, pageBody: ListBody) {
const currentReadViewIds = await this.getReadViewIds();
const modelIds = pageBody.items.filter((item) => item.viewId).map((item) => item.viewId);
// It's by design that IDs removed from the model are also removed
// from the list of read. If a condition is removed and then re-added,
// user should be notified again.
currentReadViewIds[pageId] = modelIds;
this._readStatusChangeEmitter.emit('change', currentReadViewIds);
await this._localDataService.setItem(this._storageKey, currentReadViewIds);
}
public getDataWithUnreadStatus(): Observable<ApplicationViewModel> {
return Observable.combineLatest(this._dataService.getData(),
this.observeReadViewIds(),
(appViewModel: ApplicationViewModel, readViewIds: any) => this.updateUnreadInModel(appViewModel, readViewIds));
}
public getUnreadStats(): Observable<UnreadStats> {
return this.getDataWithUnreadStatus().map((appViewModel: ApplicationViewModel) => {
const stats: UnreadStats = {changes: 0, messages: 0};
const changesPages = appViewModel.pages.filter((page) => page.viewId == 'page:changes');
if (changesPages.length == 1) {
const changesPage = (changesPages[0] as ListPageViewModel);
stats.changes = changesPage.body.items.filter((item) => item.unread).length;
}
const messagesPages = appViewModel.pages.filter((page) => page.viewId == 'page:messages');
if (messagesPages.length == 1) {
const messagesPage = (messagesPages[0] as ListPageViewModel);
stats.messages = messagesPage.body.items.filter((item) => item.unread).length;
}
return stats;
});
}
private observeReadViewIds(): Observable<any> {
return Observable.fromPromise(this.getReadViewIds())
.concat(Observable.fromEvent(this._readStatusChangeEmitter, 'change', (v) => v));
}
private async getReadViewIds(): Promise<any> {
let currentReadViewIds = await this._localDataService.getItemOrNull(this._storageKey);
if (!currentReadViewIds) currentReadViewIds = {};
return currentReadViewIds;
}
private updateUnreadInModel(viewModel: ApplicationViewModel, readStatusData: any) {
// TODO: Also highlight changes. Use map viewId->revision instead.
viewModel.pages.forEach((page) => {
if (page.__type == 'ListPageViewModel') {
const listPage = page as ListPageViewModel;
const readIdsOnPage: string[] = (readStatusData && readStatusData[listPage.viewId])
? readStatusData[listPage.viewId] : [];
this.updateUnreadInPage(listPage.body, readIdsOnPage);
}
});
return viewModel;
}
private updateUnreadInPage(pageBody: ListBody, readIdsOnPageArray: string[]) {
const readIds: Set<string> = new Set(readIdsOnPageArray);
pageBody.items.forEach((item) => {
if (item.viewId) {
item.unread = !readIds.has(item.viewId);
}
});
}
}
| sth-larp/deus-mobile | src/services/unread.service.ts | TypeScript | apache-2.0 | 3,704 |
# AUTOGENERATED FILE
FROM balenalib/aarch64-debian:bullseye-run
# remove several traces of debian python
RUN apt-get purge -y python.*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# install python dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
netbase \
&& rm -rf /var/lib/apt/lists/*
# key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported
RUN gpg --batch --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
ENV PYTHON_VERSION 3.8.9
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.0.1
ENV SETUPTOOLS_VERSION 56.0.0
RUN set -x \
&& buildDeps=' \
curl \
' \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-aarch64-openssl1.1.tar.gz" \
&& echo "8a565846e715aa422ea060155704ed2ed5b06f685e6847630d2c7e7b28b0ffc8 Python-$PYTHON_VERSION.linux-aarch64-openssl1.1.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-aarch64-openssl1.1.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-aarch64-openssl1.1.tar.gz" \
&& ldconfig \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
# set PYTHONPATH to point to dist-packages
ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Debian Bullseye \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.8.9, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | nghiant2710/base-images | balena-base-images/python/aarch64/debian/bullseye/3.8.9/run/Dockerfile | Dockerfile | apache-2.0 | 4,094 |
// Generated on 2014-09-23 using
// generator-webapp 0.5.0
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// If you want to recursively match all subfolders, use:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Configurable paths
var config = {
app: 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
config: config,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= config.app %>/scripts/{,*/}*.js'],
tasks: ['jshint'],
options: {
livereload: true
}
},
jstest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['test:watch']
},
gruntfile: {
files: ['Gruntfile.js']
},
styles: {
files: ['<%= config.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'autoprefixer']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= config.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= config.app %>/images/{,*/}*'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
open: true,
livereload: 35729,
// Change this to '0.0.0.0' to access the server from outside
hostname: 'localhost'
},
livereload: {
options: {
middleware: function(connect) {
return [
connect.static('.tmp'),
connect().use('/bower_components', connect.static('./bower_components')),
connect.static(config.app)
];
}
}
},
test: {
options: {
open: false,
port: 9001,
middleware: function(connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use('/bower_components', connect.static('./bower_components')),
connect.static(config.app)
];
}
}
},
dist: {
options: {
base: '<%= config.dist %>',
livereload: false
}
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= config.dist %>/*',
'!<%= config.dist %>/.git*'
]
}]
},
server: '.tmp'
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: [
'Gruntfile.js',
'<%= config.app %>/scripts/{,*/}*.js',
'!<%= config.app %>/scripts/vendor/*',
'test/spec/{,*/}*.js'
]
},
// Mocha testing framework configuration options
mocha: {
all: {
options: {
run: true,
urls: ['http://<%= connect.test.options.hostname %>:<%= connect.test.options.port %>/index.html']
}
}
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the HTML file
wiredep: {
app: {
ignorePath: /^\/|\.\.\//,
src: ['<%= config.app %>/index.html'],
exclude: ['bower_components/bootstrap/dist/js/bootstrap.js']
}
},
// Renames files for browser caching purposes
rev: {
dist: {
files: {
src: [
'<%= config.dist %>/scripts/{,*/}*.js',
'<%= config.dist %>/styles/{,*/}*.css',
'<%= config.dist %>/images/{,*/}*.*',
'<%= config.dist %>/styles/fonts/{,*/}*.*',
'<%= config.dist %>/*.{ico,png}'
]
}
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
options: {
dest: '<%= config.dist %>'
},
html: '<%= config.app %>/index.html'
},
// Performs rewrites based on rev and the useminPrepare configuration
usemin: {
options: {
assetsDirs: ['<%= config.dist %>', '<%= config.dist %>/images']
},
html: ['<%= config.dist %>/{,*/}*.html'],
css: ['<%= config.dist %>/styles/{,*/}*.css']
},
// The following *-min tasks produce minified files in the dist folder
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/images',
src: '{,*/}*.{gif,jpeg,jpg,png}',
dest: '<%= config.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/images',
src: '{,*/}*.svg',
dest: '<%= config.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
conservativeCollapse: true,
removeAttributeQuotes: true,
removeCommentsFromCDATA: true,
removeEmptyAttributes: true,
removeOptionalTags: true,
removeRedundantAttributes: true,
useShortDoctype: true
},
files: [{
expand: true,
cwd: '<%= config.dist %>',
src: '{,*/}*.html',
dest: '<%= config.dist %>'
}]
}
},
// By default, your `index.html`'s <!-- Usemin block --> will take care
// of minification. These next options are pre-configured if you do not
// wish to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= config.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css',
// '<%= config.app %>/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= config.dist %>/scripts/scripts.js': [
// '<%= config.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= config.app %>',
dest: '<%= config.dist %>',
src: [
'*.{ico,png,txt}',
'images/{,*/}*.webp',
'{,*/}*.html',
'styles/fonts/{,*/}*.*'
]
}, {
src: 'node_modules/apache-server-configs/dist/.htaccess',
dest: '<%= config.dist %>/.htaccess'
}, {
expand: true,
dot: true,
cwd: 'bower_components/bootstrap/dist',
src: 'fonts/*',
dest: '<%= config.dist %>'
}]
},
styles: {
expand: true,
dot: true,
cwd: '<%= config.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up build process
concurrent: {
server: [
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'copy:styles',
'imagemin',
'svgmin'
]
}
});
grunt.registerTask('serve', 'start the server and preview your app, --allow-remote for remote access', function (target) {
if (grunt.option('allow-remote')) {
grunt.config.set('connect.options.hostname', '0.0.0.0');
}
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive', 'watch']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'autoprefixer',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run([target ? ('serve:' + target) : 'serve']);
});
grunt.registerTask('test', function (target) {
if (target !== 'watch') {
grunt.task.run([
'clean:server',
'concurrent:test',
'autoprefixer'
]);
}
grunt.task.run([
'connect:test',
'mocha'
]);
});
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'cssmin',
'uglify',
'copy:dist',
'rev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
| anuteja/charting-dashboard | Gruntfile.js | JavaScript | apache-2.0 | 9,402 |
var filterReflectionByTitle = filterModule.filter('filterReflectionByTitle', function ($window) {
return function (reflections, filterCriteria) {
var strStartsWith = function (str, prefix) {
return (str + "").indexOf(prefix) === 0;
};
if (filterCriteria == null || filterCriteria === '')
return reflections;
var filtered = _.reduce(reflections, function (filteredList, reflection) {
var title = (filterCriteria.contentTextRepresentation === 'Transliteration') ?
reflection.title :
reflection.title;
if (strStartsWith(title.toUpperCase(), filterCriteria.alphabet.toUpperCase()))
filteredList.push(reflection);
return filteredList;
}, []);
return filtered;
}
});
| AjabShahar/Ajab-Shahar-TW | web/app/user/js/common/filters/filterReflectionByTitle.js | JavaScript | apache-2.0 | 830 |
//
// CBJSONEncoder.h
// CBJSON
//
// Created by Jens Alfke on 12/27/13.
// Copyright (c) 2013 Couchbase. All rights reserved.
//
#import <Foundation/Foundation.h>
/** Encodes Cocoa objects to JSON. Supports canonical encoding. */
@interface CBJSONEncoder : NSObject
- (instancetype) init;
- (BOOL) encode: (id)object;
/** If YES, JSON will be generated in canonical form, with consistently-ordered dictionary keys. */
@property BOOL canonical;
@property (readonly, nonatomic) NSError* error;
@property (readonly, nonatomic) NSData* encodedData;
+ (NSData*) encode: (id)object error: (NSError**)outError;
+ (NSData*) canonicalEncoding: (id)object error: (NSError**)outError;
/** Returns the dictionary's keys in the canonical order. */
+ (NSArray*) orderedKeys: (NSDictionary*)dict;
// PROTECTED:
@property (readonly, nonatomic) NSMutableData* output;
- (BOOL) encodeKey: (id)key value: (id)value;
- (BOOL) encodeNestedObject: (id)object;
@end
extern NSString* const CBJSONEncoderErrorDomain;
| mz2/couchbase-lite-ios | Source/CBJSONEncoder.h | C | apache-2.0 | 1,008 |
/*
* Copyright (c) 1999 Boris Fomitchev
* AUTOMATICALLY GENERATED - DO NOT EDIT !
*/
/*
*
* This wrapper is needed for Borland C++ 5.0 to get STLport
* header properly included
*/
#ifndef __STLPORT_BC_stdexcept_H
# define __STLPORT_BC_stdexcept_H
# include <..\stdexcept.>
#endif
// Local Variables:
// mode:C++
// End:
| aestesis/elektronika | src/STLport/stlport/BC50/stdexcep.h | C | apache-2.0 | 360 |
using EzFramework.Core;
using EzFramework.Data.AccessObject;
using EzFramework.Data.Attributes;
using EzFramework.Data.Map;
using EzFramework.Utils;
using System;
using System.Reflection;
namespace EzFramework.Data
{
/// <summary>
/// 数据库持久层相关扩展方法
/// </summary>
public static class ExtendFun
{
/// <summary>
/// 分页查询,此方法不在建议使用
/// </summary>
/// <param name="info">分页信息</param>
/// <param name="selectColumns">需要查询的列</param>
/// <param name="fromTableOrViewNames">表或试图</param>
/// <param name="condition">条件,不需要包含关键字 where</param>
/// <param name="orderby">排序字段</param>
/// <param name="pkname">主键名</param>
/// <returns>分页查询对象</returns>
public static PageQuery QueryObj(this PagerInfo info, string selectColumns, string fromTableOrViewNames, string condition, string orderby, string pkname)
{
return new PageQuery(selectColumns, fromTableOrViewNames, condition, info.PageIndex, info.PageSize)
{
PkName = pkname,
OrderBy = orderby
};
}
/// <summary>
/// 根据SQL描述信息执行数据库操作
/// </summary>
/// <param name="dao">数据库操作对象</param>
/// <param name="descript">数据库</param>
/// <returns></returns>
public static bool ExecuteSqlDescrip(this IDefaultDao dao, SqlDescrip descript)
{
return dao.ExecuteSql(descript.SQlString, descript.DbParams) > 0; ;
}
/// <summary>
/// 根据SQL描述信息执行数据库操作
/// </summary>
/// <param name="dao">数据库操作对象</param>
/// <param name="descript">数据库</param>
/// <param name="cachekey">清除指定key的缓存</param>
/// <returns></returns>
public static bool ExecuteSqlDescrip(this IDefaultDao dao, SqlDescrip descript, string cachekey)
{
bool success = dao.ExecuteSql(descript.SQlString, descript.DbParams) > 0;
if (success && !string.IsNullOrEmpty(cachekey))
{
try
{
CachePool.RemoveCachePool(cachekey);
}
catch (Exception exp)
{
LogHelper.Error("数据缓存清除失败(" + cachekey + "):" + exp);
}
}
return success;
}
/// <summary>
/// 根据SQL描述信息执行数据库操作
/// </summary>
/// <param name="dao">数据库操作对象</param>
/// <param name="descript">数据库</param>
/// <param name="auto_cache_clear">是否清除所有类型前缀的缓存</param>
/// <returns></returns>
public static bool ExecuteSqlDescrip(this IDefaultDao dao, SqlDescrip descript, bool auto_cache_clear)
{
bool success = dao.ExecuteSql(descript.SQlString, descript.DbParams) > 0;
if (success && auto_cache_clear && descript.EntityType != null)
{
BaseDao.clearDbCache(descript.EntityType);
}
return success;
}
/// <summary>
/// 初始化表映射类中属性类型为string和datetime
/// </summary>
/// <typeparam name="T">表映射类类型</typeparam>
/// <param name="t">表映射类实例</param>
/// <returns></returns>
public static T Normalize<T>(this T t) where T : DefaultEntity, new()
{
PropertyInfo[] target_pinfos = t.GetType().GetProperties();
foreach (var property in target_pinfos)
{
System.TypeCode tcode = System.Type.GetTypeCode(property.PropertyType);
if (!property.CanWrite && !property.CanRead && (tcode != System.TypeCode.String || tcode != System.TypeCode.DateTime))
continue;
object[] igones = property.GetCustomAttributes(typeof(IgoneTranslat), false);
if (igones != null && igones.Length > 0) continue;
igones = property.GetCustomAttributes(typeof(IgoneFiled), false);
if (igones.Length > 0) continue;
object obj = property.GetValue(t, null);
if (obj != null) continue;
if (tcode == System.TypeCode.String)
{
property.SetValue(t, "", null);
}
else if (tcode == System.TypeCode.DateTime)
{
property.SetValue(t, DateTime.MinValue, null);
}
}
return t;
}
}
}
| endfalse/EzFramework7 | src/EzFramework.Data/ExtendFun.cs | C# | apache-2.0 | 4,849 |
/*
Copyright 2008-2015 Genentech Inc.
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.
*/
package com.genentech.oechem.tools;
import openeye.oechem.*;
/**
* static final helper methods for OEAtoms
*
*/
public class Atom {
private Atom() {}
public static final void removeChiralInfo(OEAtomBase at) {
assert at.HasStereoSpecified();
OEAtomBaseVector v = new OEAtomBaseVector();
OEAtomBaseIter nbriter=at.GetAtoms();
while( nbriter.hasNext() )
v.add(nbriter.next());
nbriter.delete();
at.SetStereo(v, OEAtomStereo.Tetrahedral, OEAtomStereo.Undefined);
v.delete();
}
/**
* Get the atomic name composed of the atomic symbol followed by (index in
* the molecule+1).
*/
public static final String getAtomName(OEAtomBase at) {
return oechem.OEGetAtomicSymbol(at.GetAtomicNum()) + (at.GetIdx()+1);
}
/** find any atom connected to at1 which is not at2
* @return null if no atom found.
*/
public static OEAtomBase findExoNeighbor(OEAtomBase at1, OEAtomBase at2) {
OEAtomBase oldNat = null;
OEAtomBaseIter nAtIt=at1.GetAtoms();
while( nAtIt.hasNext() ) {
oldNat = nAtIt.next();
if( oldNat.GetIdx() != at2.GetIdx() ) break; // found atom
}
nAtIt.delete();
if( oldNat.GetIdx() == at2.GetIdx() ) return null;
return oldNat;
}
}
| chemalot/chemalot | src/com/genentech/oechem/tools/Atom.java | Java | apache-2.0 | 1,937 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OtherQuestions.cs
{
public class _006_SearchInMatrix
{
/*
* 一个矩阵行列都是递增序, 查找一个数
*/
public int FindInMatrix(int[,] input, int value)
{
if (input == null)
{
// throw exception
return -1;
}
int top = 0;
int bottom = input.GetLength(0)-1;
int right = input.GetLength(1)-1;
int mid = -1;
while (top <= bottom)
{
mid = (top + bottom) / 2;
if (value >= input[mid, 0] && value <= input[mid, right])
{
break;
}
if (value < input[mid, 0])
{
bottom = mid - 1;
}
else
{
top = mid + 1;
}
}
int left = 0;
while (left <= right)
{
int tmp = (left + right) / 2;
if (input[mid, tmp] == value)
{
return value;
}
else
{
if (value < input[mid, tmp])
{
right = tmp - 1;
}
else
{
left = tmp + 1;
}
}
}
return int.MinValue;
}
}
}
| zduan001/BusAroundMe | Console/OtherQuestions.cs/006_SearchInMatrix.cs | C# | apache-2.0 | 1,664 |
import React, { useState } from 'react';
import * as R from 'ramda';
import Head from 'next/head';
import { useQuery } from "@apollo/react-hooks";
import AllProjectsProblemsQuery from 'lib/query/AllProjectsProblems';
import getSeverityEnumQuery, {getProjectOptions, getSourceOptions} from 'components/Filters/helpers';
import { LoadingPageNoHeader } from 'pages/_loading';
import Honeycomb from "components/Honeycomb";
import MainLayout from 'layouts/MainLayout';
import SelectFilter from 'components/Filters';
import { bp } from 'lib/variables';
/**
* Displays problems page by project.
*
*/
const ProblemsDashboardByProjectPageHexDisplay = () => {
const [showCleanProjects, setShowCleanProjects] = useState(true);
const [source, setSource] = useState([]);
const [severity, setSeverity] = useState(['CRITICAL']);
const [envType, setEnvType] = useState('PRODUCTION');
const { data: severities, loading: severityLoading } = useQuery(getSeverityEnumQuery);
const { data: sources, loading: sourceLoading } = useQuery(getSourceOptions);
const { data: projectsProblems, loading: projectsProblemsLoading} =
useQuery(AllProjectsProblemsQuery, {
variables: {
severity: severity,
source: source,
envType: envType
}
});
const handleEnvTypeChange = (envType) => setEnvType(envType.value);
const handleShowAllProjectsCheck = () => setShowCleanProjects(!showCleanProjects);
const handleSourceChange = (source) => {
let values = source && source.map(s => s.value) || [];
setSource(values);
};
const handleSeverityChange = (severity) => {
let values = severity && severity.map(s => s.value) || [];
setSeverity(values);
};
const sourceOptions = (sources) => {
return sources && sources.map(s => ({ value: s, label: s}));
};
const severityOptions = (enums) => {
return enums && enums.map(s => ({ value: s.name, label: s.name}));
};
return (
<>
<Head>
<title>Problems Dashboard By Project</title>
</Head>
<MainLayout>
<div className="filters-wrapper">
<div className="filters">
<SelectFilter
title="Severity"
loading={severityLoading}
options={severities && severityOptions(severities.__type.enumValues)}
defaultValue={{value: "CRITICAL", label: "CRITICAL"}}
onFilterChange={handleSeverityChange}
isMulti
/>
<SelectFilter
title="Source"
loading={sourceLoading}
options={sources && sourceOptions(sources.sources)}
onFilterChange={handleSourceChange}
isMulti
/>
<SelectFilter
title="Type"
defaultValue={{value: 'PRODUCTION', label: 'Production'}}
options={[
{value: 'PRODUCTION', label: 'Production'},
{value: 'DEVELOPMENT', label: 'Development'}
]}
onFilterChange={handleEnvTypeChange}
/>
</div>
<div className="extra-filters">
<label>Show Projects with no problems: </label>
<input name="env-type" onClick={handleShowAllProjectsCheck} defaultChecked={showCleanProjects} type="checkbox" />
</div>
</div>
<div className="content-wrapper">
<div className="overview">
{projectsProblemsLoading && <LoadingPageNoHeader />}
{!projectsProblemsLoading &&
<Honeycomb
data={!R.isNil(projectsProblems) && projectsProblems}
filter={{showCleanProjects: showCleanProjects}}
/>
}
</div>
</div>
<style jsx>{`
.filters-wrapper, .project-filter {
margin: 32px calc((100vw / 16) * 1);
@media ${bp.wideUp} {
margin: 32px calc((100vw / 16) * 2);
}
@media ${bp.extraWideUp} {
margin: 32px calc((100vw / 16) * 3);
}
.filters {
display: flex;
flex-direction: column;
@media ${bp.wideUp} {
flex-flow: row;
}
&:first-child {
padding-bottom: 1em;
}
}
}
.extra-filters {
padding: 0 15px;
}
.content-wrapper {
h2 {
margin: 38px calc((100vw / 16) * 1) 0;
@media ${bp.wideUp} {
margin: 62px calc((100vw / 16) * 2) 0;
}
@media ${bp.extraWideUp} {
margin: 62px calc((100vw / 16) * 3) 0;
}
}
.content {
background: #fff;
margin: 0 calc((100vw / 16) * 1);
@media ${bp.wideUp} {
margin: 0 calc((100vw / 16) * 2);
}
@media ${bp.extraWideUp} {
margin: 0 calc((100vw / 16) * 3);
}
li.result {
display: inline;
}
}
.environment-wrapper {
padding: 0 1em 1em;
background: #fefefe;
margin: 0 0 2em;
h4 {
font-weight: 500;
}
}
.data-none {
display: flex;
justify-content: space-between;
padding: 1em;
border: 1px solid #efefef;
}
}
`}</style>
</MainLayout>
</>);
};
export default ProblemsDashboardByProjectPageHexDisplay;
| amazeeio/lagoon | services/ui/src/pages/problems-dashboard-by-project-hex.js | JavaScript | apache-2.0 | 5,478 |
/****************************************************************
* Licensed to the AOS Community (AOS) under one or more *
* contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The AOS 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. *
****************************************************************/
package io.aos.guice.by.ib2;
public class SplImpl {
public void splr() {
System.out.println("Helloo");
}
}
| XClouded/t4f-core | java/inject/src/main/java/io/aos/guice/by/ib2/SplImpl.java | Java | apache-2.0 | 1,304 |
<!DOCTYPE html>
<html>
<head>
<title>static content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
Hello
정적 컨텐츠입니다.
</body>
</html> | c86j224s/snippet | Java_Spring_HelloSpring/hello-spring/hello-spring/src/main/resources/static/hello-static.html | HTML | apache-2.0 | 200 |
package ru.job4j.list;
/**
* Класс для проверки замыканий/цикличностей в связном списке, основанном на
* узлах {@link ru.job4j.list.Node}.
*/
public final class ListClosuresChecker {
/**
* Поиск замыканий в списке.
* <p>На вход подаётся любой узел списка в качестве начального. Таким
* образом неоднократный вызов данного метода поможет найти все замыкания
* имеющихся узлов.</p>
*
* @param initialNode Начальный узел, от которого происходит поиск замыкания.
* @return true, если замыкание найдено, в противном случае - false.
* @throws IllegalArgumentException если передан пустой объект в качестве
* аргумента.
*/
public static boolean hasClosure(Node<?> initialNode) {
if (initialNode == null) {
throw new IllegalArgumentException("Метод принимает только непустые объекты.");
}
return initialNode.getNext() != null
&& isSimilarNodes(initialNode, initialNode.getNext());
}
/**
* Сравнение двух смежных узлов на замыкание.
*
* @param firstNode Первый узел для сравнения.
* @param secondNode Второй узел для сравнения.
* @return true, если замыкание найдено, в противном случае - false.
*/
private static boolean isSimilarNodes(Node<?> firstNode, Node<?> secondNode) {
return firstNode == secondNode
|| firstNode != null && firstNode.getNext() != null
&& secondNode != null && secondNode.getNext() != null
&& secondNode.getNext().getNext() != null
&& isSimilarNodes(firstNode.getNext(), secondNode.getNext().getNext());
}
}
| LuxCore/dkitrish | 2.Junior/001.CollectionsPRO/src/main/java/ru/job4j/list/ListClosuresChecker.java | Java | apache-2.0 | 2,025 |
package com.logginghub.logging.frontend.charting.model;
public interface StreamListener<T> {
void onNewItem(T t);
}
| logginghub/core | logginghub-frontend/src/main/java/com/logginghub/logging/frontend/charting/model/StreamListener.java | Java | apache-2.0 | 126 |
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using CrptoTrade.Assets;
using CrptoTrade.Trading;
namespace CrptoTrade
{
public enum CryptoCurrency
{
Btc = 0,
Eth,
Ltc
}
public class BuyRequest
{
public CryptoCurrency Currency { get; set; }
public decimal DollarAmount { get; set; }
}
public class SellRequest
{
public CryptoCurrency Currency { get; set; }
public decimal CurrencyAmount { get; set; }
}
[RoutePrefix("trade")]
public class TradeController : ApiController
{
private readonly TradingFactory _factory;
public TradeController(TradingFactory factory)
{
_factory = factory;
}
[HttpPost]
[Route("buy")]
public Task<HttpResponseMessage> Buy([FromBody] BuyRequest request)
{
throw new NotImplementedException();
}
[HttpPost]
[Route("sell")]
public Task<HttpResponseMessage> Sell([FromBody] SellRequest request)
{
throw new NotImplementedException();
}
[HttpGet]
[Route("fakebuy")]
public async Task<TradeResponse> FakeBuy([FromUri] int currency, [FromUri] decimal dollarAmount)
{
if (currency < 0 || currency > 2)
{
return new TradeResponse
{
Error = "Currency Value invalid, Use 0,1,2"
};
}
var currencyEnum = (CryptoCurrency) currency;
var result = await _factory.GetTrader(currencyEnum).TradeAsync(new BuyPosition(dollarAmount))
.ConfigureAwait(false);
result.Initial += " $";
result.Untraded += " $";
result.TotalTraded += $" {currencyEnum}";
return result;
}
[HttpGet]
[Route("fakesell")]
public async Task<TradeResponse> FakeSell([FromUri] int currency, [FromUri] decimal currencyAmount)
{
if (currency < 0 || currency > 2)
{
return new TradeResponse
{
Error = "Currency Value invalid, Use 0,1,2"
};
}
var currencyEnum = (CryptoCurrency) currency;
var result = await _factory.GetTrader(currencyEnum).TradeAsync(new SellPosition(currencyAmount))
.ConfigureAwait(false);
result.Initial += $" {currencyEnum}";
result.Untraded += $" {currencyEnum}";
result.TotalTraded += $" {currencyEnum}";
return result;
}
}
} | samaysar/cryptopoc | CrptoTrade/CrptoTrade/TradeController.cs | C# | apache-2.0 | 2,698 |
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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.
import collections
import copy
import functools
import uuid
from dogpile.cache import api
from dogpile.cache import region as dp_region
import six
from keystone.common.cache.backends import mongo
from keystone import exception
from keystone.tests import unit as tests
# Mock database structure sample where 'ks_cache' is database and
# 'cache' is collection. Dogpile CachedValue data is divided in two
# fields `value` (CachedValue.payload) and `meta` (CachedValue.metadata)
ks_cache = {
"cache": [
{
"value": {
"serviceType": "identity",
"allVersionsUrl": "https://dummyUrl",
"dateLastModified": "ISODDate(2014-02-08T18:39:13.237Z)",
"serviceName": "Identity",
"enabled": "True"
},
"meta": {
"v": 1,
"ct": 1392371422.015121
},
"doc_date": "ISODate('2014-02-14T09:50:22.015Z')",
"_id": "8251dc95f63842719c077072f1047ddf"
},
{
"value": "dummyValueX",
"meta": {
"v": 1,
"ct": 1392371422.014058
},
"doc_date": "ISODate('2014-02-14T09:50:22.014Z')",
"_id": "66730b9534d146f0804d23729ad35436"
}
]
}
COLLECTIONS = {}
SON_MANIPULATOR = None
class MockCursor(object):
def __init__(self, collection, dataset_factory):
super(MockCursor, self).__init__()
self.collection = collection
self._factory = dataset_factory
self._dataset = self._factory()
self._limit = None
self._skip = None
def __iter__(self):
return self
def __next__(self):
if self._skip:
for _ in range(self._skip):
next(self._dataset)
self._skip = None
if self._limit is not None and self._limit <= 0:
raise StopIteration()
if self._limit is not None:
self._limit -= 1
return next(self._dataset)
next = __next__
def __getitem__(self, index):
arr = [x for x in self._dataset]
self._dataset = iter(arr)
return arr[index]
class MockCollection(object):
def __init__(self, db, name):
super(MockCollection, self).__init__()
self.name = name
self._collection_database = db
self._documents = {}
self.write_concern = {}
def __getattr__(self, name):
if name == 'database':
return self._collection_database
def ensure_index(self, key_or_list, *args, **kwargs):
pass
def index_information(self):
return {}
def find_one(self, spec_or_id=None, *args, **kwargs):
if spec_or_id is None:
spec_or_id = {}
if not isinstance(spec_or_id, collections.Mapping):
spec_or_id = {'_id': spec_or_id}
try:
return next(self.find(spec_or_id, *args, **kwargs))
except StopIteration:
return None
def find(self, spec=None, *args, **kwargs):
return MockCursor(self, functools.partial(self._get_dataset, spec))
def _get_dataset(self, spec):
dataset = (self._copy_doc(document, dict) for document in
self._iter_documents(spec))
return dataset
def _iter_documents(self, spec=None):
return (SON_MANIPULATOR.transform_outgoing(document, self) for
document in six.itervalues(self._documents)
if self._apply_filter(document, spec))
def _apply_filter(self, document, query):
for key, search in six.iteritems(query):
doc_val = document.get(key)
if isinstance(search, dict):
op_dict = {'$in': lambda dv, sv: dv in sv}
is_match = all(
op_str in op_dict and op_dict[op_str](doc_val, search_val)
for op_str, search_val in six.iteritems(search)
)
else:
is_match = doc_val == search
return is_match
def _copy_doc(self, obj, container):
if isinstance(obj, list):
new = []
for item in obj:
new.append(self._copy_doc(item, container))
return new
if isinstance(obj, dict):
new = container()
for key, value in obj.items():
new[key] = self._copy_doc(value, container)
return new
else:
return copy.copy(obj)
def insert(self, data, manipulate=True, **kwargs):
if isinstance(data, list):
return [self._insert(element) for element in data]
return self._insert(data)
def save(self, data, manipulate=True, **kwargs):
return self._insert(data)
def _insert(self, data):
if '_id' not in data:
data['_id'] = uuid.uuid4().hex
object_id = data['_id']
self._documents[object_id] = self._internalize_dict(data)
return object_id
def find_and_modify(self, spec, document, upsert=False, **kwargs):
self.update(spec, document, upsert, **kwargs)
def update(self, spec, document, upsert=False, **kwargs):
existing_docs = [doc for doc in six.itervalues(self._documents)
if self._apply_filter(doc, spec)]
if existing_docs:
existing_doc = existing_docs[0] # should find only 1 match
_id = existing_doc['_id']
existing_doc.clear()
existing_doc['_id'] = _id
existing_doc.update(self._internalize_dict(document))
elif upsert:
existing_doc = self._documents[self._insert(document)]
def _internalize_dict(self, d):
return dict((k, copy.deepcopy(v)) for k, v in six.iteritems(d))
def remove(self, spec_or_id=None, search_filter=None):
"""Remove objects matching spec_or_id from the collection."""
if spec_or_id is None:
spec_or_id = search_filter if search_filter else {}
if not isinstance(spec_or_id, dict):
spec_or_id = {'_id': spec_or_id}
to_delete = list(self.find(spec=spec_or_id))
for doc in to_delete:
doc_id = doc['_id']
del self._documents[doc_id]
return {
"connectionId": uuid.uuid4().hex,
"n": len(to_delete),
"ok": 1.0,
"err": None,
}
class MockMongoDB(object):
def __init__(self, dbname):
self._dbname = dbname
self.mainpulator = None
def authenticate(self, username, password):
pass
def add_son_manipulator(self, manipulator):
global SON_MANIPULATOR
SON_MANIPULATOR = manipulator
def __getattr__(self, name):
if name == 'authenticate':
return self.authenticate
elif name == 'name':
return self._dbname
elif name == 'add_son_manipulator':
return self.add_son_manipulator
else:
return get_collection(self._dbname, name)
def __getitem__(self, name):
return get_collection(self._dbname, name)
class MockMongoClient(object):
def __init__(self, *args, **kwargs):
pass
def __getattr__(self, dbname):
return MockMongoDB(dbname)
def get_collection(db_name, collection_name):
mongo_collection = MockCollection(MockMongoDB(db_name), collection_name)
return mongo_collection
def pymongo_override():
global pymongo
import pymongo
if pymongo.MongoClient is not MockMongoClient:
pymongo.MongoClient = MockMongoClient
if pymongo.MongoReplicaSetClient is not MockMongoClient:
pymongo.MongoClient = MockMongoClient
class MyTransformer(mongo.BaseTransform):
"""Added here just to check manipulator logic is used correctly."""
def transform_incoming(self, son, collection):
return super(MyTransformer, self).transform_incoming(son, collection)
def transform_outgoing(self, son, collection):
return super(MyTransformer, self).transform_outgoing(son, collection)
class MongoCache(tests.BaseTestCase):
def setUp(self):
super(MongoCache, self).setUp()
global COLLECTIONS
COLLECTIONS = {}
mongo.MongoApi._DB = {}
mongo.MongoApi._MONGO_COLLS = {}
pymongo_override()
# using typical configuration
self.arguments = {
'db_hosts': 'localhost:27017',
'db_name': 'ks_cache',
'cache_collection': 'cache',
'username': 'test_user',
'password': 'test_password'
}
def test_missing_db_hosts(self):
self.arguments.pop('db_hosts')
region = dp_region.make_region()
self.assertRaises(exception.ValidationError, region.configure,
'keystone.cache.mongo',
arguments=self.arguments)
def test_missing_db_name(self):
self.arguments.pop('db_name')
region = dp_region.make_region()
self.assertRaises(exception.ValidationError, region.configure,
'keystone.cache.mongo',
arguments=self.arguments)
def test_missing_cache_collection_name(self):
self.arguments.pop('cache_collection')
region = dp_region.make_region()
self.assertRaises(exception.ValidationError, region.configure,
'keystone.cache.mongo',
arguments=self.arguments)
def test_incorrect_write_concern(self):
self.arguments['w'] = 'one value'
region = dp_region.make_region()
self.assertRaises(exception.ValidationError, region.configure,
'keystone.cache.mongo',
arguments=self.arguments)
def test_correct_write_concern(self):
self.arguments['w'] = 1
region = dp_region.make_region().configure('keystone.cache.mongo',
arguments=self.arguments)
random_key = uuid.uuid4().hex
region.set(random_key, "dummyValue10")
# There is no proxy so can access MongoCacheBackend directly
self.assertEqual(region.backend.api.w, 1)
def test_incorrect_read_preference(self):
self.arguments['read_preference'] = 'inValidValue'
region = dp_region.make_region().configure('keystone.cache.mongo',
arguments=self.arguments)
# As per delayed loading of pymongo, read_preference value should
# still be string and NOT enum
self.assertEqual(region.backend.api.read_preference,
'inValidValue')
random_key = uuid.uuid4().hex
self.assertRaises(ValueError, region.set,
random_key, "dummyValue10")
def test_correct_read_preference(self):
self.arguments['read_preference'] = 'secondaryPreferred'
region = dp_region.make_region().configure('keystone.cache.mongo',
arguments=self.arguments)
# As per delayed loading of pymongo, read_preference value should
# still be string and NOT enum
self.assertEqual(region.backend.api.read_preference,
'secondaryPreferred')
random_key = uuid.uuid4().hex
region.set(random_key, "dummyValue10")
# Now as pymongo is loaded so expected read_preference value is enum.
# There is no proxy so can access MongoCacheBackend directly
self.assertEqual(region.backend.api.read_preference, 3)
def test_missing_replica_set_name(self):
self.arguments['use_replica'] = True
region = dp_region.make_region()
self.assertRaises(exception.ValidationError, region.configure,
'keystone.cache.mongo',
arguments=self.arguments)
def test_provided_replica_set_name(self):
self.arguments['use_replica'] = True
self.arguments['replicaset_name'] = 'my_replica'
dp_region.make_region().configure('keystone.cache.mongo',
arguments=self.arguments)
self.assertTrue(True) # reached here means no initialization error
def test_incorrect_mongo_ttl_seconds(self):
self.arguments['mongo_ttl_seconds'] = 'sixty'
region = dp_region.make_region()
self.assertRaises(exception.ValidationError, region.configure,
'keystone.cache.mongo',
arguments=self.arguments)
def test_cache_configuration_values_assertion(self):
self.arguments['use_replica'] = True
self.arguments['replicaset_name'] = 'my_replica'
self.arguments['mongo_ttl_seconds'] = 60
self.arguments['ssl'] = False
region = dp_region.make_region().configure('keystone.cache.mongo',
arguments=self.arguments)
# There is no proxy so can access MongoCacheBackend directly
self.assertEqual(region.backend.api.hosts, 'localhost:27017')
self.assertEqual(region.backend.api.db_name, 'ks_cache')
self.assertEqual(region.backend.api.cache_collection, 'cache')
self.assertEqual(region.backend.api.username, 'test_user')
self.assertEqual(region.backend.api.password, 'test_password')
self.assertEqual(region.backend.api.use_replica, True)
self.assertEqual(region.backend.api.replicaset_name, 'my_replica')
self.assertEqual(region.backend.api.conn_kwargs['ssl'], False)
self.assertEqual(region.backend.api.ttl_seconds, 60)
def test_multiple_region_cache_configuration(self):
arguments1 = copy.copy(self.arguments)
arguments1['cache_collection'] = 'cache_region1'
region1 = dp_region.make_region().configure('keystone.cache.mongo',
arguments=arguments1)
# There is no proxy so can access MongoCacheBackend directly
self.assertEqual(region1.backend.api.hosts, 'localhost:27017')
self.assertEqual(region1.backend.api.db_name, 'ks_cache')
self.assertEqual(region1.backend.api.cache_collection, 'cache_region1')
self.assertEqual(region1.backend.api.username, 'test_user')
self.assertEqual(region1.backend.api.password, 'test_password')
# Should be None because of delayed initialization
self.assertIsNone(region1.backend.api._data_manipulator)
random_key1 = uuid.uuid4().hex
region1.set(random_key1, "dummyValue10")
self.assertEqual("dummyValue10", region1.get(random_key1))
# Now should have initialized
self.assertIsInstance(region1.backend.api._data_manipulator,
mongo.BaseTransform)
class_name = '%s.%s' % (MyTransformer.__module__, "MyTransformer")
arguments2 = copy.copy(self.arguments)
arguments2['cache_collection'] = 'cache_region2'
arguments2['son_manipulator'] = class_name
region2 = dp_region.make_region().configure('keystone.cache.mongo',
arguments=arguments2)
# There is no proxy so can access MongoCacheBackend directly
self.assertEqual(region2.backend.api.hosts, 'localhost:27017')
self.assertEqual(region2.backend.api.db_name, 'ks_cache')
self.assertEqual(region2.backend.api.cache_collection, 'cache_region2')
# Should be None because of delayed initialization
self.assertIsNone(region2.backend.api._data_manipulator)
random_key = uuid.uuid4().hex
region2.set(random_key, "dummyValue20")
self.assertEqual("dummyValue20", region2.get(random_key))
# Now should have initialized
self.assertIsInstance(region2.backend.api._data_manipulator,
MyTransformer)
region1.set(random_key1, "dummyValue22")
self.assertEqual("dummyValue22", region1.get(random_key1))
def test_typical_configuration(self):
dp_region.make_region().configure(
'keystone.cache.mongo',
arguments=self.arguments
)
self.assertTrue(True) # reached here means no initialization error
def test_backend_get_missing_data(self):
region = dp_region.make_region().configure(
'keystone.cache.mongo',
arguments=self.arguments
)
random_key = uuid.uuid4().hex
# should return NO_VALUE as key does not exist in cache
self.assertEqual(api.NO_VALUE, region.get(random_key))
def test_backend_set_data(self):
region = dp_region.make_region().configure(
'keystone.cache.mongo',
arguments=self.arguments
)
random_key = uuid.uuid4().hex
region.set(random_key, "dummyValue")
self.assertEqual("dummyValue", region.get(random_key))
def test_backend_set_data_with_string_as_valid_ttl(self):
self.arguments['mongo_ttl_seconds'] = '3600'
region = dp_region.make_region().configure('keystone.cache.mongo',
arguments=self.arguments)
self.assertEqual(region.backend.api.ttl_seconds, 3600)
random_key = uuid.uuid4().hex
region.set(random_key, "dummyValue")
self.assertEqual("dummyValue", region.get(random_key))
def test_backend_set_data_with_int_as_valid_ttl(self):
self.arguments['mongo_ttl_seconds'] = 1800
region = dp_region.make_region().configure('keystone.cache.mongo',
arguments=self.arguments)
self.assertEqual(region.backend.api.ttl_seconds, 1800)
random_key = uuid.uuid4().hex
region.set(random_key, "dummyValue")
self.assertEqual("dummyValue", region.get(random_key))
def test_backend_set_none_as_data(self):
region = dp_region.make_region().configure(
'keystone.cache.mongo',
arguments=self.arguments
)
random_key = uuid.uuid4().hex
region.set(random_key, None)
self.assertIsNone(region.get(random_key))
def test_backend_set_blank_as_data(self):
region = dp_region.make_region().configure(
'keystone.cache.mongo',
arguments=self.arguments
)
random_key = uuid.uuid4().hex
region.set(random_key, "")
self.assertEqual("", region.get(random_key))
def test_backend_set_same_key_multiple_times(self):
region = dp_region.make_region().configure(
'keystone.cache.mongo',
arguments=self.arguments
)
random_key = uuid.uuid4().hex
region.set(random_key, "dummyValue")
self.assertEqual("dummyValue", region.get(random_key))
dict_value = {'key1': 'value1'}
region.set(random_key, dict_value)
self.assertEqual(dict_value, region.get(random_key))
region.set(random_key, "dummyValue2")
self.assertEqual("dummyValue2", region.get(random_key))
def test_backend_multi_set_data(self):
region = dp_region.make_region().configure(
'keystone.cache.mongo',
arguments=self.arguments
)
random_key = uuid.uuid4().hex
random_key1 = uuid.uuid4().hex
random_key2 = uuid.uuid4().hex
random_key3 = uuid.uuid4().hex
mapping = {random_key1: 'dummyValue1',
random_key2: 'dummyValue2',
random_key3: 'dummyValue3'}
region.set_multi(mapping)
# should return NO_VALUE as key does not exist in cache
self.assertEqual(api.NO_VALUE, region.get(random_key))
self.assertFalse(region.get(random_key))
self.assertEqual("dummyValue1", region.get(random_key1))
self.assertEqual("dummyValue2", region.get(random_key2))
self.assertEqual("dummyValue3", region.get(random_key3))
def test_backend_multi_get_data(self):
region = dp_region.make_region().configure(
'keystone.cache.mongo',
arguments=self.arguments
)
random_key = uuid.uuid4().hex
random_key1 = uuid.uuid4().hex
random_key2 = uuid.uuid4().hex
random_key3 = uuid.uuid4().hex
mapping = {random_key1: 'dummyValue1',
random_key2: '',
random_key3: 'dummyValue3'}
region.set_multi(mapping)
keys = [random_key, random_key1, random_key2, random_key3]
results = region.get_multi(keys)
# should return NO_VALUE as key does not exist in cache
self.assertEqual(api.NO_VALUE, results[0])
self.assertEqual("dummyValue1", results[1])
self.assertEqual("", results[2])
self.assertEqual("dummyValue3", results[3])
def test_backend_multi_set_should_update_existing(self):
region = dp_region.make_region().configure(
'keystone.cache.mongo',
arguments=self.arguments
)
random_key = uuid.uuid4().hex
random_key1 = uuid.uuid4().hex
random_key2 = uuid.uuid4().hex
random_key3 = uuid.uuid4().hex
mapping = {random_key1: 'dummyValue1',
random_key2: 'dummyValue2',
random_key3: 'dummyValue3'}
region.set_multi(mapping)
# should return NO_VALUE as key does not exist in cache
self.assertEqual(api.NO_VALUE, region.get(random_key))
self.assertEqual("dummyValue1", region.get(random_key1))
self.assertEqual("dummyValue2", region.get(random_key2))
self.assertEqual("dummyValue3", region.get(random_key3))
mapping = {random_key1: 'dummyValue4',
random_key2: 'dummyValue5'}
region.set_multi(mapping)
self.assertEqual(api.NO_VALUE, region.get(random_key))
self.assertEqual("dummyValue4", region.get(random_key1))
self.assertEqual("dummyValue5", region.get(random_key2))
self.assertEqual("dummyValue3", region.get(random_key3))
def test_backend_multi_set_get_with_blanks_none(self):
region = dp_region.make_region().configure(
'keystone.cache.mongo',
arguments=self.arguments
)
random_key = uuid.uuid4().hex
random_key1 = uuid.uuid4().hex
random_key2 = uuid.uuid4().hex
random_key3 = uuid.uuid4().hex
random_key4 = uuid.uuid4().hex
mapping = {random_key1: 'dummyValue1',
random_key2: None,
random_key3: '',
random_key4: 'dummyValue4'}
region.set_multi(mapping)
# should return NO_VALUE as key does not exist in cache
self.assertEqual(api.NO_VALUE, region.get(random_key))
self.assertEqual("dummyValue1", region.get(random_key1))
self.assertIsNone(region.get(random_key2))
self.assertEqual("", region.get(random_key3))
self.assertEqual("dummyValue4", region.get(random_key4))
keys = [random_key, random_key1, random_key2, random_key3, random_key4]
results = region.get_multi(keys)
# should return NO_VALUE as key does not exist in cache
self.assertEqual(api.NO_VALUE, results[0])
self.assertEqual("dummyValue1", results[1])
self.assertIsNone(results[2])
self.assertEqual("", results[3])
self.assertEqual("dummyValue4", results[4])
mapping = {random_key1: 'dummyValue5',
random_key2: 'dummyValue6'}
region.set_multi(mapping)
self.assertEqual(api.NO_VALUE, region.get(random_key))
self.assertEqual("dummyValue5", region.get(random_key1))
self.assertEqual("dummyValue6", region.get(random_key2))
self.assertEqual("", region.get(random_key3))
def test_backend_delete_data(self):
region = dp_region.make_region().configure(
'keystone.cache.mongo',
arguments=self.arguments
)
random_key = uuid.uuid4().hex
region.set(random_key, "dummyValue")
self.assertEqual("dummyValue", region.get(random_key))
region.delete(random_key)
# should return NO_VALUE as key no longer exists in cache
self.assertEqual(api.NO_VALUE, region.get(random_key))
def test_backend_multi_delete_data(self):
region = dp_region.make_region().configure(
'keystone.cache.mongo',
arguments=self.arguments
)
random_key = uuid.uuid4().hex
random_key1 = uuid.uuid4().hex
random_key2 = uuid.uuid4().hex
random_key3 = uuid.uuid4().hex
mapping = {random_key1: 'dummyValue1',
random_key2: 'dummyValue2',
random_key3: 'dummyValue3'}
region.set_multi(mapping)
# should return NO_VALUE as key does not exist in cache
self.assertEqual(api.NO_VALUE, region.get(random_key))
self.assertEqual("dummyValue1", region.get(random_key1))
self.assertEqual("dummyValue2", region.get(random_key2))
self.assertEqual("dummyValue3", region.get(random_key3))
self.assertEqual(api.NO_VALUE, region.get("InvalidKey"))
keys = mapping.keys()
region.delete_multi(keys)
self.assertEqual(api.NO_VALUE, region.get("InvalidKey"))
# should return NO_VALUE as keys no longer exist in cache
self.assertEqual(api.NO_VALUE, region.get(random_key1))
self.assertEqual(api.NO_VALUE, region.get(random_key2))
self.assertEqual(api.NO_VALUE, region.get(random_key3))
def test_additional_crud_method_arguments_support(self):
"""Additional arguments should works across find/insert/update."""
self.arguments['wtimeout'] = 30000
self.arguments['j'] = True
self.arguments['continue_on_error'] = True
self.arguments['secondary_acceptable_latency_ms'] = 60
region = dp_region.make_region().configure(
'keystone.cache.mongo',
arguments=self.arguments
)
# There is no proxy so can access MongoCacheBackend directly
api_methargs = region.backend.api.meth_kwargs
self.assertEqual(api_methargs['wtimeout'], 30000)
self.assertEqual(api_methargs['j'], True)
self.assertEqual(api_methargs['continue_on_error'], True)
self.assertEqual(api_methargs['secondary_acceptable_latency_ms'], 60)
random_key = uuid.uuid4().hex
region.set(random_key, "dummyValue1")
self.assertEqual("dummyValue1", region.get(random_key))
region.set(random_key, "dummyValue2")
self.assertEqual("dummyValue2", region.get(random_key))
random_key = uuid.uuid4().hex
region.set(random_key, "dummyValue3")
self.assertEqual("dummyValue3", region.get(random_key))
| UTSA-ICS/keystone-kerberos | keystone/tests/unit/test_cache_backend_mongo.py | Python | apache-2.0 | 27,559 |
/*
* Copyright 2009-2014 University of Hildesheim, Software Systems Engineering
*
* 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.
*/
package net.ssehub.easy.varModel.cstEvaluation;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* Test Suite for running the CST evaluation tests.
* @author Holger Eichelberger
*/
@RunWith(Suite.class)
@SuiteClasses({
ApplyTests.class,
OperationCounter.class,
BooleanOperationsTest.class,
CompoundOperationsTest.class,
ConstraintOperationsTest.class,
EvaluationVisitorTest.class,
EvaluationVisitorIteratorTest.class,
EvaluationVisitorDefOpTest.class,
DynamicDispatchTest.class,
IntegerOperationsTest.class,
RealOperationsTest.class,
ReferenceEqualityTest.class,
ReferenceOperationsTest.class,
SequenceOperationsTest.class,
SetOperationsTest.class,
SequenceOperationsTest.class,
StringOperationsTest.class,
MetaOperationsTest.class,
EnumOperationsTest.class,
ReasonerCaseTests.class,
VersionOperationsTest.class,
CustomOpOnCustomDataTypesTest.class,
SelfTests.class,
VariableValueCopierTest.class,
CopyOperationTest.class
})
public class CstEvaluationTests {
}
| SSEHUB/EASyProducer | Plugins/VarModel/Model.tests/src/net/ssehub/easy/varModel/cstEvaluation/CstEvaluationTests.java | Java | apache-2.0 | 1,779 |
#ifndef _MAKESHIFT_CAMERA_HPP_
#define _MAKESHIFT_CAMERA_HPP_
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
class Camera {
public:
Camera(glm::vec3 pos);
// Camera Positioning
inline void setPosition(glm::vec3 pos) { _pos = pos; }
inline void move(glm::vec3 offset) { _pos += offset; }
inline const glm::vec3 position() const { return _pos; }
void changeLook(float pitch, float yaw);
void reset();
const glm::mat4 rotation() const;
// Projection Setting Modifications
void setFov(float fov);
void setAspectRatio(float ratio);
void setFar(float far);
void setNear(float near);
inline const glm::mat4 projection() const { return _proj; }
glm::vec3 right() const;
glm::vec3 up() const;
glm::vec3 forward() const;
const glm::mat4 matrix() const;
private:
void recalcProjection();
void fixAngles();
glm::vec3 _pos;
float _pitch;
float _yaw;
float _fov;
float _aspRatio;
float _far;
float _near;
glm::mat4 _proj;
};
#endif
| masp/VoxelTest | include/input/camera.hpp | C++ | apache-2.0 | 1,058 |
/*
* Copyright 2015 Dennis Vriend
*
* 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.
*/
package com.github.dnvriend
import com.typesafe.config.ConfigFactory
object HelloWorld extends App {
val config = ConfigFactory.load()
println(config.getString("example.greeting"))
}
| dnvriend/sbt-native-packager-demo | simple-javaapp-with-config/src/main/scala/com/github/dnvriend/HelloWorld.scala | Scala | apache-2.0 | 787 |
packageSearchIndex = [{"l":"All Packages","url":"allpackages-index.html"},{"l":"de.mhus.micro.ext.api.dfs"},{"l":"de.mhus.micro.ext.api.mailqueue"}] | mhus/mhus-inka | de.mhus.osgi.micro/micro-ext-api/target/apidocs/package-search-index.js | JavaScript | apache-2.0 | 148 |
planeonline Cookbook
====================
TODO: Enter the cookbook description here.
e.g.
This cookbook makes your favorite breakfast sandwich.
Requirements
------------
TODO: List your cookbook requirements. Be sure to include any requirements this cookbook has on platforms, libraries, other cookbooks, packages, operating systems, etc.
e.g.
#### packages
- `toaster` - planeonline needs toaster to brown your bagel.
Attributes
----------
TODO: List your cookbook attributes here.
e.g.
#### planeonline::default
<table>
<tr>
<th>Key</th>
<th>Type</th>
<th>Description</th>
<th>Default</th>
</tr>
<tr>
<td><tt>['planeonline']['bacon']</tt></td>
<td>Boolean</td>
<td>whether to include bacon</td>
<td><tt>true</tt></td>
</tr>
</table>
Usage
-----
#### planeonline::default
TODO: Write usage instructions for each cookbook.
e.g.
Just include `planeonline` in your node's `run_list`:
```json
{
"name":"my_node",
"run_list": [
"recipe[planeonline]"
]
}
```
Contributing
------------
TODO: (optional) If this is a public cookbook, detail the process for contributing. If this is a private cookbook, remove this section.
e.g.
1. Fork the repository on Github
2. Create a named feature branch (like `add_component_x`)
3. Write your change
4. Write tests for your change (if applicable)
5. Run the tests, ensuring they all pass
6. Submit a Pull Request using Github
License and Authors
-------------------
Authors: TODO: List authors
| planeonline/vagrant | cookbooks/planeonline/README.md | Markdown | apache-2.0 | 1,488 |
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
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. */
#pragma once
#include <math.h>
#include <iterator>
#include <random>
#include <set>
#include <string>
#include <vector>
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/selected_rows.h"
#include "paddle/fluid/operators/math/sampler.h"
#include "unsupported/Eigen/CXX11/Tensor"
#ifdef PADDLE_WITH_DISTRIBUTE
#include "paddle/fluid/operators/distributed/parameter_prefetch.h"
#endif
namespace paddle {
namespace operators {
using Tensor = framework::Tensor;
using LoDTensor = framework::LoDTensor;
using SelectedRows = framework::SelectedRows;
using Sampler = math::Sampler;
using DDim = framework::DDim;
template <typename T, int MajorType = Eigen::RowMajor,
typename IndexType = Eigen::DenseIndex>
using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>;
template <typename DeviceContext, typename T>
void PrepareSamples(const framework::ExecutionContext &context,
Sampler *sampler) {
auto label = context.Input<Tensor>("Label");
const int64_t *label_data = label->data<int64_t>();
auto label_dims = label->dims();
// for unitest
std::vector<int> custom_neg_classes =
context.Attr<std::vector<int>>("custom_neg_classes");
auto sample_labels = context.Output<Tensor>("SampleLabels");
auto sample_labels_dims = sample_labels->dims();
int64_t *sample_labels_data =
sample_labels->mutable_data<int64_t>(context.GetPlace());
int num_label = label_dims.size() == 2 ? label_dims[1] : 1;
int index = 0;
for (int64_t i = 0; i < label_dims[0]; ++i) {
int j = 0;
for (; j < num_label; ++j) {
sample_labels_data[index++] = label_data[i * num_label + j];
}
if (custom_neg_classes.size() > 0) {
for (auto label : custom_neg_classes) {
sample_labels_data[index++] = label;
}
} else {
for (; j < sample_labels_dims[1]; ++j) {
// TODO(wanghaoshuang): support more distribution sampling
sample_labels_data[index++] = sampler->Sample();
}
}
}
}
template <typename DeviceContext, typename T>
class NCEKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext &context) const override {
int sampler_type = context.Attr<int>("sampler");
int seed = context.Attr<int>("seed");
int num_total_classes = context.Attr<int>("num_total_classes");
int num_neg_samples = context.Attr<int>("num_neg_samples");
Sampler *sampler;
switch (sampler_type) {
case 0: {
sampler = new math::UniformSampler(num_total_classes - 1, seed);
break;
}
case 1: {
sampler = new math::LogUniformSampler(num_total_classes - 1, seed);
break;
}
case 2: {
auto dist_probs = context.Input<Tensor>("CustomDistProbs");
auto dist_alias = context.Input<Tensor>("CustomDistAlias");
auto dist_alias_probs = context.Input<Tensor>("CustomDistAliasProbs");
PADDLE_ENFORCE_EQ(dist_probs->numel(), num_total_classes);
PADDLE_ENFORCE_EQ(dist_alias->numel(), num_total_classes);
PADDLE_ENFORCE_EQ(dist_alias_probs->numel(), num_total_classes);
const float *probs_data = dist_probs->data<float>();
const int *alias_data = dist_alias->data<int>();
const float *alias_probs_data = dist_alias_probs->data<float>();
sampler = new math::CustomSampler(num_total_classes - 1, probs_data,
alias_data, alias_probs_data, seed);
break;
}
default: { PADDLE_THROW("Unsupported SamplerType."); }
}
PrepareSamples<DeviceContext, T>(context, sampler);
auto sample_labels = context.Output<Tensor>("SampleLabels");
const int64_t *sample_labels_data = sample_labels->data<int64_t>();
for (int x = 0; x < sample_labels->numel(); x++) {
PADDLE_ENFORCE_GE(sample_labels_data[x], 0, "nce sample label %d", x);
}
auto sample_out = context.Output<Tensor>("SampleLogits");
T *sample_out_data = sample_out->mutable_data<T>(context.GetPlace());
auto label = context.Input<Tensor>("Label");
auto sample_weight = context.Input<Tensor>("SampleWeight");
const T *sample_weight_data = nullptr;
if (sample_weight != nullptr) {
sample_weight_data = sample_weight->data<T>();
}
auto out = context.Output<Tensor>("Cost");
T *out_data = out->mutable_data<T>(context.GetPlace());
int64_t num_true_class = 1;
if (label != nullptr) {
num_true_class = label->dims()[1];
}
int64_t sampled_labels_num = sample_labels->dims()[1];
// T b = 1. / num_total_classes * num_neg_samples;
// forward bias
auto bias = context.Input<Tensor>("Bias");
if (bias != nullptr) {
const T *bias_data = bias->data<T>();
for (int64_t i = 0; i < sample_labels->numel(); ++i) {
sample_out_data[i] = bias_data[sample_labels_data[i]];
}
} else {
for (int64_t i = 0; i < sample_labels->numel(); ++i) {
sample_out_data[i] = 0;
}
}
// forward mul
auto input_mat = EigenMatrix<T>::From(*(context.Input<Tensor>("Input")));
// for remote prefetch
auto remote_prefetch = context.Attr<bool>("remote_prefetch");
auto epmap = context.Attr<std::vector<std::string>>("epmap");
if (remote_prefetch && !epmap.empty()) {
// if epmap is not empty, then the parameter will be fetched from remote
// parameter
// server
std::vector<int64_t> labels;
for (int64_t i = 0; i < sample_labels->numel(); ++i) {
labels.push_back(sample_labels_data[i]);
}
std::set<T> st(labels.begin(), labels.end());
labels.assign(st.begin(), st.end());
framework::Scope &local_scope = context.scope().NewScope();
auto height_sections =
context.Attr<std::vector<int64_t>>("height_sections");
auto table_names = context.Attr<std::vector<std::string>>("table_names");
auto *ids = local_scope.Var("Ids@Prefetch");
auto *x_tensor = ids->GetMutable<framework::LoDTensor>();
x_tensor->mutable_data<int64_t>(
framework::make_ddim({static_cast<int64_t>(labels.size()), 1}),
context.GetPlace());
// copy.
std::memcpy(x_tensor->data<int64_t>(), labels.data(),
labels.size() * sizeof(int64_t));
std::vector<int> w_dims = paddle::framework::vectorize2int(
context.Input<Tensor>("Weight")->dims());
w_dims[0] = static_cast<int>(labels.size());
auto *w_tensor = local_scope.Var("Weight@Prefetch")
->GetMutable<framework::LoDTensor>();
w_tensor->Resize(framework::make_ddim(w_dims));
#ifdef PADDLE_WITH_DISTRIBUTE
operators::distributed::prefetch("Ids@Prefetch", "Weight@Prefetch",
table_names, epmap, height_sections,
context, local_scope);
#else
PADDLE_THROW(
"paddle is not compiled with distribute support, can not do "
"parameter prefetch!");
#endif
auto weight_mat = EigenMatrix<T>::From(
(local_scope.Var("Weight@Prefetch")->Get<framework::LoDTensor>()));
for (int64_t i = 0; i < sample_labels->numel(); ++i) {
std::vector<int64_t>::iterator it =
std::find(labels.begin(), labels.end(), sample_labels_data[i]);
int idx = std::distance(labels.begin(), it);
Eigen::Tensor<T, 0, Eigen::RowMajor, Eigen::DenseIndex> result =
(input_mat.chip(static_cast<int>(i / sample_labels->dims()[1]), 0) *
weight_mat.chip(idx, 0))
.sum();
sample_out_data[i] += result(0);
sample_out_data[i] = (1. / (1. + exp(-sample_out_data[i])));
}
context.scope().DeleteScope(&local_scope);
} else {
auto weight_mat =
EigenMatrix<T>::From(*(context.Input<Tensor>("Weight")));
for (int64_t i = 0; i < sample_labels->numel(); ++i) {
Eigen::Tensor<T, 0, Eigen::RowMajor, Eigen::DenseIndex> result =
(input_mat.chip(static_cast<int>(i / sample_labels->dims()[1]), 0) *
weight_mat.chip(sample_labels_data[i], 0))
.sum();
sample_out_data[i] += result(0);
sample_out_data[i] = (1. / (1. + exp(-sample_out_data[i])));
}
}
// forward cost
for (int64_t i = 0; i < sample_labels->dims()[0]; ++i) {
out_data[i] = 0;
T w = sample_weight == nullptr ? 1. : sample_weight_data[i];
for (int64_t j = 0; j < sampled_labels_num; ++j) {
int64_t target = sample_labels_data[i * sampled_labels_num + j];
T o = sample_out_data[i * sampled_labels_num + j];
float b = sampler->Probability(target) * num_neg_samples;
T cost = (j < num_true_class) ? -log(o / (o + b)) : -log(b / (o + b));
out_data[i] += w * cost;
}
}
delete sampler;
}
};
template <typename DeviceContext, typename T>
class NCEGradKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext &context) const override {
auto d_out = context.Input<Tensor>(framework::GradVarName("Cost"));
const T *d_out_data = d_out->data<T>();
auto label = context.Input<Tensor>("Label");
auto sample_out = context.Input<Tensor>("SampleLogits");
const T *sample_out_data = sample_out->data<T>();
auto sample_labels = context.Input<Tensor>("SampleLabels");
const int64_t *sample_labels_data = sample_labels->data<int64_t>();
auto sample_weight = context.Input<Tensor>("SampleWeight");
const T *sample_weight_data = nullptr;
if (sample_weight != nullptr) {
sample_weight_data = sample_weight->data<T>();
}
int num_neg_samples = context.Attr<int>("num_neg_samples");
int num_total_classes = context.Attr<int>("num_total_classes");
int num_true_class = 1;
if (label != nullptr) {
num_true_class = label->dims()[1];
}
int sampler_type = context.Attr<int>("sampler");
int seed = context.Attr<int>("seed");
Sampler *sampler;
switch (sampler_type) {
case 0: {
sampler = new math::UniformSampler(num_total_classes - 1, seed);
break;
}
case 1: {
sampler = new math::LogUniformSampler(num_total_classes - 1, seed);
break;
}
case 2: {
auto dist_probs = context.Input<Tensor>("CustomDistProbs");
auto dist_alias = context.Input<Tensor>("CustomDistAlias");
auto dist_alias_probs = context.Input<Tensor>("CustomDistAliasProbs");
PADDLE_ENFORCE_EQ(dist_probs->numel(), num_total_classes);
PADDLE_ENFORCE_EQ(dist_alias->numel(), num_total_classes);
PADDLE_ENFORCE_EQ(dist_alias_probs->numel(), num_total_classes);
const float *probs_data = dist_probs->data<float>();
const int *alias_data = dist_alias->data<int>();
const float *alias_probs_data = dist_alias_probs->data<float>();
sampler = new math::CustomSampler(num_total_classes - 1, probs_data,
alias_data, alias_probs_data, seed);
break;
}
default: { PADDLE_THROW("Unsupported SamplerType."); }
}
// T b = 1. / num_total_classes * num_neg_samples;
Tensor sample_grad; // tmp tensor
T *sample_grad_data =
sample_grad.mutable_data<T>(sample_labels->dims(), context.GetPlace());
// backward cost
for (int64_t i = 0; i < sample_labels->numel(); ++i) {
int64_t label_idx = i % sample_labels->dims()[1];
int64_t sample_idx = i / sample_labels->dims()[1];
float b = sampler->Probability(sample_labels_data[i]) * num_neg_samples;
T o = sample_out_data[i];
T w = sample_weight == nullptr ? 1 : sample_weight_data[sample_idx];
sample_grad_data[i] = label_idx < num_true_class
? w * (b / (o + b)) * (o - 1)
: w * (o * (1 - o) / (o + b));
sample_grad_data[i] *= d_out_data[sample_idx];
}
// get d_bias
auto d_bias = context.Output<Tensor>(framework::GradVarName("Bias"));
if (d_bias != nullptr) {
T *d_bias_data = d_bias->mutable_data<T>(context.GetPlace());
std::fill(d_bias_data, d_bias_data + d_bias->numel(), 0.0);
for (int64_t i = 0; i < sample_labels->numel(); ++i) {
d_bias_data[sample_labels_data[i]] += sample_grad_data[i];
}
}
bool is_sparse = context.Attr<bool>("is_sparse");
if (!is_sparse) {
// get d_w
auto d_w = context.Output<Tensor>(framework::GradVarName("Weight"));
if (d_w != nullptr) {
auto d_w_data = d_w->mutable_data<T>(context.GetPlace());
std::fill(d_w_data, d_w_data + d_w->numel(), 0.0);
auto d_w_matrix = EigenMatrix<T>::From(*d_w);
auto x_matrix = EigenMatrix<T>::From(*(context.Input<Tensor>("Input")));
for (int64_t i = 0; i < sample_labels->numel(); ++i) {
d_w_matrix.chip(sample_labels_data[i], 0) +=
x_matrix.chip(static_cast<int>(i / sample_labels->dims()[1]), 0) *
sample_grad_data[i];
}
}
} else {
std::vector<int64_t> labels;
for (int64_t i = 0; i < sample_labels->numel(); ++i) {
labels.push_back(sample_labels_data[i]);
}
std::set<T> st(labels.begin(), labels.end());
labels.assign(st.begin(), st.end());
auto *table_var = context.InputVar("Weight");
DDim table_dim;
if (table_var->IsType<LoDTensor>()) {
table_dim = context.Input<LoDTensor>("Weight")->dims();
} else if (table_var->IsType<SelectedRows>()) {
auto *table_t = context.Input<SelectedRows>("Weight");
table_dim = table_t->value().dims();
} else {
PADDLE_THROW(
"The parameter Weight of a NCE_OP "
"must be either LoDTensor or SelectedRows");
}
auto d_w = context.Output<SelectedRows>(framework::GradVarName("Weight"));
d_w->set_rows(labels);
d_w->set_height(table_dim[0]);
auto *d_table_value = d_w->mutable_value();
d_table_value->Resize(
{static_cast<int64_t>(labels.size()), table_dim[1]});
auto d_w_data = d_table_value->mutable_data<T>(context.GetPlace());
std::fill(d_w_data, d_w_data + d_table_value->numel(), 0.0);
auto d_w_matrix = EigenMatrix<T>::From(*d_table_value);
auto x_matrix = EigenMatrix<T>::From(*(context.Input<Tensor>("Input")));
for (int64_t i = 0; i < sample_labels->numel(); ++i) {
d_w_matrix.chip(d_w->Index(sample_labels_data[i]), 0) +=
x_matrix.chip(static_cast<int>(i / sample_labels->dims()[1]), 0) *
sample_grad_data[i];
}
}
// get d_x
auto d_x = context.Output<Tensor>(framework::GradVarName("Input"));
if (d_x != nullptr) {
auto *d_x_data = d_x->mutable_data<T>(context.GetPlace());
std::fill(d_x_data, d_x_data + d_x->numel(), 0.0);
auto d_x_matrix = EigenMatrix<T>::From(*d_x);
auto w_matrix = EigenMatrix<T>::From(*(context.Input<Tensor>("Weight")));
for (int64_t i = 0; i < sample_labels->numel(); ++i) {
d_x_matrix.chip(static_cast<int>(i / sample_labels->dims()[1]), 0) +=
w_matrix.chip(sample_labels_data[i], 0) * sample_grad_data[i];
}
}
delete sampler;
}
};
} // namespace operators
} // namespace paddle
| baidu/Paddle | paddle/fluid/operators/nce_op.h | C | apache-2.0 | 16,012 |
/*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
package com.amazonaws.services.datapipeline.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.datapipeline.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* TaskObject JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class TaskObjectJsonUnmarshaller implements Unmarshaller<TaskObject, JsonUnmarshallerContext> {
public TaskObject unmarshall(JsonUnmarshallerContext context) throws Exception {
TaskObject taskObject = new TaskObject();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("taskId", targetDepth)) {
context.nextToken();
taskObject.setTaskId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("pipelineId", targetDepth)) {
context.nextToken();
taskObject.setPipelineId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("attemptId", targetDepth)) {
context.nextToken();
taskObject.setAttemptId(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("objects", targetDepth)) {
context.nextToken();
taskObject.setObjects(new MapUnmarshaller<String, PipelineObject>(context.getUnmarshaller(String.class), PipelineObjectJsonUnmarshaller
.getInstance()).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return taskObject;
}
private static TaskObjectJsonUnmarshaller instance;
public static TaskObjectJsonUnmarshaller getInstance() {
if (instance == null)
instance = new TaskObjectJsonUnmarshaller();
return instance;
}
}
| dagnir/aws-sdk-java | aws-java-sdk-datapipeline/src/main/java/com/amazonaws/services/datapipeline/model/transform/TaskObjectJsonUnmarshaller.java | Java | apache-2.0 | 3,505 |
package net.leifandersen.mobile.android.netcatch.services;
import net.leifandersen.mobile.android.netcatch.providers.ShowsProvider;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
public class UnsubscribeService extends Service {
// Public parameters
/**
* The Show ID to be unsubscribed from
*/
public static final String SHOW_ID = "show_id";
// Public return values
public static final String FINISHED = "finished ";
// Private member variable
private long mId;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onStart(Intent intent, int startId) {
onStartCommand(intent, 0, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Setup the paremeters values
mId = intent.getLongExtra(SHOW_ID, -1);
if(mId < 0)
throw new IllegalArgumentException("Bad or no ID");
// Run the thread
Thread t = new Thread(new Runnable() {
@Override
public void run() {
unsubscribe();
}
});
t.start();
return START_STICKY;
}
private void unsubscribe() {
// Delete the shows episodes
getContentResolver().delete(Uri.parse(ShowsProvider.SHOWS_CONTENT_URI
+ "/" + mId + "/episodes"), null, null);
// Delete the show itself
getContentResolver().delete(Uri.parse(ShowsProvider.SHOWS_CONTENT_URI
+ "/" + mId), null, null);
// Send out the finished broadcast, and finish
Intent broadcast = new Intent(FINISHED + mId);
sendBroadcast(broadcast);
stopSelf();
}
}
| LeifAndersen/NetCatch | src/net/leifandersen/mobile/android/netcatch/services/UnsubscribeService.java | Java | apache-2.0 | 1,577 |
/*
* Copyright 2016 Joakim Sahlström
*
* 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.
*/
package se.jsa.jles.internal.fields;
import java.nio.ByteBuffer;
public class BooleanField extends EventField {
public BooleanField(Class<?> eventType, String propertyName) {
super(eventType, propertyName);
}
@Override
public int getSize(Object event) {
return 1;
}
@Override
public void writeToBuffer(Object event, ByteBuffer buffer) {
buffer.put((byte) (Boolean.class.cast(getValue(event)) ? 1 : 0));
}
@Override
public Object readFromBuffer(ByteBuffer buffer) {
return buffer.get() == 1 ? true : false;
}
}
| joakimsahlstrom/jles | src/main/java/se/jsa/jles/internal/fields/BooleanField.java | Java | apache-2.0 | 1,137 |
package org.support.project.knowledge.filter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.support.project.common.util.StringUtils;
import org.support.project.di.Container;
import org.support.project.knowledge.config.AppConfig;
import org.support.project.knowledge.config.SystemConfig;
import org.support.project.knowledge.config.UserConfig;
import org.support.project.knowledge.logic.AccountLogic;
import org.support.project.knowledge.logic.KnowledgeAuthenticationLogic;
import org.support.project.knowledge.logic.SystemConfigLogic;
import org.support.project.knowledge.vo.UserConfigs;
import org.support.project.web.common.HttpStatus;
import org.support.project.web.common.HttpUtil;
import org.support.project.web.dao.SystemConfigsDao;
import org.support.project.web.entity.SystemConfigsEntity;
import org.support.project.web.filter.AuthenticationFilter;
import org.support.project.web.logic.AuthenticationLogic;
public class CloseAbleAuthenticationFilter extends AuthenticationFilter {
private Pattern pattern = null;
/*
* (non-Javadoc)
*
* @see org.support.project.web.filter.AuthenticationFilter#init(javax.servlet.FilterConfig)
*/
@Override
public void init(FilterConfig filterconfig) throws ServletException {
SystemConfigsDao dao = SystemConfigsDao.get();
SystemConfigsEntity config = dao.selectOnKey(SystemConfig.SYSTEM_EXPOSE_TYPE, AppConfig.get().getSystemName());
if (config != null) {
if (SystemConfig.SYSTEM_EXPOSE_TYPE_CLOSE.equals(config.getConfigValue())) {
SystemConfigLogic.get().setClose(true);
}
}
String ignoreRegularExpression = filterconfig.getInitParameter("close-ignore-regular-expression");
if (StringUtils.isNotEmpty(ignoreRegularExpression)) {
this.pattern = Pattern.compile(ignoreRegularExpression);
}
super.init(filterconfig);
}
/*
* (non-Javadoc)
*
* @see org.support.project.web.filter.AuthenticationFilter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
* javax.servlet.FilterChain)
*/
@Override
public void doFilter(ServletRequest servletrequest, ServletResponse servletresponse, FilterChain filterchain)
throws IOException, ServletException {
if (SystemConfigLogic.get().isClose()) {
HttpServletRequest req = (HttpServletRequest) servletrequest;
HttpServletResponse res = (HttpServletResponse) servletresponse;
// ブラウザから必ず送られてくるCookie値でユーザ設定情報を作成
UserConfigs userConfig = new UserConfigs();
String timezone = HttpUtil.getCookie(req, AccountLogic.get().getCookieKeyTimezone());
if (StringUtils.isNotEmpty(timezone)) {
userConfig.setTimezone(timezone);
}
String offset = HttpUtil.getCookie(req, AccountLogic.get().getCookieKeyTimezoneOffset());
if (StringUtils.isInteger(offset)) {
userConfig.setTimezoneOffset(Integer.parseInt(offset));
}
req.setAttribute(UserConfig.REQUEST_USER_CONFIG_KEY, userConfig);
try {
if (!isLogin(req)) {
AuthenticationLogic logic = Container.getComp(KnowledgeAuthenticationLogic.class);
logic.cookieLogin(req, res);
}
if (!isLogin(req)) {
// ログインしていない
if (pattern != null) {
StringBuilder pathBuilder = new StringBuilder();
pathBuilder.append(req.getServletPath());
if (req.getPathInfo() != null && req.getPathInfo().length() > 0) {
pathBuilder.append(req.getPathInfo());
}
String path = pathBuilder.toString();
Matcher matcher = pattern.matcher(path);
if (!matcher.find() && !path.equals(getLoginProcess())) {
// 対象外でないし、ログインページへの遷移でない
String page = req.getParameter("page");
req.setAttribute("page", page);
res.setStatus(HttpStatus.SC_401_UNAUTHORIZED);
StringBuilder builder = new StringBuilder();
builder.append(getLoginPage());
HttpUtil.forward(res, req, builder.toString());
return;
}
}
}
} catch (Exception e) {
throw new ServletException(e);
}
}
super.doFilter(servletrequest, servletresponse, filterchain);
}
}
| support-project/knowledge | src/main/java/org/support/project/knowledge/filter/CloseAbleAuthenticationFilter.java | Java | apache-2.0 | 5,248 |
<section id="main-content">
<section class="wrapper">
<div class="col-lg-12">
<section class="panel">
<div class="panel-body">
<form autocomplete="on" id="tkf_setting_account" action="?route=setting_account"
method="POST" role="form">
<section class="panel">
<header class="panel-heading tab-bg-dark-navy-blue ">
<ul class="nav nav-tabs">
<li class="active">
<a data-toggle="tab" href="#home"><i class="icon-user"></i> اطلاعات حساب</a>
</li>
<li class="">
<a data-toggle="tab" href="#notfication"><i class="icon-bullhorn"></i> اعلان ها</a>
</li>
<li class="">
<a data-toggle="tab" href="#private"><i class="icon-umbrella"></i> حریم خصوصی</a>
</li>
<li class="">
<a data-toggle="tab" href="#support"><i class="icon-question-sign"></i> پشتیبانی</a>
</li>
</ul>
</header>
<div class="panel-body">
<div class="tab-content">
<div id="home" class="tab-pane active">
<div class="row">
<div class="col-lg-6">
<div class="form-inline">
<div class="form-group">
<label>نام خانوادگی </label>
<input class="form-control" name="tkf$(f$name_inputs)" value="<?php echo $users['2'];?>" type="text">
</div>
<div class="col-lg-6 form-group">
<label>نام</label>
<input class="form-control" name="tkf$(l$name_inputs)" value="<?php echo $users['1'];?>" type="text">
</div>
</div>
<div class="col-lg-12">
<div class="form-group">
<label>رایانامه (E-mail)</label>
<input class=" form-control" name="tkf$(E$mail_inputs)" value="<?php echo $users['8'];?>" placeholder="رایانامه خود را وارد نمایید" type="email">
</div>
<div class="form-group">
<label>شماره همراه : (Cell-phone)</label>
<input class=" form-control" name="tkf$(tell$phone_inputs)" value="<?php echo $users['9'];?>" placeholder="رایانامه خود را وارد نمایید" type="email">
</div>
<div class="form-group">
<label>توضیحات :</label>
<textarea name="tkf$(decription$input)" placeholder="حد اکثر : 1000 کاراکتر" class="form-control" cols="60" rows="5"><?php echo $users['10'];?></textarea>
</div>
</div><!-- /.col -->
</div><!-- /.col -->
<div class="col-lg-3">
<div class="form-group">
<label>نام کاربری </label>
<input class=" form-control" name="tkf$(user$name_inputs)" value="<?php echo $users['11'];?>" type="text">
</div>
<div class="form-group">
<label>رمز عبور فعلی </label>
<input value="" name="tkf$(pass$word_inputs)" class="form-control" placeholder="رمز عبوری که با آن وارد شدید" type="password">
</div>
<div class="form-group">
<label>رمز عبور جدید </label>
<input class=" form-control" name="tkf$(new$pass$word_inputs)" placeholder="رمز عبور قدرتمند استفاده نمایید" type="password">
</div>
<div class="form-group">
<label>تایپ مجدد رمز عبور </label>
<input class=" form-control" name="tkf$(re$pass$word_inputs)" placeholder="رمز عبور قدرتمند استفاده نمایید" type="password">
</div>
<div style="text-align: justify;" class="alert alert-info fade in">
<strong>توجه!</strong></br>
اگر شما نیاز به تغییر کلمه عبور دارید فیلد های بالا را تکمیل نمایید در غیر اینصورت نیازی به تکمیل نمودن فیلد های بالا نمیباشد.
</div>
</div><!-- /.col -->
<div class="col-lg-3">
<table class="table">
<tbody>
<tr>
<th>وضعیت حساب کاربری :</th>
<td><?php echo check_state($users['5']);?></td>
</tr>
<tr>
<th>آخرین ورود :</th>
<td><?php echo ago($users['13']);?></td>
</tr>
<tr>
<th>آخرین خروج :</th>
<td><?php echo ago($users['14']);?></td>
</tr>
<tr>
<th>ای پی لاگ:</th>
<td><?php echo $users['17'];?></td>
</tr>
<tr>
<th style="display: inherit;">تصویر حساب کاربری :</th>
<td class="profile_image" > <?php
if(get_file_upload('settings_other',$users['4'],$con) =="0"){
echo '<img src="/auth/user/theme/img/no-image.png" />';
}else{
$img = get_file_upload('settings_other',$users['4'],$con);
$url = hashimage($img['8']);
echo '<img src="'.$url.'" />';
}
?></td>
</tr>
</tbody>
</table>
<div class="form-group">
<label for="exampleInputFile">ویرایش تصویر کاربری</label>
<input name="file" id="exampleInputFile" type="file">
<p class="help-block">حد اکثر حجم مجاز : 90KB </br> پسوند های مجاز : .jpg,.png,.jpeg</p>
</div>
</div> <!-- /.col -->
</div> <!-- /.row -->
</div> <!-- /#home -->
<div id="notfication" class="tab-pane">
<table class="table">
<thead>
<th>اطلاع از </th>
<th>نحوه اطلاع رسانی </th>
<th style="text-align: left;">وضعیت </th>
</thead>
<tbody>
<tr>
<th> ایجاد فاکتور جدید</th>
<td>
<a class="btn btn-xs btn-success">پیامک</a>
</td>
<td>
<input name="tkf(%f$1)" class="magic-checkbox" <?php if($nt['2']=="1"){echo "checked";}?> name="radio" id="1" value="1" type="checkbox">
<label for="1"></label>
</td>
</tr>
<tr>
<th> تمدید سرویس</th>
<td>
<a class="btn btn-xs btn-success">پیامک </a>
</td>
<td>
<input name="tkf(%f$2)" class="magic-checkbox" <?php if($nt['3']=="1"){echo "checked";}?> name="radio" id="2" value="1" type="checkbox">
<label for="2"></label>
</td>
</tr>
<tr>
<th>فاکتور ماهانه</th>
<td>
<a class="btn btn-xs btn-warning">ایمیل</a>
</td>
<td>
<input name="tkf(%f$3)" class="magic-checkbox" <?php if($nt['4']=="1"){echo "checked";}?> name="radio" id="3" value="1" type="checkbox">
<label for="3"></label>
</td>
</tr>
<tr>
<th>پاسخ به تیکت</th>
<td>
<a class="btn btn-xs btn-warning">ایمیل</a>
</td>
<td>
<input name="tkf(%f$4)" class="magic-checkbox" <?php if($nt['5']=="1"){echo "checked";}?> name="radio" id="4" value="1" type="checkbox">
<label for="4"></label>
</td>
</tr>
<tr>
<th>بسته شده تیکت</th>
<td>
<a class="btn btn-xs btn-warning">ایمیل</a>
</td>
<td>
<input name="tkf(%f$5)" class="magic-checkbox" <?php if($nt['6']=="1"){echo "checked";}?> name="radio" id="5" value="1" type="checkbox">
<label for="5"></label>
</td>
</tr>
<tr>
<th>فعال شدن سرویس</th>
<td>
<a class="btn btn-xs btn-success">پیامک</a>
</td>
<td>
<input name="tkf(%f$6)" class="magic-checkbox" <?php if($nt['7']=="1"){echo "checked";}?> name="radio" id="6" value="1" type="checkbox">
<label for="6"></label>
</td>
</tr>
<tr>
<th>حذف شدن سرویس</th>
<td>
<a class="btn btn-xs btn-warning">ایمیل</a>
</td>
<td>
<input name="tkf(%f$7)" class="magic-checkbox" <?php if($nt['8']=="1"){echo "checked";}?> name="radio" id="7" value="1" type="checkbox">
<label for="7"></label>
</td>
</tr>
<tr>
<th>لغو شدن سرویس</th>
<td>
<a class="btn btn-xs btn-warning">ایمیل</a>
</td>
<td>
<input name="tkf(%f$8)" class="magic-checkbox" <?php if($nt['9']=="1"){echo "checked";}?> name="radio" id="8" value="1" type="checkbox">
<label for="8"></label>
</td>
</tr>
<tr>
<th>دریافت پیام خصوصی جدید</th>
<td>
<a class="btn btn-xs btn-warning">ایمیل</a>
</td>
<td>
<input name="tkf(%f$9)" class="magic-checkbox" <?php if($nt['10']=="1"){echo "checked";}?> name="radio" id="9" value="1" type="checkbox">
<label for="9"></label>
</td>
</tr>
<tr>
<th>ایجاد اطلاعیه جدید</th>
<td>
<a class="btn btn-xs btn-warning">ایمیل</a>
</td>
<td>
<input name="tkf(%f$10)" class="magic-checkbox" <?php if($nt['11']=="1"){echo "checked";}?> name="radio" id="10" value="1" type="checkbox">
<label for="10"></label>
</td>
</tr>
<tr>
<th>ورود به حساب</th>
<td>
<a class="btn btn-xs btn-warning">ایمیل</a>
</td>
<td>
<input name="tkf(%f$11)" class="magic-checkbox" <?php if($nt['12']=="1"){echo "checked";}?> name="radio" id="11" value="1" type="checkbox">
<label for="11"></label>
</td>
</tr>
<tr>
<th>تغییر کلمه عبور</th>
<td>
<a class="btn btn-xs btn-success">پیامک</a>
</td>
<td>
<input name="tkf(%f$12)" class="magic-checkbox" <?php if($nt['13']=="1"){echo "checked";}?> name="radio" id="12" value="1" type="checkbox">
<label for="12"></label>
</td>
</tr>
</tbody>
</table>
</div><!-- /#notfication -->
<div id="private" class="tab-pane">
<div class="panel-group m-bot20" id="accordion">
<div class="panel panel-default">
<div style="background-color: rgb(73, 213, 169);" class="panel-heading">
<h4 class="panel-title">
<a style="font-family: yekan;" class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">مفهوم حریم خصوصی
</a>
</h4>
</div>
<div style="height: 0px;" id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
حریم شخصی یا حریم خصوصی یعنی یک فرد یا گروه بتواند خود و یا اطلاعات مربوط به خود را مجزا کند و در نتیجه بتواند خود و یا اطلاعاتش را با انتخاب خویش در برابر دیگران آشکار کند. مرزها و محتوای آنچه خصوصی قلداد میشود در میان فرهنگها و اشخاص متفاوت است، اما تم اصلی آنها مشترک است. </br>
</div>
</div>
</div>
<div class="panel panel-default">
<div style="background-color: rgb(73, 213, 169);" class="panel-heading">
<h4 class="panel-title">
<a style="font-family: yekan;" class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">حریم خصوصی اطلاعاتی
</a>
</h4>
</div>
<div id="collapseTwo" class="panel-collapse collapse">
<div class="panel-body">
حریم خصوصی اطلاعاتی یا دادهای (یا حفاظت دادهها)، رابطهای است بین جمعآوری و توزیع دادهها، تکنولوژی، انتظار عمومی از حریم خصوصی و مسائل قانونی و سیاسی در ارتباط با آنها است. نگرانیها در مورد حریم خصوصی، در هنگام جمعآوری و نگهداری به صورت دیجیتال یا غیر دیجیتال دادهها و اطلاعاتی که فردی را به صورت خاص بازشناساند، خود را نشان میدهد. ریشه و اساس مشکل حریم خصوصی مربوط به افشاگری نامناسب و بدون کنترل دادههای شخصی است. مشکلات حریم خصوصی اطلاعاتی در حقیقت مربوط به منابع مختلف و متنوع دادهها و اطلاعات میباشد.
</div>
</div>
</div>
<div class="panel panel-default">
<div style="background-color: rgb(73, 213, 169);" class="panel-heading">
<h4 class="panel-title">
<a style="font-family: yekan;" class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseThree">
حریم خصوصی من در شرکت طراحی نوین شمال
</a>
</h4>
</div>
<div id="collapseThree" class="panel-collapse collapse">
<div class="panel-body">
Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
</div>
</div>
</div>
</div>
</div><!-- /#private -->
<div id="support" class="tab-pane">
<div class="alert alert-info fade in">
<button data-dismiss="alert" class="close close-sm" type="button">
<i class="icon-remove"></i>
</button>
<strong>پشتیبانی 24 ساعته از طریق تیکت</strong></br>
پشتیبانی شرکت طراحی نوین شمال بصورت 24 ساعته در تمامی ایام هفته میباشد بصورت تیکت چه در ایام تعطیل
</div>
<div class="alert alert-success fade in">
<button data-dismiss="alert" class="close close-sm" type="button">
<i class="icon-remove"></i>
</button>
<strong>پشتیبانی آنلاین</strong> </br>
پشتیبانی آنلاین تنها در روز های کاری صورت میگیرد بصورت 24 ساعته که شما میتوانید با انتخاب بخش مورد نظر با کارشناسان آن بخش گفتگو نمایید و به حل مشکلات خود بپردازید
</div>
<div class="alert alert-warning fade in">
<button data-dismiss="alert" class="close close-sm" type="button">
<i class="icon-remove"></i>
</button>
<strong>پشتیبانی فوری (تلفنی)</strong> </br>
شما میتوانید در تمامی ایام هفته چه در روز های تعطیل و غیر کاری با شماره تماس ذیل جهت مشاوره و یا پشتیبانی تماس حاصل فرمایید تا در کمترین زمان ممکن مششکل شما رفع گردد توجه داشته باشید <strong> تنها برای موارد فوری با واحد پشتیبانی تماس حاصل فرمایید</strong>
همچنین شما میتوانید در روز های کاری با شماه ذیل جهت رفع مشکلات و یا مشاوره تماس حاصل فرمایید .
</div>
<div class="alert alert-block alert-danger fade in">
<button data-dismiss="alert" class="close close-sm" type="button">
<i class="icon-remove"></i>
</button>
<strong>واحد پشتیبانی حضوری </strong> </br>
در صورتی که نیازمند عقد قرار داد بصورت حضوری میباشید و یا نیاز به پشتیبانی داشته اید که بصورت آنلاین رفع نگردیده است میتوانید در روز های کاری به آدرس زیر مراجعه فرمایید . </br>
مازندران -
</div>
</div><!-- /#support -->
</div>
</div>
</section>
<button onClick="save_data('tkf_setting_account');return false;" type="button" class="btn btn-info">ذخیره اطلاعات</button>
</form>
</div>
</section>
</div>
</section>
<style>
.profile_image > img{
width: 128px;
height: 128px;
border-radius: 50%;
padding: 5px;
border: 1px solid rgb(221, 221, 221);
}
.profile_image > img:hover{
padding: 0px;
border: 1px solid rgb(54, 230, 0);
}
</style>
</section> | ami-karimi/monix | tk-panel/theme/setting_account.php | PHP | apache-2.0 | 25,169 |
# MarioMakerMinecraft
The tools to build Mario levels in Minecraft
Work in progress and may never be completed as I have lost interest in Minecraft recently.
| aopell/MarioMakerMinecraft | README.md | Markdown | apache-2.0 | 158 |
# Hirtella mutisii Killip & Cuatrec. SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Chrysobalanaceae/Hirtella/Hirtella mutisii/README.md | Markdown | apache-2.0 | 192 |
/*
* Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
*
* 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.
*/
/**
* Preferences controller for our user profile. Allows explicit editing of
* individual preferences.
*/
angular.module('sb.profile').controller('ProfilePreferencesController',
function ($scope, Preference, Notification, Severity) {
'use strict';
$scope.preferences = Preference.getAll();
/**
* Save all the preferences.
*/
$scope.save = function () {
$scope.saving = true;
Preference.saveAll($scope.preferences).then(
function () {
Notification.send(
'preferences',
'Preferences Saved!',
Severity.SUCCESS
);
$scope.saving = false;
},
function () {
$scope.saving = false;
}
);
};
});
| ColdrickSotK/storyboard-webclient | src/app/profile/controller/profile_preferences_controller.js | JavaScript | apache-2.0 | 1,544 |
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. 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.
from __future__ import absolute_import
import sys
import errno
import itertools
import logging
import os
import posixpath
from boto.exception import S3ResponseError
from boto.s3.key import Key
from boto.s3.prefix import Prefix
from django.utils.translation import ugettext as _
from aws import s3
from aws.s3 import normpath, s3file, translate_s3_error, S3_ROOT
from aws.s3.s3stat import S3Stat
DEFAULT_READ_SIZE = 1024 * 1024 # 1MB
LOG = logging.getLogger(__name__)
class S3FileSystem(object):
def __init__(self, s3_connection):
self._s3_connection = s3_connection
self._bucket_cache = None
def _init_bucket_cache(self):
if self._bucket_cache is None:
buckets = self._s3_connection.get_all_buckets()
self._bucket_cache = {}
for bucket in buckets:
self._bucket_cache[bucket.name] = bucket
def _get_bucket(self, name):
self._init_bucket_cache()
if name not in self._bucket_cache:
self._bucket_cache[name] = self._s3_connection.get_bucket(name)
return self._bucket_cache[name]
def _get_or_create_bucket(self, name):
try:
bucket = self._get_bucket(name)
except S3ResponseError, e:
if e.status == 404:
bucket = self._s3_connection.create_bucket(name)
self._bucket_cache[name] = bucket
else:
raise e
return bucket
def _get_key(self, path, validate=True):
bucket_name, key_name = s3.parse_uri(path)[:2]
bucket = self._get_bucket(bucket_name)
try:
return bucket.get_key(key_name, validate=validate)
except:
e, exc, tb = sys.exc_info()
raise ValueError(e)
def _stats(self, path):
if s3.is_root(path):
return S3Stat.for_s3_root()
try:
key = self._get_key(path, validate=True)
except S3ResponseError as e:
if e.status == 404:
return None
else:
exc_class, exc, tb = sys.exc_info()
raise exc_class, exc, tb
if key is None:
key = self._get_key(path, validate=False)
return self._stats_key(key)
@staticmethod
def _stats_key(key):
if key.size is not None:
is_directory_name = not key.name or key.name[-1] == '/'
return S3Stat.from_key(key, is_dir=is_directory_name)
else:
key.name = S3FileSystem._append_separator(key.name)
ls = key.bucket.get_all_keys(prefix=key.name, max_keys=1)
if len(ls) > 0:
return S3Stat.from_key(key, is_dir=True)
return None
@staticmethod
def _append_separator(path):
if path and not path.endswith('/'):
path += '/'
return path
@staticmethod
def _cut_separator(path):
return path.endswith('/') and path[:-1] or path
@staticmethod
def isroot(path):
return s3.is_root(path)
@staticmethod
def join(*comp_list):
return s3.join(*comp_list)
@staticmethod
def normpath(path):
return normpath(path)
@staticmethod
def parent_path(path):
parent_dir = S3FileSystem._append_separator(path)
if not s3.is_root(parent_dir):
bucket_name, key_name, basename = s3.parse_uri(path)
if not basename: # bucket is top-level so return root
parent_dir = S3_ROOT
else:
bucket_path = '%s%s' % (S3_ROOT, bucket_name)
key_path = '/'.join(key_name.split('/')[:-1])
parent_dir = s3.abspath(bucket_path, key_path)
return parent_dir
@translate_s3_error
def open(self, path, mode='r'):
key = self._get_key(path, validate=True)
if key is None:
raise IOError(errno.ENOENT, "No such file or directory: '%s'" % path)
return s3file.open(key, mode=mode)
@translate_s3_error
def read(self, path, offset, length):
fh = self.open(path, 'r')
fh.seek(offset, os.SEEK_SET)
return fh.read(length)
@translate_s3_error
def isfile(self, path):
stat = self._stats(path)
if stat is None:
return False
return not stat.isDir
@translate_s3_error
def isdir(self, path):
stat = self._stats(path)
if stat is None:
return False
return stat.isDir
@translate_s3_error
def exists(self, path):
return self._stats(path) is not None
@translate_s3_error
def stats(self, path):
path = normpath(path)
stats = self._stats(path)
if stats:
return stats
raise IOError(errno.ENOENT, "No such file or directory: '%s'" % path)
@translate_s3_error
def listdir_stats(self, path, glob=None):
if glob is not None:
raise NotImplementedError(_("Option `glob` is not implemented"))
if s3.is_root(path):
self._init_bucket_cache()
return [S3Stat.from_bucket(b) for b in self._bucket_cache.values()]
bucket_name, prefix = s3.parse_uri(path)[:2]
bucket = self._get_bucket(bucket_name)
prefix = self._append_separator(prefix)
res = []
for item in bucket.list(prefix=prefix, delimiter='/'):
if isinstance(item, Prefix):
res.append(S3Stat.from_key(Key(item.bucket, item.name), is_dir=True))
else:
if item.name == prefix:
continue
res.append(self._stats_key(item))
return res
def listdir(self, path, glob=None):
return [s3.parse_uri(x.path)[2] for x in self.listdir_stats(path, glob)]
@translate_s3_error
def rmtree(self, path, skipTrash=False):
if not skipTrash:
raise NotImplementedError(_('Moving to trash is not implemented for S3'))
bucket_name, key_name = s3.parse_uri(path)[:2]
if bucket_name and not key_name:
raise NotImplementedError(_('Deleting a bucket is not implemented for S3'))
key = self._get_key(path, validate=False)
if key.exists():
to_delete = iter([key])
else:
to_delete = iter([])
if self.isdir(path):
# add `/` to prevent removing of `s3://b/a_new` trying to remove `s3://b/a`
prefix = self._append_separator(key.name)
keys = key.bucket.list(prefix=prefix)
to_delete = itertools.chain(keys, to_delete)
result = key.bucket.delete_keys(to_delete)
if result.errors:
msg = "%d errors occurred during deleting '%s':\n%s" % (
len(result.errors),
'\n'.join(map(repr, result.errors)))
LOG.error(msg)
raise IOError(msg)
@translate_s3_error
def remove(self, path, skip_trash=False):
if not skip_trash:
raise NotImplementedError(_('Moving to trash is not implemented for S3'))
key = self._get_key(path, validate=False)
key.bucket.delete_key(key.name)
def restore(self, *args, **kwargs):
raise NotImplementedError(_('Moving to trash is not implemented for S3'))
@translate_s3_error
def mkdir(self, path, *args, **kwargs):
"""
Creates a directory and any parent directory if necessary.
Actually it creates an empty object: s3://[bucket]/[path]/
"""
bucket_name, key_name = s3.parse_uri(path)[:2]
self._get_or_create_bucket(bucket_name)
stats = self._stats(path)
if stats:
if stats.isDir:
return None
else:
raise IOError(errno.ENOTDIR, "'%s' already exists and is not a directory" % path)
path = self._append_separator(path) # folder-key should ends by /
self.create(path) # create empty object
@translate_s3_error
def copy(self, src, dst, recursive=False, *args, **kwargs):
self._copy(src, dst, recursive=recursive, use_src_basename=True)
@translate_s3_error
def copyfile(self, src, dst, *args, **kwargs):
if self.isdir(dst):
raise IOError(errno.EINVAL, "Copy dst '%s' is a directory" % dst)
self._copy(src, dst, recursive=False, use_src_basename=False)
@translate_s3_error
def copy_remote_dir(self, src, dst, *args, **kwargs):
self._copy(src, dst, recursive=True, use_src_basename=False)
def _copy(self, src, dst, recursive, use_src_basename):
src_st = self.stats(src)
if src_st.isDir and not recursive:
return # omitting directory
dst = s3.abspath(src, dst)
dst_st = self._stats(dst)
if src_st.isDir and dst_st and not dst_st.isDir:
raise IOError(errno.EEXIST, "Cannot overwrite non-directory '%s' with directory '%s'" % (dst, src))
src_bucket, src_key = s3.parse_uri(src)[:2]
dst_bucket, dst_key = s3.parse_uri(dst)[:2]
keep_src_basename = use_src_basename and dst_st and dst_st.isDir
src_bucket = self._get_bucket(src_bucket)
dst_bucket = self._get_bucket(dst_bucket)
if keep_src_basename:
cut = len(posixpath.dirname(src_key)) # cut of an parent directory name
if cut:
cut += 1
else:
cut = len(src_key)
if not src_key.endswith('/'):
cut += 1
for key in src_bucket.list(prefix=src_key):
if not key.name.startswith(src_key):
raise RuntimeError(_("Invalid key to transform: %s") % key.name)
dst_name = posixpath.normpath(s3.join(dst_key, key.name[cut:]))
key.copy(dst_bucket, dst_name)
@translate_s3_error
def rename(self, old, new):
new = s3.abspath(old, new)
self.copy(old, new, recursive=True)
self.rmtree(old, skipTrash=True)
@translate_s3_error
def rename_star(self, old_dir, new_dir):
if not self.isdir(old_dir):
raise IOError(errno.ENOTDIR, "'%s' is not a directory" % old_dir)
if self.isfile(new_dir):
raise IOError(errno.ENOTDIR, "'%s' is not a directory" % new_dir)
ls = self.listdir(old_dir)
for entry in ls:
self.rename(s3.join(old_dir, entry), s3.join(new_dir, entry))
@translate_s3_error
def create(self, path, overwrite=False, data=None):
key = self._get_key(path, validate=False)
key.set_contents_from_string(data or '', replace=overwrite)
@translate_s3_error
def copyFromLocal(self, local_src, remote_dst, *args, **kwargs):
local_src = self._cut_separator(local_src)
remote_dst = self._cut_separator(remote_dst)
def _copy_file(src, dst):
key = self._get_key(dst, validate=False)
fp = open(src, 'r')
key.set_contents_from_file(fp)
if os.path.isdir(local_src):
for (local_dir, sub_dirs, files) in os.walk(local_src, followlinks=False):
remote_dir = local_dir.replace(local_src, remote_dst)
if not sub_dirs and not files:
self.mkdir(remote_dir)
else:
for file_name in files:
_copy_file(os.path.join(local_dir, file_name), os.path.join(remote_dir, file_name))
else:
file_name = os.path.split(local_src)[1]
if self.isdir(remote_dst):
remote_file = os.path.join(remote_dst, file_name)
else:
remote_file = remote_dst
_copy_file(local_src, remote_file)
def setuser(self, user):
pass # user-concept doesn't have sense for this implementation
| jjmleiro/hue | desktop/libs/aws/src/aws/s3/s3fs.py | Python | apache-2.0 | 11,345 |
---
layout: post
title: "5 枚 Android 风格的 Chrome 主题"
date: 2011-07-07 18:54
author: admin
comments: true
tags: [Android, Chrome, Chrome皮肤]
---
喜欢Chrome的Android控实在是太多了。
今天推荐5枚 Android 风格的 Chrome 主题,其中第一个和最后一个我特喜欢。
<p style="text-align: center;"><a href="http://img.chromi.org/2011/07/android1.png"></a>主题1:<a href="https://chrome.google.com/webstore/detail/ffflgfldmhgejdbmcfnamncheeifkfmj" target="_blank">下载</a>
<p style="text-align: center;"><a href="http://img.chromi.org/2011/07/android2.png"></a>主题2:<a href="https://chrome.google.com/webstore/detail/emilidmimglckfploinflkilklhioffg" target="_blank">下载<!--more--></a>
<p style="text-align: center;"><a href="http://img.chromi.org/2011/07/android3.png"></a>主题3:<a href="https://chrome.google.com/webstore/detail/oeljdmeofcikjblcoehpmdnooimalbmj" target="_blank">下载</a>
<a href="http://img.chromi.org/2011/07/android4.png"></a>
<p style="text-align: center;">主题4:<a href="https://chrome.google.com/webstore/detail/hlnodmabmmljgeoccmfmghghnmnlicog" target="_blank">下载</a>
<p style="text-align: center;"><a href="http://img.chromi.org/2011/07/android5.png"></a>主题5:<a href="https://chrome.google.com/webstore/detail/ihhhgnjnpmjaikooiahhhlemccommcml" target="_blank">下载</a>
<p style="text-align: left;">via <a href="http://chromestory.com/2011/07/5-android-inspired-google-chrome-themes/" target="_blank">chromestory</a>
| chromi-org/chromi-org.github.io | _posts/2011-07-07-13376a42-9124-4816-8e6c-795274dcc965.md | Markdown | apache-2.0 | 1,833 |
# Copyright 2017 SAS Project Authors. All Rights Reserved.
#
# 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.
# This module implements the combination of the eHata and ITM models
# according to the requirements developed in the Winnforum WG1 Propagation
# task group.
import math
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from ehata import ehata
from itm import pytm
from geo import tropoClim
from geo import refractivity
from geo import ned_indexer
from geo import nlcd_indexer
from geo import land_use
from geo import vincenty
# f in MHz; d and h1/h2 all in meters
def FreeSpacePathLoss(f, d, h1, h2):
r = math.sqrt(d*d + (h1-h2)*(h1-h2))
return 20*math.log10(r) + 20*math.log10(f) - 27.56
class PropagationLossModel:
def __init__(self, itu_dir, ned_dir, nlcd_dir):
self.climIndx = tropoClim.ClimateIndexer(itu_dir)
self.refractivityIndx = refractivity.RefractivityIndexer(itu_dir)
self.nedIndx = ned_indexer.NedIndexer(ned_dir)
self.nlcdIndx = nlcd_indexer.NlcdIndexer(nlcd_dir)
# Calculate the ITM adjusted propagation loss given the
# assumptions on the ITM model.
def ITM_AdjustedPropagationLoss(self, lat1, lng1, h1, lat2, lng2, h2, f, reliability):
dielectric_constant = 25.0 # good ground
soil_conductivity = 0.02 # good ground
polarization = 1
confidence = 0.5
# get surface refractivity and radio climate from path midpoint
dist, bearing, rev_bearing = vincenty.dist_bear_vincenty(lat1, lng1, lat2, lng2)
lat_c, lng_c, alpha2 = vincenty.to_dist_bear_vincenty(lat1, lng1, dist/2.0, bearing)
print 'Midpoint = %f, %f' % (lat_c, lng_c)
radio_climate = self.climIndx.TropoClim(lat_c, lng_c)
refractivity = self.refractivityIndx.Refractivity(lat_c, lng_c)
print 'Using climate %d' % radio_climate
print 'Using refractivity %f' % refractivity
print 'Using freq %f' % f
profile = self.nedIndx.Profile(lat1, lng1, lat2, lng2)
print profile[0], profile[1]
#print profile
print 'total distance is ', profile[0]*profile[1]
loss = pytm.point_to_point(profile, h1, h2,
dielectric_constant,
soil_conductivity,
refractivity,
f,
radio_climate,
polarization,
confidence,
reliability)
print 'ITM P2P is ', loss
return loss
# Adjusted propagation loss according to the adjustments in R2-SGN-04
# distance d, heights h1, h2 all in meters
# frequency f in MHz
def ExtendedHata_AdjustedPropagationLoss(self, lat1, lng1, h1, lat2, lng2, h2, f, land_cat):
d, bearing, rev_bearing = vincenty.dist_bear_vincenty(lat1, lng1, lat2, lng2)
d = d*1000.0
print 'EHata distance=', d
if d <= 100.0:
# return FSPL
print 'FSPL'
return FreeSpacePathLoss(f, d, h1, h2)
if d > 100.0 and d <= 1000.0:
print 'interp FSPL and ehata'
# interpolate FSPL and ehata
fspl_loss = FreeSpacePathLoss(f, 100.0, h1, h2)
print ' fspl_loss=', fspl_loss
ehata_loss, abm = ehata.ExtendedHata_MedianBasicPropLoss(f, 1.0, h1, h2, land_cat)
print ' ehata_loss=', ehata_loss
print ' ( abm=', abm
return fspl_loss + (1.0 + math.log10(d/1000.0))*(ehata_loss - fspl_loss)
if d > 1000.0 and d < 80000.0:
# return eHata value without adjustment.
print 'EHata only for d=%f' % d
profile = self.nedIndx.Profile(lat1, lng1, lat2, lng2)
return ehata.ExtendedHata_PropagationLoss(f, h1, h2, land_cat, profile)
if d >= 80000.0:
print 'EHata for distance %f > 80km' % d
# Derive profile_80km
lat_80, lng_80, heading = vincenty.to_dist_bear_vincenty(lat1, lng1, 80.0, bearing)
print '80km point is %f %f' % (lat_80, lng_80)
profile_80km = self.nedIndx.Profile(lat1, lng1, lat_80, lng_80)
# Find J adjustment...
ehata_loss = ehata.ExtendedHata_PropagationLoss(f, h1, h2, land_cat, profile_80km)
itm_loss = self.ITM_AdjustedPropagationLoss(lat1, lng1, h1, lat_80, lng_80, h2, f, 0.5)
J = ehata_loss - itm_loss
print 'Got ehata=%f itm=%f J=%f' % (ehata_loss, itm_loss, J)
if J < 0.0:
J = 0.0
return self.ITM_AdjustedPropagationLoss(lat1, lng1, h1, lat2, lng2, h2, f, 0.5) + J
def LandClassification(self, lat, lng):
code = self.nlcdIndx.NlcdCode(lat, lng)
return self.nlcdIndx.NlcdLandCategory(code)
# This is the oracle for propagation loss from point 1 to point 2 at frequency f (Mhz).
def PropagationLoss(self, f, lat1, lng1, h1, lat2, lng2, h2, land_cat=''):
if land_cat == '':
code = self.nlcdIndx.NlcdCode(lat2, lng2)
if code == 11:
code = self.nlcdIndx.NlcdCode(lat1, lng1)
land_cat = land_use.NlcdLandCategory(code)
print 'Using land_cat =', land_cat
# Calculate effective heights of tx and rx:
profile = self.nedIndx.Profile(lat1, lng1, lat2, lng2)
h1eff, h2eff = EffectiveHeights(h1, h2, profile)
if land_cat == 'RURAL' or h1eff >= 200: # Only h1eff (CBSD effective height) counts
itm_loss = self.ITM_AdjustedPropagationLoss(lat1, lng1, h1, lat2, lng2, h2, f, 0.5)
print 'Returning itm_loss for rural > 200: ', itm_loss
return itm_loss
else:
itm_loss = self.ITM_AdjustedPropagationLoss(lat1, lng1, h1, lat2, lng2, h2, f, 0.5)
ehata_loss = self.ExtendedHata_AdjustedPropagationLoss(lat1, lng1, h1, lat2, lng2, h2, f, land_cat)
if ehata_loss > itm_loss:
return ehata_loss
return itm_loss
# Run directly, takes args of "lat1, lng1, h1, lat2, lng2, h2, f" and prints the
# (median) propagation loss in dB.
if __name__ == '__main__':
dir = os.path.dirname(os.path.realpath(__file__))
rootDir = os.path.dirname(os.path.dirname(dir))
ituDir = os.path.join(os.path.join(rootDir, 'data'), 'itu')
nedDir = os.path.join(os.path.join(rootDir, 'data'), 'ned')
nlcdDir = os.path.join(os.path.join(rootDir, 'data'), 'nlcd')
prop = PropagationLossModel(ituDir, nedDir, nlcdDir)
loss = prop.PropagationLoss(float(sys.argv[1]), float(sys.argv[2]), float(sys.argv[3]),
float(sys.argv[4]), float(sys.argv[5]), float(sys.argv[6]),
float(sys.argv[7]))
print 'Propagation Loss = ', loss, ' dB'
| gregbillock/Spectrum-Access-System | src/prop/model.py | Python | apache-2.0 | 6,985 |
/*
* 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.
*/
package org.apache.camel.component.elytron;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.Provider;
import java.util.Collections;
import javax.net.ssl.SSLContext;
import io.undertow.security.handlers.AuthenticationCallHandler;
import io.undertow.security.handlers.AuthenticationConstraintHandler;
import io.undertow.server.HttpHandler;
import org.apache.camel.CamelContext;
import org.apache.camel.component.undertow.HttpHandlerRegistrationInfo;
import org.apache.camel.component.undertow.UndertowComponent;
import org.apache.camel.component.undertow.UndertowEndpoint;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.annotations.Component;
import org.wildfly.elytron.web.undertow.server.ElytronContextAssociationHandler;
import org.wildfly.elytron.web.undertow.server.ElytronRunAsHandler;
import org.wildfly.security.WildFlyElytronBaseProvider;
import org.wildfly.security.auth.server.MechanismConfiguration;
import org.wildfly.security.auth.server.MechanismConfigurationSelector;
import org.wildfly.security.auth.server.MechanismRealmConfiguration;
import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.auth.server.http.HttpAuthenticationFactory;
import org.wildfly.security.http.HttpAuthenticationException;
import org.wildfly.security.http.HttpConstants;
import org.wildfly.security.http.HttpServerAuthenticationMechanismFactory;
import org.wildfly.security.http.bearer.WildFlyElytronHttpBearerProvider;
import org.wildfly.security.http.util.FilterServerMechanismFactory;
import org.wildfly.security.http.util.SecurityProviderServerMechanismFactory;
/**
* Elytron component brings elytron security over came-undertow component.
*
* Component work either as producer and as consumer.
*
* User has to define its SecurityDomain.Builder which will be used for creation of security domain.
* MechanismName then allows to define mechanism, which will take care of authentication from security context.
* MechanismName should be selected with regard to default securityRealm.
*
* Example: to use bearer_token, mechanism name has to be "BEARER_TOKEN" and realm has to be TokenSecurityRealm.
*
*/
@Metadata(label = "verifiers", enums = "parameters,connectivity")
@Component("elytron")
public class ElytronComponent extends UndertowComponent {
@Metadata(label = "advanced", required = true)
private SecurityDomain.Builder securityDomainBuilder;
@Metadata(label = "advanced", defaultValue = HttpConstants.BEARER_TOKEN)
private String mechanismName = HttpConstants.BEARER_TOKEN;
@Metadata(label = "advanced", defaultValue = "instance of WildFlyElytronHttpBearerProvider")
private WildFlyElytronBaseProvider elytronProvider = WildFlyElytronHttpBearerProvider.getInstance();
private SecurityDomain securityDomain;
public ElytronComponent() {
}
public ElytronComponent(CamelContext context) {
super(context);
}
@Override
protected String getComponentName() {
return "elytron";
}
@Override
protected UndertowEndpoint createEndpointInstance(URI endpointUri, UndertowComponent component) throws URISyntaxException {
return new ElytronEndpoint(endpointUri.toString(), component);
}
@Override
public HttpHandler registerEndpoint(HttpHandlerRegistrationInfo registrationInfo, SSLContext sslContext, HttpHandler handler) {
//injecting elytron
return super.registerEndpoint(registrationInfo, sslContext, wrap(handler, getSecurityDomain()));
}
/**
* Definition of Builder, which will be used for creation of security domain.
*/
public SecurityDomain.Builder getSecurityDomainBuilder() {
return securityDomainBuilder;
}
public void setSecurityDomainBuilder(SecurityDomain.Builder securityDomainBuilder) {
this.securityDomainBuilder = securityDomainBuilder;
}
/**
* Name of the mechanism, which will be used for selection of authentication mechanism.
*/
public String getMechanismName() {
return mechanismName;
}
public void setMechanismName(String mechanismName) {
this.mechanismName = mechanismName;
}
/**
* Elytron security provider, has to support mechanism from parameter mechanismName.
*/
public WildFlyElytronBaseProvider getElytronProvider() {
return elytronProvider;
}
public void setElytronProvider(WildFlyElytronBaseProvider elytronProvider) {
this.elytronProvider = elytronProvider;
}
SecurityDomain getSecurityDomain() {
if (securityDomain == null) {
securityDomain = securityDomainBuilder.build();
}
return securityDomain;
}
private HttpHandler wrap(final HttpHandler toWrap, final SecurityDomain securityDomain) {
HttpAuthenticationFactory httpAuthenticationFactory = createHttpAuthenticationFactory(securityDomain);
HttpHandler rootHandler = new ElytronRunAsHandler(toWrap);
rootHandler = new AuthenticationCallHandler(rootHandler);
rootHandler = new AuthenticationConstraintHandler(rootHandler);
return ElytronContextAssociationHandler.builder()
.setNext(rootHandler)
.setMechanismSupplier(() -> {
try {
return Collections.singletonList(httpAuthenticationFactory.createMechanism(mechanismName));
} catch (HttpAuthenticationException e) {
throw new RuntimeException(e);
}
}).build();
}
private HttpAuthenticationFactory createHttpAuthenticationFactory(final SecurityDomain securityDomain) {
HttpServerAuthenticationMechanismFactory providerFactory = new SecurityProviderServerMechanismFactory(() -> new Provider[]{getElytronProvider()});
HttpServerAuthenticationMechanismFactory httpServerMechanismFactory = new FilterServerMechanismFactory(providerFactory, true, mechanismName);
return HttpAuthenticationFactory.builder()
.setSecurityDomain(securityDomain)
.setMechanismConfigurationSelector(MechanismConfigurationSelector.constantSelector(
MechanismConfiguration.builder()
.addMechanismRealm(MechanismRealmConfiguration.builder().setRealmName("Elytron Realm").build())
.build()))
.setFactory(httpServerMechanismFactory)
.build();
}
}
| CodeSmell/camel | components/camel-elytron/src/main/java/org/apache/camel/component/elytron/ElytronComponent.java | Java | apache-2.0 | 7,341 |
Clazz.declarePackage ("J.script");
Clazz.load (["J.script.ScriptCompilationTokenParser", "J.util.JmolList"], "J.script.ScriptCompiler", ["java.lang.Boolean", "$.Character", "$.Float", "java.util.Hashtable", "J.api.Interface", "J.i18n.GT", "J.io.JmolBinary", "J.modelset.Bond", "$.Group", "J.script.ContextToken", "$.SV", "$.ScriptContext", "$.ScriptEvaluator", "$.ScriptFlowContext", "$.ScriptFunction", "$.T", "J.util.ArrayUtil", "$.BS", "$.Escape", "$.Logger", "$.Parser", "$.SB", "$.TextFormat", "J.viewer.Viewer"], function () {
c$ = Clazz.decorateAsClass (function () {
this.filename = null;
this.isSilent = false;
this.contextVariables = null;
this.aatokenCompiled = null;
this.lineNumbers = null;
this.lineIndices = null;
this.lnLength = 8;
this.preDefining = false;
this.isShowScriptOutput = false;
this.isCheckOnly = false;
this.haveComments = false;
this.scriptExtensions = null;
this.thisFunction = null;
this.flowContext = null;
this.ltoken = null;
this.lltoken = null;
this.vBraces = null;
this.ichBrace = 0;
this.cchToken = 0;
this.cchScript = 0;
this.nSemiSkip = 0;
this.parenCount = 0;
this.braceCount = 0;
this.setBraceCount = 0;
this.bracketCount = 0;
this.ptSemi = 0;
this.forPoint3 = 0;
this.setEqualPt = 0;
this.iBrace = 0;
this.iHaveQuotedString = false;
this.isEndOfCommand = false;
this.needRightParen = false;
this.endOfLine = false;
this.comment = null;
this.tokLastMath = 0;
this.checkImpliedScriptCmd = false;
this.vFunctionStack = null;
this.allowMissingEnd = false;
this.isShowCommand = false;
this.isComment = false;
this.isUserToken = false;
this.implicitString = false;
this.tokInitialPlusPlus = 0;
this.vPush = null;
this.pushCount = 0;
this.chFirst = '\0';
Clazz.instantialize (this, arguments);
}, J.script, "ScriptCompiler", J.script.ScriptCompilationTokenParser);
Clazz.prepareFields (c$, function () {
this.vPush = new J.util.JmolList ();
});
Clazz.makeConstructor (c$,
function (viewer) {
Clazz.superConstructor (this, J.script.ScriptCompiler, []);
this.viewer = viewer;
}, "J.viewer.Viewer");
$_M(c$, "compile",
function (filename, script, isPredefining, isSilent, debugScript, isCheckOnly) {
this.isCheckOnly = isCheckOnly;
this.filename = filename;
this.isSilent = isSilent;
this.script = script;
this.logMessages = (!isSilent && !isPredefining && debugScript);
this.preDefining = (filename === "#predefine");
var doFull = true;
var isOK = this.compile0 (doFull);
if (!isOK) this.handleError ();
var sc = new J.script.ScriptContext ();
isOK = (this.iBrace == 0 && this.parenCount == 0 && this.braceCount == 0 && this.bracketCount == 0);
sc.isComplete = isOK;
sc.script = script;
sc.scriptExtensions = this.scriptExtensions;
sc.errorType = this.errorType;
if (this.errorType != null) {
sc.iCommandError = this.iCommand;
this.setAaTokenCompiled ();
}sc.aatoken = this.aatokenCompiled;
sc.errorMessage = this.errorMessage;
sc.errorMessageUntranslated = (this.errorMessageUntranslated == null ? this.errorMessage : this.errorMessageUntranslated);
if (this.allowMissingEnd && sc.errorMessage != null && sc.errorMessageUntranslated.indexOf ("missing END") >= 0) sc.errorMessage = sc.errorMessageUntranslated;
sc.lineIndices = this.lineIndices;
sc.lineNumbers = this.lineNumbers;
sc.contextVariables = this.contextVariables;
return sc;
}, "~S,~S,~B,~B,~B,~B");
$_M(c$, "addContextVariable",
($fz = function (ident) {
this.theToken = J.script.T.o (1073741824, ident);
if (this.pushCount > 0) {
var ct = this.vPush.get (this.pushCount - 1);
ct.addName (ident);
if (ct.tok != 364558) return;
}if (this.thisFunction == null) {
if (this.contextVariables == null) this.contextVariables = new java.util.Hashtable ();
J.script.ScriptCompiler.addContextVariable (this.contextVariables, ident);
} else {
this.thisFunction.addVariable (ident, false);
}}, $fz.isPrivate = true, $fz), "~S");
c$.addContextVariable = $_M(c$, "addContextVariable",
function (contextVariables, name) {
contextVariables.put (name, J.script.SV.newVariable (4, "").setName (name));
}, "java.util.Map,~S");
$_M(c$, "isContextVariable",
($fz = function (ident) {
for (var i = this.vPush.size (); --i >= 0; ) {
var ct = this.vPush.get (i);
if (ct.contextVariables != null && ct.contextVariables.containsKey (ident)) return true;
}
return (this.thisFunction != null ? this.thisFunction.isVariable (ident) : this.contextVariables != null && this.contextVariables.containsKey (ident));
}, $fz.isPrivate = true, $fz), "~S");
$_M(c$, "cleanScriptComments",
($fz = function (script) {
if (script.indexOf ('\u201C') >= 0) script = script.$replace ('\u201C', '"');
if (script.indexOf ('\u201D') >= 0) script = script.$replace ('\u201D', '"');
if (script.indexOf ('\uFEFF') >= 0) script = script.$replace ('\uFEFF', ' ');
var pt = (script.indexOf ("\1##"));
if (pt >= 0) {
this.scriptExtensions = script.substring (pt + 1);
script = script.substring (0, pt);
this.allowMissingEnd = (this.scriptExtensions.indexOf ("##noendcheck") >= 0);
}this.haveComments = (script.indexOf ("#") >= 0);
return J.io.JmolBinary.getEmbeddedScript (script);
}, $fz.isPrivate = true, $fz), "~S");
$_M(c$, "addTokenToPrefix",
($fz = function (token) {
if (this.logMessages) J.util.Logger.debug ("addTokenToPrefix" + token);
this.ltoken.addLast (token);
if (token.tok != 0) this.lastToken = token;
}, $fz.isPrivate = true, $fz), "J.script.T");
$_M(c$, "compile0",
($fz = function (isFull) {
this.vFunctionStack = new J.util.JmolList ();
this.htUserFunctions = new java.util.Hashtable ();
this.script = this.cleanScriptComments (this.script);
this.ichToken = this.script.indexOf ("# Jmol state version ");
this.isStateScript = (this.ichToken >= 0);
if (this.isStateScript) {
this.ptSemi = this.script.indexOf (";", this.ichToken);
if (this.ptSemi >= this.ichToken) this.viewer.setStateScriptVersion (this.script.substring (this.ichToken + "# Jmol state version ".length, this.ptSemi).trim ());
}this.cchScript = this.script.length;
this.contextVariables = null;
this.lineNumbers = null;
this.lineIndices = null;
this.aatokenCompiled = null;
this.thisFunction = null;
this.flowContext = null;
this.errorType = null;
this.errorMessage = null;
this.errorMessageUntranslated = null;
this.errorLine = null;
this.nSemiSkip = 0;
this.ichToken = 0;
this.ichCurrentCommand = 0;
this.ichComment = 0;
this.ichBrace = 0;
this.lineCurrent = 1;
this.iCommand = 0;
this.tokLastMath = 0;
this.lastToken = J.script.T.tokenOff;
this.vBraces = new J.util.JmolList ();
this.vPush = new J.util.JmolList ();
this.pushCount = 0;
this.iBrace = 0;
this.braceCount = 0;
this.parenCount = 0;
this.ptSemi = -10;
this.cchToken = 0;
this.lnLength = 8;
this.lineNumbers = Clazz.newShortArray (this.lnLength, 0);
this.lineIndices = Clazz.newIntArray (this.lnLength, 2, 0);
this.isNewSet = this.isSetBrace = false;
this.ptNewSetModifier = 1;
this.isShowScriptOutput = false;
this.iHaveQuotedString = false;
this.checkImpliedScriptCmd = false;
this.lltoken = new J.util.JmolList ();
this.ltoken = new J.util.JmolList ();
this.tokCommand = 0;
this.lastFlowCommand = null;
this.tokenAndEquals = null;
this.tokInitialPlusPlus = 0;
this.setBraceCount = 0;
this.bracketCount = 0;
this.forPoint3 = -1;
this.setEqualPt = 2147483647;
this.endOfLine = false;
this.comment = null;
this.isEndOfCommand = false;
this.needRightParen = false;
this.theTok = 0;
var iLine = 1;
for (; true; this.ichToken += this.cchToken) {
if ((this.nTokens = this.ltoken.size ()) == 0) {
if (this.thisFunction != null && this.thisFunction.chpt0 == 0) this.thisFunction.chpt0 = this.ichToken;
this.ichCurrentCommand = this.ichToken;
iLine = this.lineCurrent;
}if (this.lookingAtLeadingWhitespace ()) continue;
this.endOfLine = false;
if (!this.isEndOfCommand) {
this.endOfLine = this.lookingAtEndOfLine ();
switch (this.endOfLine ? 0 : this.lookingAtComment ()) {
case 2:
continue;
case 3:
this.isEndOfCommand = true;
continue;
case 1:
this.isEndOfCommand = true;
this.comment = this.script.substring (this.ichToken, this.ichToken + this.cchToken).trim ();
break;
}
this.isEndOfCommand = this.isEndOfCommand || this.endOfLine || this.lookingAtTerminator ();
}if (this.isEndOfCommand) {
this.isEndOfCommand = false;
switch (this.processTokenList (iLine, isFull)) {
case 2:
continue;
case 4:
return false;
}
this.checkImpliedScriptCmd = false;
if (this.ichToken < this.cchScript) continue;
this.setAaTokenCompiled ();
return (this.flowContext == null || this.errorStr (11, J.script.T.nameOf (this.flowContext.token.tok)));
}if (this.nTokens > 0) {
switch (this.checkSpecialParameterSyntax ()) {
case 2:
continue;
case 4:
return false;
}
}if (this.lookingAtLookupToken (this.ichToken)) {
var ident = this.getPrefixToken ();
switch (this.parseKnownToken (ident)) {
case 2:
continue;
case 4:
return false;
}
switch (this.parseCommandParameter (ident)) {
case 2:
continue;
case 4:
return false;
}
this.addTokenToPrefix (this.theToken);
continue;
}if (this.nTokens == 0 || (this.isNewSet || this.isSetBrace) && this.nTokens == this.ptNewSetModifier) {
if (this.nTokens == 0) {
if (this.lookingAtString (true)) {
this.addTokenToPrefix (this.setCommand (J.script.T.tokenScript));
this.cchToken = 0;
continue;
}if (this.lookingAtImpliedString (true, true, true)) this.ichEnd = this.ichToken + this.cchToken;
}return this.commandExpected ();
}return this.errorStr (19, this.script.substring (this.ichToken, this.ichToken + 1));
}
}, $fz.isPrivate = true, $fz), "~B");
$_M(c$, "setAaTokenCompiled",
($fz = function () {
this.aatokenCompiled = this.lltoken.toArray ( new Array (this.lltoken.size ()));
}, $fz.isPrivate = true, $fz));
$_M(c$, "lookingAtLeadingWhitespace",
($fz = function () {
var ichT = this.ichToken;
while (J.script.ScriptCompiler.isSpaceOrTab (this.charAt (ichT))) ++ichT;
if (this.isLineContinuation (ichT, true)) ichT += 1 + this.nCharNewLine (ichT + 1);
this.cchToken = ichT - this.ichToken;
return this.cchToken > 0;
}, $fz.isPrivate = true, $fz));
$_M(c$, "isLineContinuation",
($fz = function (ichT, checkMathop) {
var isEscaped = (ichT + 2 < this.cchScript && this.script.charAt (ichT) == '\\' && this.nCharNewLine (ichT + 1) > 0 || checkMathop && this.lookingAtMathContinuation (ichT));
if (isEscaped) this.lineCurrent++;
return isEscaped;
}, $fz.isPrivate = true, $fz), "~N,~B");
$_M(c$, "lookingAtMathContinuation",
($fz = function (ichT) {
var n;
if ((n = this.nCharNewLine (ichT)) == 0 || this.lastToken.tok == 1048586) return false;
if (this.parenCount > 0 || this.bracketCount > 0) return true;
if ((this.tokCommand != 1085443 || !this.isNewSet) && this.tokCommand != 36865 && this.tokCommand != 36869) return false;
if (this.lastToken.tok == this.tokLastMath) return true;
ichT += n;
while (J.script.ScriptCompiler.isSpaceOrTab (this.charAt (ichT))) ++ichT;
return (this.lookingAtLookupToken (ichT) && this.tokLastMath == 1);
}, $fz.isPrivate = true, $fz), "~N");
$_M(c$, "lookingAtEndOfLine",
($fz = function () {
if (this.ichToken >= this.cchScript) {
this.ichEnd = this.cchScript;
return true;
}return ((this.cchToken = this.nCharNewLine (this.ichEnd = this.ichToken)) > 0);
}, $fz.isPrivate = true, $fz));
$_M(c$, "nCharNewLine",
($fz = function (ichT) {
var ch;
return ((ch = this.charAt (ichT)) != '\r' ? (ch == '\n' ? 1 : 0) : this.charAt (++ichT) == '\n' ? 2 : 1);
}, $fz.isPrivate = true, $fz), "~N");
$_M(c$, "lookingAtTerminator",
($fz = function () {
var isSemi = (this.script.charAt (this.ichToken) == ';');
if (isSemi && this.nTokens > 0) this.ptSemi = this.nTokens;
if (!isSemi || this.nSemiSkip-- > 0) return false;
this.cchToken = 1;
return true;
}, $fz.isPrivate = true, $fz));
$_M(c$, "lookingAtComment",
($fz = function () {
var ch = this.script.charAt (this.ichToken);
var ichT = this.ichToken;
var ichFirstSharp = -1;
if (this.ichToken == this.ichCurrentCommand && ch == '$' && (this.isShowScriptOutput || this.ichToken == 0)) {
this.isShowScriptOutput = true;
this.isShowCommand = true;
if (this.charAt (++ichT) == '[') while (ch != ']' && !this.eol (ch = this.charAt (ichT))) ++ichT;
this.cchToken = ichT - this.ichToken;
return 2;
} else if (this.isShowScriptOutput && !this.isShowCommand) {
ichFirstSharp = ichT;
}if (ch == '/' && ichT + 1 < this.cchScript) switch (this.script.charAt (++ichT)) {
case '/':
ichFirstSharp = this.ichToken;
this.ichEnd = ichT - 1;
break;
case '*':
this.ichEnd = ichT - 1;
var terminator = ((ch = this.charAt (++ichT)) == '*' ? "**/" : "*/");
ichT = this.script.indexOf (terminator, this.ichToken + 2);
if (ichT < 0) {
this.ichToken = this.cchScript;
return 3;
}this.incrementLineCount (this.script.substring (this.ichToken, ichT));
this.cchToken = ichT + (ch == '*' ? 3 : 2) - this.ichToken;
return 2;
default:
return 0;
}
var isSharp = (ichFirstSharp < 0);
if (isSharp && !this.haveComments) return 0;
if (this.ichComment > ichT) ichT = this.ichComment;
for (; ichT < this.cchScript; ichT++) {
if (this.eol (ch = this.script.charAt (ichT))) {
this.ichEnd = ichT;
if (ichT > 0 && this.isLineContinuation (ichT - 1, false)) {
ichT += this.nCharNewLine (ichT);
continue;
}if (!isSharp && ch == ';') continue;
break;
}if (ichFirstSharp >= 0) continue;
if (ch == '#') ichFirstSharp = ichT;
}
if (ichFirstSharp < 0) return 0;
this.ichComment = ichFirstSharp;
if (isSharp && this.nTokens == 0 && this.cchScript - ichFirstSharp >= 3 && this.script.charAt (ichFirstSharp + 1) == 'j' && this.script.charAt (ichFirstSharp + 2) == 'c') {
this.cchToken = ichT - this.ichToken;
return 2;
}if (ichFirstSharp != this.ichToken) return 0;
if (isSharp && this.cchScript > this.ichToken + 3 && this.script.charAt (this.ichToken + 1) == 'j' && this.script.charAt (this.ichToken + 2) == 'x' && J.script.ScriptCompiler.isSpaceOrTab (this.script.charAt (this.ichToken + 3))) {
this.cchToken = 4;
return 2;
}if (ichT == this.ichToken) return 0;
this.cchToken = ichT - this.ichToken;
return (this.nTokens == 0 ? 1 : 2);
}, $fz.isPrivate = true, $fz));
$_M(c$, "charAt",
($fz = function (i) {
return (i < this.cchScript ? this.script.charAt (i) : '\0');
}, $fz.isPrivate = true, $fz), "~N");
$_M(c$, "processTokenList",
($fz = function (iLine, doCompile) {
if (this.nTokens > 0 || this.comment != null) {
if (this.nTokens == 0) {
this.ichCurrentCommand = this.ichToken;
if (this.comment != null) {
this.isComment = true;
this.addTokenToPrefix (J.script.T.o (0, this.comment));
}} else if (this.setBraceCount > 0 && this.endOfLine && this.ichToken < this.cchScript) {
return 2;
}if (this.tokCommand == 135271429 && this.checkImpliedScriptCmd) {
var s = (this.nTokens == 2 ? this.lastToken.value.toString ().toUpperCase () : null);
if (this.nTokens > 2 && !(this.tokAt (2) == 269484048 && this.ltoken.get (1).value.toString ().endsWith (".spt")) || s != null && (s.endsWith (".SORT") || s.endsWith (".REVERSE") || s.indexOf (".SORT(") >= 0 || s.indexOf (".REVERSE(") >= 0)) {
this.ichToken = this.ichCurrentCommand;
this.nTokens = 0;
this.ltoken.clear ();
this.cchToken = 0;
this.tokCommand = 0;
return 2;
}}if (this.isNewSet && this.nTokens > 2 && this.tokAt (2) == 1048584 && (this.tokAt (3) == 1276117010 || this.tokAt (3) == 1141899269)) {
this.ltoken.set (0, J.script.T.tokenSet);
this.ltoken.add (1, this.ltoken.get (1));
} else if (this.tokInitialPlusPlus != 0) {
if (!this.isNewSet) this.checkNewSetCommand ();
this.tokenizePlusPlus (this.tokInitialPlusPlus, true);
}this.iCommand = this.lltoken.size ();
if (this.thisFunction != null && this.thisFunction.cmdpt0 < 0) {
this.thisFunction.cmdpt0 = this.iCommand;
}if (this.nTokens == 1 && this.braceCount == 1) {
if (this.lastFlowCommand == null) {
this.parenCount = this.setBraceCount = this.braceCount = 0;
this.ltoken.remove (0);
this.iBrace++;
var t = J.script.ContextToken.newContext (true);
this.addTokenToPrefix (this.setCommand (t));
this.pushCount++;
this.vPush.addLast (t);
this.vBraces.addLast (this.tokenCommand);
} else {
this.parenCount = this.setBraceCount = 0;
this.setCommand (this.lastFlowCommand);
if (this.lastFlowCommand.tok != 102439 && (this.tokAt (0) == 1048586)) this.ltoken.remove (0);
this.lastFlowCommand = null;
}}if (this.bracketCount > 0 || this.setBraceCount > 0 || this.parenCount > 0 || this.braceCount == 1 && !this.checkFlowStartBrace (true)) {
this.error (this.nTokens == 1 ? 2 : 4);
return 4;
}if (this.needRightParen) {
this.addTokenToPrefix (J.script.T.tokenRightParen);
this.needRightParen = false;
}if (this.ltoken.size () > 0) {
if (doCompile && !this.compileCommand ()) return 4;
if (this.logMessages) {
J.util.Logger.debug ("-------------------------------------");
}var doEval = true;
switch (this.tokCommand) {
case 364558:
case 102436:
case 135368713:
case 1150985:
doEval = (this.atokenInfix.length > 0 && this.atokenInfix[0].intValue != 2147483647);
break;
}
if (doEval) {
if (this.iCommand == this.lnLength) {
this.lineNumbers = J.util.ArrayUtil.doubleLengthShort (this.lineNumbers);
var lnI = Clazz.newIntArray (this.lnLength * 2, 2, 0);
System.arraycopy (this.lineIndices, 0, lnI, 0, this.lnLength);
this.lineIndices = lnI;
this.lnLength *= 2;
}this.lineNumbers[this.iCommand] = iLine;
this.lineIndices[this.iCommand][0] = this.ichCurrentCommand;
this.lineIndices[this.iCommand][1] = Math.max (this.ichCurrentCommand, Math.min (this.cchScript, this.ichEnd == this.ichCurrentCommand ? this.ichToken : this.ichEnd));
this.lltoken.addLast (this.atokenInfix);
this.iCommand = this.lltoken.size ();
}if (this.tokCommand == 1085443) this.lastFlowCommand = null;
}this.setCommand (null);
this.comment = null;
this.iHaveQuotedString = this.isNewSet = this.isSetBrace = this.needRightParen = false;
this.ptNewSetModifier = 1;
this.ltoken.clear ();
this.nTokens = this.nSemiSkip = 0;
this.tokInitialPlusPlus = 0;
this.tokenAndEquals = null;
this.ptSemi = -10;
this.forPoint3 = -1;
this.setEqualPt = 2147483647;
}if (this.endOfLine) {
if (this.flowContext != null && this.flowContext.checkForceEndIf ()) {
if (!this.isComment) this.forceFlowEnd (this.flowContext.token);
this.isEndOfCommand = true;
this.cchToken = 0;
this.ichCurrentCommand = this.ichToken;
this.lineCurrent--;
return 2;
}this.isComment = false;
this.isShowCommand = false;
++this.lineCurrent;
}if (this.ichToken >= this.cchScript) {
this.setCommand (J.script.T.tokenAll);
this.theTok = 0;
switch (this.checkFlowEndBrace ()) {
case 4:
return 4;
case 2:
this.isEndOfCommand = true;
this.cchToken = 0;
return 2;
}
this.ichToken = this.cchScript;
return 0;
}return 0;
}, $fz.isPrivate = true, $fz), "~N,~B");
$_M(c$, "compileCommand",
($fz = function () {
switch (this.ltoken.size ()) {
case 0:
this.atokenInfix = new Array (0);
return true;
case 4:
if (this.isNewSet && this.tokenAt (2).value.equals (".") && this.tokenAt (3).value.equals ("spt")) {
var fname = this.tokenAt (1).value + "." + this.tokenAt (3).value;
this.ltoken.clear ();
this.addTokenToPrefix (J.script.T.tokenScript);
this.addTokenToPrefix (J.script.T.o (4, fname));
this.isNewSet = false;
}}
this.setCommand (this.tokenAt (0));
var size = this.ltoken.size ();
if (size == 1 && J.script.T.tokAttr (this.tokCommand, 524288)) this.addTokenToPrefix (J.script.T.tokenOn);
if (this.tokenAndEquals != null) {
var j;
var i = 0;
for (i = 1; i < size; i++) {
if ((j = this.tokAt (i)) == 269484242) break;
}
size = i;
i++;
if (this.ltoken.size () < i) {
J.util.Logger.error ("COMPILER ERROR! - andEquals ");
} else {
for (j = 1; j < size; j++, i++) this.ltoken.add (i, this.tokenAt (j));
this.ltoken.set (size, J.script.T.tokenEquals);
this.ltoken.add (i, this.tokenAndEquals);
this.ltoken.add (++i, J.script.T.tokenLeftParen);
this.addTokenToPrefix (J.script.T.tokenRightParen);
}}this.atokenInfix = this.ltoken.toArray ( new Array (size = this.ltoken.size ()));
if (this.logMessages) {
J.util.Logger.debug ("token list:");
for (var i = 0; i < this.atokenInfix.length; i++) J.util.Logger.debug (i + ": " + this.atokenInfix[i]);
J.util.Logger.debug ("vBraces list:");
for (var i = 0; i < this.vBraces.size (); i++) J.util.Logger.debug (i + ": " + this.vBraces.get (i));
J.util.Logger.debug ("-------------------------------------");
}return this.compileExpressions ();
}, $fz.isPrivate = true, $fz));
$_M(c$, "tokenAt",
($fz = function (i) {
return this.ltoken.get (i);
}, $fz.isPrivate = true, $fz), "~N");
Clazz.overrideMethod (c$, "tokAt",
function (i) {
return (i < this.ltoken.size () ? this.tokenAt (i).tok : 0);
}, "~N");
$_M(c$, "setCommand",
($fz = function (token) {
this.tokenCommand = token;
if (token == null) {
this.tokCommand = 0;
} else {
this.tokCommand = this.tokenCommand.tok;
this.isMathExpressionCommand = (this.tokCommand == 1073741824 || J.script.T.tokAttr (this.tokCommand, 36864));
this.isSetOrDefine = (this.tokCommand == 1085443 || this.tokCommand == 1060866);
this.isCommaAsOrAllowed = J.script.T.tokAttr (this.tokCommand, 12288);
this.implicitString = J.script.T.tokAttr (this.tokCommand, 20480);
}return token;
}, $fz.isPrivate = true, $fz), "J.script.T");
$_M(c$, "replaceCommand",
($fz = function (token) {
this.ltoken.remove (0);
this.ltoken.add (0, this.setCommand (token));
}, $fz.isPrivate = true, $fz), "J.script.T");
$_M(c$, "getPrefixToken",
($fz = function () {
var ident = this.script.substring (this.ichToken, this.ichToken + this.cchToken);
var identLC = ident.toLowerCase ();
var isUserVar = this.isContextVariable (identLC);
if (this.nTokens == 0) this.isUserToken = isUserVar;
if (this.nTokens == 1 && (this.tokCommand == 135368713 || this.tokCommand == 102436 || this.tokCommand == 36868) || this.nTokens != 0 && isUserVar || this.isUserFunction (identLC) && (this.thisFunction == null || !this.thisFunction.name.equals (identLC))) {
ident = identLC;
this.theToken = null;
} else if (ident.length == 1 || this.lastToken.tok == 269484066) {
if ((this.theToken = J.script.T.getTokenFromName (ident)) == null && (this.theToken = J.script.T.getTokenFromName (identLC)) != null) this.theToken = J.script.T.tv (this.theToken.tok, this.theToken.intValue, ident);
} else {
ident = identLC;
this.theToken = J.script.T.getTokenFromName (ident);
}if (this.theToken == null) {
if (ident.indexOf ("property_") == 0) this.theToken = J.script.T.o (1716520985, ident);
else this.theToken = J.script.T.o (1073741824, ident);
}this.theTok = this.theToken.tok;
return ident;
}, $fz.isPrivate = true, $fz));
$_M(c$, "checkSpecialParameterSyntax",
($fz = function () {
if (this.lookingAtString (!this.implicitString)) {
if (this.cchToken < 0) return this.ERROR (4);
var str = this.getUnescapedStringLiteral (this.lastToken != null && !this.iHaveQuotedString && this.lastToken.tok != 1073741983 && (this.tokCommand == 1085443 && this.nTokens == 2 && this.lastToken.tok == 545259546 || this.tokCommand == 135271426 || this.tokCommand == 1610616835 || this.tokCommand == 135271429));
this.iHaveQuotedString = true;
if (this.tokCommand == 135271426 && this.lastToken.tok == 135270407 || this.tokCommand == 135270407 && str.indexOf ("@") < 0) {
if (!this.getData (str)) {
return this.ERROR (11, "data");
}} else {
this.addTokenToPrefix (J.script.T.o (4, str));
if (this.implicitString) this.isEndOfCommand = true;
}return 2;
}if (this.lastToken.tok == 1074790550 && this.lookingAtImpliedString (false, false, false)) {
this.addTokenToPrefix (J.script.T.o (4, this.script.substring (this.ichToken, this.ichToken + this.cchToken)));
return 2;
}var ch;
if (this.nTokens == this.ptNewSetModifier) {
ch = this.script.charAt (this.ichToken);
var isAndEquals = ("+-\\*/&|=".indexOf (ch) >= 0);
var isOperation = (isAndEquals || ch == '.' || ch == '[');
var ch2 = this.charAt (this.ichToken + 1);
if (!this.isNewSet && this.isUserToken && isOperation && (ch == '=' || ch2 == ch || ch2 == '=')) {
this.isNewSet = true;
}if (this.isNewSet || this.tokCommand == 1085443 || J.script.T.tokAttr (this.tokCommand, 536870912)) {
if (ch == '=') this.setEqualPt = this.ichToken;
if (J.script.T.tokAttr (this.tokCommand, 536870912) && ch == '=' || (this.isNewSet || this.isSetBrace) && isOperation) {
this.setCommand (isAndEquals ? J.script.T.tokenSet : ch == '[' && !this.isSetBrace ? J.script.T.tokenSetArray : J.script.T.tokenSetProperty);
this.ltoken.add (0, this.tokenCommand);
this.cchToken = 1;
switch (ch) {
case '[':
this.addTokenToPrefix (J.script.T.o (269484096, "["));
this.bracketCount++;
return 2;
case '.':
this.addTokenToPrefix (J.script.T.o (1048584, "."));
return 2;
case '-':
case '+':
case '*':
case '/':
case '\\':
case '&':
case '|':
if (ch2.charCodeAt (0) == 0) return this.ERROR (4);
if (ch2 != ch && ch2 != '=') return this.ERROR (1, "\"" + ch + "\"");
break;
default:
this.lastToken = J.script.T.tokenMinus;
return 2;
}
}}}switch (this.tokCommand) {
case 135271426:
case 135271429:
case 135270410:
if (this.script.charAt (this.ichToken) == '@') {
this.iHaveQuotedString = true;
return 0;
}if (this.tokCommand == 135271426) {
if ((this.nTokens == 1 || this.nTokens == 2 && this.tokAt (1) == 1073741839) && this.lookingAtLoadFormat ()) {
var strFormat = this.script.substring (this.ichToken, this.ichToken + this.cchToken);
var token = J.script.T.getTokenFromName (strFormat.toLowerCase ());
switch (token == null ? 0 : token.tok) {
case 1073742015:
case 1073741839:
if (this.nTokens != 1) return 4;
case 135270407:
case 1229984263:
case 1073741983:
case 1095766028:
case 135267336:
case 536870926:
case 4156:
this.addTokenToPrefix (token);
break;
default:
var tok = (strFormat.indexOf ("=") == 0 || strFormat.indexOf ("$") == 0 ? 4 : J.util.Parser.isOneOf (strFormat = strFormat.toLowerCase (), ";xyz;vxyz;vibration;temperature;occupancy;partialcharge;") ? 1073741824 : 0);
if (tok != 0) {
this.addTokenToPrefix (J.script.T.o (tok, strFormat));
this.iHaveQuotedString = (tok == 4);
}}
return 2;
}var bs;
if (this.script.charAt (this.ichToken) == '{' || this.parenCount > 0) break;
if ((bs = this.lookingAtBitset ()) != null) {
this.addTokenToPrefix (J.script.T.o (10, bs));
return 2;
}}if (!this.iHaveQuotedString && this.lookingAtImpliedString (false, this.tokCommand == 135271426, this.nTokens > 1 || this.tokCommand != 135271429)) {
var str = this.script.substring (this.ichToken, this.ichToken + this.cchToken);
if (this.tokCommand == 135271429 && str.startsWith ("javascript:")) {
this.lookingAtImpliedString (true, true, true);
str = this.script.substring (this.ichToken, this.ichToken + this.cchToken);
}this.iHaveQuotedString = true;
this.addTokenToPrefix (J.script.T.o (4, str));
return 2;
}break;
case 4156:
if (this.nTokens == 1 && this.lookForSyncID ()) {
var ident = this.script.substring (this.ichToken, this.ichToken + this.cchToken);
var iident = J.util.Parser.parseInt (ident);
if (iident == -2147483648 || Math.abs (iident) < 1000) this.addTokenToPrefix (J.script.T.o (1073741824, ident));
else this.addTokenToPrefix (J.script.T.i (iident));
return 2;
}break;
case 135270421:
if (this.nTokens == 2 && this.lastToken.tok == 4115) this.iHaveQuotedString = true;
if (!this.iHaveQuotedString) {
if (this.script.charAt (this.ichToken) == '@') {
this.iHaveQuotedString = true;
return 0;
}if (this.lookingAtImpliedString (true, true, true)) {
var pt = this.cchToken;
var str = this.script.substring (this.ichToken, this.ichToken + this.cchToken);
if (str.indexOf (" ") < 0) {
this.addTokenToPrefix (J.script.T.o (4, str));
this.iHaveQuotedString = true;
return 2;
}this.cchToken = pt;
}}break;
}
if (this.implicitString && !(this.tokCommand == 135271429 && this.iHaveQuotedString) && this.lookingAtImpliedString (true, true, true)) {
var str = this.script.substring (this.ichToken, this.ichToken + this.cchToken);
if (this.tokCommand == 1826248715 && J.util.Parser.isOneOf (str.toLowerCase (), "on;off;hide;display")) this.addTokenToPrefix (J.script.T.getTokenFromName (str.toLowerCase ()));
else this.addTokenToPrefix (J.script.T.o (4, str));
return 2;
}if (this.lookingAtObjectID ()) {
this.addTokenToPrefix (J.script.T.getTokenFromName ("$"));
this.addTokenToPrefix (J.script.T.o (1073741824, this.script.substring (this.ichToken, this.ichToken + this.cchToken)));
return 2;
}var value;
if (!Float.isNaN (value = this.lookingAtExponential ())) {
this.addTokenToPrefix (J.script.T.o (3, Float.$valueOf (value)));
return 2;
}if (this.lookingAtDecimal ()) {
value = J.util.Parser.fVal (this.script.substring (this.ichToken, this.ichToken + this.cchToken));
var intValue = (J.script.ScriptEvaluator.getFloatEncodedInt (this.script.substring (this.ichToken, this.ichToken + this.cchToken)));
this.addTokenToPrefix (J.script.T.tv (3, intValue, Float.$valueOf (value)));
return 2;
}if (this.lookingAtSeqcode ()) {
ch = this.script.charAt (this.ichToken);
try {
var seqNum = (ch == '*' || ch == '^' ? 2147483647 : Integer.parseInt (this.script.substring (this.ichToken, this.ichToken + this.cchToken - 2)));
var insertionCode = this.script.charAt (this.ichToken + this.cchToken - 1);
if (insertionCode == '^') insertionCode = ' ';
if (seqNum < 0) {
seqNum = -seqNum;
this.addTokenToPrefix (J.script.T.tokenMinus);
}var seqcode = J.modelset.Group.getSeqcodeFor (seqNum, insertionCode);
this.addTokenToPrefix (J.script.T.tv (5, seqcode, "seqcode"));
} catch (nfe) {
if (Clazz.exceptionOf (nfe, NumberFormatException)) {
return this.ERROR (9, "" + ch);
} else {
throw nfe;
}
}
return 2;
}var val = this.lookingAtInteger ();
if (val != 2147483647) {
var intString = this.script.substring (this.ichToken, this.ichToken + this.cchToken);
if (this.tokCommand == 102407 || this.tokCommand == 102408) {
if (this.nTokens != 1) return this.ERROR (0);
var f = (this.flowContext == null ? null : this.flowContext.getBreakableContext (val = Math.abs (val)));
if (f == null) return this.ERROR (1, this.tokenCommand.value);
this.tokenAt (0).intValue = f.pt0;
}if (val == 0 && intString.equals ("-0")) this.addTokenToPrefix (J.script.T.tokenMinus);
this.addTokenToPrefix (J.script.T.tv (2, val, intString));
return 2;
}if (!this.isMathExpressionCommand && this.parenCount == 0 || this.lastToken.tok != 1073741824 && !J.script.ScriptCompilationTokenParser.tokenAttr (this.lastToken, 135266304)) {
var isBondOrMatrix = (this.script.charAt (this.ichToken) == '[');
var bs = this.lookingAtBitset ();
if (bs != null) {
this.addTokenToPrefix (J.script.T.o (10, isBondOrMatrix ? new J.modelset.Bond.BondSet (bs) : bs));
return 2;
}if (isBondOrMatrix) {
var m = this.lookingAtMatrix ();
if (Clazz.instanceOf (m, J.util.Matrix3f) || Clazz.instanceOf (m, J.util.Matrix4f)) {
this.addTokenToPrefix (J.script.T.o ((Clazz.instanceOf (m, J.util.Matrix3f) ? 11 : 12), m));
return 2;
}}}return 0;
}, $fz.isPrivate = true, $fz));
$_M(c$, "lookingAtMatrix",
($fz = function () {
var ipt;
var m;
if (this.ichToken + 4 >= this.cchScript || this.script.charAt (this.ichToken) != '[' || this.script.charAt (this.ichToken + 1) != '[' || (ipt = this.script.indexOf ("]]", this.ichToken)) < 0 || (m = J.util.Escape.unescapeMatrix (this.script.substring (this.ichToken, ipt + 2))) == null) return null;
this.cchToken = ipt + 2 - this.ichToken;
return m;
}, $fz.isPrivate = true, $fz));
$_M(c$, "parseKnownToken",
($fz = function (ident) {
var token;
if (this.tokLastMath != 0) this.tokLastMath = this.theTok;
if (this.flowContext != null && this.flowContext.token.tok == 102410 && this.flowContext.$var != null && this.theTok != 102411 && this.theTok != 102413 && this.lastToken.tok != 102410) return this.ERROR (1, ident);
if (this.lastToken.tok == 1060866 && this.theTok != 1048586 && this.nTokens != 1) {
this.addTokenToPrefix (J.script.T.o (4, ident));
return 2;
}switch (this.theTok) {
case 1073741824:
if (this.nTokens == 0 && !this.checkImpliedScriptCmd) {
if (ident.charAt (0) == '\'') {
this.addTokenToPrefix (this.setCommand (J.script.T.tokenScript));
this.cchToken = 0;
return 2;
}if (this.charAt (this.ichToken + this.cchToken) == '.') {
this.addTokenToPrefix (this.setCommand (J.script.T.tokenScript));
this.nTokens = 1;
this.cchToken = 0;
this.checkImpliedScriptCmd = true;
return 2;
}}break;
case 269484242:
if (this.nSemiSkip == this.forPoint3 && this.nTokens == this.ptSemi + 2) {
token = this.lastToken;
this.addTokenToPrefix (J.script.T.tokenEquals);
this.addTokenToPrefix (token);
token = J.script.T.getTokenFromName (ident.substring (0, 1));
this.addTokenToPrefix (token);
this.addTokenToPrefix (J.script.T.tokenLeftParen);
this.needRightParen = true;
return 2;
}this.checkNewSetCommand ();
if (this.tokCommand == 1085443) {
this.tokenAndEquals = J.script.T.getTokenFromName (ident.substring (0, 1));
this.setEqualPt = this.ichToken;
return 0;
}if (this.tokCommand == 554176565 || this.tokCommand == 554176526) {
this.addTokenToPrefix (this.tokenCommand);
this.replaceCommand (J.script.T.tokenSet);
this.tokenAndEquals = J.script.T.getTokenFromName (ident.substring (0, 1));
this.setEqualPt = this.ichToken;
return 0;
}return 2;
case 1150985:
case 364548:
if (this.flowContext != null) this.flowContext.forceEndIf = false;
case 364547:
if (this.nTokens > 0) {
this.isEndOfCommand = true;
this.cchToken = 0;
return 2;
}break;
case 135369224:
if (this.bracketCount > 0) break;
case 102411:
case 102413:
case 102402:
case 135369225:
case 102410:
case 102406:
case 102412:
if (this.nTokens > 1 && this.tokCommand != 1085443) {
this.isEndOfCommand = true;
if (this.flowContext != null) this.flowContext.forceEndIf = true;
this.cchToken = 0;
return 2;
}break;
case 269484225:
case 269484226:
if (!this.isNewSet && this.nTokens == 1) this.checkNewSetCommand ();
if (this.isNewSet && this.parenCount == 0 && this.bracketCount == 0 && this.ichToken <= this.setEqualPt) {
this.tokenizePlusPlus (this.theTok, false);
return 2;
} else if (this.nSemiSkip == this.forPoint3 && this.nTokens == this.ptSemi + 2) {
token = this.lastToken;
this.addTokenToPrefix (J.script.T.tokenEquals);
this.addTokenToPrefix (token);
this.addTokenToPrefix (this.theTok == 269484225 ? J.script.T.tokenMinus : J.script.T.tokenPlus);
this.addTokenToPrefix (J.script.T.i (1));
return 2;
}break;
case 269484436:
if (this.parenCount == 0 && this.bracketCount == 0) this.setEqualPt = this.ichToken;
break;
case 1048584:
if (this.tokCommand == 1085443 && this.parenCount == 0 && this.bracketCount == 0 && this.ichToken < this.setEqualPt) {
this.ltoken.add (1, J.script.T.tokenExpressionBegin);
this.addTokenToPrefix (J.script.T.tokenExpressionEnd);
this.ltoken.set (0, J.script.T.tokenSetProperty);
this.setEqualPt = 0;
}break;
case 1048586:
this.braceCount++;
if (this.braceCount == 1 && this.parenCount == 0 && this.checkFlowStartBrace (false)) {
this.isEndOfCommand = true;
if (this.flowContext != null) this.flowContext.forceEndIf = false;
return 2;
}case 269484048:
this.parenCount++;
if (this.nTokens > 1 && (this.lastToken.tok == 135280132 || this.lastToken.tok == 135369224 || this.lastToken.tok == 135369225)) this.nSemiSkip += 2;
break;
case 1048590:
if (this.iBrace > 0 && this.parenCount == 0 && this.braceCount == 0) {
this.ichBrace = this.ichToken;
if (this.nTokens == 0) {
this.braceCount = this.parenCount = 1;
} else {
this.braceCount = this.parenCount = this.nSemiSkip = 0;
if (this.theToken.tok != 102411 && this.theToken.tok != 102413) this.vBraces.addLast (this.theToken);
this.iBrace++;
this.isEndOfCommand = true;
this.ichEnd = this.ichToken;
return 2;
}}this.braceCount--;
case 269484049:
this.parenCount--;
if (this.parenCount < 0) return this.ERROR (16, ident);
if (this.parenCount == 0) this.nSemiSkip = 0;
if (this.needRightParen) {
this.addTokenToPrefix (J.script.T.tokenRightParen);
this.needRightParen = false;
}break;
case 269484096:
if (this.ichToken > 0 && Character.isWhitespace (this.script.charAt (this.ichToken - 1))) this.addTokenToPrefix (J.script.T.tokenSpaceBeforeSquare);
this.bracketCount++;
break;
case 269484097:
this.bracketCount--;
if (this.bracketCount < 0) return this.ERROR (16, "]");
}
return 0;
}, $fz.isPrivate = true, $fz), "~S");
$_M(c$, "tokenizePlusPlus",
($fz = function (tok, isPlusPlusX) {
if (isPlusPlusX) {
this.setCommand (J.script.T.tokenSet);
this.ltoken.add (0, this.tokenCommand);
}this.nTokens = this.ltoken.size ();
this.addTokenToPrefix (J.script.T.tokenEquals);
this.setEqualPt = 0;
for (var i = 1; i < this.nTokens; i++) this.addTokenToPrefix (this.ltoken.get (i));
this.addTokenToPrefix (tok == 269484225 ? J.script.T.tokenMinus : J.script.T.tokenPlus);
this.addTokenToPrefix (J.script.T.i (1));
}, $fz.isPrivate = true, $fz), "~N,~B");
$_M(c$, "checkNewSetCommand",
($fz = function () {
var name = this.ltoken.get (0).value.toString ();
if (!this.isContextVariable (name.toLowerCase ())) return false;
var t = this.setNewSetCommand (false, name);
this.setCommand (J.script.T.tokenSet);
this.ltoken.add (0, this.tokenCommand);
this.ltoken.set (1, t);
return true;
}, $fz.isPrivate = true, $fz));
$_M(c$, "parseCommandParameter",
($fz = function (ident) {
this.nTokens = this.ltoken.size ();
switch (this.tokCommand) {
case 0:
this.lastToken = J.script.T.tokenOff;
this.ichCurrentCommand = this.ichEnd = this.ichToken;
this.setCommand (this.theToken);
if (J.script.T.tokAttr (this.tokCommand, 102400)) {
this.lastFlowCommand = this.tokenCommand;
}var ret = this.checkFlowEndBrace ();
if (ret == 4) return 4;
else if (ret == 2) {
this.isEndOfCommand = true;
this.cchToken = 0;
return 2;
}if (J.script.T.tokAttr (this.tokCommand, 102400)) {
if (!this.checkFlowCommand (this.tokenCommand.value)) return 4;
this.theToken = this.tokenCommand;
if (this.theTok == 102411) {
this.addTokenToPrefix (this.tokenCommand);
this.theToken = J.script.T.tokenLeftParen;
}break;
}if (this.theTok == 269484066) {
this.braceCount++;
this.isEndOfCommand = true;
break;
}if (this.theTok == 1048590) {
this.vBraces.addLast (this.tokenCommand);
this.iBrace++;
this.tokCommand = 0;
return 2;
}if (this.theTok != 1048586) this.lastFlowCommand = null;
if (J.script.T.tokAttr (this.tokCommand, 4096)) break;
this.isSetBrace = (this.theTok == 1048586);
if (this.isSetBrace) {
if (!this.lookingAtSetBraceSyntax ()) {
this.isEndOfCommand = true;
if (this.flowContext != null) this.flowContext.forceEndIf = false;
}} else {
switch (this.theTok) {
case 269484226:
case 269484225:
this.tokInitialPlusPlus = this.theTok;
this.tokCommand = 0;
return 2;
case 1073741824:
case 36868:
case 1060866:
case 269484048:
break;
default:
if (!J.script.T.tokAttr (this.theTok, 1073741824) && !J.script.T.tokAttr (this.theTok, 536870912) && !this.isContextVariable (ident)) {
this.commandExpected ();
return 4;
}}
}this.theToken = this.setNewSetCommand (this.isSetBrace, ident);
break;
case 102412:
switch (this.nTokens) {
case 1:
if (this.theTok != 269484048) return this.ERROR (15, "(");
break;
case 2:
if (this.theTok != 269484049) (this.tokenCommand).name0 = ident;
this.addContextVariable (ident);
break;
case 3:
if (this.theTok != 269484049) return this.ERROR (15, ")");
this.isEndOfCommand = true;
this.ichEnd = this.ichToken + 1;
this.flowContext.setLine ();
break;
default:
return this.ERROR (0);
}
break;
case 102436:
case 135368713:
if (this.tokenCommand.intValue == 0) {
if (this.nTokens != 1) break;
this.tokenCommand.value = ident;
return 2;
}if (this.nTokens == 1) {
if (this.thisFunction != null) this.vFunctionStack.add (0, this.thisFunction);
this.thisFunction = (this.tokCommand == 102436 ? J.script.ScriptCompiler.newScriptParallelProcessor (ident, this.tokCommand) : new J.script.ScriptFunction (ident, this.tokCommand));
this.htUserFunctions.put (ident, Boolean.TRUE);
this.flowContext.setFunction (this.thisFunction);
break;
}if (this.nTokens == 2) {
if (this.theTok != 269484048) return this.ERROR (15, "(");
break;
}if (this.nTokens == 3 && this.theTok == 269484049) break;
if (this.nTokens % 2 == 0) {
if (this.theTok != 269484080 && this.theTok != 269484049) return this.ERROR (15, ")");
break;
}this.thisFunction.addVariable (ident, true);
break;
case 102411:
if (this.nTokens > 1 && this.parenCount == 0 && this.braceCount == 0 && this.theTok == 269484066) {
this.addTokenToPrefix (J.script.T.tokenRightParen);
this.braceCount = 1;
this.isEndOfCommand = true;
this.cchToken = 0;
return 2;
}break;
case 102413:
if (this.nTokens > 1) {
this.braceCount = 1;
this.isEndOfCommand = true;
this.cchToken = 0;
return 2;
}break;
case 364547:
if (this.nTokens == 1 && this.theTok != 135369225) {
this.isEndOfCommand = true;
this.cchToken = 0;
return 2;
}if (this.nTokens != 1 || this.theTok != 135369225 && this.theTok != 1048586) return this.ERROR (0);
this.replaceCommand (this.flowContext.token = J.script.ContextToken.newCmd (102402, "elseif"));
this.tokCommand = 102402;
return 2;
case 36868:
if (this.nTokens != 1) break;
this.addContextVariable (ident);
this.replaceCommand (J.script.T.tokenSetVar);
this.tokCommand = 1085443;
break;
case 1150985:
if (this.nTokens != 1) return this.ERROR (0);
if (!this.checkFlowEnd (this.theTok, ident, this.ichCurrentCommand)) return 4;
if (this.theTok == 135368713 || this.theTok == 102436) {
return 2;
}break;
case 102410:
case 102406:
if (this.nTokens > 2 && this.braceCount == 0 && this.parenCount == 0) {
this.isEndOfCommand = true;
this.ichEnd = this.ichToken + 1;
this.flowContext.setLine ();
}break;
case 102402:
case 135369225:
if (this.nTokens > 2 && this.braceCount == 0 && this.parenCount == 0) {
this.isEndOfCommand = true;
this.ichEnd = this.ichToken + 1;
this.flowContext.setLine ();
}break;
case 102439:
this.isEndOfCommand = true;
this.ichEnd = this.ichToken + 1;
this.flowContext.setLine ();
break;
case 135369224:
if (this.nTokens == 1) {
if (this.theTok != 269484048) return this.ERROR (19, ident);
this.forPoint3 = this.nSemiSkip = 0;
this.nSemiSkip += 2;
} else if (this.nTokens == 3 && this.tokAt (2) == 36868) {
this.addContextVariable (ident);
} else if ((this.nTokens == 3 || this.nTokens == 4) && this.theTok == 1073741980) {
this.nSemiSkip -= 2;
this.forPoint3 = 2;
this.addTokenToPrefix (this.theToken);
this.theToken = J.script.T.tokenLeftParen;
} else if (this.braceCount == 0 && this.parenCount == 0) {
this.isEndOfCommand = true;
this.ichEnd = this.ichToken + 1;
this.flowContext.setLine ();
}break;
case 1085443:
if (this.theTok == 1048586) this.setBraceCount++;
else if (this.theTok == 1048590) {
this.setBraceCount--;
if (this.isSetBrace && this.setBraceCount == 0 && this.ptNewSetModifier == 2147483647) this.ptNewSetModifier = this.nTokens + 1;
}if (this.nTokens == this.ptNewSetModifier) {
var token = this.tokenAt (0);
if (this.theTok == 269484048 || this.isUserFunction (token.value.toString ())) {
this.ltoken.set (0, this.setCommand (J.script.T.tv (1073741824, 0, token.value)));
this.setBraceCount = 0;
break;
}if (this.theTok != 1073741824 && this.theTok != 269484242 && this.theTok != 1060866 && (!J.script.T.tokAttr (this.theTok, 536870912))) {
if (this.isNewSet) this.commandExpected ();
else this.errorIntStr2 (18, "SET", ": " + ident);
return 4;
}if (this.nTokens == 1 && (this.lastToken.tok == 269484226 || this.lastToken.tok == 269484225)) {
this.replaceCommand (J.script.T.tokenSet);
this.addTokenToPrefix (this.lastToken);
break;
}}break;
case 135271426:
if (this.theTok == 1060866 && (this.nTokens == 1 || this.lastToken.tok == 1073741940 || this.lastToken.tok == 1073742152)) {
this.addTokenToPrefix (J.script.T.tokenDefineString);
return 2;
}if (this.theTok == 1073741848) this.iHaveQuotedString = false;
break;
case 1610625028:
case 12294:
case 12295:
case 135280132:
case 12291:
case 1060866:
if (this.tokCommand == 1060866) {
if (this.nTokens == 1) {
if (this.theTok != 1073741824) {
if (this.preDefining) {
if (!J.script.T.tokAttr (this.theTok, 3145728)) {
this.errorStr2 ("ERROR IN Token.java or JmolConstants.java -- the following term was used in JmolConstants.java but not listed as predefinedset in Token.java: " + ident, null);
return 4;
}} else if (J.script.T.tokAttr (this.theTok, 3145728)) {
J.util.Logger.warn ("WARNING: predefined term '" + ident + "' has been redefined by the user until the next file load.");
} else if (!this.isCheckOnly && ident.length > 1) {
J.util.Logger.warn ("WARNING: redefining " + ident + "; was " + this.theToken + "not all commands may continue to be functional for the life of the applet!");
this.theTok = this.theToken.tok = 1073741824;
J.script.T.addToken (ident, this.theToken);
}}this.addTokenToPrefix (this.theToken);
this.lastToken = J.script.T.tokenComma;
return 2;
}if (this.nTokens == 2) {
if (this.theTok == 269484436) {
this.ltoken.add (0, J.script.T.tokenSet);
return 2;
}}}if (this.bracketCount == 0 && this.theTok != 1073741824 && !J.script.T.tokAttr (this.theTok, 1048576) && !J.script.T.tokAttr (this.theTok, 1073741824) && (this.theTok & 480) != this.theTok) return this.ERROR (9, ident);
break;
case 12289:
if (this.theTok != 1073741824 && this.theTok != 1048583 && !J.script.T.tokAttr (this.theTok, 1048576)) return this.ERROR (9, ident);
break;
case 135190:
case 135188:
case 135180:
var ch = this.charAt (this.ichToken + this.cchToken);
if (this.parenCount == 0 && this.bracketCount == 0 && ".:/\\+-!?".indexOf (ch) >= 0 && !(ch == '-' && ident.equals ("="))) this.checkUnquotedFileName ();
break;
case 4148:
if (this.nTokens == 2 && this.tokAt (1) == 1073742158 && this.theTok == 269484208) this.implicitString = true;
break;
}
return 0;
}, $fz.isPrivate = true, $fz), "~S");
c$.newScriptParallelProcessor = $_M(c$, "newScriptParallelProcessor",
($fz = function (name, tok) {
var jpp = J.api.Interface.getOptionInterface ("parallel.ScriptParallelProcessor");
jpp.set (name, tok);
return jpp;
}, $fz.isPrivate = true, $fz), "~S,~N");
$_M(c$, "setNewSetCommand",
($fz = function (isSetBrace, ident) {
this.tokCommand = 1085443;
this.isNewSet = (!isSetBrace && !this.isUserFunction (ident));
this.setBraceCount = (isSetBrace ? 1 : 0);
this.bracketCount = 0;
this.setEqualPt = 2147483647;
this.ptNewSetModifier = (this.isNewSet ? (ident.equals ("(") ? 2 : 1) : 2147483647);
return ((isSetBrace || this.theToken.tok == 269484226 || this.theToken.tok == 269484225) ? this.theToken : J.script.T.o (1073741824, ident));
}, $fz.isPrivate = true, $fz), "~B,~S");
$_M(c$, "checkUnquotedFileName",
($fz = function () {
var ichT = this.ichToken;
var ch;
while (++ichT < this.cchScript && !Character.isWhitespace (ch = this.script.charAt (ichT)) && ch != '#' && ch != ';' && ch != '}') {
}
var name = this.script.substring (this.ichToken, ichT).$replace ('\\', '/');
this.cchToken = ichT - this.ichToken;
this.theToken = J.script.T.o (4, name);
}, $fz.isPrivate = true, $fz));
$_M(c$, "checkFlowStartBrace",
($fz = function (atEnd) {
if ((!J.script.T.tokAttr (this.tokCommand, 102400) || this.tokCommand == 102407 || this.tokCommand == 102408)) return false;
if (atEnd) {
if (this.tokenCommand.tok != 102411 && this.tokenCommand.tok != 102413) {
this.iBrace++;
this.vBraces.addLast (this.tokenCommand);
this.lastFlowCommand = null;
}this.parenCount = this.braceCount = 0;
}return true;
}, $fz.isPrivate = true, $fz), "~B");
$_M(c$, "checkFlowEndBrace",
($fz = function () {
if (this.iBrace <= 0 || this.vBraces.get (this.iBrace - 1).tok != 1048590) return 0;
this.vBraces.remove (--this.iBrace);
var token = this.vBraces.remove (--this.iBrace);
if (this.theTok == 1048586) {
this.braceCount--;
this.parenCount--;
}if (token.tok == 266280) {
this.vPush.remove (--this.pushCount);
this.addTokenToPrefix (this.setCommand (J.script.ContextToken.newContext (true)));
this.isEndOfCommand = true;
return 2;
}switch (this.flowContext == null ? 0 : this.flowContext.token.tok) {
case 135369225:
case 102402:
case 364547:
if (this.tokCommand == 364547 || this.tokCommand == 102402) return 0;
break;
case 102410:
case 102411:
case 102413:
if (this.tokCommand == 102411 || this.tokCommand == 102413) return 0;
}
return this.forceFlowEnd (token);
}, $fz.isPrivate = true, $fz));
$_M(c$, "forceFlowEnd",
($fz = function (token) {
var t0 = this.tokenCommand;
this.setCommand (J.script.T.o (1150985, "end"));
if (!this.checkFlowCommand ("end")) return 0;
this.addTokenToPrefix (this.tokenCommand);
switch (token.tok) {
case 135369225:
case 364547:
case 102402:
token = J.script.T.tokenIf;
break;
case 102413:
case 102411:
token = J.script.T.tokenSwitch;
break;
default:
token = J.script.T.getTokenFromName (token.value);
break;
}
if (!this.checkFlowEnd (token.tok, token.value, this.ichBrace)) return 4;
if (token.tok != 135368713 && token.tok != 102436 && token.tok != 364558) this.addTokenToPrefix (token);
this.setCommand (t0);
return 2;
}, $fz.isPrivate = true, $fz), "J.script.T");
c$.isBreakableContext = $_M(c$, "isBreakableContext",
function (tok) {
return tok == 135369224 || tok == 102439 || tok == 102406 || tok == 102411 || tok == 102413;
}, "~N");
$_M(c$, "checkFlowCommand",
($fz = function (ident) {
var pt = this.lltoken.size ();
var isEnd = false;
var isNew = true;
switch (this.tokCommand) {
case 135368713:
case 102436:
if (this.flowContext != null) return this.errorStr (1, J.script.T.nameOf (this.tokCommand));
break;
case 1150985:
if (this.flowContext == null) return this.errorStr (1, ident);
isEnd = true;
if (this.flowContext.token.tok != 135368713 && this.flowContext.token.tok != 102436 && this.flowContext.token.tok != 364558) this.setCommand (J.script.T.tv (this.tokCommand, (this.flowContext.ptDefault > 0 ? this.flowContext.ptDefault : -this.flowContext.pt0), ident));
break;
case 364558:
case 102412:
break;
case 135369224:
case 135369225:
case 102439:
case 102410:
case 102406:
break;
case 364548:
isEnd = true;
if (this.flowContext == null || this.flowContext.token.tok != 135369225 && this.flowContext.token.tok != 102439 && this.flowContext.token.tok != 364547 && this.flowContext.token.tok != 102402) return this.errorStr (1, ident);
break;
case 364547:
if (this.flowContext == null || this.flowContext.token.tok != 135369225 && this.flowContext.token.tok != 102402) return this.errorStr (1, ident);
this.flowContext.token.intValue = this.flowContext.setPt0 (pt, false);
break;
case 102407:
case 102408:
isNew = false;
var f = (this.flowContext == null ? null : this.flowContext.getBreakableContext (0));
if (this.tokCommand == 102408) while (f != null && f.token.tok != 135369224 && f.token.tok != 102406) f = f.getParent ();
if (f == null) return this.errorStr (1, ident);
this.setCommand (J.script.T.tv (this.tokCommand, f.pt0, ident));
break;
case 102413:
if (this.flowContext == null || this.flowContext.token.tok != 102410 && this.flowContext.token.tok != 102411 && this.flowContext.ptDefault > 0) return this.errorStr (1, ident);
this.flowContext.token.intValue = this.flowContext.setPt0 (pt, true);
break;
case 102411:
if (this.flowContext == null || this.flowContext.token.tok != 102410 && this.flowContext.token.tok != 102411 && this.flowContext.token.tok != 102413) return this.errorStr (1, ident);
this.flowContext.token.intValue = this.flowContext.setPt0 (pt, false);
break;
case 102402:
if (this.flowContext == null || this.flowContext.token.tok != 135369225 && this.flowContext.token.tok != 102402 && this.flowContext.token.tok != 364547) return this.errorStr (1, "elseif");
this.flowContext.token.intValue = this.flowContext.setPt0 (pt, false);
break;
}
if (isEnd) {
this.flowContext.token.intValue = (this.tokCommand == 102412 ? -pt : pt);
if (this.tokCommand == 364548) this.flowContext = this.flowContext.getParent ();
} else if (isNew) {
var ct = J.script.ContextToken.newCmd (this.tokCommand, this.tokenCommand.value);
if (this.tokCommand == 102410) ct.addName ("_var");
this.setCommand (ct);
switch (this.tokCommand) {
case 364558:
this.flowContext = new J.script.ScriptFlowContext (this, ct, pt, this.flowContext);
if (this.thisFunction != null) this.vFunctionStack.add (0, this.thisFunction);
this.thisFunction = J.script.ScriptCompiler.newScriptParallelProcessor ("", this.tokCommand);
this.flowContext.setFunction (this.thisFunction);
this.pushCount++;
this.vPush.addLast (ct);
break;
case 364547:
case 102402:
this.flowContext.token = ct;
break;
case 102411:
case 102413:
ct.contextVariables = this.flowContext.token.contextVariables;
this.flowContext.token = ct;
break;
case 102439:
case 135369224:
case 102406:
case 102412:
this.pushCount++;
this.vPush.addLast (ct);
case 135369225:
case 102410:
default:
this.flowContext = new J.script.ScriptFlowContext (this, ct, pt, this.flowContext);
break;
}
}return true;
}, $fz.isPrivate = true, $fz), "~S");
$_M(c$, "checkFlowEnd",
($fz = function (tok, ident, pt1) {
if (this.flowContext == null || this.flowContext.token.tok != tok) {
var isOK = true;
switch (tok) {
case 135369225:
isOK = (this.flowContext.token.tok == 364547 || this.flowContext.token.tok == 102402);
break;
case 102410:
isOK = (this.flowContext.token.tok == 102411 || this.flowContext.token.tok == 102413);
break;
default:
isOK = false;
}
if (!isOK) return this.errorStr (1, "end " + ident);
}switch (tok) {
case 135369225:
case 102410:
break;
case 102412:
case 135369224:
case 102439:
case 102406:
this.vPush.remove (--this.pushCount);
break;
case 102436:
case 135368713:
case 364558:
if (!this.isCheckOnly) {
this.addTokenToPrefix (J.script.T.o (tok, this.thisFunction));
J.script.ScriptFunction.setFunction (this.thisFunction, this.script, pt1, this.lltoken.size (), this.lineNumbers, this.lineIndices, this.lltoken);
}this.thisFunction = (this.vFunctionStack.size () == 0 ? null : this.vFunctionStack.remove (0));
this.tokenCommand.intValue = 0;
if (tok == 364558) this.vPush.remove (--this.pushCount);
break;
default:
return this.errorStr (19, "end " + ident);
}
this.flowContext = this.flowContext.getParent ();
return true;
}, $fz.isPrivate = true, $fz), "~N,~S,~N");
$_M(c$, "getData",
($fz = function (key) {
this.addTokenToPrefix (J.script.T.o (4, key));
this.ichToken += key.length + 2;
if (this.charAt (this.ichToken) == '\r') {
this.lineCurrent++;
this.ichToken++;
}if (this.charAt (this.ichToken) == '\n') {
this.lineCurrent++;
this.ichToken++;
}var i = this.script.indexOf (this.chFirst + key + this.chFirst, this.ichToken) - 4;
if (i < 0 || !this.script.substring (i, i + 4).equalsIgnoreCase ("END ")) return false;
var str = this.script.substring (this.ichToken, i);
this.incrementLineCount (str);
this.addTokenToPrefix (J.script.T.o (135270407, str));
this.addTokenToPrefix (J.script.T.o (1073741824, "end"));
this.addTokenToPrefix (J.script.T.o (4, key));
this.cchToken = i - this.ichToken + key.length + 6;
return true;
}, $fz.isPrivate = true, $fz), "~S");
$_M(c$, "incrementLineCount",
($fz = function (str) {
var ch;
var pt = str.indexOf ('\r');
var pt2 = str.indexOf ('\n');
if (pt < 0 && pt2 < 0) return 0;
var n = this.lineCurrent;
if (pt < 0 || pt2 < pt) pt = pt2;
for (var i = str.length; --i >= pt; ) {
if ((ch = str.charAt (i)) == '\n' || ch == '\r') this.lineCurrent++;
}
return this.lineCurrent - n;
}, $fz.isPrivate = true, $fz), "~S");
c$.isSpaceOrTab = $_M(c$, "isSpaceOrTab",
($fz = function (ch) {
return ch == ' ' || ch == '\t';
}, $fz.isPrivate = true, $fz), "~S");
$_M(c$, "eol",
($fz = function (ch) {
return (ch == '\0' || ch == '\r' || ch == '\n' || ch == ';' && this.nSemiSkip <= 0);
}, $fz.isPrivate = true, $fz), "~S");
$_M(c$, "lookingAtSetBraceSyntax",
($fz = function () {
var ichT = this.ichToken;
var nParen = 1;
while (++ichT < this.cchScript && nParen > 0) {
switch (this.script.charAt (ichT)) {
case '{':
nParen++;
break;
case '}':
nParen--;
break;
}
}
if (this.charAt (ichT) == '[' && ++nParen == 1) while (++ichT < this.cchScript && nParen > 0) {
switch (this.script.charAt (ichT)) {
case '[':
nParen++;
break;
case ']':
nParen--;
break;
}
}
if (this.charAt (ichT) == '.' && nParen == 0) {
return true;
}return false;
}, $fz.isPrivate = true, $fz));
$_M(c$, "lookingAtString",
($fz = function (allowPrime) {
if (this.ichToken + 2 > this.cchScript) return false;
this.chFirst = this.script.charAt (this.ichToken);
if (this.chFirst != '"' && (!allowPrime || this.chFirst != '\'')) return false;
var ichT = this.ichToken;
var ch;
var previousCharBackslash = false;
while (++ichT < this.cchScript) {
ch = this.script.charAt (ichT);
if (ch == this.chFirst && !previousCharBackslash) break;
previousCharBackslash = (ch == '\\' ? !previousCharBackslash : false);
}
if (ichT == this.cchScript) {
this.cchToken = -1;
this.ichEnd = this.cchScript;
} else {
this.cchToken = ++ichT - this.ichToken;
}return true;
}, $fz.isPrivate = true, $fz), "~B");
$_M(c$, "getUnescapedStringLiteral",
($fz = function (isFileName) {
if (isFileName) {
var s = this.script.substring (this.ichToken + 1, this.ichToken + this.cchToken - 1);
if (s.indexOf ("\\u") >= 0) s = J.util.Escape.unescapeUnicode (s);
return s;
}var sb = J.util.SB.newN (this.cchToken - 2);
var ichMax = this.ichToken + this.cchToken - 1;
var ich = this.ichToken + 1;
while (ich < ichMax) {
var ch = this.script.charAt (ich++);
if (ch == '\\' && ich < ichMax) {
ch = this.script.charAt (ich++);
switch (ch) {
case 'n':
ch = '\n';
break;
case 't':
ch = '\t';
break;
case 'r':
ch = '\r';
case '"':
case '\\':
case '\'':
break;
case 'x':
case 'u':
var digitCount = ch == 'x' ? 2 : 4;
if (ich < ichMax) {
var unicode = 0;
for (var k = digitCount; --k >= 0 && ich < ichMax; ) {
var chT = this.script.charAt (ich);
var hexit = J.util.Escape.getHexitValue (chT);
if (hexit < 0) break;
unicode <<= 4;
unicode += hexit;
++ich;
}
ch = String.fromCharCode (unicode);
}}
}sb.appendC (ch);
}
return sb.toString ();
}, $fz.isPrivate = true, $fz), "~B");
$_M(c$, "lookingAtLoadFormat",
($fz = function () {
var ichT = this.ichToken;
var allchar = J.viewer.Viewer.isDatabaseCode (this.charAt (ichT));
var ch;
while ((Character.isLetterOrDigit (ch = this.charAt (ichT)) && (allchar || Character.isLetter (ch)) || allchar && (!this.eol (ch) && !Character.isWhitespace (ch)))) ++ichT;
if (!allchar && ichT == this.ichToken || !J.script.ScriptCompiler.isSpaceOrTab (ch)) return false;
this.cchToken = ichT - this.ichToken;
return true;
}, $fz.isPrivate = true, $fz));
$_M(c$, "lookingAtImpliedString",
($fz = function (allowSpace, allowEquals, allowSptParen) {
var ichT = this.ichToken;
var ch = this.script.charAt (ichT);
var isID = (this.lastToken.tok == 1074790550);
var parseVariables = (isID || !J.script.T.tokAttr (this.tokCommand, 20480) && (this.tokCommand & 1) == 1);
var isVariable = (ch == '@');
var isMath = (isVariable && ichT + 3 < this.cchScript && this.script.charAt (ichT + 1) == '{');
if (isMath && parseVariables) {
ichT = J.util.TextFormat.ichMathTerminator (this.script, this.ichToken + 1, this.cchScript);
return (!isID && ichT != this.cchScript && (this.cchToken = ichT + 1 - this.ichToken) > 0);
}var ptSpace = -1;
var ptLastChar = -1;
var isOK = true;
var parenpt = 0;
while (isOK && !this.eol (ch = this.charAt (ichT))) {
switch (ch) {
case '(':
if (!allowSptParen) {
if (ichT >= 5 && (this.script.substring (ichT - 4, ichT).equals (".spt") || this.script.substring (ichT - 4, ichT).equals (".png") || this.script.substring (ichT - 5, ichT).equals (".pngj"))) {
isOK = false;
continue;
}}break;
case '=':
if (!allowEquals) {
isOK = false;
continue;
}break;
case '{':
parenpt++;
break;
case '}':
parenpt--;
if (parenpt < 0 && (this.braceCount > 0 || this.iBrace > 0)) {
isOK = false;
continue;
}break;
default:
if (Character.isWhitespace (ch)) {
if (ptSpace < 0) ptSpace = ichT;
} else {
ptLastChar = ichT;
}break;
}
++ichT;
}
if (allowSpace) ichT = ptLastChar + 1;
else if (ptSpace > 0) ichT = ptSpace;
if (isVariable && (!allowSpace || ptSpace < 0 && parenpt <= 0 && ichT - this.ichToken > 1)) {
return false;
}return (this.cchToken = ichT - this.ichToken) > 0;
}, $fz.isPrivate = true, $fz), "~B,~B,~B");
$_M(c$, "lookingAtExponential",
($fz = function () {
if (this.ichToken == this.cchScript) return NaN;
var ichT = this.ichToken;
var pt0 = ichT;
if (this.script.charAt (ichT) == '-') ++ichT;
var isOK = false;
var ch = 'X';
while (Character.isDigit (ch = this.charAt (ichT))) {
++ichT;
isOK = true;
}
if (ichT < this.cchScript && ch == '.') ++ichT;
while (Character.isDigit (ch = this.charAt (ichT))) {
++ichT;
isOK = true;
}
if (ichT == this.cchScript || !isOK) return NaN;
isOK = (ch != 'E' && ch != 'e');
if (isOK || ++ichT == this.cchScript) return NaN;
ch = this.script.charAt (ichT);
if (ch == '-' || ch == '+') ichT++;
while (Character.isDigit (this.charAt (ichT))) {
ichT++;
isOK = true;
}
if (!isOK) return NaN;
this.cchToken = ichT - this.ichToken;
return J.util.Parser.dVal (this.script.substring (pt0, ichT));
}, $fz.isPrivate = true, $fz));
$_M(c$, "lookingAtDecimal",
($fz = function () {
if (this.ichToken == this.cchScript) return false;
var ichT = this.ichToken;
if (this.script.charAt (ichT) == '-') ++ichT;
var digitSeen = false;
var ch;
while (Character.isDigit (ch = this.charAt (ichT++))) digitSeen = true;
if (ch != '.') return false;
var ch1;
if (!this.eol (ch1 = this.charAt (ichT))) {
if (Character.isLetter (ch1) || ch1 == '?' || ch1 == '*') return false;
if (Character.isLetter (ch1 = this.charAt (ichT + 1)) || ch1 == '?') return false;
}while (Character.isDigit (this.charAt (ichT))) {
++ichT;
digitSeen = true;
}
this.cchToken = ichT - this.ichToken;
return digitSeen;
}, $fz.isPrivate = true, $fz));
$_M(c$, "lookingAtSeqcode",
($fz = function () {
var ichT = this.ichToken;
var ch;
if (this.charAt (ichT + 1) == '^' && this.script.charAt (ichT) == '*') {
ch = '^';
++ichT;
} else {
if (this.script.charAt (ichT) == '-') ++ichT;
while (Character.isDigit (ch = this.charAt (ichT))) ++ichT;
}if (ch != '^') return false;
ichT++;
if (ichT == this.cchScript) ch = ' ';
else ch = this.script.charAt (ichT++);
if (ch != ' ' && ch != '*' && ch != '?' && !Character.isLetter (ch)) return false;
this.cchToken = ichT - this.ichToken;
return true;
}, $fz.isPrivate = true, $fz));
$_M(c$, "lookingAtInteger",
($fz = function () {
if (this.ichToken == this.cchScript) return 2147483647;
var ichT = this.ichToken;
if (this.script.charAt (this.ichToken) == '-') ++ichT;
var ichBeginDigits = ichT;
while (Character.isDigit (this.charAt (ichT))) ++ichT;
if (ichBeginDigits == ichT) return 2147483647;
this.cchToken = ichT - this.ichToken;
try {
var val = Integer.parseInt (this.script.substring (this.ichToken, ichT));
return val;
} catch (e) {
if (Clazz.exceptionOf (e, NumberFormatException)) {
} else {
throw e;
}
}
return 2147483647;
}, $fz.isPrivate = true, $fz));
$_M(c$, "lookingAtBitset",
function () {
if (this.script.indexOf ("({null})", this.ichToken) == this.ichToken) {
this.cchToken = 8;
return new J.util.BS ();
}var ichT;
if (this.ichToken + 4 > this.cchScript || this.script.charAt (this.ichToken + 1) != '{' || (ichT = this.script.indexOf ("}", this.ichToken)) < 0 || ichT + 1 == this.cchScript) return null;
var bs = J.util.Escape.uB (this.script.substring (this.ichToken, ichT + 2));
if (bs != null) this.cchToken = ichT + 2 - this.ichToken;
return bs;
});
$_M(c$, "lookingAtObjectID",
($fz = function () {
var allowWildID = (this.nTokens == 1);
var ichT = this.ichToken;
if (this.charAt (ichT) != '$') return false;
if (this.charAt (++ichT) == '"') return false;
while (ichT < this.cchScript) {
var ch;
if (Character.isWhitespace (ch = this.script.charAt (ichT))) {
if (ichT == this.ichToken + 1) return false;
break;
}if (!Character.isLetterOrDigit (ch)) {
switch (ch) {
default:
return false;
case '*':
if (!allowWildID) return false;
break;
case '~':
case '_':
break;
}
}ichT++;
}
this.cchToken = ichT - (++this.ichToken);
return true;
}, $fz.isPrivate = true, $fz));
$_M(c$, "lookingAtLookupToken",
($fz = function (ichT) {
if (ichT == this.cchScript) return false;
var ichT0 = ichT;
this.tokLastMath = 0;
var ch;
switch (ch = this.script.charAt (ichT++)) {
case '-':
case '+':
case '&':
case '|':
case '*':
if (ichT < this.cchScript) {
if (this.script.charAt (ichT) == ch) {
++ichT;
if (ch == '-' || ch == '+') break;
if (ch == '&' && this.charAt (ichT) == ch) ++ichT;
} else if (this.script.charAt (ichT) == '=') {
++ichT;
}}this.tokLastMath = 1;
break;
case '/':
if (this.charAt (ichT) == '/') break;
case '\\':
case '!':
if (this.charAt (ichT) == '=') ++ichT;
this.tokLastMath = 1;
break;
case ')':
case ']':
case '}':
case '.':
break;
case '@':
case '{':
this.tokLastMath = 2;
break;
case ':':
this.tokLastMath = 1;
break;
case '(':
case ',':
case '$':
case ';':
case '[':
case '%':
this.tokLastMath = 1;
break;
case '<':
case '=':
case '>':
if ((ch = this.charAt (ichT)) == '<' || ch == '=' || ch == '>') ++ichT;
this.tokLastMath = 1;
break;
default:
if (!Character.isLetter (ch)) return false;
case '~':
case '_':
case '\'':
case '?':
if (ch == '?') this.tokLastMath = 1;
while (Character.isLetterOrDigit (ch = this.charAt (ichT)) || ch == '_' || ch == '?' || ch == '~' || ch == '\'' || ch == '\\' && this.charAt (ichT + 1) == '?' || ch == '^' && ichT > ichT0 && Character.isDigit (this.charAt (ichT - 1))) ++ichT;
break;
}
this.cchToken = ichT - ichT0;
return true;
}, $fz.isPrivate = true, $fz), "~N");
$_M(c$, "lookForSyncID",
($fz = function () {
var ch;
if ((ch = this.charAt (this.ichToken)) == '"' || ch == '@' || ch == '\0') return false;
var ichT = this.ichToken;
while (!J.script.ScriptCompiler.isSpaceOrTab (ch = this.script.charAt (ichT)) && ch != '#' && ch != '}' && !this.eol (ch)) ++ichT;
this.cchToken = ichT - this.ichToken;
return true;
}, $fz.isPrivate = true, $fz));
$_M(c$, "ERROR",
($fz = function (error) {
this.errorIntStr2 (error, null, null);
return 4;
}, $fz.isPrivate = true, $fz), "~N");
$_M(c$, "ERROR",
($fz = function (error, value) {
this.errorStr (error, value);
return 4;
}, $fz.isPrivate = true, $fz), "~N,~S");
$_M(c$, "handleError",
($fz = function () {
this.errorType = this.errorMessage;
this.errorLine = this.script.substring (this.ichCurrentCommand, this.ichEnd <= this.ichCurrentCommand ? this.ichToken : this.ichEnd);
var lineInfo = (this.ichToken < this.ichEnd ? this.errorLine.substring (0, this.ichToken - this.ichCurrentCommand) + " >>>> " + this.errorLine.substring (this.ichToken - this.ichCurrentCommand) : this.errorLine) + " <<<<";
this.errorMessage = J.i18n.GT._ ("script compiler ERROR: ") + this.errorMessage + J.script.ScriptEvaluator.getErrorLineMessage (null, this.filename, this.lineCurrent, this.iCommand, lineInfo);
if (!this.isSilent) {
this.ichToken = Math.max (this.ichEnd, this.ichToken);
while (!this.lookingAtEndOfLine () && !this.lookingAtTerminator ()) this.ichToken++;
this.errorLine = this.script.substring (this.ichCurrentCommand, this.ichToken);
this.viewer.addCommand (this.errorLine + "#??");
J.util.Logger.error (this.errorMessage);
}return false;
}, $fz.isPrivate = true, $fz));
Clazz.defineStatics (c$,
"OK", 0,
"OK2", 1,
"CONTINUE", 2,
"EOL", 3,
"$ERROR", 4);
});
| DeepLit/WHG | root/static/js/jsmol/j2s/J/script/ScriptCompiler.js | JavaScript | apache-2.0 | 67,931 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_15.html">Class Test_AbaRouteValidator_15</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_32626_bad
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_15.html?line=3025#src-3025" >testAbaNumberCheck_32626_bad</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:44:44
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_32626_bad</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/exceptions/AbaRouteValidationException.html?id=22119#AbaRouteValidationException" title="AbaRouteValidationException" name="sl-43">com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/ErrorCodes.html?id=22119#ErrorCodes" title="ErrorCodes" name="sl-42">com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes</a>
</td>
<td>
<span class="sortValue">0.5714286</span>57.1%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="57.1% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:57.1%"></div></div></div> </td>
</tr>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=22119#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.29411766</span>29.4%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="29.4% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:29.4%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html> | dcarda/aba.route.validator | target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_15_testAbaNumberCheck_32626_bad_h2f.html | HTML | apache-2.0 | 10,985 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/ec2/EC2Request.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/ec2/model/Filter.h>
#include <utility>
namespace Aws
{
namespace EC2
{
namespace Model
{
/**
*/
class AWS_EC2_API DescribeLocalGatewayVirtualInterfacesRequest : public EC2Request
{
public:
DescribeLocalGatewayVirtualInterfacesRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "DescribeLocalGatewayVirtualInterfaces"; }
Aws::String SerializePayload() const override;
protected:
void DumpBodyToUrl(Aws::Http::URI& uri ) const override;
public:
/**
* <p>The IDs of the virtual interfaces.</p>
*/
inline const Aws::Vector<Aws::String>& GetLocalGatewayVirtualInterfaceIds() const{ return m_localGatewayVirtualInterfaceIds; }
/**
* <p>The IDs of the virtual interfaces.</p>
*/
inline bool LocalGatewayVirtualInterfaceIdsHasBeenSet() const { return m_localGatewayVirtualInterfaceIdsHasBeenSet; }
/**
* <p>The IDs of the virtual interfaces.</p>
*/
inline void SetLocalGatewayVirtualInterfaceIds(const Aws::Vector<Aws::String>& value) { m_localGatewayVirtualInterfaceIdsHasBeenSet = true; m_localGatewayVirtualInterfaceIds = value; }
/**
* <p>The IDs of the virtual interfaces.</p>
*/
inline void SetLocalGatewayVirtualInterfaceIds(Aws::Vector<Aws::String>&& value) { m_localGatewayVirtualInterfaceIdsHasBeenSet = true; m_localGatewayVirtualInterfaceIds = std::move(value); }
/**
* <p>The IDs of the virtual interfaces.</p>
*/
inline DescribeLocalGatewayVirtualInterfacesRequest& WithLocalGatewayVirtualInterfaceIds(const Aws::Vector<Aws::String>& value) { SetLocalGatewayVirtualInterfaceIds(value); return *this;}
/**
* <p>The IDs of the virtual interfaces.</p>
*/
inline DescribeLocalGatewayVirtualInterfacesRequest& WithLocalGatewayVirtualInterfaceIds(Aws::Vector<Aws::String>&& value) { SetLocalGatewayVirtualInterfaceIds(std::move(value)); return *this;}
/**
* <p>The IDs of the virtual interfaces.</p>
*/
inline DescribeLocalGatewayVirtualInterfacesRequest& AddLocalGatewayVirtualInterfaceIds(const Aws::String& value) { m_localGatewayVirtualInterfaceIdsHasBeenSet = true; m_localGatewayVirtualInterfaceIds.push_back(value); return *this; }
/**
* <p>The IDs of the virtual interfaces.</p>
*/
inline DescribeLocalGatewayVirtualInterfacesRequest& AddLocalGatewayVirtualInterfaceIds(Aws::String&& value) { m_localGatewayVirtualInterfaceIdsHasBeenSet = true; m_localGatewayVirtualInterfaceIds.push_back(std::move(value)); return *this; }
/**
* <p>The IDs of the virtual interfaces.</p>
*/
inline DescribeLocalGatewayVirtualInterfacesRequest& AddLocalGatewayVirtualInterfaceIds(const char* value) { m_localGatewayVirtualInterfaceIdsHasBeenSet = true; m_localGatewayVirtualInterfaceIds.push_back(value); return *this; }
/**
* <p>One or more filters.</p> <ul> <li> <p> <code>local-address</code> - The local
* address.</p> </li> <li> <p> <code>local-bgp-asn</code> - The Border Gateway
* Protocol (BGP) Autonomous System Number (ASN) of the local gateway.</p> </li>
* <li> <p> <code>local-gateway-id</code> - The ID of the local gateway.</p> </li>
* <li> <p> <code>local-gateway-virtual-interface-id</code> - The ID of the virtual
* interface.</p> </li> <li> <p>
* <code>local-gateway-virtual-interface-group-id</code> - The ID of the virtual
* interface group.</p> </li> <li> <p> <code>owner-id</code> - The ID of the Amazon
* Web Services account that owns the local gateway virtual interface.</p> </li>
* <li> <p> <code>peer-address</code> - The peer address.</p> </li> <li> <p>
* <code>peer-bgp-asn</code> - The peer BGP ASN.</p> </li> <li> <p>
* <code>vlan</code> - The ID of the VLAN.</p> </li> </ul>
*/
inline const Aws::Vector<Filter>& GetFilters() const{ return m_filters; }
/**
* <p>One or more filters.</p> <ul> <li> <p> <code>local-address</code> - The local
* address.</p> </li> <li> <p> <code>local-bgp-asn</code> - The Border Gateway
* Protocol (BGP) Autonomous System Number (ASN) of the local gateway.</p> </li>
* <li> <p> <code>local-gateway-id</code> - The ID of the local gateway.</p> </li>
* <li> <p> <code>local-gateway-virtual-interface-id</code> - The ID of the virtual
* interface.</p> </li> <li> <p>
* <code>local-gateway-virtual-interface-group-id</code> - The ID of the virtual
* interface group.</p> </li> <li> <p> <code>owner-id</code> - The ID of the Amazon
* Web Services account that owns the local gateway virtual interface.</p> </li>
* <li> <p> <code>peer-address</code> - The peer address.</p> </li> <li> <p>
* <code>peer-bgp-asn</code> - The peer BGP ASN.</p> </li> <li> <p>
* <code>vlan</code> - The ID of the VLAN.</p> </li> </ul>
*/
inline bool FiltersHasBeenSet() const { return m_filtersHasBeenSet; }
/**
* <p>One or more filters.</p> <ul> <li> <p> <code>local-address</code> - The local
* address.</p> </li> <li> <p> <code>local-bgp-asn</code> - The Border Gateway
* Protocol (BGP) Autonomous System Number (ASN) of the local gateway.</p> </li>
* <li> <p> <code>local-gateway-id</code> - The ID of the local gateway.</p> </li>
* <li> <p> <code>local-gateway-virtual-interface-id</code> - The ID of the virtual
* interface.</p> </li> <li> <p>
* <code>local-gateway-virtual-interface-group-id</code> - The ID of the virtual
* interface group.</p> </li> <li> <p> <code>owner-id</code> - The ID of the Amazon
* Web Services account that owns the local gateway virtual interface.</p> </li>
* <li> <p> <code>peer-address</code> - The peer address.</p> </li> <li> <p>
* <code>peer-bgp-asn</code> - The peer BGP ASN.</p> </li> <li> <p>
* <code>vlan</code> - The ID of the VLAN.</p> </li> </ul>
*/
inline void SetFilters(const Aws::Vector<Filter>& value) { m_filtersHasBeenSet = true; m_filters = value; }
/**
* <p>One or more filters.</p> <ul> <li> <p> <code>local-address</code> - The local
* address.</p> </li> <li> <p> <code>local-bgp-asn</code> - The Border Gateway
* Protocol (BGP) Autonomous System Number (ASN) of the local gateway.</p> </li>
* <li> <p> <code>local-gateway-id</code> - The ID of the local gateway.</p> </li>
* <li> <p> <code>local-gateway-virtual-interface-id</code> - The ID of the virtual
* interface.</p> </li> <li> <p>
* <code>local-gateway-virtual-interface-group-id</code> - The ID of the virtual
* interface group.</p> </li> <li> <p> <code>owner-id</code> - The ID of the Amazon
* Web Services account that owns the local gateway virtual interface.</p> </li>
* <li> <p> <code>peer-address</code> - The peer address.</p> </li> <li> <p>
* <code>peer-bgp-asn</code> - The peer BGP ASN.</p> </li> <li> <p>
* <code>vlan</code> - The ID of the VLAN.</p> </li> </ul>
*/
inline void SetFilters(Aws::Vector<Filter>&& value) { m_filtersHasBeenSet = true; m_filters = std::move(value); }
/**
* <p>One or more filters.</p> <ul> <li> <p> <code>local-address</code> - The local
* address.</p> </li> <li> <p> <code>local-bgp-asn</code> - The Border Gateway
* Protocol (BGP) Autonomous System Number (ASN) of the local gateway.</p> </li>
* <li> <p> <code>local-gateway-id</code> - The ID of the local gateway.</p> </li>
* <li> <p> <code>local-gateway-virtual-interface-id</code> - The ID of the virtual
* interface.</p> </li> <li> <p>
* <code>local-gateway-virtual-interface-group-id</code> - The ID of the virtual
* interface group.</p> </li> <li> <p> <code>owner-id</code> - The ID of the Amazon
* Web Services account that owns the local gateway virtual interface.</p> </li>
* <li> <p> <code>peer-address</code> - The peer address.</p> </li> <li> <p>
* <code>peer-bgp-asn</code> - The peer BGP ASN.</p> </li> <li> <p>
* <code>vlan</code> - The ID of the VLAN.</p> </li> </ul>
*/
inline DescribeLocalGatewayVirtualInterfacesRequest& WithFilters(const Aws::Vector<Filter>& value) { SetFilters(value); return *this;}
/**
* <p>One or more filters.</p> <ul> <li> <p> <code>local-address</code> - The local
* address.</p> </li> <li> <p> <code>local-bgp-asn</code> - The Border Gateway
* Protocol (BGP) Autonomous System Number (ASN) of the local gateway.</p> </li>
* <li> <p> <code>local-gateway-id</code> - The ID of the local gateway.</p> </li>
* <li> <p> <code>local-gateway-virtual-interface-id</code> - The ID of the virtual
* interface.</p> </li> <li> <p>
* <code>local-gateway-virtual-interface-group-id</code> - The ID of the virtual
* interface group.</p> </li> <li> <p> <code>owner-id</code> - The ID of the Amazon
* Web Services account that owns the local gateway virtual interface.</p> </li>
* <li> <p> <code>peer-address</code> - The peer address.</p> </li> <li> <p>
* <code>peer-bgp-asn</code> - The peer BGP ASN.</p> </li> <li> <p>
* <code>vlan</code> - The ID of the VLAN.</p> </li> </ul>
*/
inline DescribeLocalGatewayVirtualInterfacesRequest& WithFilters(Aws::Vector<Filter>&& value) { SetFilters(std::move(value)); return *this;}
/**
* <p>One or more filters.</p> <ul> <li> <p> <code>local-address</code> - The local
* address.</p> </li> <li> <p> <code>local-bgp-asn</code> - The Border Gateway
* Protocol (BGP) Autonomous System Number (ASN) of the local gateway.</p> </li>
* <li> <p> <code>local-gateway-id</code> - The ID of the local gateway.</p> </li>
* <li> <p> <code>local-gateway-virtual-interface-id</code> - The ID of the virtual
* interface.</p> </li> <li> <p>
* <code>local-gateway-virtual-interface-group-id</code> - The ID of the virtual
* interface group.</p> </li> <li> <p> <code>owner-id</code> - The ID of the Amazon
* Web Services account that owns the local gateway virtual interface.</p> </li>
* <li> <p> <code>peer-address</code> - The peer address.</p> </li> <li> <p>
* <code>peer-bgp-asn</code> - The peer BGP ASN.</p> </li> <li> <p>
* <code>vlan</code> - The ID of the VLAN.</p> </li> </ul>
*/
inline DescribeLocalGatewayVirtualInterfacesRequest& AddFilters(const Filter& value) { m_filtersHasBeenSet = true; m_filters.push_back(value); return *this; }
/**
* <p>One or more filters.</p> <ul> <li> <p> <code>local-address</code> - The local
* address.</p> </li> <li> <p> <code>local-bgp-asn</code> - The Border Gateway
* Protocol (BGP) Autonomous System Number (ASN) of the local gateway.</p> </li>
* <li> <p> <code>local-gateway-id</code> - The ID of the local gateway.</p> </li>
* <li> <p> <code>local-gateway-virtual-interface-id</code> - The ID of the virtual
* interface.</p> </li> <li> <p>
* <code>local-gateway-virtual-interface-group-id</code> - The ID of the virtual
* interface group.</p> </li> <li> <p> <code>owner-id</code> - The ID of the Amazon
* Web Services account that owns the local gateway virtual interface.</p> </li>
* <li> <p> <code>peer-address</code> - The peer address.</p> </li> <li> <p>
* <code>peer-bgp-asn</code> - The peer BGP ASN.</p> </li> <li> <p>
* <code>vlan</code> - The ID of the VLAN.</p> </li> </ul>
*/
inline DescribeLocalGatewayVirtualInterfacesRequest& AddFilters(Filter&& value) { m_filtersHasBeenSet = true; m_filters.push_back(std::move(value)); return *this; }
/**
* <p>The maximum number of results to return with a single call. To retrieve the
* remaining results, make another call with the returned <code>nextToken</code>
* value.</p>
*/
inline int GetMaxResults() const{ return m_maxResults; }
/**
* <p>The maximum number of results to return with a single call. To retrieve the
* remaining results, make another call with the returned <code>nextToken</code>
* value.</p>
*/
inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; }
/**
* <p>The maximum number of results to return with a single call. To retrieve the
* remaining results, make another call with the returned <code>nextToken</code>
* value.</p>
*/
inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; }
/**
* <p>The maximum number of results to return with a single call. To retrieve the
* remaining results, make another call with the returned <code>nextToken</code>
* value.</p>
*/
inline DescribeLocalGatewayVirtualInterfacesRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;}
/**
* <p>The token for the next page of results.</p>
*/
inline const Aws::String& GetNextToken() const{ return m_nextToken; }
/**
* <p>The token for the next page of results.</p>
*/
inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }
/**
* <p>The token for the next page of results.</p>
*/
inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }
/**
* <p>The token for the next page of results.</p>
*/
inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }
/**
* <p>The token for the next page of results.</p>
*/
inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }
/**
* <p>The token for the next page of results.</p>
*/
inline DescribeLocalGatewayVirtualInterfacesRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}
/**
* <p>The token for the next page of results.</p>
*/
inline DescribeLocalGatewayVirtualInterfacesRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}
/**
* <p>The token for the next page of results.</p>
*/
inline DescribeLocalGatewayVirtualInterfacesRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}
/**
* <p>Checks whether you have the required permissions for the action, without
* actually making the request, and provides an error response. If you have the
* required permissions, the error response is <code>DryRunOperation</code>.
* Otherwise, it is <code>UnauthorizedOperation</code>.</p>
*/
inline bool GetDryRun() const{ return m_dryRun; }
/**
* <p>Checks whether you have the required permissions for the action, without
* actually making the request, and provides an error response. If you have the
* required permissions, the error response is <code>DryRunOperation</code>.
* Otherwise, it is <code>UnauthorizedOperation</code>.</p>
*/
inline bool DryRunHasBeenSet() const { return m_dryRunHasBeenSet; }
/**
* <p>Checks whether you have the required permissions for the action, without
* actually making the request, and provides an error response. If you have the
* required permissions, the error response is <code>DryRunOperation</code>.
* Otherwise, it is <code>UnauthorizedOperation</code>.</p>
*/
inline void SetDryRun(bool value) { m_dryRunHasBeenSet = true; m_dryRun = value; }
/**
* <p>Checks whether you have the required permissions for the action, without
* actually making the request, and provides an error response. If you have the
* required permissions, the error response is <code>DryRunOperation</code>.
* Otherwise, it is <code>UnauthorizedOperation</code>.</p>
*/
inline DescribeLocalGatewayVirtualInterfacesRequest& WithDryRun(bool value) { SetDryRun(value); return *this;}
private:
Aws::Vector<Aws::String> m_localGatewayVirtualInterfaceIds;
bool m_localGatewayVirtualInterfaceIdsHasBeenSet;
Aws::Vector<Filter> m_filters;
bool m_filtersHasBeenSet;
int m_maxResults;
bool m_maxResultsHasBeenSet;
Aws::String m_nextToken;
bool m_nextTokenHasBeenSet;
bool m_dryRun;
bool m_dryRunHasBeenSet;
};
} // namespace Model
} // namespace EC2
} // namespace Aws
| aws/aws-sdk-cpp | aws-cpp-sdk-ec2/include/aws/ec2/model/DescribeLocalGatewayVirtualInterfacesRequest.h | C | apache-2.0 | 16,905 |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Utilities for VariableMgr."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections as pycoll
import operator
import numpy as np
import tensorflow.compat.v1 as tf
# pylint: disable=g-direct-tensorflow-import
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import data_flow_ops
from tensorflow.python.ops import math_ops
PS_SHADOW_VAR_PREFIX = 'ps_var'
AutoLossScaleParams = pycoll.namedtuple(
'AutoLossScaleParams',
[
# If true, enable automatic loss scaling.
'enable_auto_loss_scale',
# The value to scale the loss before computing gradients.
'loss_scale',
# Number of normal steps with the current `loss_scale`.
'loss_scale_normal_steps',
# Increase loss scale every n steps.
'inc_loss_scale_every_n',
# If true, the current worker is chief. The current implementation
# relies on the chief to update loss_scale value, but in future, we
# might change this to ask the parameter server to update loss_scales
# for better performance.
# TODO(tanmingxing): remove this if loss_scale is updated in ps.
'is_chief',
])
def get_loss_scale_update_op(loss_scale, loss_scale_normal_steps,
inc_loss_scale_every_n):
"""Returns the update op for loss scaling variables.
We maintain the counter `loss_scale_normal_steps` to count the number of steps
we have been using the current `loss_scale`. In most cases, this function
increments `loss_scale_normal_steps`. However, if `loss_scale_normal_steps` is
greater than the threshold `inc_loss_scale_every_n`, we double `loss_scale`
and reset `loss_scale_normal_steps` to zero.
This op is only called if the gradients don't have any infs or nans. Instead,
if infs or nans occur in the gradients, we immeditately halve `loss_scale` and
reset `loss_scale_normal_steps` to zero.
Args:
loss_scale: a tf.Variable represneting the loss_scale value.
loss_scale_normal_steps: a tf.Variable representing the number of training
steps that have run since the loss_scale last changed.
inc_loss_scale_every_n: a Python integer threshold. `loss_scale` is
increased every `inc_loss_scale_every_n` steps, unless the gradients have
infs or nans.
Returns:
An op for updating `loss_scale` and `loss_scale_normal_steps`.
"""
def increment_loss_scale_normal_steps_func():
return tf.group(loss_scale_normal_steps.assign_add(1))
def increase_loss_scale_func():
return tf.group(
tf.assign(loss_scale_normal_steps, 0),
tf.assign(loss_scale, loss_scale * 2))
# true_fn and false_fn must have the same type.
return tf.cond(loss_scale_normal_steps < inc_loss_scale_every_n,
increment_loss_scale_normal_steps_func,
increase_loss_scale_func)
def append_gradients_with_loss_scale(training_ops, get_apply_gradients_ops_func,
loss_scale_params, grad_has_inf_nan):
"""Selectively appends gradients update ops with loss scaling.
Args:
training_ops: a list of training ops to be executed.
get_apply_gradients_ops_func: a function that returns a list of ops for
applying gradients. Here, we must pass a function instead of the actual
list of ops; otherwise, those ops would be executed unconditionally due to
the semantics of tf.cond.
loss_scale_params: An AutoLossScaleParams tuple.
grad_has_inf_nan: Boolean tensor indicating whether the gradients have infs
or nans.
"""
is_chief = loss_scale_params.is_chief
loss_scale = loss_scale_params.loss_scale
loss_scale_normal_steps = loss_scale_params.loss_scale_normal_steps
inc_loss_scale_every_n = loss_scale_params.inc_loss_scale_every_n
enable_auto_loss_scale = loss_scale_params.enable_auto_loss_scale
if loss_scale is None or not enable_auto_loss_scale or not is_chief:
training_ops.extend(get_apply_gradients_ops_func())
else:
# If nans/infs occurred, skip applying gradients and instead update
# loss_scale (halve loss_scale and reset loss_scale_normal_steps to zero).
def update_op_if_nan_or_inf():
"""Update loss_scale and discard gradients if nans/infs occurred."""
return tf.group(
tf.assign(loss_scale, loss_scale / 2.),
tf.assign(loss_scale_normal_steps, 0))
# Otherwise, apply gradients, and update loss_scale and
# loss_scale_normal_steps.
def update_op_if_no_nan_or_inf():
"""Apply gradients, and update loss scaling."""
return tf.group(
get_loss_scale_update_op(loss_scale, loss_scale_normal_steps,
inc_loss_scale_every_n),
*get_apply_gradients_ops_func())
# TODO(tanmingxing): Add support for independent and distributed all_reduce.
assert grad_has_inf_nan is not None
update_op = tf.cond(
grad_has_inf_nan,
update_op_if_nan_or_inf,
update_op_if_no_nan_or_inf,
name='cond_if_grad_has_inf_nan'
)
training_ops.append(update_op)
# To be used with custom_getter on tf.get_variable.
class OverrideCachingDevice(object):
"""Variable getter which caches variables on the least loaded device.
Variables smaller than a certain threshold are cached on a single specific
device, as specified in the constructor. All other variables are load balanced
across a pool of devices, by caching each variable on the least loaded device.
Note that variable creation only happen when building the model graph on the
first device (see how it sets the 'reuse' parameter in
VariableMgr.*.create_outer_variable_scope()). That means, for all other
devices, the variable scope will reuse the variables created before, which
requires that we set the caching_device correctly as otherwise it may not be
able to find the previously created variable and will create a new one. This
requires when building the model graph on different devices, variables with
the same name should have same size.
TODO(laigd): consider adding tests or verification logic to enforce this, or
refactor it.
"""
def __init__(self, devices, device_for_small_variables,
small_variable_size_threshold):
self.devices = devices
self.sizes = [0] * len(self.devices)
self.device_for_small_variables = device_for_small_variables
self.small_variable_size_threshold = small_variable_size_threshold
def __call__(self, getter, *args, **kwargs):
size = tf.TensorShape(kwargs['shape']).num_elements()
if size < self.small_variable_size_threshold:
device_name = self.device_for_small_variables
else:
device_index, _ = min(enumerate(self.sizes), key=operator.itemgetter(1))
device_name = self.devices[device_index]
self.sizes[device_index] += size
kwargs['caching_device'] = device_name
var = getter(*args, **kwargs)
return var
# To be used with custom_getter on tf.get_variable. Ensures the created variable
# is in LOCAL_VARIABLES and not GLOBAL_VARIBLES collection.
class OverrideToLocalVariableIfNotPsVar(object):
# args and kwargs come from the custom_getter interface for Tensorflow
# variables, and matches tf.get_variable's signature, with the addition of
# 'getter' at the beginning.
def __call__(self, getter, name, *args, **kwargs):
if name.startswith(PS_SHADOW_VAR_PREFIX):
return getter(*args, **kwargs)
if 'collections' in kwargs:
collections = kwargs['collections']
if not collections:
collections = [tf.GraphKeys.GLOBAL_VARIABLES]
else:
collections = collections[:]
collections.remove(tf.GraphKeys.GLOBAL_VARIABLES)
collections.append(tf.GraphKeys.LOCAL_VARIABLES)
kwargs['collections'] = list(collections)
return getter(name, *args, **kwargs)
class ParamServerDeviceSetter(object):
"""Helper class to assign variables on the least loaded ps-device."""
def __init__(self, worker_device, ps_devices):
"""Initializer for ParamServerDevicSetter.
Args:
worker_device: the device to use for computer ops.
ps_devices: a list of device to use for Variable ops. Each variable is
assigned to the least loaded device.
"""
self.ps_devices = ps_devices
self.worker_device = worker_device
self.ps_sizes = [0] * len(self.ps_devices)
def __call__(self, op):
if op.device:
return op.device
if op.type not in ['Variable', 'VariableV2']:
return self.worker_device
device_index, _ = min(enumerate(self.ps_sizes), key=operator.itemgetter(1))
device_name = self.ps_devices[device_index]
var_size = op.outputs[0].get_shape().num_elements()
self.ps_sizes[device_index] += var_size
return device_name
class StagedModelVariable(object):
"""Staging variable wrapper that decouples reads and updates.
This class represents a variable through a staging buffer. Reads from this
variable directly gets from the staging buffer. Updates are stacked into
another staging buffer, and will be processed later.
"""
def __init__(self, real_var, var_stage_get, variable_mgr):
"""Initializer for the model variables through a staging buffer.
Args:
real_var: the underlying real variable.
var_stage_get: the read op from the staging buffer.
variable_mgr: the parent variable-manager.
"""
self.real_var = real_var
self.var_stage_get = var_stage_get
self.variable_mgr = variable_mgr
def _value(self):
"""The read access of this variable. The content from the staging buffer."""
return self.var_stage_get
def _ref(self):
"""Return the underlying variable ref, required by tf.colocate_with."""
return self.real_var._ref() # pylint: disable=protected-access
def read_value(self):
"""Mimics tf.Variable.read_value()."""
return tf.identity(self.var_stage_get, name='read')
@property
def dtype(self):
"""Return the non-reference dtype."""
return self.var_stage_get.dtype
def assign_sub(self, delta, name=None, read_value=True):
"""Mimic the updates to the variable.
Args:
delta: is pushed into a staging buffer and will be pumped later.
name: currently ignored; names of ops and the StagingArea are
computed without using this pass name.
read_value: if True, will return something which evaluates to the new
value of the variable; if False will return the assign op.
Returns:
The actual updates. The colocation constraint will be reapplied.
"""
# This parameter is ignored: the StagingArea only supports setting
# the shared name, not the names of individual ops it uses.
del name
# colocate_with(None, True) clears the colocation constraints.
# Push the delta into a staging buffer.
with ops.colocate_with(None, True), tf.device(self.var_stage_get.device):
delta_staging_area = data_flow_ops.StagingArea(
[self.var_stage_get.dtype], shapes=[self.var_stage_get.shape])
delta_put_op = delta_staging_area.put([delta])
self.variable_mgr.staging_delta_ops.append(delta_put_op)
delta_get_op = delta_staging_area.get()[0]
# Return the actual updates. The colocation constraint will be reapplied.
return self.real_var.assign_sub(delta_get_op, read_value=read_value)
@staticmethod
# pylint: disable=bad-staticmethod-argument,invalid-name
def _TensorConversionFunction(self, dtype=None, name=None, as_ref=False):
"""Utility function for converting a StagedModelVariable to a Tensor."""
del dtype, name # unused: this function returns the cached ref or value.
if as_ref:
return self._ref()
else:
return self._value()
ops.register_tensor_conversion_function(
StagedModelVariable, StagedModelVariable._TensorConversionFunction) # pylint: disable=protected-access
class StagedVariableGetter(object):
"""A variable getter through staging buffers on devices.
Instead of a caching device, this getter tracks where the variable is used.
And on each device, it goes through a staging buffer.
"""
def __init__(self, device_num, devices, cpu_device, variable_mgr):
"""Initializer for StagedVariableGetter.
Args:
device_num: the current device index.
devices: a list of all the devices to build towers.
cpu_device: a cpu_device for this replica. If None, no cpu-caching is
done.
variable_mgr: the parent variable manager.
"""
self.device_num = device_num
self.devices = devices
self.cpu_device = cpu_device
self.variable_mgr = variable_mgr
def __call__(self, getter, name, *args, **kwargs):
staging_ops = self.variable_mgr.staging_vars_on_devices[self.device_num]
if name in staging_ops:
put_op, get_op = staging_ops[name]
return get_op
real_var = getter(name, *args, **kwargs)
shape = kwargs['shape']
dtype = kwargs['dtype']
trainable = kwargs['trainable']
if self.cpu_device:
with tf.device(self.cpu_device):
# This helps copying the weights from the parameter to this server only
# once.
if name in self.variable_mgr.staged_vars_on_cpu:
cpu_var = self.variable_mgr.staged_vars_on_cpu[name]
else:
cpu_var = tf.identity(real_var)
self.variable_mgr.staged_vars_on_cpu[name] = cpu_var
var_to_stage = cpu_var
else:
var_to_stage = tf.identity(real_var) # de-reference the variable.
with tf.device(self.devices[self.device_num]):
staging_area = data_flow_ops.StagingArea([dtype], shapes=[shape])
put_op = staging_area.put([var_to_stage])
get_op = staging_area.get()[0]
staging_ops[name] = (put_op, get_op)
if trainable:
# For trainable variables, they are managed separatedly through
# apply_gradients.
return get_op
else:
# For other shadow variables, the access is decoupled through a wrapper
# class.
return StagedModelVariable(real_var, get_op, self.variable_mgr)
def trainable_variables_on_device(self, rel_device_num, abs_device_num,
writable):
"""Return the set of trainable variables on the specified device.
Args:
rel_device_num: local worker device index.
abs_device_num: global graph device index.
writable: whether the returned variables is writable or read-only.
Returns:
Return the set of trainable variables on the specified device.
"""
del abs_device_num
params_refs = tf.trainable_variables()
if writable:
return params_refs
params = []
for param in params_refs:
var_name = param.name.split(':')[0]
_, var_get_op = self.variable_mgr.staging_vars_on_devices[rel_device_num][
var_name]
params.append(var_get_op)
return params
def aggregate_gradients_using_copy_with_device_selection(
benchmark_cnn, tower_grads, use_mean, check_inf_nan):
"""Aggregate gradients, controlling device for the aggregation.
Args:
benchmark_cnn: benchmark_cnn class.
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over towers. The inner list is over individual gradients.
use_mean: if True, mean is taken, else sum of gradients is taken.
check_inf_nan: If true, check grads for nans and infs.
Returns:
The tuple ([(average_gradient, variable),], has_nan_or_inf) where the
gradient has been averaged across all towers. The variable is chosen from
the first tower. The has_nan_or_inf indicates the grads has nan or inf.
"""
if benchmark_cnn.local_parameter_device_flag == 'gpu':
avail_devices = benchmark_cnn.raw_devices
else:
avail_devices = [benchmark_cnn.param_server_device]
agg_grads = []
has_nan_or_inf_list = []
for i, single_grads in enumerate(zip(*tower_grads)):
with tf.device(avail_devices[i % len(avail_devices)]):
grad_and_var, has_nan_or_inf = aggregate_single_gradient_using_copy(
single_grads, use_mean, check_inf_nan)
agg_grads.append(grad_and_var)
has_nan_or_inf_list.append(has_nan_or_inf)
if check_inf_nan:
return agg_grads, tf.reduce_any(has_nan_or_inf_list)
else:
return agg_grads, None
def aggregate_gradients_using_copy_with_variable_colocation(
tower_grads, use_mean, check_inf_nan):
"""Aggregate gradients, colocating computation with the gradient's variable.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over towers. The inner list is over individual gradients. All variables
of the same gradient across towers must be the same (that is,
tower_grads[x][a][1] == tower_grads[y][a][1] for all indices x, y, and a)
use_mean: if True, mean is taken, else sum of gradients is taken.
check_inf_nan: If true, check grads for nans and infs.
Returns:
The tuple ([(average_gradient, variable),], has_nan_or_inf) where the
gradient has been averaged across all towers. The variable is chosen from
the first tower. The has_nan_or_inf indicates the grads has nan or inf.
"""
agg_grads = []
has_nan_or_inf_list = []
for single_grads in zip(*tower_grads):
# Note that each single_grads looks like the following:
# ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))
var = single_grads[0][1]
for _, v in single_grads:
assert v == var
with tf.device(var.device):
grad_and_var, has_nan_or_inf = aggregate_single_gradient_using_copy(
single_grads, use_mean, check_inf_nan)
agg_grads.append(grad_and_var)
has_nan_or_inf_list.append(has_nan_or_inf)
if check_inf_nan:
return agg_grads, tf.reduce_any(has_nan_or_inf_list)
else:
return agg_grads, None
def aggregate_gradients_using_copy(tower_grads, use_mean, check_inf_nan):
"""Calculate the average gradient for each shared variable across all towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over towers. The inner list is over individual gradients.
use_mean: if True, mean is taken, else sum of gradients is taken.
check_inf_nan: check grads for nans and infs.
Returns:
The tuple ([(average_gradient, variable),], has_nan_or_inf) where the
gradient has been averaged across all towers. The variable is chosen from
the first tower. The has_nan_or_inf indicates the grads has nan or inf.
"""
agg_grads = []
has_nan_or_inf_list = []
for single_grads in zip(*tower_grads):
grad_and_var, has_nan_or_inf = aggregate_single_gradient_using_copy(
single_grads, use_mean, check_inf_nan)
agg_grads.append(grad_and_var)
has_nan_or_inf_list.append(has_nan_or_inf)
if check_inf_nan:
return agg_grads, tf.reduce_any(has_nan_or_inf_list)
else:
return agg_grads, None
# The following two functions are copied from
# tensorflow/python/eager/backprop.py. We do not directly use them as they are
# not exported and subject to change at any time.
def flatten_nested_indexed_slices(grad):
assert isinstance(grad, ops.IndexedSlices)
if isinstance(grad.values, ops.Tensor):
return grad
else:
assert isinstance(grad.values, ops.IndexedSlices)
g = flatten_nested_indexed_slices(grad.values)
return ops.IndexedSlices(g.values, array_ops.gather(grad.indices,
g.indices),
g.dense_shape)
def aggregate_indexed_slices_gradients(grads):
"""Aggregates gradients containing `IndexedSlices`s."""
if len(grads) < 1:
return None
elif len(grads) == 1:
return grads[0]
else:
grads = [g for g in grads if g is not None]
# If any gradient is a `Tensor`, sum them up and return a dense tensor
# object.
if any(isinstance(g, ops.Tensor) for g in grads):
return math_ops.add_n(grads)
# The following `_as_indexed_slices_list` casts ids of IndexedSlices into
# int64. It is to make sure the inputs of `concat` all have same the data
# type.
grads = math_ops._as_indexed_slices_list(grads) # pylint: disable=protected-access
grads = [flatten_nested_indexed_slices(x) for x in grads]
# Form IndexedSlices out of the concatenated values and indices.
concat_grad = ops.IndexedSlices(
array_ops.concat([x.values for x in grads], axis=0),
array_ops.concat([x.indices for x in grads], axis=0),
grads[0].dense_shape)
return concat_grad
def aggregate_single_gradient_using_copy(grad_and_vars, use_mean,
check_inf_nan):
"""Calculate the average gradient for a shared variable across all towers.
Note that this function provides a synchronization point across all towers.
Args:
grad_and_vars: A list or tuple of (gradient, variable) tuples. Each
(gradient, variable) pair within the outer list represents the gradient
of the variable calculated for a single tower, and the number of pairs
equals the number of towers.
use_mean: if True, mean is taken, else sum of gradients is taken.
check_inf_nan: check grads for nans and infs.
Returns:
The tuple ([(average_gradient, variable),], has_nan_or_inf) where the
gradient has been averaged across all towers. The variable is chosen from
the first tower. The has_nan_or_inf indicates the grads has nan or inf.
"""
grads = [g for g, _ in grad_and_vars]
if any(isinstance(g, tf.IndexedSlices) for g in grads):
# TODO(reedwm): All-reduce IndexedSlices more effectively.
grad = aggregate_indexed_slices_gradients(grads)
else:
grad = tf.add_n(grads)
if use_mean and len(grads) > 1:
grad = tf.scalar_mul(1.0 / len(grads), grad)
v = grad_and_vars[0][1]
if check_inf_nan:
with tf.name_scope('check_for_inf_and_nan'):
has_nan_or_inf = tf.logical_not(tf.reduce_all(tf.is_finite(grads)))
return (grad, v), has_nan_or_inf
else:
return (grad, v), None
# This class is copied from
# https://github.com/tensorflow/tensorflow/blob/590d6eef7e91a6a7392c8ffffb7b58f2e0c8bc6b/tensorflow/contrib/training/python/training/device_setter.py#L56.
# We copy it since contrib has been removed from TensorFlow.
class GreedyLoadBalancingStrategy(object):
"""Returns the least-loaded ps task for op placement.
The load is calculated by a user-specified load function passed in at
construction. There are no units for load, and the load function is
responsible for providing an internally consistent measure.
Note that this strategy is very sensitive to the exact order in which
ps ops (typically variables) are created, as it greedily places ops
on the least-loaded ps at the point each op is processed.
One reasonable heuristic is the `byte_size_load_fn`, which
estimates load as the number of bytes that would be used to store and
transmit the entire variable. More advanced load functions
could consider the difference in access patterns across ops, or trade
off CPU-intensive ops with RAM-intensive ops with network bandwidth.
This class is intended to be used as a `ps_strategy` in
`tf.compat.v1.train.replica_device_setter`.
"""
def __init__(self, num_tasks, load_fn):
"""Create a new `LoadBalancingStrategy`.
Args:
num_tasks: Number of ps tasks to cycle among.
load_fn: A callable that takes an `Operation` and returns a
numeric load value for that op.
"""
self._num_tasks = num_tasks
self._load_fn = load_fn
self._ps_loads = np.zeros(num_tasks)
def __call__(self, op):
"""Choose a ps task index for the given `Operation`.
Args:
op: A `Operation` to be placed on ps.
Returns:
The next ps task index to use for the `Operation`. Greedily
places the op on the least-loaded ps task so far, as determined
by the load function.
"""
task = np.argmin(self._ps_loads)
self._ps_loads[task] += self._load_fn(op)
return task
# This function is copied from
# https://github.com/tensorflow/tensorflow/blob/590d6eef7e91a6a7392c8ffffb7b58f2e0c8bc6b/tensorflow/contrib/training/python/training/device_setter.py#L105.
# We copy it since contrib has been removed from TensorFlow.
def byte_size_load_fn(op):
"""Load function that computes the byte size of a single-output `Operation`.
This is intended to be used with `"Variable"` ops, which have a single
`Tensor` output with the contents of the variable. However, it can also be
used for calculating the size of any op that has a single output.
Intended to be used with `GreedyLoadBalancingStrategy`.
Args:
op: An `Operation` with a single output, typically a "Variable" op.
Returns:
The number of bytes in the output `Tensor`.
Raises:
ValueError: if `op` does not have a single output, or if the shape of the
single output is not fully-defined.
"""
if len(op.outputs) != 1:
raise ValueError('Op %s must have a single output' % op)
output = op.outputs[0]
elem_size = output.dtype.size
shape = output.get_shape()
if not shape.is_fully_defined():
# Due to legacy behavior, scalar "Variable" ops have output Tensors that
# have unknown shape when the op is created (and hence passed to this
# load function for placement), even though the scalar shape is set
# explicitly immediately afterward.
shape = tensor_shape.TensorShape(op.get_attr('shape'))
shape.assert_is_fully_defined()
return shape.num_elements() * elem_size
| tensorflow/benchmarks | scripts/tf_cnn_benchmarks/variable_mgr_util.py | Python | apache-2.0 | 26,469 |
# [Floobits](https://floobits.com/) plugin for Sublime Text 2
Real-time collaborative editing. Think Etherpad, but with native editors. This is the plugin for Sublime Text 2. We're also working on plugins for [Emacs](https://github.com/Floobits/emacs-plugin) and [Vim](https://github.com/Floobits/vim-plugin).
**Sublime Text 3 Beta users:** You want the [Sublime Text 3 plugin](https://github.com/Floobits/sublime-text-2-plugin/tree/st3).
### Development status: Reasonably stable. We dogfood it daily and rarely run into issues.
## Windows
This plugin does not work on Windows. However, the [Sublime Text 3 plugin](https://github.com/Floobits/sublime-text-2-plugin/tree/st3) does. Windows users are encouraged to install Sublime Text 3. The Python included with the Windows version of Sublime Text 2 does not have the [select](http://docs.python.org/2/library/select.html) module.
# Installation instructions
* If you don't have one already, go to [Floobits](https://floobits.com/) and create an account (or sign in with GitHub). (It's free.)
* Clone this repository or download and extract [this tarball](https://github.com/Floobits/sublime-text-2-plugin/archive/master.zip).
* Rename the directory to "Floobits".
* In Sublime Text, go to Preferences -> Browse Packages.
* Drag, copy, or move the Floobits directory into your Packages directory.
If you'd rather create a symlink instead of copy/moving, run something like:
ln -s ~/code/sublime-text-2-plugin ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/Floobits
# Configuration
Edit your Floobits.sublime-settings file (in `Package Settings -> Floobits -> Settings - User`) and fill in the following info:
{
"username": "user",
"secret": "THIS-IS-YOUR-API-KEY DO-NOT-USE-YOUR-PASSWORD",
}
Replace user with your Floobits username. The secret is your API secret, which you can see in [your settings](https://floobits.com/dash/settings/).
# Using Floobits to Collaborate
After creating your account, you’ll want to create a room or two. A room is a collection of files and buffers that users can collaborate on.
See https://floobits.com/help for instructions on how to set up rooms and collaborate with others.
| nilbus/sublime-text-2-plugin | README.md | Markdown | apache-2.0 | 2,214 |
angular.module('restServices', [ 'ngResource' ]).factory('RestService',
[ '$resource', function($resource) {
return function(restEntitiesUrl) {
return $resource(restEntitiesUrl, {}, {
query : {
method : 'GET',
isArray : false
},
update : {
method : 'PUT'
}
});
};
} ]); | emarkhauser/taxaccounting | src/main/webapp/js/restServices.js | JavaScript | apache-2.0 | 338 |
# Binary Authorization API Client Library for Java
The management interface for Binary Authorization, a service that provides policy-based deployment validation and control for images deployed to Google Kubernetes Engine (GKE), Anthos Service Mesh, Anthos Clusters, and Cloud Run.
This page contains information about getting started with the Binary Authorization API
using the Google API Client Library for Java. In addition, you may be interested
in the following documentation:
* Browse the [Javadoc reference for the Binary Authorization API][javadoc]
* Read the [Developer's Guide for the Google API Client Library for Java][google-api-client].
* Interact with this API in your browser using the [APIs Explorer for the Binary Authorization API][api-explorer]
## Installation
### Maven
Add the following lines to your `pom.xml` file:
```xml
<project>
<dependencies>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-binaryauthorization</artifactId>
<version>v1beta1-rev20211112-1.32.1</version>
</dependency>
</dependencies>
</project>
```
### Gradle
```gradle
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.apis:google-api-services-binaryauthorization:v1beta1-rev20211112-1.32.1'
}
```
[javadoc]: https://googleapis.dev/java/google-api-services-binaryauthorization/latest/index.html
[google-api-client]: https://github.com/googleapis/google-api-java-client/
[api-explorer]: https://developers.google.com/apis-explorer/#p/binaryauthorization/v1/
| googleapis/google-api-java-client-services | clients/google-api-services-binaryauthorization/v1beta1/README.md | Markdown | apache-2.0 | 1,545 |
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.sasportal.v1alpha1.model;
/**
* Device grant. It is an authorization provided by the Spectrum Access System to a device to
* transmit using specified operating parameters after a successful heartbeat by the device.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the SAS Portal API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class SasPortalDeviceGrant extends com.google.api.client.json.GenericJson {
/**
* Type of channel used.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String channelType;
/**
* The expiration time of the grant.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String expireTime;
/**
* The transmission frequency range.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private SasPortalFrequencyRange frequencyRange;
/**
* Grant Id.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String grantId;
/**
* Maximum Equivalent Isotropically Radiated Power (EIRP) permitted by the grant. The maximum EIRP
* is in units of dBm/MHz. The value of `maxEirp` represents the average (RMS) EIRP that would be
* measured by the procedure defined in FCC part 96.41(e)(3).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Double maxEirp;
/**
* The DPA move lists on which this grant appears.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<SasPortalDpaMoveList> moveList;
/**
* State of the grant.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String state;
/**
* If the grant is suspended, the reason(s) for suspension.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> suspensionReason;
/**
* Type of channel used.
* @return value or {@code null} for none
*/
public java.lang.String getChannelType() {
return channelType;
}
/**
* Type of channel used.
* @param channelType channelType or {@code null} for none
*/
public SasPortalDeviceGrant setChannelType(java.lang.String channelType) {
this.channelType = channelType;
return this;
}
/**
* The expiration time of the grant.
* @return value or {@code null} for none
*/
public String getExpireTime() {
return expireTime;
}
/**
* The expiration time of the grant.
* @param expireTime expireTime or {@code null} for none
*/
public SasPortalDeviceGrant setExpireTime(String expireTime) {
this.expireTime = expireTime;
return this;
}
/**
* The transmission frequency range.
* @return value or {@code null} for none
*/
public SasPortalFrequencyRange getFrequencyRange() {
return frequencyRange;
}
/**
* The transmission frequency range.
* @param frequencyRange frequencyRange or {@code null} for none
*/
public SasPortalDeviceGrant setFrequencyRange(SasPortalFrequencyRange frequencyRange) {
this.frequencyRange = frequencyRange;
return this;
}
/**
* Grant Id.
* @return value or {@code null} for none
*/
public java.lang.String getGrantId() {
return grantId;
}
/**
* Grant Id.
* @param grantId grantId or {@code null} for none
*/
public SasPortalDeviceGrant setGrantId(java.lang.String grantId) {
this.grantId = grantId;
return this;
}
/**
* Maximum Equivalent Isotropically Radiated Power (EIRP) permitted by the grant. The maximum EIRP
* is in units of dBm/MHz. The value of `maxEirp` represents the average (RMS) EIRP that would be
* measured by the procedure defined in FCC part 96.41(e)(3).
* @return value or {@code null} for none
*/
public java.lang.Double getMaxEirp() {
return maxEirp;
}
/**
* Maximum Equivalent Isotropically Radiated Power (EIRP) permitted by the grant. The maximum EIRP
* is in units of dBm/MHz. The value of `maxEirp` represents the average (RMS) EIRP that would be
* measured by the procedure defined in FCC part 96.41(e)(3).
* @param maxEirp maxEirp or {@code null} for none
*/
public SasPortalDeviceGrant setMaxEirp(java.lang.Double maxEirp) {
this.maxEirp = maxEirp;
return this;
}
/**
* The DPA move lists on which this grant appears.
* @return value or {@code null} for none
*/
public java.util.List<SasPortalDpaMoveList> getMoveList() {
return moveList;
}
/**
* The DPA move lists on which this grant appears.
* @param moveList moveList or {@code null} for none
*/
public SasPortalDeviceGrant setMoveList(java.util.List<SasPortalDpaMoveList> moveList) {
this.moveList = moveList;
return this;
}
/**
* State of the grant.
* @return value or {@code null} for none
*/
public java.lang.String getState() {
return state;
}
/**
* State of the grant.
* @param state state or {@code null} for none
*/
public SasPortalDeviceGrant setState(java.lang.String state) {
this.state = state;
return this;
}
/**
* If the grant is suspended, the reason(s) for suspension.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSuspensionReason() {
return suspensionReason;
}
/**
* If the grant is suspended, the reason(s) for suspension.
* @param suspensionReason suspensionReason or {@code null} for none
*/
public SasPortalDeviceGrant setSuspensionReason(java.util.List<java.lang.String> suspensionReason) {
this.suspensionReason = suspensionReason;
return this;
}
@Override
public SasPortalDeviceGrant set(String fieldName, Object value) {
return (SasPortalDeviceGrant) super.set(fieldName, value);
}
@Override
public SasPortalDeviceGrant clone() {
return (SasPortalDeviceGrant) super.clone();
}
}
| googleapis/google-api-java-client-services | clients/google-api-services-sasportal/v1alpha1/1.31.0/com/google/api/services/sasportal/v1alpha1/model/SasPortalDeviceGrant.java | Java | apache-2.0 | 6,999 |
# -----------------------------------------------------------------------------
#
# Package : github.com/openzipkin/zipkin-go
# Version : v0.2.2
# Source repo : https://github.com/openzipkin/zipkin-go
# Tested on : RHEL 8.3
# Script License: Apache License, Version 2 or later
# Maintainer : BulkPackageSearch Automation <sethp@us.ibm.com>
#
# Disclaimer: This script has been tested in root mode on given
# ========== platform using the mentioned version of the package.
# It may not work as expected with newer versions of the
# package and/or distribution. In such case, please
# contact "Maintainer" of this script.
#
# ----------------------------------------------------------------------------
PACKAGE_NAME=github.com/openzipkin/zipkin-go
PACKAGE_VERSION=v0.2.2
PACKAGE_URL=https://github.com/openzipkin/zipkin-go
yum -y update && yum install -y nodejs nodejs-devel nodejs-packaging npm python38 python38-devel ncurses git jq wget gcc-c++
wget https://golang.org/dl/go1.16.1.linux-ppc64le.tar.gz && tar -C /bin -xf go1.16.1.linux-ppc64le.tar.gz && mkdir -p /home/tester/go/src /home/tester/go/bin /home/tester/go/pkg
export PATH=$PATH:/bin/go/bin
export GOPATH=/home/tester/go
OS_NAME=`python3 -c "os_file_data=open('/etc/os-release').readlines();os_info = [i.replace('PRETTY_NAME=','').strip() for i in os_file_data if i.startswith('PRETTY_NAME')];print(os_info[0])"`
export PATH=$GOPATH/bin:$PATH
export GO111MODULE=on
function test_with_master_without_flag_u(){
echo "Building $PACKAGE_PATH with master branch"
export GO111MODULE=auto
if ! go get -d -t $PACKAGE_NAME; then
echo "------------------$PACKAGE_NAME:install_fails-------------------------------------"
echo "$PACKAGE_VERSION $PACKAGE_NAME" > /home/tester/output/install_fails
echo "$PACKAGE_NAME | $PACKAGE_VERSION | master | $OS_NAME | GitHub | Fail | Install_Fails" > /home/tester/output/version_tracker
exit 0
else
cd $(ls -d $GOPATH/pkg/mod/$PACKAGE_NAME*)
echo "Testing $PACKAGE_PATH with master branch without flag -u"
# Ensure go.mod file exists
go mod init
if ! gi test ./...; then
echo "------------------$PACKAGE_NAME:install_success_but_test_fails---------------------"
echo "$PACKAGE_VERSION $PACKAGE_NAME" > /home/tester/output/test_fails
echo "$PACKAGE_NAME | $PACKAGE_VERSION | master | $OS_NAME | GitHub | Fail | Install_success_but_test_Fails" > /home/tester/output/version_tracker
exit 0
else
echo "------------------$PACKAGE_NAME:install_&_test_both_success-------------------------"
echo "$PACKAGE_VERSION $PACKAGE_NAME" > /home/tester/output/test_success
echo "$PACKAGE_NAME | $PACKAGE_VERSION | master | $OS_NAME | GitHub | Pass | Both_Install_and_Test_Success" > /home/tester/output/version_tracker
exit 0
fi
fi
}
function test_with_master(){
echo "Building $PACKAGE_PATH with master"
export GO111MODULE=auto
if ! go get -d -u -t $PACKAGE_NAME@$PACKAGE_VERSION; then
test_with_master_without_flag_u
exit 0
fi
cd $(ls -d $GOPATH/pkg/mod/$PACKAGE_NAME*)
echo "Testing $PACKAGE_PATH with $PACKAGE_VERSION"
# Ensure go.mod file exists
go mod init
if ! go test ./...; then
test_with_master_without_flag_u
exit 0
else
echo "------------------$PACKAGE_NAME:install_&_test_both_success-------------------------"
echo "$PACKAGE_VERSION $PACKAGE_NAME" > /home/tester/output/test_success
echo "$PACKAGE_NAME | $PACKAGE_VERSION | $PACKAGE_VERSION | $OS_NAME | GitHub | Pass | Both_Install_and_Test_Success" > /home/tester/output/version_tracker
exit 0
fi
}
function test_without_flag_u(){
echo "Building $PACKAGE_PATH with $PACKAGE_VERSION and without -u flag"
if ! go get -d -t $PACKAGE_NAME@$PACKAGE_VERSION; then
test_with_master
exit 0
fi
cd $(ls -d $GOPATH/pkg/mod/$PACKAGE_NAME*)
echo "Testing $PACKAGE_PATH with $PACKAGE_VERSION"
# Ensure go.mod file exists
go mod init
if ! go test ./...; then
test_with_master
exit 0
else
echo "------------------$PACKAGE_NAME:install_&_test_both_success-------------------------"
echo "$PACKAGE_VERSION $PACKAGE_NAME" > /home/tester/output/test_success
echo "$PACKAGE_NAME | $PACKAGE_VERSION | $PACKAGE_VERSION | $OS_NAME | GitHub | Pass | Both_Install_and_Test_Success" > /home/tester/output/version_tracker
exit 0
fi
}
echo "Building $PACKAGE_PATH with $PACKAGE_VERSION"
if ! go get -d -u -t $PACKAGE_NAME@$PACKAGE_VERSION; then
test_without_flag_u
exit 0
fi
cd $(ls -d $GOPATH/pkg/mod/$PACKAGE_NAME*)
echo "Testing $PACKAGE_PATH with $PACKAGE_VERSION"
# Ensure go.mod file exists
go mod init
if ! go test ./...; then
test_with_master
exit 0
else
echo "------------------$PACKAGE_NAME:install_&_test_both_success-------------------------"
echo "$PACKAGE_VERSION $PACKAGE_NAME" > /home/tester/output/test_success
echo "$PACKAGE_NAME | $PACKAGE_VERSION | $PACKAGE_VERSION | $OS_NAME | GitHub | Pass | Both_Install_and_Test_Success" > /home/tester/output/version_tracker
exit 0
fi
| ppc64le/build-scripts | g/github.com__openzipkin__zipkin-go/github.com__openzipkin__zipkin-go_rhel_8.3.sh | Shell | apache-2.0 | 5,081 |
from bson import ObjectId
import jsonschema
import numpy
from girder.exceptions import ValidationException
from girder.models.file import File
from girder.models.model_base import Model
from girder.models.upload import Upload
from girder.utility.acl_mixin import AccessControlMixin
from .image import Image
from .segmentation_helpers import ScikitSegmentationHelper
from .study import Study
from .user import User
class Annotation(AccessControlMixin, Model):
def initialize(self):
self.name = 'annotation'
self.ensureIndices(['studyId', 'imageId', 'userId'])
# TODO: resourceColl should be ['study', 'isic_archive'], but upstream support is unclear
self.resourceColl = 'folder'
self.resourceParent = 'studyId'
def createAnnotation(self, study, image, user):
annotation = self.save({
'studyId': study['_id'],
'imageId': image['_id'],
'userId': user['_id'],
'startTime': None,
'stopTime': None,
'status': None,
'log': [],
'responses': {},
'markups': {},
})
return annotation
def getState(self, annotation):
return (Study().State.COMPLETE
if annotation['stopTime'] is not None
else Study().State.ACTIVE)
def _superpixelsToMasks(self, superpixelValues, image):
possibleSuperpixelNums = numpy.array([
superpixelNum
for superpixelNum, featureValue
in enumerate(superpixelValues)
if featureValue == 0.5
])
definiteSuperpixelNums = numpy.array([
superpixelNum
for superpixelNum, featureValue
in enumerate(superpixelValues)
if featureValue == 1.0
])
superpixelsLabelData = Image().superpixelsData(image)
possibleMask = numpy.in1d(
superpixelsLabelData.flat,
possibleSuperpixelNums
).reshape(superpixelsLabelData.shape)
possibleMask = possibleMask.astype(numpy.bool_)
definiteMask = numpy.in1d(
superpixelsLabelData.flat,
definiteSuperpixelNums
).reshape(superpixelsLabelData.shape)
definiteMask = definiteMask.astype(numpy.bool_)
return possibleMask, definiteMask
def _superpixelsToMaskMarkup(self, superpixelValues, image):
possibleMask, definiteMask = self._superpixelsToMasks(superpixelValues, image)
markupMask = numpy.zeros(possibleMask.shape, dtype=numpy.uint8)
markupMask[possibleMask] = 128
markupMask[definiteMask] = 255
return markupMask
def saveSuperpixelMarkup(self, annotation, featureId, superpixelValues):
image = Image().load(annotation['imageId'], force=True, exc=True)
annotator = User().load(annotation['userId'], force=True, exc=True)
markupMask = self._superpixelsToMaskMarkup(superpixelValues, image)
markupMaskEncodedStream = ScikitSegmentationHelper.writeImage(markupMask, 'png')
markupFile = Upload().uploadFromFile(
obj=markupMaskEncodedStream,
size=len(markupMaskEncodedStream.getvalue()),
name='annotation_%s_%s.png' % (
annotation['_id'],
# Rename features to ensure the file is downloadable on Windows
featureId.replace(' : ', ' ; ').replace('/', ',')
),
# TODO: change this once a bug in upstream Girder is fixed
parentType='annotation',
parent=annotation,
attachParent=True,
user=annotator,
mimeType='image/png'
)
markupFile['superpixels'] = superpixelValues
# TODO: remove this once a bug in upstream Girder is fixed
markupFile['attachedToType'] = ['annotation', 'isic_archive']
markupFile = File().save(markupFile)
annotation['markups'][featureId] = {
'fileId': markupFile['_id'],
'present': bool(markupMask.any())
}
return Annotation().save(annotation)
def getMarkupFile(self, annotation, featureId, includeSuperpixels=False):
if featureId in annotation['markups']:
markupFile = File().load(
annotation['markups'][featureId]['fileId'],
force=True,
exc=True,
fields={'superpixels': includeSuperpixels}
)
return markupFile
else:
return None
def renderMarkup(self, annotation, featureId):
image = Image().load(annotation['imageId'], force=True, exc=True)
renderData = Image().imageData(image)
markupFile = Annotation().getMarkupFile(annotation, featureId)
if markupFile:
markupMask = Image()._decodeDataFromFile(markupFile)
else:
image = Image().load(annotation['imageId'], force=True, exc=True)
markupMask = numpy.zeros(
(
image['meta']['acquisition']['pixelsY'],
image['meta']['acquisition']['pixelsX']
),
dtype=numpy.uint8
)
possibleMask = markupMask == 128
definiteMask = markupMask == 255
POSSIBLE_OVERLAY_COLOR = numpy.array([250, 250, 0])
DEFINITE_OVERLAY_COLOR = numpy.array([0, 0, 255])
renderData[possibleMask] = POSSIBLE_OVERLAY_COLOR
renderData[definiteMask] = DEFINITE_OVERLAY_COLOR
return renderData
def filter(self, annotation, user=None, additionalKeys=None):
output = {
'_id': annotation['_id'],
'_modelType': 'annotation',
'studyId': annotation['studyId'],
'image': Image().filterSummary(
Image().load(annotation['imageId'], force=True, exc=True),
user),
'user': User().filterSummary(
user=User().load(annotation['userId'], force=True, exc=True),
accessorUser=user),
'state': Annotation().getState(annotation)
}
if Annotation().getState(annotation) == Study().State.COMPLETE:
output.update({
'status': annotation['status'],
'startTime': annotation['startTime'],
'stopTime': annotation['stopTime'],
'responses': annotation['responses'],
'markups': {
featureId: markup['present']
for featureId, markup
in annotation['markups'].items()
},
'log': annotation.get('log', [])
})
return output
def filterSummary(self, annotation, user=None):
return {
'_id': annotation['_id'],
'studyId': annotation['studyId'],
'userId': annotation['userId'],
'imageId': annotation['imageId'],
'state': self.getState(annotation)
}
def remove(self, annotation, **kwargs):
for featureId in annotation['markups'].keys():
File().remove(self.getMarkupFile(annotation, featureId))
return super(Annotation, self).remove(annotation)
def validate(self, doc): # noqa C901
for field in ['studyId', 'userId', 'imageId']:
if not isinstance(doc.get(field), ObjectId):
raise ValidationException(f'Annotation field "{field}" must be an ObjectId')
study = Study().load(doc['studyId'], force=True, exc=False)
if not study:
raise ValidationException(
'Annotation field "studyId" must reference an existing Study.')
# If annotation is complete
if doc.get('stopTime'):
schema = {
# '$schema': 'http://json-schema.org/draft-07/schema#',
'title': 'annotation',
'type': 'object',
'properties': {
'_id': {
# TODO
},
'studyId': {
# TODO
},
'imageId': {
# TODO
},
'userId': {
# TODO
},
'startTime': {
# TODO
},
'stopTime': {
# TODO
},
'status': {
'type': 'string',
'enum': ['ok', 'phi', 'quality', 'zoom', 'inappropriate', 'other']
},
'responses': {
'type': 'object',
'properties': {
question['id']: {
'type': 'string',
# TODO: Support non-'select' question types
'enum': question['choices']
}
for question in study['meta']['questions']
},
'additionalProperties': False
},
'markups': {
'type': 'object',
'properties': {
feature['id']: {
'type': 'object',
'properties': {
'fileId': {
# TODO
},
'present': {
'type': 'boolean'
}
},
'required': ['fileId', 'present'],
'additionalProperties': False
}
for feature in study['meta']['features']
},
'additionalProperties': False
},
'log': {
# TODO
}
},
'required': [
'_id', 'studyId', 'imageId', 'userId', 'startTime', 'stopTime', 'status',
'responses', 'markups', 'log'
],
'additionalProperties': False
}
try:
jsonschema.validate(doc, schema)
except jsonschema.ValidationError as e:
raise ValidationException(f'Invalid annotation: {str(e)}')
return doc
| ImageMarkup/isic-archive | isic_archive/models/annotation.py | Python | apache-2.0 | 10,692 |
<?xml version="1.0" encoding="utf-8"?>
<!-- generator="Joomla! - Open Source Content Management" -->
<?xml-stylesheet href="http://waterboard.lk/web/plugins/system/osolcaptcha/osolCaptcha/captchaStyle.css" type="text/css"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>முகப்பு</title>
<description><![CDATA[National Water Supply and Drainage Board]]></description>
<link>http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta</link>
<lastBuildDate>Mon, 19 Oct 2015 18:24:57 +0000</lastBuildDate>
<generator>Joomla! - Open Source Content Management</generator>
<atom:link rel="self" type="application/rss+xml" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss"/>
<language>ta-in</language>
<managingEditor>donotreply@waterboard.lk (National Water Supply and Drainage Board)</managingEditor>
<item>
<title>Western Central</title>
<link>http://waterboard.lk/web/index.php?option=com_content&view=article&id=42&catid=16&Itemid=202&lang=ta</link>
<guid isPermaLink="true">http://waterboard.lk/web/index.php?option=com_content&view=article&id=42&catid=16&Itemid=202&lang=ta</guid>
<description><![CDATA[<p style="text-align: justify;">System of Regional Support Centre (RSC) was established for smooth management of Operation & Maintenance (O&M) Section in 1992. This was a recommendation made by the Institutional Development Programme funded by USAID. At the inception, only four RSCs were established for Western, Southern, Central and North Central Provinces. All Water Supply Schemes (WSS) except Kalutara WSS were under the Western RSC. With the expansion of water supply facilities in Western Province, it was decided to divide Western RSC in to 3 RSCs in 2008. Accordingly, RSC- Western Central (WC) was established to coordinate activities related to the central part of Western Province.</p>
<p style="text-align: justify;">At present, RSC-WC geographically covers all areas in Colombo District except Dehiwala-Mount Lavinia and Moratuwa Municipal Council Areas. It consists of 02 Municipal Councils (Colombo & Sri Jayawardhanapura), 05 Urban Councils, 04 Provincial Council areas falling within 08 Divisional Secretary areas. RSC-WC has the largest number of connections (about 365,000 as at May 2012) when compared to all other RSCs. It generates the highest income for NWS&DB and in year 2011 the income was Rs. 5,152 million which was about 40% of the total annual income of NWS&DB.</p>
<p style="text-align: justify;">Organization structure of the RSC-WC is very much similar to the other RSCs with only few exceptions. RSC-WC is headed by the Deputy General Manager (DGM). Owing to the complexity of works involved in, DGM is assisted by three Assistant General Managers (AGMs) separately for Development, O&M and Water Loss Management. RSC had a total of 1,396 Staff as at May 2012.</p>
<div class="nn_sliders accordion panel-group" id="set-nn_sliders-1">
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-1" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#location-of-the-area"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
Location of the Area
</span></a>
</div>
<div class="accordion-body collapse" id="location-of-the-area">
<div class="accordion-inner panel-body">
<p><a href="http://waterboard.lk/web/images/contents/regional_support_centres/western_central/western_central_map.jpg" target="_blank"><img style="display: block; margin-left: auto; margin-right: auto;" src="http://waterboard.lk/web/images/contents/regional_support_centres/western_central/western_central_map.jpg" alt="western central map" width="500" height="313" /></a></p>
<p style="text-align: justify;">Click on below link to View or Download the original map published by the Survey Department of the Government of Sri Lanka.</p>
<ul class="pdf">
<li style="text-align: justify;"><a href="http://waterboard.lk/web/images/contents/regional_support_centres/western_central/colombo_map.pdf" target="_blank">Colombo District Map <br />[ PDF - 601 KB ]</a></li>
</ul>
</div></div></div></div>]]></description>
<author>test@maoil.com (piyo)</author>
<category>Regional Support Centres</category>
<pubDate>Mon, 18 Aug 2014 00:21:16 +0000</pubDate>
</item>
<item>
<title>Western - North (Gampaha District)</title>
<link>http://waterboard.lk/web/index.php?option=com_content&view=article&id=44&catid=16&Itemid=204&lang=ta</link>
<guid isPermaLink="true">http://waterboard.lk/web/index.php?option=com_content&view=article&id=44&catid=16&Itemid=204&lang=ta</guid>
<description><![CDATA[<p style="text-align: justify;">A Deputy General Manager (DGM) heads the Western North RSC with an Assistant General Manager (AGM) providing support in running the RSC unit. The O&M activities are divided by regions namely the Gampaha Region and the Towns North of Colombo (TNC) region and are managed by two different regional managers. The principal RSC functions are to provide necessary support to the two regional offices in the day to day O&M activities and to provide help and guidance in the ongoing scheme rehabilitation, and augmentation work.</p>
<p style="text-align: justify;">The O&M managers report to the DGM through the AGM and all RSC functions are monitored by the Additional General Manager for Western Zone. The RSC provides services to the regional offices only within their capacity; any additional help as necessary is obtained from the head office (HO) through the respective Additional General Manager.</p>
<div class="nn_sliders accordion panel-group" id="set-nn_sliders-2">
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-2" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#location-of-the-area-2"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
Location of the Area
</span></a>
</div>
<div class="accordion-body collapse" id="location-of-the-area-2">
<div class="accordion-inner panel-body">
<p style="text-align: center;"><a href="http://waterboard.lk/web/images/contents/regional_support_centres/western_north/gampaha_map.pdf" target="_blank"><img src="http://waterboard.lk/web/images/contents/regional_support_centres/western_north/gampaha_map.jpg" alt="gampaha map" width="600" height="530" /></a></p>
<p style="text-align: justify;">Click on below link to View or Download the original map published by the Survey Department of the Government of Sri Lanka.</p>
<ul class="pdf">
<li style="text-align: justify;"><a href="http://waterboard.lk/web/images/contents/regional_support_centres/western_north/gampaha_map.pdf" target="_blank">Gampaha District Map<br />[ PDF - 519 KB ]</a></li>
</ul>
</div></div></div>
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-2" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#comparison-of-service-connections"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
Comparison of Service Connections
</span></a>
</div>
<div class="accordion-body collapse" id="comparison-of-service-connections">
<div class="accordion-inner panel-body">
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;">As at end of</td>
<td style="text-align: center;">No. of Connection</td>
</tr>
<tr class="r1">
<td style="text-align: center;">2006</td>
<td style="text-align: center;" align="right">114318</td>
</tr>
<tr class="r2">
<td style="text-align: center;">2007</td>
<td style="text-align: center;" align="right">121535</td>
</tr>
<tr class="r1">
<td style="text-align: center;">2008</td>
<td style="text-align: center;" align="right">128851</td>
</tr>
<tr class="r2">
<td style="text-align: center;">2009</td>
<td style="text-align: center;" align="right">133387</td>
</tr>
<tr class="r1">
<td style="text-align: center;">2012</td>
<td style="text-align: center;" align="right">177981</td>
</tr>
<tr id="r2" class="r2">
<td style="text-align: center;">2013</td>
<td style="text-align: center;" align="right">198,273</td>
</tr>
<tr class="r1">
<td style="text-align: center;">2014 August</td>
<td style="text-align: center;" align="right">213,762</td>
</tr>
</tbody>
</table>
</div></div></div>
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-2" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#details-of-schemes-within-the-area"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
Details of Schemes within the area
</span></a>
</div>
<div class="accordion-body collapse" id="details-of-schemes-within-the-area">
<div class="accordion-inner panel-body">
<p>The quality of water being supplied is tested regularly. <a href="http://waterboard.lk/web/index.php?option=com_content&view=article&id=68&Itemid=273&lang=en">Click here</a> for a summary of test results taken island-wide.</p>
<h4>Schemes which are presently in operation</h4>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td>Region</td>
<td>Scheme</td>
<td style="text-align: right;">Total no. of connections as end of 31st March 2015</td>
<td>Average Monthly Production (m3/ month)</td>
</tr>
<tr class="r1">
<td rowspan="3">Towns North of Colombo</td>
<td>Kelaniya</td>
<td style="text-align: right;" align="right">61762</td>
<td style="text-align: right;" rowspan="3" align="right">4999444</td>
</tr>
<tr class="r2">
<td>Biyagama</td>
<td style="text-align: right;">66890</td>
</tr>
<tr class="r1">
<td>Ja-Ela</td>
<td style="text-align: right;">33279</td>
</tr>
<tr class="r2">
<td rowspan="19">Gampaha Region</td>
<td>Kirindiwela</td>
<td style="text-align: right;" align="right">3028</td>
<td style="text-align: right;" align="right">50090</td>
</tr>
<tr class="r1">
<td>Ranpokunagama</td>
<td style="text-align: right;" align="right">2985</td>
<td style="text-align: right;" align="right">87971</td>
</tr>
<tr class="r2">
<td>Gampaha</td>
<td style="text-align: right;" align="right">4377</td>
<td style="text-align: right;" align="right">112407</td>
</tr>
<tr class="r1">
<td>Udugampola</td>
<td style="text-align: right;" align="right">260</td>
<td style="text-align: right;" align="right">4511</td>
</tr>
<tr class="r2">
<td>Bataleeya</td>
<td style="text-align: right;" align="right">479</td>
<td style="text-align: right;" align="right">9318</td>
</tr>
<tr class="r1">
<td>Yakkala</td>
<td style="text-align: right;" align="right">6119</td>
<td style="text-align: right;" align="right">102317</td>
</tr>
<tr class="r2">
<td>Veyangoda/ Nittambuwa</td>
<td style="text-align: right;" align="right">6089</td>
<td style="text-align: right;" align="right">13317</td>
</tr>
<tr class="r1">
<td>Raddoluwa</td>
<td style="text-align: right;" align="right">6353</td>
<td style="text-align: right;" align="right">201907</td>
</tr>
<tr class="r2">
<td>Mirigama</td>
<td style="text-align: right;" align="right">1104</td>
<td align="right">19248</td>
</tr>
<tr class="r1">
<td>Pugoda</td>
<td style="text-align: right;" align="right">1125</td>
<td align="right">19821</td>
</tr>
<tr class="r2">
<td>Negombo</td>
<td style="text-align: right;" align="right">27472</td>
<td align="right">912680</td>
</tr>
<tr class="r1">
<td>Divulapitiya</td>
<td style="text-align: right;" align="right">2157</td>
<td align="right">27412</td>
</tr>
<tr class="r2">
<td>Minuwangoda</td>
<td style="text-align: right;" align="right">967</td>
<td align="right">17355</td>
</tr>
<tr class="r1">
<td>Katunayake</td>
<td style="text-align: right;">614</td>
<td style="text-align: right;">108063</td>
</tr>
<tr class="r2">
<td>Malwana</td>
<td style="text-align: right;" rowspan="5"> </td>
<td style="text-align: right;" rowspan="5"> </td>
</tr>
<tr class="r1">
<td>Mabima Heiyanthuduwa</td>
</tr>
<tr class="r2">
<td>Galahitiyawa</td>
</tr>
<tr class="r1">
<td>Urapola</td>
</tr>
<tr class="r2">
<td>Dompe</td>
</tr>
<tr class="mhead">
<td style="text-align: center;" colspan="2">Total</td>
<td style="text-align: right;" align="right">188480</td>
<td style="text-align: right;" align="right">6685861</td>
</tr>
</tbody>
</table>
<br />
</div></div></div>
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-2" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#contact-details"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
Contact Details
</span></a>
</div>
<div class="accordion-body collapse" id="contact-details">
<div class="accordion-inner panel-body">
<p>Please <a href="http://waterboard.lk/web/images/contents/regional_support_centres/western_north/contacts_western_north.pdf" target="_blank">click here</a> to view / download full contact list for Regional Support Centre (Western - North)</p>
<table>
<tbody>
<tr valign="top">
<td><strong>Postal Address</strong></td>
<td><strong>:</strong></td>
<td>Regional Support Centre (Western - North)<br />National Water Supply & Drainage Board<br />433/4A, Ganemulla Road,<br />Kadawatha.</td>
</tr>
<tr valign="top">
<td><strong>Telephone</strong></td>
<td><strong>:</strong></td>
<td>+94 11 2922131, +94 11 2922137, +94 11 2922145,<br />+94 11 2922129, +94 11 2927177</td>
</tr>
<tr valign="top">
<td><strong>Fax</strong></td>
<td><strong>:</strong></td>
<td>+94 11 2922146</td>
</tr>
</tbody>
</table>
<table class="mtable conname" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td>Name & Designation</td>
<td>Mobile</td>
<td>E-mail</td>
</tr>
<tr class="r1">
<td><strong>Mr. K.W. Premasiri</strong><br />Deputy General Manager</td>
<td>+94 77 7591525</td>
<td><a href="mailto:dgmwn@waterboard.lk">dgmwn@waterboard.lk</a></td>
</tr>
<tr class="r2">
<td><strong>Mr. S.D.A.N. ranjith</strong><br />Assistant General Manager</td>
<td>+94 77 7700867</td>
<td><a href="mailto:agmwn@waterboard.lk">agmwn@waterboard.lk</a></td>
</tr>
</tbody>
</table>
<h4>Managers (Operational & Maintenance)</h4>
<table class="mtable conname" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td>Name & Designation</td>
<td>Telephone</td>
<td>Fax</td>
<td>Mobile</td>
<td>E-mail</td>
</tr>
<tr class="r1">
<td><strong>Mr. K.S.A.U. Gunenayake</strong><br />(Gampaha)<br /><em><strong>Responsive Areas:</strong></em> Gampaha, Negombo, Veyangoda, Nittambuwa, Yakkala, Raddoluwa, Divulapitiya, Meerigama, Minuwangoda, Pugoda, Bataleeya, Ranpokunagama</td>
<td>+94 33 2231464, +94 11 2232718</td>
<td>+94 33 2231464, +94 11 2232718</td>
<td>+94 77 2265505</td>
<td><a href="mailto:managergam@waterboard.lk">managergam<br />@waterboard.lk</a></td>
</tr>
<tr class="r2">
<td><strong>Mr. A.S. Wijerathna</strong><br />(Towns North of Colombo)<br /><em><strong>Responsive Areas:</strong></em> Kelaniya, Biyagama, Ja-Ela, Dompe, Wattala, Ragama, Kandana, Mahara</td>
<td>+94 11 2909854</td>
<td>+94 11 4741981</td>
<td>+94 71 8240948</td>
<td><a href="mailto:managertnc@waterboard.lk">managertnc<br />@waterboard.lk</a></td>
</tr>
</tbody>
</table>
<p><span style="font-family: Arial, Helvetica, sans-serif; font-size: 12.1599998474121px; font-weight: bold; line-height: 15.8079996109009px;">Area Engineer's Office (Kelaniya)</span></p>
<table class="mtable conname" style="width: 678px;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td>Office Name</td>
<td>Telephone</td>
<td>Fax</td>
<td>Mobile</td>
<td>E-mail</td>
</tr>
<tr class="r1">
<td><strong>Area Engineer's Office - Kelaniya</strong></td>
<td>+94 11 4886818, +94 71 8148456</td>
<td>-</td>
<td>+94 77 2265505</td>
<td><a href="mailto:managergam@waterboard.lk"> </a></td>
</tr>
<tr class="r2">
<td><strong>OIC Office - Kelaniya</strong></td>
<td>+94 11 2911009</td>
<td>-</td>
<td>+94 775176690</td>
<td> </td>
</tr>
<tr class="r2">
<td><strong>OIC Office - Wattala</strong></td>
<td>+94 11 2952770</td>
<td>-</td>
<td>+94 718618241</td>
<td> </td>
</tr>
</tbody>
</table>
<p style="font-size: 12.1599998474121px; line-height: 15.8079996109009px;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 12.1599998474121px; font-weight: bold; line-height: 15.8079996109009px;">Area Engineer's Office (Biyagama)</span></p>
<table class="mtable conname" style="width: 678px;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td>Office Name</td>
<td>Telephone</td>
<td>Fax</td>
<td>Mobile</td>
<td>E-mail</td>
</tr>
<tr class="r1">
<td><strong>Area Engineer's Office -Biyagama</strong></td>
<td>+94 11 2920244, +94 71 8148456</td>
<td>-</td>
<td>+94 77 6711299</td>
<td><a href="mailto:managergam@waterboard.lk"> </a></td>
</tr>
<tr class="r2">
<td><strong>OIC Office - Mahara</strong></td>
<td>+94 11 4942146</td>
<td>-</td>
<td>+94 71 4451932</td>
<td> </td>
</tr>
<tr class="r2">
<td><strong>OIC Office - Biyagama</strong></td>
<td>+94 11 2487003</td>
<td>-</td>
<td>+94 71 4458316</td>
<td> </td>
</tr>
</tbody>
</table>
<p style="font-size: 12.1599998474121px; line-height: 15.8079996109009px;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 12.1599998474121px; font-weight: bold; line-height: 15.8079996109009px;">Area Engineer's Office (Ja Ela)</span></p>
<table class="mtable conname" style="width: 678px;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td>Office Name</td>
<td>Telephone</td>
<td>Fax</td>
<td>Mobile</td>
<td>E-mail</td>
</tr>
<tr class="r1">
<td><strong>Area Engineer's Office -Ja Ela</strong></td>
<td>+94 11 2237477, +94 11 5333068</td>
<td>-</td>
<td>+94 71 1771845</td>
<td><a href="mailto:managergam@waterboard.lk"> </a></td>
</tr>
<tr class="r2">
<td><strong>OIC Office - Ja Ela</strong></td>
<td>+94 11 2229828</td>
<td>-</td>
<td>+94 71 8055609</td>
<td> </td>
</tr>
<tr class="r2">
<td><strong>OIC Office - Ragama</strong></td>
<td>+94 11 2951552</td>
<td>-</td>
<td>+94 71 3166858</td>
<td> </td>
</tr>
</tbody>
</table>
</div></div></div>
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-2" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#key-facts-and-figures"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
Key Facts and Figures
</span></a>
</div>
<div class="accordion-body collapse" id="key-facts-and-figures">
<div class="accordion-inner panel-body">
<h4>Service Standard Indicators</h4>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;" rowspan="2">Service Indicators </td>
<td style="text-align: center;" colspan="3">RSC (Western - North) 2008</td>
</tr>
<tr class="mhead">
<td style="text-align: center; width: 60px;">Towns North</td>
<td style="text-align: center; width: 70px;">Gamapaha</td>
<td style="text-align: center; width: 60px;">Regional Average</td>
</tr>
<tr class="r1">
<td>Water Coverage (%) Pipe System maintained by NWSDB</td>
<td style="text-align: right;" align="right">39.4%</td>
<td style="text-align: right;" align="right">13.0%</td>
<td style="text-align: right;" align="right">25.1%</td>
</tr>
<tr class="r2">
<td>Per Capita Consumption (l/c/d)</td>
<td style="text-align: right;" align="right">117.3</td>
<td style="text-align: right;" align="right">116.7</td>
<td style="text-align: right;" align="right">117.1</td>
</tr>
<tr class="r1">
<td>Water Availability (hours)</td>
<td style="text-align: right;" align="right">23.5</td>
<td style="text-align: right;" align="right">16.4</td>
<td style="text-align: right;" align="right">21.4</td>
</tr>
<tr class="r2">
<td>Water Quality - Bacteriological Quality Compliance</td>
<td style="text-align: right;">n/a</td>
<td style="text-align: right;">n/a</td>
<td style="text-align: right;" align="right">94.7%</td>
</tr>
<tr class="r1">
<td>Water Quality - Bacteriological Testing Compliance</td>
<td style="text-align: right;">n/a</td>
<td style="text-align: right;">n/a</td>
<td style="text-align: right;" align="right">100%</td>
</tr>
<tr class="r2">
<td>Water Quality - All Samples Compliance</td>
<td style="text-align: right;">n/a</td>
<td style="text-align: right;">n/a</td>
<td style="text-align: right;" align="right">95.8%</td>
</tr>
<tr class="r1">
<td>Sewerage Coverage (%)</td>
<td style="text-align: right;" align="right">0.0%</td>
<td style="text-align: right;" align="right">3.4%</td>
<td style="text-align: right;" align="right">2.5%</td>
</tr>
</tbody>
</table>
<h4>Operational Indicators</h4>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;" rowspan="2">Operational Indicators</td>
<td style="text-align: center;" colspan="3">RSC (Western - North) 2008</td>
</tr>
<tr class="mhead">
<td style="text-align: center; width: 60px;">Towns North</td>
<td style="text-align: center; width: 70px;">Gamapaha</td>
<td style="text-align: center; width: 60px;">Regional Average</td>
</tr>
<tr class="r1">
<td>Non-Revenue Water (%)</td>
<td style="text-align: right;">22.9%</td>
<td style="text-align: right;">17.0%</td>
<td style="text-align: right;">24.1%</td>
</tr>
<tr class="r2">
<td>Non-Revenue Water - m3/conn/day</td>
<td align="right">0.25</td>
<td align="right">0.17</td>
<td align="right">0.23</td>
</tr>
<tr class="r1">
<td>Defective Meters per '000 connections</td>
<td align="right">30</td>
<td align="right">100</td>
<td align="right">51</td>
</tr>
<tr class="r2">
<td>Total Staff/ 1000 connection</td>
<td align="right">3</td>
<td align="right">8</td>
<td align="right">5</td>
</tr>
<tr class="r1">
<td>Operational Staff/ 1000 connection</td>
<td align="right">2</td>
<td align="right">6</td>
<td align="right">3</td>
</tr>
<tr class="r2">
<td>Estimated Bills/ 1000 connections</td>
<td align="right">161</td>
<td align="right">41</td>
<td align="right">126</td>
</tr>
</tbody>
</table>
<h4>Performance in Customer Service</h4>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;" rowspan="2">Customer Service Indicators</td>
<td style="text-align: center;" colspan="3">RSC (Western - North) 2008</td>
</tr>
<tr class="mhead">
<td style="text-align: center; width: 60px;">Towns North</td>
<td style="text-align: center; width: 70px;">Gamapaha</td>
<td style="text-align: center; width: 60px;">Regional Average</td>
</tr>
<tr class="r1">
<td>Response to requests for new service connections (%)</td>
<td style="text-align: right;">98.5%</td>
<td style="text-align: right;">86.2%</td>
<td style="text-align: right;">95.8%</td>
</tr>
<tr class="r2">
<td>Customer Complaints Volume (Complaints/ 1000 connection)</td>
<td style="text-align: right;">90.3</td>
<td style="text-align: right;">154.4</td>
<td style="text-align: right;">109.1</td>
</tr>
<tr class="r1">
<td>Customer Complaints Resolution</td>
<td style="text-align: right;">95.5%</td>
<td style="text-align: right;">73.0%</td>
<td style="text-align: right;">86.2%</td>
</tr>
</tbody>
</table>
<h4>Key Performance Indicators (KPIs)</h4>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;" rowspan="2">Financial KPIs</td>
<td style="text-align: center;" colspan="3">RSC (Western - North) 2008</td>
</tr>
<tr class="mhead">
<td style="text-align: center; width: 60px;">Kelaniya</td>
<td style="text-align: center; width: 70px;">Gamapaha</td>
<td style="text-align: center; width: 60px;">Regional Average</td>
</tr>
<tr class="r1">
<td>Collection Ratio (%)</td>
<td style="text-align: right;">104.5%</td>
<td style="text-align: right;">98.7%</td>
<td style="text-align: right;">102.0%</td>
</tr>
<tr class="r2">
<td>Accounts Receivable Period (months)</td>
<td style="text-align: right;" align="right">5.9</td>
<td style="text-align: right;" align="right">2.1</td>
<td style="text-align: right;" align="right">4.2</td>
</tr>
<tr class="r1">
<td>Collectable Accounts Receivable Period (months)</td>
<td style="text-align: right;" align="right">2.4</td>
<td style="text-align: right;" align="right">0</td>
<td style="text-align: right;" align="right">1.4</td>
</tr>
<tr class="r2">
<td>Operating Ratio</td>
<td style="text-align: right;" align="right">1.02</td>
<td style="text-align: right;" align="right">1</td>
<td style="text-align: right;" align="right">1.01</td>
</tr>
<tr class="r1">
<td>Production Cost (LKR/ m3 Produced)</td>
<td style="text-align: right;" align="right">13.72</td>
<td style="text-align: right;" align="right">26.39</td>
<td style="text-align: right;" align="right">17.08</td>
</tr>
<tr class="r2">
<td>Average Tariff (LKR/ m3 Sold)</td>
<td style="text-align: right;" align="right">13.04</td>
<td style="text-align: right;" align="right">26.03</td>
<td style="text-align: right;" align="right">16.68</td>
</tr>
<tr class="r1">
<td>Stock Efficiency (LKR/ connection)</td>
<td style="text-align: right;">n/a</td>
<td style="text-align: right;">n/a</td>
<td style="text-align: right;" align="right">2189</td>
</tr>
</tbody>
</table>
</div></div></div></div>]]></description>
<author>test@maoil.com (piyo)</author>
<category>Regional Support Centres</category>
<pubDate>Mon, 18 Aug 2014 00:22:29 +0000</pubDate>
</item>
<item>
<title>North - Western (Puttalam and Kurunegala Districts)</title>
<link>http://waterboard.lk/web/index.php?option=com_content&view=article&id=47&catid=16&Itemid=207&lang=ta</link>
<guid isPermaLink="true">http://waterboard.lk/web/index.php?option=com_content&view=article&id=47&catid=16&Itemid=207&lang=ta</guid>
<description><![CDATA[<p style="text-align: justify;">Under the present setup of RSC (North Western), both Deputy General Manager (DGM) and Assistant General Manager (AGM) look after the O&M functions in addition to their development functions. The Manager (O&M) usually coordinates with the AGM for his normal O&M functions but in the case of development functions like rehabilitation, he involves the DGM. In addition budgetary controls are also being managed through the DGM’s office.</p>
<p style="text-align: justify;">The District Engineer (DE) Kurunegala office is located within the same premises as the Manager (O&M) office as a result of which the independence and identity of DE’s office Kurunegala is in question. Most of the coordination and consumer relation functions are commonly handled at both offices but in some instances customers tend to bypass the DE and directly access the Manager (O&M). In contrast, the DE office Puttalam which is located in Chilaw which is far away from the Manager (O&M) Kurunegala office appears to be functioning better. A major portion of the service connections are now in Puttalam district compared to Kurunegala district which has developed only a limited number of water supply systems in the past.</p>
<table>
<tbody>
<tr>
<td> <img src="http://waterboard.lk/web/images/contents/regional_support_centres/north_western/Wariyapola2.jpg" alt="Wariyapola2" width="728" height="447" /></td>
</tr>
</tbody>
</table>
<div class="nn_sliders accordion panel-group" id="set-nn_sliders-3">
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-3" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#location-of-the-area-3"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
Location of the Area
</span></a>
</div>
<div class="accordion-body collapse" id="location-of-the-area-3">
<div class="accordion-inner panel-body">
<table style="width: 100%;">
<tbody>
<tr valign="top">
<td style="text-align: center;"><a href="http://waterboard.lk/web/images/contents/regional_support_centres/north_western/north_western_map.png" target="_blank"><img src="http://waterboard.lk/web/images/contents/regional_support_centres/north_western/north_western_map.png" alt="north western map" width="350" height="243" /></a><br /><em>Please click on map to enlarge it</em></td>
<td>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;" colspan="2">Statistics of the Area</td>
</tr>
<tr class="r1">
<td>Total Area</td>
<td style="text-align: right;">7,888.0 km2</td>
</tr>
<tr class="r2">
<td>Population (2012)</td>
<td style="text-align: right;" align="right">2,372,185</td>
</tr>
</tbody>
</table>
* Estimated mid year Population by the Department of Census and Statistics - Sri Lanka</td>
</tr>
</tbody>
</table>
<p style="text-align: justify;">Click on below links to View or Download the original map published by the Survey Department of the Government of Sri Lanka.</p>
<ul class="pdf">
<li style="text-align: justify;"><a href="http://waterboard.lk/web/images/contents/regional_support_centres/north_western/puttalam_district_map.pdf" target="_blank">Puttalam District Map<br />[ PDF - 397 KB ]</a></li>
<li style="text-align: justify;"><a href="http://waterboard.lk/web/images/contents/regional_support_centres/north_western/kurunegala_district_map.pdf" target="_blank">Kurunegala District Map<br />[ PDF - 573 KB ]</a></li>
</ul>
</div></div></div>
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-3" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#comparison-of-service-connections-2"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
Comparison of Service Connections
</span></a>
</div>
<div class="accordion-body collapse" id="comparison-of-service-connections-2">
<div class="accordion-inner panel-body">
<table class="mtable" style="width: 694px; height: 325px;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;">As at end of</td>
<td style="text-align: center;">No. of Connection</td>
<td style="text-align: center;" rowspan="9"><img src="http://waterboard.lk/web/images/contents/regional_support_centres/north_western/North_Western.JPG" alt="North Western" width="468" height="296" /></td>
</tr>
<tr class="r1">
<td style="text-align: center;">2006</td>
<td style="text-align: center;" align="right">26,218</td>
</tr>
<tr class="r2">
<td style="text-align: center;">2007</td>
<td style="text-align: center;" align="right">28,470</td>
</tr>
<tr class="r1">
<td style="text-align: center;">2008</td>
<td style="text-align: center;" align="right">32,684</td>
</tr>
<tr class="r2">
<td style="text-align: center;">2009</td>
<td style="text-align: center;" align="right">36,347</td>
</tr>
<tr class="r1">
<td style="text-align: center;">2010</td>
<td style="text-align: center;" align="right">40,069</td>
</tr>
<tr class="r2">
<td style="text-align: center;">2011</td>
<td style="text-align: center;" align="right">46,500</td>
</tr>
<tr class="r1">
<td style="text-align: center;">2012</td>
<td style="text-align: center;" align="right">53,580</td>
</tr>
<tr class="r2">
<td style="text-align: center;">2013</td>
<td style="text-align: center;" align="right">58,805</td>
</tr>
</tbody>
</table>
</div></div></div>
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-3" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#details-of-schemes-within-the-area-2"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
Details of Schemes within the area
</span></a>
</div>
<div class="accordion-body collapse" id="details-of-schemes-within-the-area-2">
<div class="accordion-inner panel-body">
<p>The quality of water being supplied is tested regularly. <a href="http://waterboard.lk/web/index.php?option=com_content&view=article&id=68&Itemid=273&lang=en">Click here</a> for a summary of test results taken island-wide.</p>
<h4>Schemes which are presently in operation</h4>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td>Region</td>
<td>Scheme</td>
<td style="text-align: center;">Total no. of connections as end of 31st December 2013</td>
<td style="text-align: center;">Average Monthly Production (m3/ month)</td>
</tr>
<tr class="r1">
<td rowspan="21">Kurunegala Distrct</td>
<td>Polgahawela</td>
<td style="text-align: right;" align="right">4,050</td>
<td class="r2" style="text-align: right;" align="right">64,059</td>
</tr>
<tr class="r2">
<td>Alawwa</td>
<td style="text-align: right;" align="right">1,340</td>
<td style="text-align: right;" align="right">19,407</td>
</tr>
<tr class="r1">
<td>Ambanpola</td>
<td style="text-align: right;" align="right">1,089</td>
<td style="text-align: right;" align="right">14,364</td>
</tr>
<tr class="r2">
<td>Ogodapola</td>
<td style="text-align: right;" align="right">441</td>
<td style="text-align: right;" align="right">7,272</td>
</tr>
<tr class="r1">
<td>Dambadeniya</td>
<td style="text-align: right;" align="right">1,490</td>
<td style="text-align: right;" align="right">24,650</td>
</tr>
<tr class="r2">
<td>Narammala</td>
<td style="text-align: right;" align="right">2,638</td>
<td style="text-align: right;" align="right">36,220</td>
</tr>
<tr class="r1">
<td>Nikaweratiya</td>
<td style="text-align: right;" align="right">2,366</td>
<td style="text-align: right;" align="right">50,317</td>
</tr>
<tr class="r2">
<td>Pannala</td>
<td style="text-align: right;" align="right">360</td>
<td style="text-align: right;" align="right">5,311</td>
</tr>
<tr class="r1">
<td>Gokarella</td>
<td style="text-align: right;" align="right">571</td>
<td style="text-align: right;" align="right">7,148</td>
</tr>
<tr class="r2">
<td>Wariyapola</td>
<td style="text-align: right;" align="right">2,533</td>
<td style="text-align: right;" align="right">32,033</td>
</tr>
<tr class="r1">
<td>Dodamgaslanda</td>
<td style="text-align: right;" align="right">655</td>
<td style="text-align: right;" align="right">9,113</td>
</tr>
<tr class="r2">
<td>Giriulla</td>
<td style="text-align: right;" align="right">1,305</td>
<td style="text-align: right;" align="right">23,622</td>
</tr>
<tr class="r1">
<td>Galgamuwa</td>
<td style="text-align: right;" align="right">1,510</td>
<td style="text-align: right;" align="right">24,207</td>
</tr>
<tr class="r2">
<td>Rambadagalla</td>
<td style="text-align: right;" align="right">717</td>
<td style="text-align: right;" align="right">10,399</td>
</tr>
<tr class="r1">
<td>Udugama</td>
<td style="text-align: right;">49</td>
<td style="text-align: right;">517</td>
</tr>
<tr class="r2">
<td>Kurunegala</td>
<td style="text-align: right;">-</td>
<td style="text-align: right;">178,824</td>
</tr>
<tr class="r1">
<td>Hettipola</td>
<td style="text-align: right;">-</td>
<td style="text-align: right;">9,257</td>
</tr>
<tr class="r2">
<td>Wannigama</td>
<td style="text-align: right;">168</td>
<td style="text-align: right;">2,061</td>
</tr>
<tr class="r1">
<td>Padeniya</td>
<td style="text-align: right;">353</td>
<td style="text-align: right;">-</td>
</tr>
<tr class="r2">
<td>Buluwala</td>
<td style="text-align: right;">154</td>
<td style="text-align: right;">-</td>
</tr>
<tr class="r1">
<td>Lake Side</td>
<td style="text-align: right;">10</td>
<td style="text-align: right;">-</td>
</tr>
<tr class="r2">
<td rowspan="10">Puttalam District</td>
<td>Rahamathnagar</td>
<td style="text-align: right;" align="right">1,705</td>
<td style="text-align: right;" align="right">23,280</td>
</tr>
<tr class="r1">
<td>Kakkapalliya</td>
<td style="text-align: right;" align="right">6,095</td>
<td style="text-align: right;" align="right">94,002</td>
</tr>
<tr class="r2">
<td>Andigama</td>
<td style="text-align: right;" align="right">395</td>
<td style="text-align: right;" align="right">4,408</td>
</tr>
<tr class="r1">
<td>Chilaw</td>
<td style="text-align: right;" align="right">6,713</td>
<td style="text-align: right;" align="right">121,279</td>
</tr>
<tr class="r2">
<td>Puttalam</td>
<td style="text-align: right;" align="right">11,401</td>
<td style="text-align: right;" align="right">209,838</td>
</tr>
<tr class="r1">
<td>Anamaduwa</td>
<td style="text-align: right;" align="right">967</td>
<td style="text-align: right;" align="right">11,348</td>
</tr>
<tr class="r2">
<td>Wennappuwa</td>
<td style="text-align: right;" align="right">1,484</td>
<td style="text-align: right;" align="right">22,154</td>
</tr>
<tr class="r1">
<td>Dankotuwa</td>
<td style="text-align: right;" align="right">3,544</td>
<td style="text-align: right;" align="right">62,321</td>
</tr>
<tr class="r2">
<td>Nattandiya</td>
<td style="text-align: right;" align="right">2,179</td>
<td style="text-align: right;" align="right">30,379</td>
</tr>
<tr class="r1">
<td>Samudigama</td>
<td style="text-align: right;">-</td>
<td style="text-align: right;">-</td>
</tr>
<tr class="mhead">
<td style="text-align: center;" colspan="2">Total</td>
<td style="text-align: right;" align="right">56,284</td>
<td style="text-align: right;" align="right">1,097,790</td>
</tr>
</tbody>
</table>
<h4>Ongoing Projects</h4>
<h5>Small and Medium Water Supply Projects</h5>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td rowspan="2">Project Name </td>
<td style="text-align: center; width: 75px;" rowspan="2">No. of Beneficiaries </td>
<td style="text-align: center; width: 130px;" rowspan="2">Total Cost Estimate<br />(Rs. Million) </td>
<td style="text-align: center;" colspan="2">Duration</td>
</tr>
<tr class="mhead">
<td style="text-align: center;">From</td>
<td style="text-align: center;">To</td>
</tr>
<tr class="r1">
<td>Nikaweratiya, Maho, Wariyapola Water Supply Project</td>
<td align="right">60,000</td>
<td align="right">996.7</td>
<td align="right">1999</td>
<td align="right">2014</td>
</tr>
<tr class="r2">
<td>Ibbagamuwa Water Supply Project</td>
<td align="right">7,200</td>
<td align="right">239.0</td>
<td align="right">2012</td>
<td align="right">2015</td>
</tr>
<tr class="r1">
<td>Dambadeniya Water Supply Project</td>
<td align="right">50,000</td>
<td align="right">796.0</td>
<td align="right">2012</td>
<td align="right">2015</td>
</tr>
<tr class="r2">
<td>Divulagane Water Supply Project</td>
<td align="right">1,800</td>
<td align="right">47.0</td>
<td align="right">2013</td>
<td align="right">2014</td>
</tr>
</tbody>
</table>
</div></div></div>
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-3" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#contact-details-2"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
Contact Details
</span></a>
</div>
<div class="accordion-body collapse" id="contact-details-2">
<div class="accordion-inner panel-body">
<p>Please <a href="https://drive.google.com/uc?export=download&id=0BwBg25kWbLu2WV9QSS1weXBkWms" target="_blank">click here</a> to view / download full contact list for Regional Support Centre (North Western)</p>
<table>
<tbody>
<tr valign="top">
<td><strong>Postal Address</strong></td>
<td><strong>:</strong></td>
<td>Regional Support Centre (North Western)<br />National Water Supply & Drainage Board<br />Dambulla Road, Kurunegala</td>
</tr>
<tr valign="top">
<td><strong>Telephone</strong></td>
<td><strong>:</strong></td>
<td>+94 37 2221161, +94 37 2223158, +94 37 2225862</td>
</tr>
<tr valign="top">
<td><strong>Fax</strong></td>
<td><strong>:</strong></td>
<td>+94 37 2230086, +94 37 2228564</td>
</tr>
</tbody>
</table>
<table class="mtable conname" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td>Name & Designation</td>
<td style="text-align: center;">Telephone</td>
<td style="text-align: center;">Mobile</td>
<td>E-mail</td>
</tr>
<tr class="r1">
<td>
<p><strong>Mr. N.E.M.S.B. Ekanayaka</strong><br />Deputy General Manager</p>
<p> </p>
</td>
<td style="text-align: center;">+94 37 2221161,<br />+94 37 2223158,<br />+94 37 2225862 </td>
<td style="text-align: center;">+94 77 2017800</td>
<td><a href="mailto:dgmnw@waterboard.lk">dgmnw@waterboard.lk</a></td>
</tr>
<tr class="r2">
<td><strong>Mr. M.A.G. Susantha</strong><br />Assistant General Manager (North Western)</td>
<td style="text-align: center;">
<p>+94 37 2221161,<br />+94 37 2223158,<br />+94 37 2225862</p>
</td>
<td style="text-align: center;">
<p>+94 77 2017799</p>
</td>
<td><a href="mailto:agmnw@waterboard.lk">agmnw@waterboard.lk</a></td>
</tr>
</tbody>
</table>
<h4>Managers (Operational & Maintenance)</h4>
<table class="mtable conname" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td>Name & Designation</td>
<td style="text-align: center;">Telephone</td>
<td style="text-align: center;">Fax</td>
<td style="text-align: center;">Mobile</td>
<td>E-mail</td>
</tr>
<tr class="r1">
<td><strong>Mr. G.W. Deshapriya</strong><br />(Kurunegala)<br /><em><strong>Responsive Areas:</strong></em> Kurunegala & Puttalam Districts</td>
<td style="text-align: center;">+94 37 2221161,<br />+94 37 2223158,<br />+94 37 2225862</td>
<td style="text-align: center;">+94 37 2231401</td>
<td style="text-align: center;">+94 77 489653</td>
<td><a href="mailto:managerkuru@waterboard.lk">managerkuru<br />@waterboard.lk</a></td>
</tr>
</tbody>
</table>
</div></div></div>
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-3" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#key-facts-and-figures-2"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
Key Facts and Figures
</span></a>
</div>
<div class="accordion-body collapse" id="key-facts-and-figures-2">
<div class="accordion-inner panel-body">
<h4>Service Standard Indicators</h4>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;" rowspan="2">Service Indicators </td>
<td style="text-align: center;">RSC (North Western) 2013</td>
</tr>
<tr class="mhead">
<td style="text-align: center; width: 200px;">Regional Average</td>
</tr>
<tr class="r1">
<td>Water Coverage (%) Pipe System maintained by NWSDB</td>
<td style="text-align: right;" align="right">9.0%</td>
</tr>
<tr class="r2">
<td>Per Capita Consumption (l/c/d)</td>
<td style="text-align: right;" align="right">99.7</td>
</tr>
<tr class="r1">
<td>Water Availability (hours)</td>
<td style="text-align: right;" align="right">21</td>
</tr>
<tr class="r2">
<td>Water Quality - Bacteriological Quality Compliance</td>
<td style="text-align: right;" align="right">99%</td>
</tr>
<tr class="r1">
<td>Water Quality - Bacteriological Testing Compliance</td>
<td style="text-align: right;" align="right">100.0%</td>
</tr>
</tbody>
</table>
<h4>Operational Indicators</h4>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;" rowspan="2">Operational Indicators</td>
<td style="text-align: center;">RSC (North Western) 2013</td>
</tr>
<tr class="mhead">
<td style="text-align: center; width: 200px;">Regional Average</td>
</tr>
<tr class="r1">
<td>Non-Revenue Water (%)</td>
<td style="text-align: right;">12.66%</td>
</tr>
<tr class="r2">
<td>Non-Revenue Water - m3/conn/day</td>
<td align="right">0.081</td>
</tr>
<tr class="r1">
<td>Defective Meters per '000 connections</td>
<td align="right">12</td>
</tr>
<tr class="r2">
<td>Total Staff/ 1000 connection</td>
<td align="right">7.1</td>
</tr>
<tr class="r1">
<td>Operational Staff/ 1000 connection</td>
<td align="right">5.3</td>
</tr>
<tr class="r2">
<td>Estimated Bills/ 1000 connections</td>
<td align="right">24.8</td>
</tr>
</tbody>
</table>
<h4>Performance in Customer Service</h4>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;" rowspan="2">Customer Service Indicators</td>
<td style="text-align: center;">RSC (North Western) 2013</td>
</tr>
<tr class="mhead">
<td style="text-align: center; width: 200px;">Regional Average</td>
</tr>
<tr class="r1">
<td>Response to requests for new service connections (%)</td>
<td style="text-align: right;">100.0%</td>
</tr>
<tr class="r2">
<td>Customer Complaints Volume (Complaints/ 1000 connection)</td>
<td style="text-align: right;">1.7</td>
</tr>
<tr class="r1">
<td>Customer Complaints Resolution</td>
<td style="text-align: right;">86.9%</td>
</tr>
</tbody>
</table>
<h4>Key Performance Indicators (KPIs)</h4>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;" rowspan="2">Financial KPIs</td>
<td style="text-align: center;">RSC (North Western) 2013</td>
</tr>
<tr class="mhead">
<td style="text-align: center; width: 200px;">Regional Average</td>
</tr>
<tr class="r1">
<td>Collection Ratio (%)</td>
<td style="text-align: right;">99.5%</td>
</tr>
<tr class="r2">
<td>Accounts Receivable Period (months)</td>
<td style="text-align: right;" align="right">0.62</td>
</tr>
<tr class="r1">
<td>Collectable Accounts Receivable Period (months)</td>
<td style="text-align: right;" align="right">0.1</td>
</tr>
<tr class="r2">
<td>Operating Ratio</td>
<td style="text-align: right;" align="right">1.28</td>
</tr>
<tr class="r1">
<td>Production Cost (LKR/ m3 Produced)</td>
<td style="text-align: right;" align="right">31.70</td>
</tr>
<tr class="r2">
<td>Average Tariff (LKR/ m3 Sold)</td>
<td style="text-align: right;" align="right">15.31</td>
</tr>
<tr class="r1">
<td>Stock Efficiency (LKR/ connection)</td>
<td style="text-align: right;" align="right">2,624</td>
</tr>
</tbody>
</table>
</div></div></div>
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-3" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#ckd-programme-in-year-2014"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
<span style="font-size: 12.1599998474121px; line-height: 15.8079996109009px;">CKD Programme in Year 2014</span>
</span></a>
</div>
<div class="accordion-body collapse" id="ckd-programme-in-year-2014">
<div class="accordion-inner panel-body">
<h4>RURAL WATER SECTION – NORTH WESTERN PROVINCE - WORK DONE UNDER CKD PROGRAMME IN YEAR 2014</h4>
<p>• Hand Pumps Rehabilitation Programme expending 13.10 MRs.</p>
<p>• Pipe Line Extension - Maho to Polpithigama expending 80.00 MRs</p>
<p>• Rain Water Harvesting Tanks <br /> Supply & installation of 41 Nos. of Rain water Harvesting Tanks for 25 Schools expending 4.0 MRs.</p>
<p>• Water Quality Testing Programme expending 3.0 MRs.</p>
<table style="height: 381px; width: 304px;">
<tbody>
<tr>
<td><img src="http://waterboard.lk/web/images/contents/regional_support_centres/north_western/image003.jpg" alt="image003" width="296" height="395" /> </td>
<td><img src="http://waterboard.lk/web/images/contents/regional_support_centres/north_western/image005.jpg" alt="image005" width="406" height="304" /> </td>
</tr>
</tbody>
</table>
<p> </p>
</div></div></div>
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-3" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#north-western-rsc-of-n-w-s-d-b-for-patients-suffering-from-kidney-disease-in-kurunegala-district"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
North Western RSC of N.W.S.& D.B. for patients suffering from kidney disease in Kurunegala district
</span></a>
</div>
<div class="accordion-body collapse" id="north-western-rsc-of-n-w-s-d-b-for-patients-suffering-from-kidney-disease-in-kurunegala-district">
<div class="accordion-inner panel-body">
<h4><strong>The Services rendered by North Western RSC of N.W.S.& D.B. for patients suffering from kidney disease in Kurunegala district</strong></h4>
<p>The data bank of the Department of Health reveals that the no. of CKDu patients in 11 no. of MOH divisions in the Kurunegala district is increasing rapidly. The quality of drinking water could be a major component for the increase of CKDu patients. Hence the N.W.S.& D.B. has initiated no. of projects in these areas.<br />• In the Polpithigama and Maho MOH divisions, 252 kidney patients have been provided with 250 no.s of Rain water collecting tanks with capacity of 2000 L. <br />• 25 no.s selected schools in the above areas have been provided with 41 Rain water collecting tanks with capacity of 5000 L.<br />• Work has commenced for restoring hand pumps and extending the distribution line to supply water from the Maho WSS to these affected areas.<br />• In addition to this we have lounged a joint programme along with the DHS office in Kurunegala to monitor the quality of drinking water sources (Dug wells) of these affected areas namely Polpithigama, Giribawa and Galgamuwa.</p>
<p> </p>
</div></div></div></div>
<p> </p>]]></description>
<author>test@maoil.com (piyo)</author>
<category>Regional Support Centres</category>
<pubDate>Mon, 18 Aug 2014 00:24:11 +0000</pubDate>
</item>
<item>
<title>North - Central (Anuradhapura and Polonnaruwa Districts)</title>
<link>http://waterboard.lk/web/index.php?option=com_content&view=article&id=48&catid=16&Itemid=208&lang=ta</link>
<guid isPermaLink="true">http://waterboard.lk/web/index.php?option=com_content&view=article&id=48&catid=16&Itemid=208&lang=ta</guid>
<description><![CDATA[<p style="text-align: justify;">The Deputy General Manager (DGM) heading the North Central RSC is supported by an Assistant General Manager (AGM) in running the RSC unit. O&M activities are looked after by the Anuradhapura Region O&M manager, who is responsible for all the O&M activities of Anuradhapura and Polonnaruwa districts. The RSC functions are mainly to provide necessary support to regional offices for the day to day O&M activities and to provide help and guidance in existing scheme rehabilitation and augmentation work.</p>
<p style="text-align: justify;">The O&M manager reports to the DGM through the AGM but all RSC functions are monitored by Additional General Manager from H/O. The RSC provides services to the regional offices within their capacity and any additional help as necessary is obtained from H/O through the respective Additional General Manager.</p>
<div class="nn_sliders accordion panel-group" id="set-nn_sliders-4">
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-4" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#location-of-the-area-4"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
Location of the Area
</span></a>
</div>
<div class="accordion-body collapse" id="location-of-the-area-4">
<div class="accordion-inner panel-body">
<table style="width: 100%;">
<tbody>
<tr valign="top">
<td style="text-align: center;"><a href="http://waterboard.lk/web/images/contents/regional_support_centres/north_central/north_central_map.png" target="_blank"><img src="http://waterboard.lk/web/images/contents/regional_support_centres/north_central/north_central_map.png" alt="north central map" width="350" height="226" /></a><br /><em>Please click on map to enlarge it</em></td>
<td>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;" colspan="2">Statistics of the Area</td>
</tr>
<tr class="r1">
<td>Total Area</td>
<td style="text-align: right;">10,714.0 km<sup>2</sup></td>
</tr>
<tr class="r2">
<td>Population (2001)</td>
<td style="text-align: right;" align="right">1,104,664</td>
</tr>
<tr class="r1">
<td>Population (2009)*</td>
<td style="text-align: right;" align="right">1,225,000</td>
</tr>
<tr class="r2">
<td>Population Density (2009)</td>
<td style="text-align: right;" align="right">114.3/km<sup>2</sup></td>
</tr>
</tbody>
</table>
* Estimated mid year Population by the Department of Census and Statistics - Sri Lanka</td>
</tr>
</tbody>
</table>
<p style="text-align: justify;">Click on below links to View or Download the original map published by the Survey Department of the Government of Sri Lanka.</p>
<ul class="pdf">
<li style="text-align: justify;"><a href="http://waterboard.lk/web/images/contents/regional_support_centres/north_central/polonnaruwa_district_map.pdf" target="_blank">Polonnaruwa District Map<br />[ PDF - 468 KB ]</a></li>
<li style="text-align: justify;"><a href="http://waterboard.lk/web/images/contents/regional_support_centres/north_central/anuradhapura_district_map.pdf" target="_blank">Anuradhapura District Map<br />[ PDF - 753 KB ]</a></li>
</ul>
</div></div></div>
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-4" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#comparison-of-service-connections-3"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
Comparison of Service Connections
</span></a>
</div>
<div class="accordion-body collapse" id="comparison-of-service-connections-3">
<div class="accordion-inner panel-body">
<table style="width: 100%;">
<tbody>
<tr>
<td>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;"><strong>As at end of</strong></td>
<td style="text-align: center;"><strong>No. of Connection</strong></td>
</tr>
<tr class="r1">
<td style="text-align: center;">2010</td>
<td style="text-align: center;">62,579</td>
</tr>
<tr class="r2">
<td style="text-align: center;">2011</td>
<td style="text-align: center;">67,294</td>
</tr>
<tr class="r1">
<td style="text-align: center;">2012</td>
<td style="text-align: center;" align="right">80,314</td>
</tr>
<tr class="r2">
<td style="text-align: center;">2013</td>
<td style="text-align: center;" align="right">85,912</td>
</tr>
</tbody>
</table>
</td>
<td><img src="http://waterboard.lk/web/images/contents/regional_support_centres/north_central/North_Central.JPG" alt="North Central" width="414" height="289" /></td>
</tr>
</tbody>
</table>
<h4>Water Supply Coverage Maps</h4>
<table style="width: 100%;">
<tbody>
<tr align="center">
<td style="width: 33%;"><a href="http://waterboard.lk/web/images/contents/regional_support_centres/north_central/water_supply_coverage_maps/nc_deep_tube_wells.jpg" target="_blank"><img src="http://waterboard.lk/web/images/contents/regional_support_centres/north_central/water_supply_coverage_maps/nc_deep_tube_wells.jpg" alt="nc deep tube wells" width="210" height="149" /></a></td>
<td><a href="http://waterboard.lk/web/images/contents/regional_support_centres/north_central/water_supply_coverage_maps/nc_pipe_water.jpg" target="_blank"><img src="http://waterboard.lk/web/images/contents/regional_support_centres/north_central/water_supply_coverage_maps/nc_pipe_water.jpg" alt="nc deep tube wells" width="210" height="149" /></a></td>
<td style="width: 33%;"><a href="http://waterboard.lk/web/images/contents/regional_support_centres/north_central/water_supply_coverage_maps/nc_rwh.jpg" target="_blank"><img src="http://waterboard.lk/web/images/contents/regional_support_centres/north_central/water_supply_coverage_maps/nc_rwh.jpg" alt="nc deep tube wells" width="210" height="149" /></a></td>
</tr>
<tr align="center">
<td><a href="http://waterboard.lk/web/images/contents/regional_support_centres/north_central/water_supply_coverage_maps/nc_common_shallow_wells.jpg" target="_blank"><img src="http://waterboard.lk/web/images/contents/regional_support_centres/north_central/water_supply_coverage_maps/nc_common_shallow_wells.jpg" alt="nc deep tube wells" width="210" height="149" /></a></td>
<td><a href="http://waterboard.lk/web/images/contents/regional_support_centres/north_central/water_supply_coverage_maps/nc_ind_shallow_wells.jpg" target="_blank"><img src="http://waterboard.lk/web/images/contents/regional_support_centres/north_central/water_supply_coverage_maps/nc_ind_shallow_wells.jpg" alt="nc deep tube wells" width="210" height="149" /></a></td>
<td> </td>
</tr>
</tbody>
</table>
</div></div></div>
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-4" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#details-of-schemes-within-the-area-3"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
Details of Schemes within the area
</span></a>
</div>
<div class="accordion-body collapse" id="details-of-schemes-within-the-area-3">
<div class="accordion-inner panel-body">
<p>The quality of water being supplied is tested regularly. <a href="http://waterboard.lk/web/index.php?option=com_content&view=article&id=68&Itemid=273&lang=en">Click here</a> for a summary of test results taken island-wide.</p>
<h4>Schemes which are presently in operation</h4>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td>Region</td>
<td style="width: 155px;">Scheme</td>
<td style="text-align: center;">Total no. of connections as end of<br />31st December 2013</td>
<td style="text-align: center;">Average Monthly Production<br />(m3/ month)</td>
</tr>
<tr class="r1">
<td rowspan="21">Anuradhapura Distrct</td>
<td>Kebithigollawa</td>
<td style="text-align: right;">952</td>
<td style="text-align: right;">14,868</td>
</tr>
<tr class="r2">
<td>Anuradhapura East</td>
<td style="text-align: right;">6,397</td>
<td style="text-align: right;">139,075</td>
</tr>
<tr class="r1">
<td>Anuradhapura North</td>
<td style="text-align: right;">7,800</td>
<td style="text-align: right;">74,563 </td>
</tr>
<tr class="r2">
<td>A'pura New Town</td>
<td style="text-align: right;">11,611</td>
<td style="text-align: right;">360,372 </td>
</tr>
<tr class="r1">
<td>Maradankadawala</td>
<td style="text-align: right;">1,613</td>
<td style="text-align: right;" rowspan="3">144,782</td>
</tr>
<tr class="r2">
<td>Kekirawa</td>
<td style="text-align: right;">3,740</td>
</tr>
<tr class="r1">
<td>Ihalagama</td>
<td style="text-align: right;">4,508</td>
</tr>
<tr class="r1">
<td>Sacred-City</td>
<td style="text-align: right;">5,845</td>
<td style="text-align: right;">154,463</td>
</tr>
<tr class="r2">
<td>Eppawala</td>
<td style="text-align: right;">172</td>
<td style="text-align: right;">3,584</td>
</tr>
<tr class="r1">
<td>Kahatagasdigiliya</td>
<td style="text-align: right;">1,224</td>
<td style="text-align: right;">20,260</td>
</tr>
<tr class="r2">
<td>Thambuttegama</td>
<td style="text-align: right;">3,398</td>
<td style="text-align: right;">57,343</td>
</tr>
<tr class="r1">
<td>Galnewa - Bulnewa</td>
<td style="text-align: right;">3,304</td>
<td style="text-align: right;">43,053</td>
</tr>
<tr class="r2">
<td>Horowpathana</td>
<td style="text-align: right;">189</td>
<td style="text-align: right;">3,890</td>
</tr>
<tr class="r1">
<td>Habarana</td>
<td style="text-align: right;">811</td>
<td style="text-align: right;">11,983</td>
</tr>
<tr class="r2">
<td>Madawachchiya</td>
<td style="text-align: right;">1,399</td>
<td style="text-align: right;">25,640</td>
</tr>
<tr class="r1">
<td>Padaviya</td>
<td style="text-align: right;">627</td>
<td style="text-align: right;">11,281</td>
</tr>
<tr class="r2">
<td>Talawa</td>
<td style="text-align: right;">4,983</td>
<td style="text-align: right;">88,023</td>
</tr>
<tr class="r1">
<td>Nachchiyaduwa</td>
<td style="text-align: right;">2,125</td>
<td style="text-align: right;">31,301</td>
</tr>
<tr class="r2">
<td>Mihintale</td>
<td style="text-align: right;">3,085</td>
<td style="text-align: right;">145,834</td>
</tr>
<tr class="r2">
<td>Oyamaduwa</td>
<td style="text-align: right;">56</td>
<td style="text-align: right;">830 </td>
</tr>
<tr class="r2">
<td>Thanthirimale</td>
<td style="text-align: right;">250</td>
<td style="text-align: right;">809 </td>
</tr>
<tr class="r1">
<td class="r2" rowspan="9">Polonnaruwa District</td>
<td>Higurakgoda</td>
<td style="text-align: right;">3,391</td>
<td style="text-align: right;">76,540</td>
</tr>
<tr class="r2">
<td>Minneriya</td>
<td style="text-align: right;">2,364</td>
<td style="text-align: right;">75,766</td>
</tr>
<tr class="r2">
<td>Polonnaruwa</td>
<td style="text-align: right;">9,030</td>
<td style="text-align: right;">214,376</td>
</tr>
<tr class="r1">
<td>Bakamuna</td>
<td style="text-align: right;">969</td>
<td style="text-align: right;">17,552</td>
</tr>
<tr class="r2">
<td>Dimbulagala</td>
<td style="text-align: right;">2</td>
<td style="text-align: right;">4,845</td>
</tr>
<tr class="r2">
<td>Gallella</td>
<td style="text-align: right;">1,285</td>
<td style="text-align: right;">19,340</td>
</tr>
<tr class="r2">
<td>Bendiwewa</td>
<td style="text-align: right;">972</td>
<td style="text-align: right;" rowspan="2">47,975</td>
</tr>
<tr class="r2">
<td>Sewagama</td>
<td style="text-align: right;">2,549</td>
</tr>
<tr class="r2">
<td>Manampitiya</td>
<td style="text-align: right;">1,261</td>
<td style="text-align: right;">30,806</td>
</tr>
<tr class="mhead">
<td style="text-align: center;" colspan="2">Total</td>
<td style="text-align: right;">85,912</td>
<td style="text-align: right;">1,819,152</td>
</tr>
</tbody>
</table>
<h4>Ongoing Projects</h4>
<h5>Small and Medium Water Supply Projects</h5>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td rowspan="2">Project Name</td>
<td style="width: 110px; text-align: center;" rowspan="2">No. of Beneficiaries</td>
<td style="width: 100px; text-align: center;" rowspan="2">Total Cost Estimate<br />(Rs. Million)</td>
<td style="text-align: center;" colspan="2">Duration</td>
</tr>
<tr class="mhead">
<td style="width: 50px; text-align: center;">From</td>
<td style="width: 50px; text-align: center;">To</td>
</tr>
<tr class="r1">
<td>Hingurakgoda Water Supply</td>
<td style="text-align: right;" align="right">2,900 in 2015</td>
<td style="text-align: right;" align="right">130.0</td>
<td align="right">Jan 2004</td>
<td align="right">Dec 2014</td>
</tr>
<tr class="r1">
<td>Minneriya Water Supply - Stage II</td>
<td style="text-align: right;" align="right">2,800 in 2015</td>
<td style="text-align: right;" align="right">100.0</td>
<td align="right">Jan 2007</td>
<td align="right">Dec 2014</td>
</tr>
<tr class="r2">
<td>Medirigiriya Water Supply - Stage I</td>
<td style="text-align: right;">72,000 in 2025</td>
<td style="text-align: right;">919.0</td>
<td align="right">Jun 2007</td>
<td align="right">Dec 2014</td>
</tr>
<tr class="r1">
<td>Ippalogama Housing Scheme WS</td>
<td style="text-align: right;" align="right">152,000 in 2030</td>
<td style="text-align: right;" align="right">798.0</td>
<td align="right">Jun 2007</td>
<td align="right">Dec 2014</td>
</tr>
<tr class="r1">
<td>Parasangaswewa</td>
<td style="text-align: right;" align="right">2,855 in 2025</td>
<td style="text-align: right;" align="right">31.6</td>
<td align="right">Sep 2012</td>
<td align="right">Dec 2015</td>
</tr>
</tbody>
</table>
<h5>Large Scale Water Supply and Sanitation Projects</h5>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td rowspan="2">Project Name Name</td>
<td style="width: 110px; text-align: center;" rowspan="2">No. of Beneficiaries</td>
<td style="width: 100px; text-align: center;" rowspan="2">Total Cost Estimate<br />(Rs. Million)</td>
<td style="text-align: center;" colspan="2">Duration</td>
</tr>
<tr class="mhead">
<td style="width: 50px; text-align: center;">From</td>
<td style="width: 50px; text-align: center;">To</td>
</tr>
<tr class="r1">
<td>Anuradhapura North WSP - Phase 01 (JICA Funded)</td>
<td style="text-align: center;" align="right">113,900 in 2034</td>
<td align="right">10,400</td>
<td align="right">2013</td>
<td align="right">2017</td>
</tr>
</tbody>
</table>
</div></div></div>
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-4" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#contact-details-3"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
Contact Details
</span></a>
</div>
<div class="accordion-body collapse" id="contact-details-3">
<div class="accordion-inner panel-body">
<p>Please <a href="http://waterboard.lk/web/images/contents/regional_support_centres/north_central/contacts_north_central.pdf" target="_blank">click here</a> to view / download full contact list for Regional Support Centre (North Central)</p>
<table>
<tbody>
<tr valign="top">
<td><strong>Postal Address</strong></td>
<td><strong>:</strong></td>
<td>Regional Support Centre (North Central)<br />National Water Supply & Drainage Board<br />Godage Mawatha, Anuradhapura</td>
</tr>
<tr valign="top">
<td><strong>Telephone<br /></strong></td>
<td><strong>:</strong></td>
<td>+94 25 2235993, +94 25 2222295-6<br />+94 25 2220727, +94 25 2225951</td>
</tr>
<tr>
<td><strong>Fax</strong><em><strong><br /></strong></em></td>
<td><strong>:</strong></td>
<td>+94 25 2225609</td>
</tr>
</tbody>
</table>
<table class="mtable conname" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td>Name & Designation</td>
<td style="text-align: center;">Telephone / Fax</td>
<td style="text-align: center;">Mobile</td>
<td>E-mail</td>
</tr>
<tr class="r1">
<td><strong>Eng. C.C.H.S. Fernando</strong><br />Deputy General Manager</td>
<td style="text-align: center;"> </td>
<td style="text-align: center;"> +94 77 7899230</td>
<td><a href="mailto:dgmnc@waterboard.lk">dgmnc@waterboard.lk</a></td>
</tr>
<tr class="r2">
<td><strong>Eng. M.A.G.Susantha</strong><br />Assistant General Manager (North Central)</td>
<td style="text-align: center;">+94 25 2235993,<br />+94 25 2225951/2/6</td>
<td style="text-align: center;">+94 77 2017799</td>
<td><a href="mailto:agmnc@waterboard.lk">agmnc@waterboard.lk</a></td>
</tr>
</tbody>
</table>
<h4>Managers (Operational & Maintenance)</h4>
<table class="mtable conname" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td>Name & Designation</td>
<td style="text-align: center;">Telephone / Fax</td>
<td style="text-align: center;">Mobile</td>
<td>E-mail</td>
</tr>
<tr class="r1">
<td><strong>Eng. S.C. Ratnayake</strong><br /><em><strong><br /></strong></em></td>
<td style="text-align: center;">+94 25 2224454, +94 25 2222296<br /><strong>Fax:</strong> +94 25 2235495</td>
<td style="text-align: center;">+94 71 4305176</td>
<td><a href="mailto:manageranu@waterboard.lk">manageranu<br />@waterboard.lk</a></td>
</tr>
<tr class="r1">
<td colspan="4">
<p><strong><a href="mailto:manageranu@waterboard.lk"></a>Responsible Area: </strong>Anuradhapura, Vijayapura, Nachchaduwa, Thalawa, Sacred City, Mihintale, Medawachchiya, Kahatagasdigiliya, Horowpathana, Kebithigollawa, Padaviya, Eppawala, Thambuttegama, Galnewa, Bulnewa, Kekirawa, Habarana, Maradankadawala, Ihalagama, Oyamaduwa, Thanthirimale</p>
<p>Polonnaruwa, Hingurakgoda, Minneriya, Bakamoona, Dimbulagala, Gallella, Bendiwewa, Sewagama, Manampitiya</p>
</td>
</tr>
</tbody>
</table>
</div></div></div>
<div class="accordion-group panel">
<div class="accordion-heading panel-heading">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#set-nn_sliders-4" href="http://waterboard.lk/web/index.php?option=com_content&view=category&id=16&Itemid=101&lang=ta&format=feed&type=rss#key-facts-and-figures-3"><div class="clo"></div><div class="ope"></div><span class="nn_sliders-toggle-inner">
Key Facts and Figures
</span></a>
</div>
<div class="accordion-body collapse" id="key-facts-and-figures-3">
<div class="accordion-inner panel-body">
<h4>Service Standard Indicators</h4>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;" rowspan="2">Service Indicators </td>
<td style="text-align: center;">RSC (North Central) 2013</td>
</tr>
<tr class="mhead">
<td style="text-align: center; width: 200px;">Regional Average</td>
</tr>
<tr class="r1">
<td>Water Coverage (%) Pipe System maintained by NWSDB</td>
<td style="text-align: right;" align="right">30.7%</td>
</tr>
<tr class="r2">
<td>Per Capita Consumption (l/c/d)</td>
<td style="text-align: right;" align="right">126.2</td>
</tr>
<tr class="r1">
<td>Water Availability (hours)</td>
<td style="text-align: right;" align="right">24.0</td>
</tr>
<tr class="r2">
<td>Water Quality - Bacteriological Quality Compliance</td>
<td style="text-align: right;" align="right">100.0%</td>
</tr>
<tr class="r1">
<td>Water Quality - Bacteriological Testing Compliance</td>
<td style="text-align: right;" align="right"> 100.0%</td>
</tr>
<tr class="r2">
<td>Water Quality - All Samples Compliance</td>
<td style="text-align: right;" align="right">100.0% </td>
</tr>
<tr class="r1">
<td>Sewerage Coverage (%)</td>
<td style="text-align: right;" align="right">-</td>
</tr>
</tbody>
</table>
<h4>Operational Indicators</h4>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;" rowspan="2">Operational Indicators</td>
<td style="text-align: center;">RSC (North Central) 2013</td>
</tr>
<tr class="mhead">
<td style="text-align: center; width: 200px;">Regional Average</td>
</tr>
<tr class="r1">
<td>Non-Revenue Water (%)</td>
<td style="text-align: right;">19.6%</td>
</tr>
<tr class="r2">
<td>Non-Revenue Water - m<sup>3</sup>/conn/day</td>
<td align="right">0.14</td>
</tr>
<tr class="r1">
<td>Defective Meters per '000 connections</td>
<td align="right">63</td>
</tr>
<tr class="r2">
<td>Total Staff/ 1000 connection</td>
<td align="right">4</td>
</tr>
<tr class="r1">
<td>Operational Staff/ 1000 connection</td>
<td align="right">3</td>
</tr>
<tr class="r2">
<td>Estimated Bills/ 1000 connections</td>
<td align="right">29</td>
</tr>
</tbody>
</table>
<h4>Performance in Customer Service</h4>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;" rowspan="2">Customer Service Indicators</td>
<td style="text-align: center;">RSC (North Central) 2013</td>
</tr>
<tr class="mhead">
<td style="text-align: center; width: 200px;">Regional Average</td>
</tr>
<tr class="r1">
<td>Response to requests for new service connections (%)</td>
<td style="text-align: right;">100.0%</td>
</tr>
<tr class="r2">
<td>Customer Complaints Volume (Complaints/ 1000 connection)</td>
<td style="text-align: right;">11.1</td>
</tr>
<tr class="r1">
<td>Customer Complaints Resolution</td>
<td style="text-align: right;">95.0%</td>
</tr>
</tbody>
</table>
<h4>Key Performance Indicators (KPIs)</h4>
<table class="mtable" style="width: 100%;" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr class="mhead">
<td style="text-align: center;" rowspan="2">Financial KPIs</td>
<td style="text-align: center;">RSC (North Central) 2013</td>
</tr>
<tr class="mhead">
<td style="text-align: center; width: 200px;">Regional Average</td>
</tr>
<tr class="r1">
<td>Collection Ratio (%)</td>
<td style="text-align: right;">102.3%</td>
</tr>
<tr class="r2">
<td>Accounts Receivable Period (months)</td>
<td style="text-align: right;" align="right">2.4</td>
</tr>
<tr class="r1">
<td>Collectable Accounts Receivable Period (months)</td>
<td style="text-align: right;" align="right">2.2</td>
</tr>
<tr class="r2">
<td>Operating Ratio</td>
<td style="text-align: right;" align="right">0.85</td>
</tr>
<tr class="r1">
<td>Production Cost (LKR/ m<sup>3</sup> Produced)</td>
<td style="text-align: right;" align="right">29.54</td>
</tr>
<tr class="r2">
<td>Average Tariff (LKR/ m<sup>3</sup> Sold)</td>
<td style="text-align: right;" align="right">36.72</td>
</tr>
<tr class="r1">
<td>Stock Efficiency (LKR/ connection)</td>
<td style="text-align: right;" align="right">1,256</td>
</tr>
</tbody>
</table>
</div></div></div></div>]]></description>
<author>test@maoil.com (piyo)</author>
<category>Regional Support Centres</category>
<pubDate>Mon, 18 Aug 2014 00:24:49 +0000</pubDate>
</item>
</channel>
</rss>
| cmaere/lwb | templates/protostar/index19e2.php | PHP | apache-2.0 | 76,794 |
# Leptinella calcarea (D.G.Lloyd) D.G.Lloyd & C.J.Webb SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Cotula calcarea D.G.Lloyd
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Leptinella calcarea/README.md | Markdown | apache-2.0 | 223 |
// -------------------------------------------------------------------------
// @FileName : NFCEquipModule.cpp
// @Author : LvSheng.Huang
// @Date : 2013-06-11
// @Module : NFCEquipModule
// @Desc :
// -------------------------------------------------------------------------
#include "NFCEquipModule.h"
#include "NFComm/NFCore/NFTimer.h"
#include "NFComm/NFPluginModule/NFINetModule.h"
bool NFCEquipModule::Init()
{
return true;
}
bool NFCEquipModule::Shut()
{
return true;
}
bool NFCEquipModule::Execute()
{
//λÖÃÄØ
return true;
}
bool NFCEquipModule::AfterInit()
{
m_pKernelModule = pPluginManager->FindModule<NFIKernelModule>();
m_pElementModule = pPluginManager->FindModule<NFIElementModule>();
m_pSceneProcessModule = pPluginManager->FindModule<NFISceneProcessModule>();
m_pPropertyModule = pPluginManager->FindModule<NFIPropertyModule>();
m_pLogModule = pPluginManager->FindModule<NFILogModule>();
m_pUUIDModule = pPluginManager->FindModule<NFIUUIDModule>();
m_pPackModule = pPluginManager->FindModule<NFIPackModule>();
m_pCommonConfigModule = pPluginManager->FindModule<NFICommonConfigModule>();
m_pGameServerNet_ServerModule = pPluginManager->FindModule<NFIGameServerNet_ServerModule>();
std::string strEquipPath = pPluginManager->GetConfigPath();
strEquipPath += "NFDataCfg/Ini/Common/EqupConfig.xml";
m_pCommonConfigModule->LoadConfig(strEquipPath);
if (!m_pGameServerNet_ServerModule->GetNetModule()->AddReceiveCallBack(NFMsg::EGEC_REQ_INTENSIFYLEVEL_TO_EQUIP, this, &NFCEquipModule::OnIntensifylevelToEquipMsg)) { return false; }
if (!m_pGameServerNet_ServerModule->GetNetModule()->AddReceiveCallBack(NFMsg::EGEC_REQ_HOLE_TO_EQUIP, this, &NFCEquipModule::OnHoleToEquipMsg)) { return false; }
if (!m_pGameServerNet_ServerModule->GetNetModule()->AddReceiveCallBack(NFMsg::EGEC_REQ_INLAYSTONE_TO_EQUIP, this, &NFCEquipModule::OnInlaystoneToEquipMsg)) { return false; }
if (!m_pGameServerNet_ServerModule->GetNetModule()->AddReceiveCallBack(NFMsg::EGEC_REQ_ELEMENTLEVEL_TO_EQUIP, this, &NFCEquipModule::OnElementlevelToEquipMsg)) { return false; }
if (!m_pGameServerNet_ServerModule->GetNetModule()->AddReceiveCallBack(NFMsg::EGEC_WEAR_EQUIP, this, &NFCEquipModule::OnReqWearEquipMsg)) { return false; }
if (!m_pGameServerNet_ServerModule->GetNetModule()->AddReceiveCallBack(NFMsg::EGEC_TAKEOFF_EQUIP, this, &NFCEquipModule::OnTakeOffEquipMsg)) { return false; }
return true;
}
bool NFCEquipModule::IntensifylevelToEquip( const NFGUID& self, const NFGUID& xEquipID )
{
const int nLevel = GetEquipIntensifyLevel(self, xEquipID);
const int nCostMoney = m_pCommonConfigModule->GetAttributeInt("IntensifylevelToEquip", lexical_cast<std::string>(nLevel), "CostMoney");
const int nConstItemCount = m_pCommonConfigModule->GetAttributeInt("IntensifylevelToEquip", lexical_cast<std::string>(nLevel), "ConstItemCount");
const std::string& strCostItemID = m_pCommonConfigModule->GetAttributeString("IntensifylevelToEquip", lexical_cast<std::string>(nLevel), "ConstItem");
if (!strCostItemID.empty())
{
if (!m_pPackModule->EnoughItem(self, strCostItemID, nConstItemCount))
{
return false;
}
}
if (!m_pPropertyModule->EnoughMoney(self, nCostMoney))
{
return false;
}
if (!m_pPropertyModule->ConsumeMoney(self, nCostMoney))
{
return false;
}
if (!m_pPackModule->DeleteItem(self, strCostItemID, nConstItemCount))
{
return false;
}
if (Ramdom(nLevel, 100))
{
return AddEquipIntensifyLevel(self, xEquipID);
}
return false;
}
bool NFCEquipModule::HoleToEquip( const NFGUID& self, const NFGUID& xEquipID )
{
const int nHoleCount = GetEquipHoleCount(self, xEquipID);
const int nCostMoney = m_pCommonConfigModule->GetAttributeInt("HoleToEquip", lexical_cast<std::string>(nHoleCount), "CostMoney");
const int nConstItemCount = m_pCommonConfigModule->GetAttributeInt("HoleToEquip", lexical_cast<std::string>(nHoleCount), "ConstItemCount");
const std::string& strCostItemID = m_pCommonConfigModule->GetAttributeString("HoleToEquip", lexical_cast<std::string>(nHoleCount), "ConstItem");
if (!strCostItemID.empty())
{
if (!m_pPackModule->EnoughItem(self, strCostItemID, nConstItemCount))
{
return false;
}
}
if (!m_pPropertyModule->EnoughMoney(self, nCostMoney))
{
return false;
}
if (!m_pPropertyModule->ConsumeMoney(self, nCostMoney))
{
return false;
}
if (!m_pPackModule->DeleteItem(self, strCostItemID, nConstItemCount))
{
return false;
}
if (Ramdom(nHoleCount, 10))
{
return AddEquipHoleCount(self, xEquipID);
}
return true;
}
bool NFCEquipModule::InlaystoneToEquip( const NFGUID& self, const NFGUID& xEquipID, const std::string& strStoneID, const int nHoleIndex )
{
if (xEquipID.IsNull() || self.IsNull() || strStoneID.empty())
{
return false;
}
if (!m_pElementModule->ExistElement(strStoneID))
{
return false;
}
if (nHoleIndex < NFrame::Player::BagEquipList::BagEquipList_InlayStone1
|| nHoleIndex > NFrame::Player::BagEquipList::BagEquipList_InlayStone10)
{
return false;
}
const int nHoleCount = GetEquipHoleCount(self, xEquipID);
if ((nHoleIndex - NFrame::Player::BagEquipList::BagEquipList_InlayStone1) <= nHoleCount)
{
return false;
}
const int nHoleID = nHoleIndex - NFrame::Player::BagEquipList::BagEquipList_InlayStone1 + 1;
const int nCostMoney = m_pCommonConfigModule->GetAttributeInt("ElementlevelToEquip", lexical_cast<std::string>(nHoleID), "CostMoney");
const int nConstItemCount = m_pCommonConfigModule->GetAttributeInt("ElementlevelToEquip", lexical_cast<std::string>(nHoleID), "ConstItemCount");
const std::string& strCostItemID = m_pCommonConfigModule->GetAttributeString("ElementlevelToEquip", lexical_cast<std::string>(nHoleID), "ConstItem");
if (!strCostItemID.empty())
{
if (!m_pPackModule->EnoughItem(self, strCostItemID, nConstItemCount))
{
return false;
}
}
if (!m_pPropertyModule->EnoughMoney(self, nCostMoney))
{
return false;
}
if (!m_pPropertyModule->ConsumeMoney(self, nCostMoney))
{
return false;
}
if (!m_pPackModule->DeleteItem(self, strCostItemID, nConstItemCount))
{
return false;
}
if (!m_pPackModule->DeleteItem(self, strStoneID, 1))
{
return false;
}
return SetEquipInlayStoneID(self, xEquipID, (NFrame::Player::BagEquipList)nHoleIndex, strStoneID);
}
bool NFCEquipModule::ElementlevelToEquip( const NFGUID& self, const NFGUID& xEquipID, const NFMsg::EGameElementType& eElemetType )
{
const int nElementIndex = NFrame::Player::BagEquipList::BagEquipList_ElementLevel1_FIRE + eElemetType;
const int nElementLevel = GetEquipElementLevel(self, xEquipID, (NFrame::Player::BagEquipList)nElementIndex);
const int nCostMoney = m_pCommonConfigModule->GetAttributeInt("ElementlevelToEquip", lexical_cast<std::string>(nElementLevel), "CostMoney");
const int nConstItemCount = m_pCommonConfigModule->GetAttributeInt("ElementlevelToEquip", lexical_cast<std::string>(nElementLevel), "ConstItemCount");
const std::string& strCostItemID = m_pCommonConfigModule->GetAttributeString("ElementlevelToEquip", lexical_cast<std::string>(nElementLevel), "ConstItem");
if (!strCostItemID.empty())
{
if (!m_pPackModule->EnoughItem(self, strCostItemID, nConstItemCount))
{
return false;
}
}
if (!m_pPropertyModule->EnoughMoney(self, nCostMoney))
{
return false;
}
if (!m_pPropertyModule->ConsumeMoney(self, nCostMoney))
{
return false;
}
if (!m_pPackModule->DeleteItem(self, strCostItemID, nConstItemCount))
{
return false;
}
if (Ramdom(nElementLevel, 100))
{
const int nAfterLevel = nElementLevel + 1;
return AddEquipElementLevel(self, xEquipID, (NFrame::Player::BagEquipList)nElementIndex);
}
else
{
const int nIsDownLevel = m_pCommonConfigModule->GetAttributeInt("IntensifylevelToEquip", lexical_cast<std::string>(nElementLevel), "IsDownLevel");
if (nIsDownLevel > 0)
{
int nAfterLevel = nElementLevel - 1;
if (nAfterLevel < 0 )
{
nAfterLevel = 0;
}
return AddEquipElementLevel(self, xEquipID, (NFrame::Player::BagEquipList)nElementIndex);
}
return false;
}
return false;
}
bool NFCEquipModule::Ramdom( const int nNowLevel , const int nMaxLevel)
{
if (nNowLevel >= nMaxLevel)
{
return false;
}
if (nNowLevel < 0)
{
return false;
}
if (nMaxLevel <= 0)
{
return false;
}
NFCDataList varList;
m_pKernelModule->Random(0, nMaxLevel, 1, varList);
const NFINT64 nRandomNum = varList.Int(0);
if (nRandomNum > nNowLevel && nRandomNum <= nMaxLevel)
{
return true;
}
return false;
}
bool NFCEquipModule::DressEquipForHero(const NFGUID& self, const NFGUID& hero, const NFGUID& id)
{
if (id.IsNull() || self.IsNull() || hero.IsNull())
{
return false;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self);
if (NULL == pObject)
{
return false;
}
NF_SHARE_PTR<NFIRecord> pBagRecord = pObject->GetRecordManager()->GetElement(NFrame::Player::R_BagEquipList());
if (!pBagRecord)
{
return false;
}
NF_SHARE_PTR<NFIRecord> pHeroRecord = pObject->GetRecordManager()->GetElement(NFrame::Player::R_PlayerHero());
if (!pHeroRecord)
{
return false;
}
NFCDataList xEquipDataList;
pBagRecord->FindObject(NFrame::Player::BagEquipList_GUID, id, xEquipDataList);
if (xEquipDataList.GetCount() != 1)
{
return false;
}
NFCDataList xHeroDataList;
pHeroRecord->FindObject(NFrame::Player::PlayerHero_GUID, id, xHeroDataList);
if (xHeroDataList.GetCount() != 1)
{
return false;
}
const int nEquipRow = xEquipDataList.Int(0);
const int nHeroRow = xHeroDataList.Int(0);
const std::string& strEquipID = pBagRecord->GetString(nEquipRow, NFrame::Player::BagEquipList_ConfigID);
const int nEquipPos = m_pElementModule->GetPropertyInt(strEquipID, NFrame::Equip::ItemSubType());
if (nEquipRow < 0
|| nHeroRow < 0
|| strEquipID.empty()
|| nEquipPos < 0
|| nEquipPos > (NFrame::Player::PlayerHero_Equip6 - NFrame::Player::PlayerHero_Equip1))
{
return false;
}
//so there have any bind?
//hero, position
pHeroRecord->SetObject(nHeroRow, nEquipPos + NFrame::Player::PlayerHero_Equip1, id);
pBagRecord->SetObject(nEquipRow, NFrame::Player::BagEquipList_WearGUID, hero);
return false;
}
bool NFCEquipModule::TakeOffEquipForm(const NFGUID& self, const NFGUID& hero, const NFGUID& id)
{
if (id.IsNull() || self.IsNull() || hero.IsNull())
{
return false;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self);
if (NULL == pObject)
{
return false;
}
NF_SHARE_PTR<NFIRecord> pBagRecord = pObject->GetRecordManager()->GetElement(NFrame::Player::R_BagEquipList());
if (!pBagRecord)
{
return false;
}
NF_SHARE_PTR<NFIRecord> pHeroRecord = pObject->GetRecordManager()->GetElement(NFrame::Player::R_PlayerHero());
if (!pHeroRecord)
{
return false;
}
NFCDataList xEquipDataList;
pBagRecord->FindObject(NFrame::Player::BagEquipList_GUID, id, xEquipDataList);
if (xEquipDataList.GetCount() != 1)
{
return false;
}
NFCDataList xHeroDataList;
pHeroRecord->FindObject(NFrame::Player::PlayerHero_GUID, id, xHeroDataList);
if (xHeroDataList.GetCount() != 1)
{
return false;
}
const int nEquipRow = xEquipDataList.Int(0);
const int nHeroRow = xHeroDataList.Int(0);
const std::string& strEquipID = pBagRecord->GetString(nEquipRow, NFrame::Player::BagEquipList_ConfigID);
const int nEquipPos = m_pElementModule->GetPropertyInt(strEquipID, NFrame::Equip::ItemSubType());
if (nEquipRow < 0
|| nHeroRow < 0
|| strEquipID.empty()
|| nEquipPos < 0
|| nEquipPos >(NFrame::Player::PlayerHero_Equip6 - NFrame::Player::PlayerHero_Equip1))
{
return false;
}
//so there have any bind?
//hero, position
pHeroRecord->SetObject(nHeroRow, nEquipPos + NFrame::Player::PlayerHero_Equip1, NFGUID());
pBagRecord->SetObject(nEquipRow, NFrame::Player::BagEquipList_WearGUID, NFGUID());
}
bool NFCEquipModule::SetEquipRandPropertyID(const NFGUID& self, const NFGUID& id, const std::string& strPropertyID)
{
if (id.IsNull() || self.IsNull() || strPropertyID.empty())
{
return false;
}
if (!m_pElementModule->ExistElement(strPropertyID))
{
return false;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self);
if (NULL == pObject)
{
return false;
}
NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement(NFrame::Player::R_BagEquipList());
if (!pRecord)
{
return false;
}
NFCDataList xDataList;
pRecord->FindObject(NFrame::Player::BagEquipList_GUID, id, xDataList);
if (xDataList.GetCount() != 1)
{
return false;
}
const int nRow = xDataList.Int(0);
pRecord->SetString(nRow, NFrame::Player::BagEquipList_RandPropertyID, strPropertyID);
return true;
}
bool NFCEquipModule::AddEquipHoleCount(const NFGUID& self, const NFGUID& id)
{
if (id.IsNull() || self.IsNull())
{
return false;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self);
if (NULL == pObject)
{
return false;
}
NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement(NFrame::Player::R_BagEquipList());
if (!pRecord)
{
return false;
}
NFCDataList xDataList;
pRecord->FindObject(NFrame::Player::BagEquipList_GUID, id, xDataList);
if (xDataList.GetCount() != 1)
{
return false;
}
const int nRow = xDataList.Int(0);
const int nSoltCount = pRecord->GetInt(nRow, NFrame::Player::BagEquipList_SlotCount);
pRecord->SetInt(nRow, NFrame::Player::BagEquipList_SlotCount, nSoltCount + 1);
return true;
}
int NFCEquipModule::GetEquipHoleCount(const NFGUID & self, const NFGUID & id)
{
if (id.IsNull() || self.IsNull())
{
return false;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self);
if (NULL == pObject)
{
return false;
}
NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement(NFrame::Player::R_BagEquipList());
if (!pRecord)
{
return false;
}
NFCDataList xDataList;
pRecord->FindObject(NFrame::Player::BagEquipList_GUID, id, xDataList);
if (xDataList.GetCount() != 1)
{
return false;
}
const int nRow = xDataList.Int(0);
return pRecord->GetInt(nRow, NFrame::Player::BagEquipList_SlotCount);
}
bool NFCEquipModule::SetEquipInlayStoneID(const NFGUID& self, const NFGUID& id, NFrame::Player::BagEquipList eIndex, const std::string& strStoneID)
{
if (id.IsNull() || self.IsNull() || strStoneID.empty())
{
return false;
}
if (eIndex > NFrame::Player::BagEquipList_InlayStone10
|| eIndex < NFrame::Player::BagEquipList_InlayStone1)
{
return false;
}
if (!m_pElementModule->ExistElement(strStoneID))
{
return false;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self);
if (NULL == pObject)
{
return false;
}
NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement(NFrame::Player::R_BagEquipList());
if (!pRecord)
{
return false;
}
NFCDataList xDataList;
pRecord->FindObject(NFrame::Player::BagEquipList_GUID, id, xDataList);
if (xDataList.GetCount() != 1)
{
return false;
}
const int nRow = xDataList.Int(0);
const int nSoltCount = pRecord->GetInt(nRow, NFrame::Player::BagEquipList_SlotCount);
if ((eIndex - NFrame::Player::BagEquipList_InlayStone1) <= nSoltCount)
{
return false;
}
pRecord->SetString(nRow, eIndex, strStoneID);
return true;
}
bool NFCEquipModule::AddEquipIntensifyLevel(const NFGUID& self, const NFGUID& id)
{
if (id.IsNull() || self.IsNull())
{
return false;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self);
if (NULL == pObject)
{
return false;
}
NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement(NFrame::Player::R_BagEquipList());
if (!pRecord)
{
return false;
}
NFCDataList xDataList;
pRecord->FindObject(NFrame::Player::BagEquipList_GUID, id, xDataList);
if (xDataList.GetCount() != 1)
{
return false;
}
const int nRow = xDataList.Int(0);
const int nLevel = pRecord->GetInt(nRow, NFrame::Player::BagEquipList_IntensifyLevel);
pRecord->SetInt(nRow, NFrame::Player::BagEquipList_IntensifyLevel, nLevel + 1);
return true;
}
int NFCEquipModule::GetEquipIntensifyLevel(const NFGUID & self, const NFGUID & id)
{
if (id.IsNull() || self.IsNull())
{
return -1;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self);
if (NULL == pObject)
{
return -1;
}
NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement(NFrame::Player::R_BagEquipList());
if (!pRecord)
{
return -1;
}
NFCDataList xDataList;
pRecord->FindObject(NFrame::Player::BagEquipList_GUID, id, xDataList);
if (xDataList.GetCount() != 1)
{
return -1;
}
const int nRow = xDataList.Int(0);
return pRecord->GetInt(nRow, NFrame::Player::BagEquipList_IntensifyLevel);
}
bool NFCEquipModule::AddEquipElementLevel(const NFGUID& self, const NFGUID& id, NFrame::Player::BagEquipList eIndex)
{
if (id.IsNull() || self.IsNull())
{
return false;
}
if (eIndex > NFrame::Player::BagEquipList_ElementLevel5_POISON
|| eIndex < NFrame::Player::BagEquipList_ElementLevel1_FIRE)
{
return false;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self);
if (NULL == pObject)
{
return false;
}
NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement(NFrame::Player::R_BagEquipList());
if (!pRecord)
{
return false;
}
NFCDataList xDataList;
pRecord->FindObject(NFrame::Player::BagEquipList_GUID, id, xDataList);
if (xDataList.GetCount() != 1)
{
return false;
}
const int nRow = xDataList.Int(0);
const int nLevel = GetEquipElementLevel(self, id, eIndex);
pRecord->SetInt(nRow, eIndex, nLevel + 1);
return true;
}
int NFCEquipModule::GetEquipElementLevel(const NFGUID & self, const NFGUID & id, NFrame::Player::BagEquipList eIndex)
{
if (id.IsNull() || self.IsNull())
{
return -1;
}
if (eIndex > NFrame::Player::BagEquipList_ElementLevel5_POISON
|| eIndex < NFrame::Player::BagEquipList_ElementLevel1_FIRE)
{
return -1;
}
NF_SHARE_PTR<NFIObject> pObject = m_pKernelModule->GetObject(self);
if (NULL == pObject)
{
return -1;
}
NF_SHARE_PTR<NFIRecord> pRecord = pObject->GetRecordManager()->GetElement(NFrame::Player::R_BagEquipList());
if (!pRecord)
{
return -1;
}
NFCDataList xDataList;
pRecord->FindObject(NFrame::Player::BagEquipList_GUID, id, xDataList);
if (xDataList.GetCount() != 1)
{
return -1;
}
const int nRow = xDataList.Int(0);
return pRecord->GetInt(nRow, eIndex);
}
//////////////////////////////////////////////////////////////////////////
//msg process
void NFCEquipModule::OnIntensifylevelToEquipMsg( const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen )
{
CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqIntensifylevelToEquip);
const NFGUID self = NFINetModule::PBToNF((xMsg.selfid()));
const NFGUID xEquipID = NFINetModule::PBToNF((xMsg.equipid()));
int nResult = IntensifylevelToEquip(self, xEquipID);
NFMsg::AckIntensifylevelToEquip xAck;
*xAck.mutable_selfid() = xMsg.selfid();
*xAck.mutable_equipid() = xMsg.equipid();
xAck.set_result(nResult);
m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGEC_ACK_INTENSIFYLEVEL_TO_EQUIP, xAck, self);
}
void NFCEquipModule::OnHoleToEquipMsg( const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen )
{
CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqHoleToEquip);
const NFGUID self = NFINetModule::PBToNF((xMsg.selfid()));
const NFGUID xEquipID = NFINetModule::PBToNF((xMsg.equipid()));
int nResult = HoleToEquip(self, xEquipID);
NFMsg::AckHoleToEquip xAck;
*xAck.mutable_selfid() = xMsg.selfid();
*xAck.mutable_equipid() = xMsg.equipid();
xAck.set_result(nResult);
m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGEC_ACK_HOLE_TO_EQUIP, xAck, self);
}
void NFCEquipModule::OnInlaystoneToEquipMsg( const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen )
{
CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqInlaystoneToEquip);
const NFGUID self = NFINetModule::PBToNF((xMsg.selfid()));
const NFGUID xEquipID = NFINetModule::PBToNF((xMsg.equipid()));
const std::string& strStoneID = xMsg.stoneid();
const int nHoleIndex = xMsg.hole_index();
int nResult = InlaystoneToEquip(self, xEquipID, strStoneID, nHoleIndex);
NFMsg::AckInlaystoneToEquip xAck;
*xAck.mutable_selfid() = xMsg.selfid();
*xAck.mutable_equipid() = xMsg.equipid();
xAck.set_result(nResult);
m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGEC_ACK_INLAYSTONE_TO_EQUIP, xAck, self);
}
void NFCEquipModule::OnElementlevelToEquipMsg( const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen )
{
CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqElementlevelToEquip);
const NFGUID self = NFINetModule::PBToNF((xMsg.selfid()));
const NFGUID xEquipID = NFINetModule::PBToNF((xMsg.equipid()));
int nResult = ElementlevelToEquip(self, xEquipID, xMsg.eelementtype());
NFMsg::AckElementlevelToEquip xAck;
*xAck.mutable_selfid() = xMsg.selfid();
*xAck.mutable_equipid() = xMsg.equipid();
xAck.set_result(nResult);
m_pGameServerNet_ServerModule->SendMsgPBToGate(NFMsg::EGEC_ACK_ELEMENTLEVEL_TO_EQUIP, xAck, self);
}
void NFCEquipModule::OnReqWearEquipMsg( const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen )
{
CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::ReqWearEquip);
const NFGUID self = NFINetModule::PBToNF((xMsg.selfid()));
const NFGUID xEquipID = NFINetModule::PBToNF((xMsg.equipid()));
const NFGUID xTarget = NFINetModule::PBToNF((xMsg.targetid()));
DressEquipForHero(self, xTarget, xEquipID);
}
void NFCEquipModule::OnTakeOffEquipMsg( const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen )
{
CLIENT_MSG_PROCESS(nSockIndex, nMsgID, msg, nLen, NFMsg::TakeOffEquip);
const NFGUID self = NFINetModule::PBToNF((xMsg.selfid()));
const NFGUID xEquipID = NFINetModule::PBToNF((xMsg.equipid()));
const NFGUID xTarget = NFINetModule::PBToNF((xMsg.targetid()));
TakeOffEquipForm(self, xTarget, xEquipID);
}
| zh423328/NFServer | NFServer/NFGameLogicPlugin/NFCEquipModule.cpp | C++ | apache-2.0 | 22,813 |
<!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_24) on Mon May 16 13:35:14 BST 2011 -->
<TITLE>
PacketHandler (leJOS NXJ PC API documentation)
</TITLE>
<META NAME="date" CONTENT="2011-05-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="PacketHandler (leJOS NXJ PC API documentation)";
}
}
</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> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../lejos/nxt/rcxcomm/Opcode.html" title="interface in lejos.nxt.rcxcomm"><B>PREV CLASS</B></A>
<A HREF="../../../lejos/nxt/rcxcomm/RCXAbstractPort.html" title="class in lejos.nxt.rcxcomm"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?lejos/nxt/rcxcomm/PacketHandler.html" target="_top"><B>FRAMES</B></A>
<A HREF="PacketHandler.html" target="_top"><B>NO FRAMES</B></A>
<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>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
lejos.nxt.rcxcomm</FONT>
<BR>
Class PacketHandler</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>lejos.nxt.rcxcomm.PacketHandler</B>
</PRE>
<DL>
<DT><B>Direct Known Subclasses:</B> <DD><A HREF="../../../lejos/nxt/rcxcomm/LLCHandler.html" title="class in lejos.nxt.rcxcomm">LLCHandler</A>, <A HREF="../../../lejos/nxt/rcxcomm/LLCReliableHandler.html" title="class in lejos.nxt.rcxcomm">LLCReliableHandler</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public abstract class <B>PacketHandler</B><DT>extends java.lang.Object</DL>
</PRE>
<P>
Abstract packet handler.
Implementations must include sendPacket, receivePacket and
isPacketAvailable(). The other methods are optional.
<P>
<P>
<HR>
<P>
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Field Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html" title="class in lejos.nxt.rcxcomm">PacketHandler</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html#lowerHandler">lowerHandler</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html#PacketHandler()">PacketHandler</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html#PacketHandler(lejos.nxt.rcxcomm.PacketHandler)">PacketHandler</A></B>(<A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html" title="class in lejos.nxt.rcxcomm">PacketHandler</A> handler)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html#close()">close</A></B>()</CODE>
<BR>
Close this packet handler and all lower layers.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html#getError()">getError</A></B>()</CODE>
<BR>
Get the last error.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html#isAckAvailable()">isAckAvailable</A></B>()</CODE>
<BR>
Check if an ack is available</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>abstract boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html#isPacketAvailable()">isPacketAvailable</A></B>()</CODE>
<BR>
Check if a packet is available</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html#open(byte, byte)">open</A></B>(byte source,
byte destination)</CODE>
<BR>
Set the source and destination for this connection.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html#receiveAck(byte[])">receiveAck</A></B>(byte[] buffer)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>abstract int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html#receivePacket(byte[])">receivePacket</A></B>(byte[] buffer)</CODE>
<BR>
Receive a packet.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html#reset()">reset</A></B>()</CODE>
<BR>
Reset sequence numbers for this handler</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>abstract boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html#sendPacket(byte[], int)">sendPacket</A></B>(byte[] packet,
int len)</CODE>
<BR>
Send a packet.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html#setListen(boolean)">setListen</A></B>(boolean listen)</CODE>
<BR>
Set or unset the listen flag to keep a PC serial tower alive</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ FIELD DETAIL =========== -->
<A NAME="field_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Field Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="lowerHandler"><!-- --></A><H3>
lowerHandler</H3>
<PRE>
protected <A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html" title="class in lejos.nxt.rcxcomm">PacketHandler</A> <B>lowerHandler</B></PRE>
<DL>
<DL>
</DL>
</DL>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="PacketHandler()"><!-- --></A><H3>
PacketHandler</H3>
<PRE>
public <B>PacketHandler</B>()</PRE>
<DL>
</DL>
<HR>
<A NAME="PacketHandler(lejos.nxt.rcxcomm.PacketHandler)"><!-- --></A><H3>
PacketHandler</H3>
<PRE>
public <B>PacketHandler</B>(<A HREF="../../../lejos/nxt/rcxcomm/PacketHandler.html" title="class in lejos.nxt.rcxcomm">PacketHandler</A> handler)</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="open(byte, byte)"><!-- --></A><H3>
open</H3>
<PRE>
public void <B>open</B>(byte source,
byte destination)</PRE>
<DL>
<DD>Set the source and destination for this connection.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="reset()"><!-- --></A><H3>
reset</H3>
<PRE>
public void <B>reset</B>()</PRE>
<DL>
<DD>Reset sequence numbers for this handler
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="setListen(boolean)"><!-- --></A><H3>
setListen</H3>
<PRE>
public void <B>setListen</B>(boolean listen)</PRE>
<DL>
<DD>Set or unset the listen flag to keep a PC serial tower alive
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>listen</CODE> - true to set listen mode, else false</DL>
</DD>
</DL>
<HR>
<A NAME="sendPacket(byte[], int)"><!-- --></A><H3>
sendPacket</H3>
<PRE>
public abstract boolean <B>sendPacket</B>(byte[] packet,
int len)</PRE>
<DL>
<DD>Send a packet.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>packet</CODE> - the bytes to send<DD><CODE>len</CODE> - the number of bytes to send
<DT><B>Returns:</B><DD>true if the send was successful, else false</DL>
</DD>
</DL>
<HR>
<A NAME="receivePacket(byte[])"><!-- --></A><H3>
receivePacket</H3>
<PRE>
public abstract int <B>receivePacket</B>(byte[] buffer)</PRE>
<DL>
<DD>Receive a packet.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>buffer</CODE> - the buffer to receive the packet into
<DT><B>Returns:</B><DD>the number of bytes received</DL>
</DD>
</DL>
<HR>
<A NAME="receiveAck(byte[])"><!-- --></A><H3>
receiveAck</H3>
<PRE>
public int <B>receiveAck</B>(byte[] buffer)</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="isPacketAvailable()"><!-- --></A><H3>
isPacketAvailable</H3>
<PRE>
public abstract boolean <B>isPacketAvailable</B>()</PRE>
<DL>
<DD>Check if a packet is available
<P>
<DD><DL>
<DT><B>Returns:</B><DD>true if a Packet is available, else false</DL>
</DD>
</DL>
<HR>
<A NAME="isAckAvailable()"><!-- --></A><H3>
isAckAvailable</H3>
<PRE>
public boolean <B>isAckAvailable</B>()</PRE>
<DL>
<DD>Check if an ack is available
<P>
<DD><DL>
<DT><B>Returns:</B><DD>true if a ack is available, else false</DL>
</DD>
</DL>
<HR>
<A NAME="close()"><!-- --></A><H3>
close</H3>
<PRE>
public void <B>close</B>()</PRE>
<DL>
<DD>Close this packet handler and all lower layers.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="getError()"><!-- --></A><H3>
getError</H3>
<PRE>
public int <B>getError</B>()</PRE>
<DL>
<DD>Get the last error.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>the error number, or zero for success</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<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> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../lejos/nxt/rcxcomm/Opcode.html" title="interface in lejos.nxt.rcxcomm"><B>PREV CLASS</B></A>
<A HREF="../../../lejos/nxt/rcxcomm/RCXAbstractPort.html" title="class in lejos.nxt.rcxcomm"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?lejos/nxt/rcxcomm/PacketHandler.html" target="_top"><B>FRAMES</B></A>
<A HREF="PacketHandler.html" target="_top"><B>NO FRAMES</B></A>
<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>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| AndrewZurn/sju-compsci-archive | CS200s/CS217b/OriginalFiles/doc/lejos/nxt/rcxcomm/PacketHandler.html | HTML | apache-2.0 | 18,274 |
---
license: 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.
---
batterycritical
===========
This is an event that fires when a PhoneGap application detects the battery has reached the critical level threshold.
window.addEventListener("batterycritical", yourCallbackFunction, false);
Details
-------
This event that fires when a PhoneGap application detects the percentage of battery has reached the critical battery threshold. This value is device specific.
The batterycritical handler will be called with an object that contains two properties:
- __level:__ The percentage of battery (0-100). _(Number)_
- __isPlugged:__ A boolean that represents whether or not the device is plugged in or not. _(Boolean)_
Typically, you will want to attach an event listener with `window.addEventListener` once you receive the PhoneGap 'deviceready' event.
Supported Platforms
-------------------
- iOS
- Android
- BlackBerry WebWorks (OS 5.0 and higher)
Quick Example
-------------
window.addEventListener("batterycritical", onBatteryCritical, false);
function onBatteryCritical(info) {
// Handle the battery critical event
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
Full Example
------------
<!DOCTYPE html>
<html>
<head>
<title>PhoneGap Device Ready Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.3.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Call onDeviceReady when PhoneGap is loaded.
//
// At this point, the document has loaded but phonegap-1.3.0.js has not.
// When PhoneGap is loaded and talking with the native device,
// it will call the event `deviceready`.
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
window.addEventListener("batterycritical", onBatteryCritical, false);
}
// Handle the batterycritical event
//
function onBatteryCritical(info) {
alert("Battery Level Critical " + info.level + "%\nRecharge Soon!");
}
</script>
</head>
<body onload="onLoad()">
</body>
</html>
| maveriklko9719/Coffee-Spills | docs/en/1.3.0/phonegap/events/events.batterycritical.md | Markdown | apache-2.0 | 3,208 |
var row_data = [
{ id: "api_sample", title: "API SAMPLE", hasChild: true, dst: "api_sample"},
{ id: "login", title: "LOGIN SAMPLE", hasChild: true, dst: "login" }
];
rows = [];
row_data.map(function(row){
rows.push(Titanium.UI.createTableViewRow(row));
});
$.main_menu.appendRow(rows);
$.main_menu.addEventListener('click', function(e) {
Ti.API.info("================================================");
Ti.API.info(e.rowData.title);
Ti.API.info(e.rowData.dst);
Ti.API.info("================================================");
if(e.rowData.dst != "") {
var args = {};
var view = Alloy.createController(e.rowData.dst, args).getView();
$.tab1.open(view);
};
});
$.index.open();
Alloy.Globals.tab1 = $.tab1;
Alloy.Globals.tab2 = $.tab2; | ryo0508/AlloySample | app/controllers/index.js | JavaScript | apache-2.0 | 777 |
package com.hp.hpl.spring.test;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import com.hp.hpl.spring.beans.User;
public class UserFactoryBean implements FactoryBean, InitializingBean{
@Override
public Object getObject() throws Exception {
return new User();
}
@Override
public Class getObjectType() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isSingleton() {
// TODO Auto-generated method stub
return false;
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet");
}
}
| duantonghai1984/Research | src/main/java/com/hp/hpl/spring/test/UserFactoryBean.java | Java | apache-2.0 | 655 |
/*
* Copyright 2005-2017 Dozer 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.
*/
package org.dozer.vo.runtimesubclass;
/**
* @author Dmitry Buzdin
*/
public class UserPrime {
private UserGroupPrime userGroupPrime;
public UserGroupPrime getUserGroup() {
return userGroupPrime;
}
public void setUserGroup(UserGroupPrime userGroupPrime) {
this.userGroupPrime = userGroupPrime;
}
}
| STRiDGE/dozer | core/src/test/java/org/dozer/vo/runtimesubclass/UserPrime.java | Java | apache-2.0 | 956 |
package com.examw.oa.controllers.adm;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.examw.aware.IUserAware;
import com.examw.model.DataGrid;
import com.examw.model.Json;
import com.examw.oa.domain.adm.Leave;
import com.examw.oa.domain.security.Right;
import com.examw.oa.model.adm.LeaveInfo;
import com.examw.oa.service.adm.ILeaveApprovalService;
import com.examw.oa.service.adm.ILeaveService;
/**
* 请假条审批控制器。
* @author yangyong.
* @since 2014-07-29.
*/
@Controller
@RequestMapping(value = "/adm/leave/approval")
public class LeaveApprovalController implements IUserAware {
private static final Logger logger = Logger.getLogger(LeaveApprovalController.class);
private String current_user_id;
//注入请假条审批服务接口。
@Resource
private ILeaveApprovalService leaveApprovalService;
//注入请假条服务接口。
@Resource
private ILeaveService leaveService;
/*
* 设置当前用户ID。
* @see com.examw.aware.IUserAware#setUserId(java.lang.String)
*/
@Override
public void setUserId(String userId) {
if(logger.isDebugEnabled()) logger.debug("注入当前用户[userId="+ userId +"]...");
this.current_user_id = userId;
}
/*
* 设置当前用户姓名。
* @see com.examw.aware.IUserAware#setUserName(java.lang.String)
*/
@Override
public void setUserName(String userName) {}
/*
* 设置当前用户昵称。
* @see com.examw.aware.IUserAware#setUserNickName(java.lang.String)
*/
@Override
public void setUserNickName(String userNickName){}
/**
* 加载请假条视图页面。
* @param id
* @param model
* @return
*/
@RequestMapping(value = {"/view/{id}"}, method = RequestMethod.GET)
public String view(@PathVariable String id, Model model){
model.addAttribute("STATUS_APPROVAL_DEPT_NAME", this.leaveService.loadStatusName(Leave.STATUS_APPROVAL_DEPT));
model.addAttribute("STATUS_APPROVAL_HR_NAME", this.leaveService.loadStatusName(Leave.STATUS_APPROVAL_HR));
model.addAttribute("STATUS_APPROVAL_BOSS_NAME", this.leaveService.loadStatusName(Leave.STATUS_APPROVAL_BOSS));
model.addAttribute("Leave",this.leaveApprovalService.loadLeave(id));
return "adm/leave_approval_view";
}
/**
* 加载请假审批(部门)列表页面。
* @return
*/
@RequiresPermissions({ModuleConstant.ADM_LEAVE_DEPT_APPROVAL + ":" + Right.VIEW})
@RequestMapping(value = {"/dept","/dept/list"}, method = RequestMethod.GET)
public String deptList(Model model){
if(logger.isDebugEnabled()) logger.debug("加载请假审批(部门)列表页面...");
model.addAttribute("PER_UPDATE", ModuleConstant.ADM_LEAVE_DEPT_APPROVAL + ":" + Right.UPDATE);
model.addAttribute("PER_DELETE", ModuleConstant.ADM_LEAVE_DEPT_APPROVAL + ":" + Right.DELETE);
model.addAttribute("CURRENT_STATUS_VALUE", Leave.STATUS_APPROVAL_DEPT);
model.addAttribute("CURRENT_RESULT_VALUE", Leave.RESULT_POST);
return "adm/leave_approval_dept_list";
}
/**
* 加载请假审批(部门)列表页面数据。
* @param info
* @return
*/
@RequiresPermissions({ModuleConstant.ADM_LEAVE_DEPT_APPROVAL + ":" + Right.VIEW})
@RequestMapping(value = {"/dept/datagrid"}, method = RequestMethod.POST)
@ResponseBody
public DataGrid<LeaveInfo> deptListDataGrid(LeaveInfo info){
if(logger.isDebugEnabled()) logger.debug("加载请假审批(部门)列表页面数据...");
info.setDeptId(this.leaveApprovalService.loadDeptIdOfEmployee(this.current_user_id));
return this.leaveApprovalService.datagrid(info);
}
/**
* 加载请假审批(部门)审批页面。
* @param id
* @param model
* @return
*/
@RequiresPermissions({ModuleConstant.ADM_LEAVE_DEPT_APPROVAL + ":" + Right.UPDATE})
@RequestMapping(value = {"/dept/edit"}, method = RequestMethod.GET)
public String deptEdit(String id, Model model){
if(logger.isDebugEnabled()) logger.debug("加载请假审批(部门)审批页面[id="+ id +"]...");
return this.loadApprovalEdit(id, model);
}
//加载审批页面。
private String loadApprovalEdit(String id, Model model){
model.addAttribute("CURRENT_LEAVE_ID", StringUtils.isEmpty(id) ? "" : id);
model.addAttribute("RESULT_AGREE_VALUE", Leave.RESULT_AGREE);
model.addAttribute("RESULT_AGREE_NAME", this.leaveService.loadResultName(Leave.RESULT_AGREE));
model.addAttribute("RESULT_DISAGREE_VALUE", Leave.RESULT_DISAGREE);
model.addAttribute("RESULT_DISAGREE_NAME", this.leaveService.loadResultName(Leave.RESULT_DISAGREE));
return "adm/leave_approval_edit";
}
/**
* 加载请假审批(部门)审批。
* @param id
* @param model
* @return
*/
@RequiresPermissions({ModuleConstant.ADM_LEAVE_DEPT_APPROVAL + ":" + Right.UPDATE})
@RequestMapping(value = {"/dept/update"}, method = RequestMethod.POST)
@ResponseBody
public Json deptApproval(LeaveInfo info){
if(logger.isDebugEnabled())logger.debug("请假审批(部门)...");
return this.updateApproval(info, Leave.STATUS_APPROVAL_DEPT);
}
//请假条审批处理。
private Json updateApproval(LeaveInfo info, Integer status){
Json result = new Json();
try {
info.setCurrentUserId(this.current_user_id);
info.setStatus(status);
result.setData(this.leaveApprovalService.update(info));
result.setSuccess(true);
} catch (Exception e) {
result.setSuccess(false);
result.setMsg(e.getMessage());
logger.error("更新数据发生异常", e);
}
return result;
}
/**
* 加载请假审批(HR)列表页面。
* @return
*/
@RequiresPermissions({ModuleConstant.ADM_LEAVE_HR_APPROVAL + ":" + Right.VIEW})
@RequestMapping(value = {"/hr","/hr/list"}, method = RequestMethod.GET)
public String hrList(Model model){
if(logger.isDebugEnabled()) logger.debug("加载请假审批(HR)列表页面...");
model.addAttribute("PER_UPDATE", ModuleConstant.ADM_LEAVE_HR_APPROVAL + ":" + Right.UPDATE);
model.addAttribute("PER_DELETE", ModuleConstant.ADM_LEAVE_HR_APPROVAL + ":" + Right.DELETE);
model.addAttribute("CURRENT_STATUS_VALUE", Leave.STATUS_APPROVAL_HR);
model.addAttribute("CURRENT_RESULT_VALUE", Leave.RESULT_APPROVAL);
return "adm/leave_approval_hr_list";
}
/**
* 加载请假审批(HR)列表页面数据。
* @param info
* @return
*/
@RequiresPermissions({ModuleConstant.ADM_LEAVE_HR_APPROVAL + ":" + Right.VIEW})
@RequestMapping(value = {"/hr/datagrid"}, method = RequestMethod.POST)
@ResponseBody
public DataGrid<LeaveInfo> hrListDataGrid(LeaveInfo info){
if(logger.isDebugEnabled()) logger.debug("加载请假审批(HR)列表页面数据...");
return this.leaveApprovalService.datagrid(info);
}
/**
* 加载请假审批(HR)审批页面。
* @param id
* @param model
* @return
*/
@RequiresPermissions({ModuleConstant.ADM_LEAVE_HR_APPROVAL + ":" + Right.UPDATE})
@RequestMapping(value = {"/hr/edit"}, method = RequestMethod.GET)
public String hrEdit(String id, Model model){
if(logger.isDebugEnabled()) logger.debug("加载请假审批(HR)审批页面[id="+ id +"]...");
return this.loadApprovalEdit(id, model);
}
/**
* 加载请假审批(HR)审批。
* @param id
* @param model
* @return
*/
@RequiresPermissions({ModuleConstant.ADM_LEAVE_HR_APPROVAL + ":" + Right.UPDATE})
@RequestMapping(value = {"/hr/update"}, method = RequestMethod.POST)
@ResponseBody
public Json hrApproval(LeaveInfo info){
if(logger.isDebugEnabled())logger.debug("请假审批(HR)...");
return this.updateApproval(info, Leave.STATUS_APPROVAL_HR);
}
/**
* 加载请假审批(总经理)列表页面。
* @return
*/
@RequiresPermissions({ModuleConstant.ADM_LEAVE_BOSS_APPROVAL + ":" + Right.VIEW})
@RequestMapping(value = {"/boss","/boss/list"}, method = RequestMethod.GET)
public String bossList(Model model){
if(logger.isDebugEnabled()) logger.debug("加载请假审批(总经理)列表页面...");
model.addAttribute("PER_UPDATE", ModuleConstant.ADM_LEAVE_BOSS_APPROVAL + ":" + Right.UPDATE);
model.addAttribute("PER_DELETE", ModuleConstant.ADM_LEAVE_BOSS_APPROVAL + ":" + Right.DELETE);
model.addAttribute("CURRENT_STATUS_VALUE", Leave.STATUS_APPROVAL_BOSS);
model.addAttribute("CURRENT_RESULT_VALUE", Leave.RESULT_APPROVAL);
return "adm/leave_approval_boss_list";
}
/**
* 加载请假审批(总经理)列表页面数据。
* @param info
* @return
*/
@RequiresPermissions({ModuleConstant.ADM_LEAVE_BOSS_APPROVAL + ":" + Right.VIEW})
@RequestMapping(value = {"/boss/datagrid"}, method = RequestMethod.POST)
@ResponseBody
public DataGrid<LeaveInfo> bossListDataGrid(LeaveInfo info){
if(logger.isDebugEnabled()) logger.debug("加载请假审批(总经理)列表页面数据...");
return this.leaveApprovalService.datagrid(info);
}
/**
* 加载请假审批(总经理)审批页面。
* @param id
* @param model
* @return
*/
@RequiresPermissions({ModuleConstant.ADM_LEAVE_HR_APPROVAL + ":" + Right.UPDATE})
@RequestMapping(value = {"/boss/edit"}, method = RequestMethod.GET)
public String bossEdit(String id, Model model){
if(logger.isDebugEnabled()) logger.debug("加载请假审批(总经理)审批页面[id="+ id +"]...");
return this.loadApprovalEdit(id, model);
}
/**
* 加载请假审批(总经理)审批。
* @param id
* @param model
* @return
*/
@RequiresPermissions({ModuleConstant.ADM_LEAVE_BOSS_APPROVAL + ":" + Right.UPDATE})
@RequestMapping(value = {"/boss/update"}, method = RequestMethod.POST)
@ResponseBody
public Json bossApproval(LeaveInfo info){
if(logger.isDebugEnabled())logger.debug("请假审批(总经理)...");
return this.updateApproval(info, Leave.STATUS_APPROVAL_BOSS);
}
} | jeasonyoung/examw-oa | src/main/java/com/examw/oa/controllers/adm/LeaveApprovalController.java | Java | apache-2.0 | 10,140 |
/*
* Copyright 2015 Smartling, Inc.
*
* 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.
*/
package com.changefirst.keycloak.provider;
import com.changefirst.api.user.UserRepository;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.Config.Scope;
import org.keycloak.common.util.MultivaluedHashMap;
import org.keycloak.component.ComponentModel;
import org.keycloak.credential.CredentialModel;
import org.keycloak.models.*;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
/**
* Remote user federation provider factory tests.
*/
public class RestUserFederationProviderTest {
RestUserFederationProviderFactory factory;
@Mock
private KeycloakSessionFactory keycloakSessionFactory;
@Mock
private KeycloakSession keycloakSession;
@Mock
private Scope config;
@Mock
private ComponentModel userFederationProviderModel;
@Mock
private RealmModel realm;
@Mock
private UserModel user;
@Mock
private UserCredentialModel input;
@Mock
private UserRepository repository;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
factory = new RestUserFederationProviderFactory();
MultivaluedHashMap<String, String> config = new MultivaluedHashMap<String, String>();
config.putSingle(RestUserFederationProviderFactory.PROPERTY_URL, "http://localhost.com");
when(userFederationProviderModel.getConfig())
.thenReturn(config);
when(user.getUsername()).thenReturn("user1@changefirst.com");
when(input.getValue()).thenReturn("password");
when(input.getType()).thenReturn(CredentialModel.PASSWORD);
}
@Test
public void testGetInstance() throws Exception {
Object provider = factory.create(keycloakSession, userFederationProviderModel);
assertNotNull(provider);
assertTrue(provider instanceof RestUserFederationProvider);
}
@Test
public void testclose() throws Exception {
RestUserFederationProvider provider = factory.create(keycloakSession, userFederationProviderModel);
provider.close();
verifyZeroInteractions(config);
}
} | istvano/keycloak-import-federation | src/test/java/com/changefirst/keycloak/provider/RestUserFederationProviderTest.java | Java | apache-2.0 | 2,909 |
package com.martinbechtle.jcanary.boot;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* * Integration test for the case in which jcanary is disabled (see application-enabled.properties)
*
* @author Martin Bechtle
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {IntegrationTestConfig.class})
@WebAppConfiguration
@ActiveProfiles({"enabled"})
public class CanaryControllerEnabledIntegrationTest {
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context)
.build();
}
@Test
public void canaryEndpoint_ShouldReturnOk_WhenEnabledInConfig() throws Exception {
mockMvc.perform(get("/canary"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.serviceName").value("test-service"))
.andExpect(jsonPath("$.result").value("OK"))
.andExpect(jsonPath("$.tweets[0].dependency.importance").value("PRIMARY"))
.andExpect(jsonPath("$.tweets[0].dependency.type").value("RESOURCE"))
.andExpect(jsonPath("$.tweets[0].dependency.name").value("dummyMonitor"))
.andExpect(jsonPath("$.tweets[0].result.status").value("HEALTHY"))
.andExpect(jsonPath("$.tweets[0].result.statusText").value(""));
}
}
| MartinBechtle/jcanary | jcanary-boot/src/test/java/com/martinbechtle/jcanary/boot/CanaryControllerEnabledIntegrationTest.java | Java | apache-2.0 | 2,243 |
/// <reference path="../../factory.ts" />
/// <reference path="../../visitor.ts" />
/// <reference path="../destructuring.ts" />
/*@internal*/
namespace ts {
export function transformSystemModule(context: TransformationContext) {
interface DependencyGroup {
name: StringLiteral;
externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[];
}
const {
startLexicalEnvironment,
endLexicalEnvironment,
hoistVariableDeclaration
} = context;
const compilerOptions = context.getCompilerOptions();
const resolver = context.getEmitResolver();
const host = context.getEmitHost();
const previousOnSubstituteNode = context.onSubstituteNode;
const previousOnEmitNode = context.onEmitNode;
context.onSubstituteNode = onSubstituteNode;
context.onEmitNode = onEmitNode;
context.enableSubstitution(SyntaxKind.Identifier); // Substitutes expression identifiers for imported symbols.
context.enableSubstitution(SyntaxKind.BinaryExpression); // Substitutes assignments to exported symbols.
context.enableSubstitution(SyntaxKind.PrefixUnaryExpression); // Substitutes updates to exported symbols.
context.enableSubstitution(SyntaxKind.PostfixUnaryExpression); // Substitutes updates to exported symbols.
context.enableEmitNotification(SyntaxKind.SourceFile); // Restore state when substituting nodes in a file.
const moduleInfoMap: ExternalModuleInfo[] = []; // The ExternalModuleInfo for each file.
const deferredExports: Statement[][] = []; // Exports to defer until an EndOfDeclarationMarker is found.
const exportFunctionsMap: Identifier[] = []; // The export function associated with a source file.
const noSubstitutionMap: boolean[][] = []; // Set of nodes for which substitution rules should be ignored for each file.
let currentSourceFile: SourceFile; // The current file.
let moduleInfo: ExternalModuleInfo; // ExternalModuleInfo for the current file.
let exportFunction: Identifier; // The export function for the current file.
let contextObject: Identifier; // The context object for the current file.
let hoistedStatements: Statement[];
let enclosingBlockScopedContainer: Node;
let noSubstitution: boolean[]; // Set of nodes for which substitution rules should be ignored.
return transformSourceFile;
/**
* Transforms the module aspects of a SourceFile.
*
* @param node The SourceFile node.
*/
function transformSourceFile(node: SourceFile) {
if (node.isDeclarationFile || !(isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & TransformFlags.ContainsDynamicImport)) {
return node;
}
const id = getOriginalNodeId(node);
currentSourceFile = node;
enclosingBlockScopedContainer = node;
// System modules have the following shape:
//
// System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
//
// The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
// is used to publish exported values. 'exports' returns its 'value' argument so in
// most cases expressions that mutate exported values can be rewritten as:
//
// expr -> exports('name', expr)
//
// The only exception in this rule is postfix unary operators,
// see comment to 'substitutePostfixUnaryExpression' for more details
// Collect information about the external module and dependency groups.
moduleInfo = moduleInfoMap[id] = collectExternalModuleInfo(node, resolver, compilerOptions);
// Make sure that the name of the 'exports' function does not conflict with
// existing identifiers.
exportFunction = createUniqueName("exports");
exportFunctionsMap[id] = exportFunction;
contextObject = createUniqueName("context");
// Add the body of the module.
const dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
const moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
const moduleBodyFunction = createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
[
createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
],
/*type*/ undefined,
moduleBodyBlock
);
// Write the call to `System.register`
// Clear the emit-helpers flag for later passes since we'll have already used it in the module body
// So the helper will be emit at the correct position instead of at the top of the source-file
const moduleName = tryGetModuleNameFromFile(node, host, compilerOptions);
const dependencies = createArrayLiteral(map(dependencyGroups, dependencyGroup => dependencyGroup.name));
const updated = setEmitFlags(
updateSourceFileNode(
node,
setTextRange(
createNodeArray([
createStatement(
createCall(
createPropertyAccess(createIdentifier("System"), "register"),
/*typeArguments*/ undefined,
moduleName
? [moduleName, dependencies, moduleBodyFunction]
: [dependencies, moduleBodyFunction]
)
)
]),
node.statements
)
), EmitFlags.NoTrailingComments);
if (!(compilerOptions.outFile || compilerOptions.out)) {
moveEmitHelpers(updated, moduleBodyBlock, helper => !helper.scoped);
}
if (noSubstitution) {
noSubstitutionMap[id] = noSubstitution;
noSubstitution = undefined;
}
currentSourceFile = undefined;
moduleInfo = undefined;
exportFunction = undefined;
contextObject = undefined;
hoistedStatements = undefined;
enclosingBlockScopedContainer = undefined;
return aggregateTransformFlags(updated);
}
/**
* Collects the dependency groups for this files imports.
*
* @param externalImports The imports for the file.
*/
function collectDependencyGroups(externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[]) {
const groupIndices = createMap<number>();
const dependencyGroups: DependencyGroup[] = [];
for (let i = 0; i < externalImports.length; i++) {
const externalImport = externalImports[i];
const externalModuleName = getExternalModuleNameLiteral(externalImport, currentSourceFile, host, resolver, compilerOptions);
if (externalModuleName) {
const text = externalModuleName.text;
const groupIndex = groupIndices.get(text);
if (groupIndex !== undefined) {
// deduplicate/group entries in dependency list by the dependency name
dependencyGroups[groupIndex].externalImports.push(externalImport);
}
else {
groupIndices.set(text, dependencyGroups.length);
dependencyGroups.push({
name: externalModuleName,
externalImports: [externalImport]
});
}
}
}
return dependencyGroups;
}
/**
* Adds the statements for the module body function for the source file.
*
* @param node The source file for the module.
* @param dependencyGroups The grouped dependencies of the module.
*/
function createSystemModuleBody(node: SourceFile, dependencyGroups: DependencyGroup[]) {
// Shape of the body in system modules:
//
// function (exports) {
// <list of local aliases for imports>
// <hoisted variable declarations>
// <hoisted function declarations>
// return {
// setters: [
// <list of setter function for imports>
// ],
// execute: function() {
// <module statements>
// }
// }
// <temp declarations>
// }
//
// i.e:
//
// import {x} from 'file1'
// var y = 1;
// export function foo() { return y + x(); }
// console.log(y);
//
// Will be transformed to:
//
// function(exports) {
// function foo() { return y + file_1.x(); }
// exports("foo", foo);
// var file_1, y;
// return {
// setters: [
// function(v) { file_1 = v }
// ],
// execute(): function() {
// y = 1;
// console.log(y);
// }
// };
// }
const statements: Statement[] = [];
// We start a new lexical environment in this function body, but *not* in the
// body of the execute function. This allows us to emit temporary declarations
// only in the outer module body and not in the inner one.
startLexicalEnvironment();
// Add any prologue directives.
const ensureUseStrict = compilerOptions.alwaysStrict || (!compilerOptions.noImplicitUseStrict && isExternalModule(currentSourceFile));
const statementOffset = addPrologue(statements, node.statements, ensureUseStrict, sourceElementVisitor);
// var __moduleName = context_1 && context_1.id;
statements.push(
createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList([
createVariableDeclaration(
"__moduleName",
/*type*/ undefined,
createLogicalAnd(
contextObject,
createPropertyAccess(contextObject, "id")
)
)
])
)
);
// Visit the synthetic external helpers import declaration if present
visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, isStatement);
// Visit the statements of the source file, emitting any transformations into
// the `executeStatements` array. We do this *before* we fill the `setters` array
// as we both emit transformations as well as aggregate some data used when creating
// setters. This allows us to reduce the number of times we need to loop through the
// statements of the source file.
const executeStatements = visitNodes(node.statements, sourceElementVisitor, isStatement, statementOffset);
// Emit early exports for function declarations.
addRange(statements, hoistedStatements);
// We emit hoisted variables early to align roughly with our previous emit output.
// Two key differences in this approach are:
// - Temporary variables will appear at the top rather than at the bottom of the file
addRange(statements, endLexicalEnvironment());
const exportStarFunction = addExportStarIfNeeded(statements);
const moduleObject = createObjectLiteral([
createPropertyAssignment("setters",
createSettersArray(exportStarFunction, dependencyGroups)
),
createPropertyAssignment("execute",
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
/*parameters*/ [],
/*type*/ undefined,
createBlock(executeStatements, /*multiLine*/ true)
)
)
]);
moduleObject.multiLine = true;
statements.push(createReturn(moduleObject));
return createBlock(statements, /*multiLine*/ true);
}
/**
* Adds an exportStar function to a statement list if it is needed for the file.
*
* @param statements A statement list.
*/
function addExportStarIfNeeded(statements: Statement[]) {
if (!moduleInfo.hasExportStarsToExportValues) {
return;
}
// when resolving exports local exported entries/indirect exported entries in the module
// should always win over entries with similar names that were added via star exports
// to support this we store names of local/indirect exported entries in a set.
// this set is used to filter names brought by star expors.
// local names set should only be added if we have anything exported
if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
// no exported declarations (export var ...) or export specifiers (export {x})
// check if we have any non star export declarations.
let hasExportDeclarationWithExportClause = false;
for (const externalImport of moduleInfo.externalImports) {
if (externalImport.kind === SyntaxKind.ExportDeclaration && externalImport.exportClause) {
hasExportDeclarationWithExportClause = true;
break;
}
}
if (!hasExportDeclarationWithExportClause) {
// we still need to emit exportStar helper
const exportStarFunction = createExportStarFunction(/*localNames*/ undefined);
statements.push(exportStarFunction);
return exportStarFunction.name;
}
}
const exportedNames: ObjectLiteralElementLike[] = [];
if (moduleInfo.exportedNames) {
for (const exportedLocalName of moduleInfo.exportedNames) {
if (exportedLocalName.text === "default") {
continue;
}
// write name of exported declaration, i.e 'export var x...'
exportedNames.push(
createPropertyAssignment(
createLiteral(exportedLocalName),
createTrue()
)
);
}
}
for (const externalImport of moduleInfo.externalImports) {
if (externalImport.kind !== SyntaxKind.ExportDeclaration) {
continue;
}
const exportDecl = <ExportDeclaration>externalImport;
if (!exportDecl.exportClause) {
// export * from ...
continue;
}
for (const element of exportDecl.exportClause.elements) {
// write name of indirectly exported entry, i.e. 'export {x} from ...'
exportedNames.push(
createPropertyAssignment(
createLiteral((element.name || element.propertyName).text),
createTrue()
)
);
}
}
const exportedNamesStorageRef = createUniqueName("exportedNames");
statements.push(
createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList([
createVariableDeclaration(
exportedNamesStorageRef,
/*type*/ undefined,
createObjectLiteral(exportedNames, /*multiline*/ true)
)
])
)
);
const exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
statements.push(exportStarFunction);
return exportStarFunction.name;
}
/**
* Creates an exportStar function for the file, with an optional set of excluded local
* names.
*
* @param localNames An optional reference to an object containing a set of excluded local
* names.
*/
function createExportStarFunction(localNames: Identifier | undefined) {
const exportStarFunction = createUniqueName("exportStar");
const m = createIdentifier("m");
const n = createIdentifier("n");
const exports = createIdentifier("exports");
let condition: Expression = createStrictInequality(n, createLiteral("default"));
if (localNames) {
condition = createLogicalAnd(
condition,
createLogicalNot(
createCall(
createPropertyAccess(localNames, "hasOwnProperty"),
/*typeArguments*/ undefined,
[n]
)
)
);
}
return createFunctionDeclaration(
/*decorators*/ undefined,
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
exportStarFunction,
/*typeParameters*/ undefined,
[createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)],
/*type*/ undefined,
createBlock([
createVariableStatement(
/*modifiers*/ undefined,
createVariableDeclarationList([
createVariableDeclaration(
exports,
/*type*/ undefined,
createObjectLiteral([])
)
])
),
createForIn(
createVariableDeclarationList([
createVariableDeclaration(n, /*type*/ undefined)
]),
m,
createBlock([
setEmitFlags(
createIf(
condition,
createStatement(
createAssignment(
createElementAccess(exports, n),
createElementAccess(m, n)
)
)
),
EmitFlags.SingleLine
)
])
),
createStatement(
createCall(
exportFunction,
/*typeArguments*/ undefined,
[exports]
)
)
], /*multiline*/ true)
);
}
/**
* Creates an array setter callbacks for each dependency group.
*
* @param exportStarFunction A reference to an exportStarFunction for the file.
* @param dependencyGroups An array of grouped dependencies.
*/
function createSettersArray(exportStarFunction: Identifier, dependencyGroups: DependencyGroup[]) {
const setters: Expression[] = [];
for (const group of dependencyGroups) {
// derive a unique name for parameter from the first named entry in the group
const localName = forEach(group.externalImports, i => getLocalNameForExternalImport(i, currentSourceFile));
const parameterName = localName ? getGeneratedNameForNode(localName) : createUniqueName("");
const statements: Statement[] = [];
for (const entry of group.externalImports) {
const importVariableName = getLocalNameForExternalImport(entry, currentSourceFile);
switch (entry.kind) {
case SyntaxKind.ImportDeclaration:
if (!(<ImportDeclaration>entry).importClause) {
// 'import "..."' case
// module is imported only for side-effects, no emit required
break;
}
// falls through
case SyntaxKind.ImportEqualsDeclaration:
Debug.assert(importVariableName !== undefined);
// save import into the local
statements.push(
createStatement(
createAssignment(importVariableName, parameterName)
)
);
break;
case SyntaxKind.ExportDeclaration:
Debug.assert(importVariableName !== undefined);
if ((<ExportDeclaration>entry).exportClause) {
// export {a, b as c} from 'foo'
//
// emit as:
//
// exports_({
// "a": _["a"],
// "c": _["b"]
// });
const properties: PropertyAssignment[] = [];
for (const e of (<ExportDeclaration>entry).exportClause.elements) {
properties.push(
createPropertyAssignment(
createLiteral(e.name.text),
createElementAccess(
parameterName,
createLiteral((e.propertyName || e.name).text)
)
)
);
}
statements.push(
createStatement(
createCall(
exportFunction,
/*typeArguments*/ undefined,
[createObjectLiteral(properties, /*multiline*/ true)]
)
)
);
}
else {
// export * from 'foo'
//
// emit as:
//
// exportStar(foo_1_1);
statements.push(
createStatement(
createCall(
exportStarFunction,
/*typeArguments*/ undefined,
[parameterName]
)
)
);
}
break;
}
}
setters.push(
createFunctionExpression(
/*modifiers*/ undefined,
/*asteriskToken*/ undefined,
/*name*/ undefined,
/*typeParameters*/ undefined,
[createParameter(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)],
/*type*/ undefined,
createBlock(statements, /*multiLine*/ true)
)
);
}
return createArrayLiteral(setters, /*multiLine*/ true);
}
//
// Top-level Source Element Visitors
//
/**
* Visit source elements at the top-level of a module.
*
* @param node The node to visit.
*/
function sourceElementVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ImportDeclaration:
return visitImportDeclaration(<ImportDeclaration>node);
case SyntaxKind.ImportEqualsDeclaration:
return visitImportEqualsDeclaration(<ImportEqualsDeclaration>node);
case SyntaxKind.ExportDeclaration:
// ExportDeclarations are elided as they are handled via
// `appendExportsOfDeclaration`.
return undefined;
case SyntaxKind.ExportAssignment:
return visitExportAssignment(<ExportAssignment>node);
default:
return nestedElementVisitor(node);
}
}
/**
* Visits an ImportDeclaration node.
*
* @param node The node to visit.
*/
function visitImportDeclaration(node: ImportDeclaration): VisitResult<Statement> {
let statements: Statement[];
if (node.importClause) {
hoistVariableDeclaration(getLocalNameForExternalImport(node, currentSourceFile));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
}
else {
statements = appendExportsOfImportDeclaration(statements, node);
}
return singleOrMany(statements);
}
/**
* Visits an ImportEqualsDeclaration node.
*
* @param node The node to visit.
*/
function visitImportEqualsDeclaration(node: ImportEqualsDeclaration): VisitResult<Statement> {
Debug.assert(isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
let statements: Statement[];
hoistVariableDeclaration(getLocalNameForExternalImport(node, currentSourceFile));
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
}
else {
statements = appendExportsOfImportEqualsDeclaration(statements, node);
}
return singleOrMany(statements);
}
/**
* Visits an ExportAssignment node.
*
* @param node The node to visit.
*/
function visitExportAssignment(node: ExportAssignment): VisitResult<Statement> {
if (node.isExportEquals) {
// Elide `export=` as it is illegal in a SystemJS module.
return undefined;
}
const expression = visitNode(node.expression, destructuringAndImportCallVisitor, isExpression);
const original = node.original;
if (original && hasAssociatedEndOfDeclarationMarker(original)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportStatement(deferredExports[id], createIdentifier("default"), expression, /*allowComments*/ true);
}
else {
return createExportStatement(createIdentifier("default"), expression, /*allowComments*/ true);
}
}
/**
* Visits a FunctionDeclaration, hoisting it to the outer module body function.
*
* @param node The node to visit.
*/
function visitFunctionDeclaration(node: FunctionDeclaration): VisitResult<Statement> {
if (hasModifier(node, ModifierFlags.Export)) {
hoistedStatements = append(hoistedStatements,
updateFunctionDeclaration(
node,
node.decorators,
visitNodes(node.modifiers, modifierVisitor, isModifier),
node.asteriskToken,
getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true),
/*typeParameters*/ undefined,
visitNodes(node.parameters, destructuringAndImportCallVisitor, isParameterDeclaration),
/*type*/ undefined,
visitNode(node.body, destructuringAndImportCallVisitor, isBlock)));
}
else {
hoistedStatements = append(hoistedStatements, visitEachChild(node, destructuringAndImportCallVisitor, context));
}
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
}
else {
hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
}
return undefined;
}
/**
* Visits a ClassDeclaration, hoisting its name to the outer module body function.
*
* @param node The node to visit.
*/
function visitClassDeclaration(node: ClassDeclaration): VisitResult<Statement> {
let statements: Statement[];
// Hoist the name of the class declaration to the outer module body function.
const name = getLocalName(node);
hoistVariableDeclaration(name);
// Rewrite the class declaration into an assignment of a class expression.
statements = append(statements,
setTextRange(
createStatement(
createAssignment(
name,
setTextRange(
createClassExpression(
/*modifiers*/ undefined,
node.name,
/*typeParameters*/ undefined,
visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, isHeritageClause),
visitNodes(node.members, destructuringAndImportCallVisitor, isClassElement)
),
node
)
)
),
node
)
);
if (hasAssociatedEndOfDeclarationMarker(node)) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
}
else {
statements = appendExportsOfHoistedDeclaration(statements, node);
}
return singleOrMany(statements);
}
/**
* Visits a variable statement, hoisting declared names to the top-level module body.
* Each declaration is rewritten into an assignment expression.
*
* @param node The node to visit.
*/
function visitVariableStatement(node: VariableStatement): VisitResult<Statement> {
if (!shouldHoistVariableDeclarationList(node.declarationList)) {
return visitNode(node, destructuringAndImportCallVisitor, isStatement);
}
let expressions: Expression[];
const isExportedDeclaration = hasModifier(node, ModifierFlags.Export);
const isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
for (const variable of node.declarationList.declarations) {
if (variable.initializer) {
expressions = append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
}
else {
hoistBindingElement(variable);
}
}
let statements: Statement[];
if (expressions) {
statements = append(statements, setTextRange(createStatement(inlineExpressions(expressions)), node));
}
if (isMarkedDeclaration) {
// Defer exports until we encounter an EndOfDeclarationMarker node
const id = getOriginalNodeId(node);
deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
}
else {
statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
}
return singleOrMany(statements);
}
/**
* Hoists the declared names of a VariableDeclaration or BindingElement.
*
* @param node The declaration to hoist.
*/
function hoistBindingElement(node: VariableDeclaration | BindingElement): void {
if (isBindingPattern(node.name)) {
for (const element of node.name.elements) {
if (!isOmittedExpression(element)) {
hoistBindingElement(element);
}
}
}
else {
hoistVariableDeclaration(getSynthesizedClone(node.name));
}
}
/**
* Determines whether a VariableDeclarationList should be hoisted.
*
* @param node The node to test.
*/
function shouldHoistVariableDeclarationList(node: VariableDeclarationList) {
// hoist only non-block scoped declarations or block scoped declarations parented by source file
return (getEmitFlags(node) & EmitFlags.NoHoisting) === 0
&& (enclosingBlockScopedContainer.kind === SyntaxKind.SourceFile
|| (getOriginalNode(node).flags & NodeFlags.BlockScoped) === 0);
}
/**
* Transform an initialized variable declaration into an expression.
*
* @param node The node to transform.
* @param isExportedDeclaration A value indicating whether the variable is exported.
*/
function transformInitializedVariable(node: VariableDeclaration, isExportedDeclaration: boolean): Expression {
const createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
return isBindingPattern(node.name)
? flattenDestructuringAssignment(
node,
destructuringAndImportCallVisitor,
context,
FlattenLevel.All,
/*needsValue*/ false,
createAssignment
)
: createAssignment(node.name, visitNode(node.initializer, destructuringAndImportCallVisitor, isExpression));
}
/**
* Creates an assignment expression for an exported variable declaration.
*
* @param name The name of the variable.
* @param value The value of the variable's initializer.
* @param location The source map location for the assignment.
*/
function createExportedVariableAssignment(name: Identifier, value: Expression, location?: TextRange) {
return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
}
/**
* Creates an assignment expression for a non-exported variable declaration.
*
* @param name The name of the variable.
* @param value The value of the variable's initializer.
* @param location The source map location for the assignment.
*/
function createNonExportedVariableAssignment(name: Identifier, value: Expression, location?: TextRange) {
return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
}
/**
* Creates an assignment expression for a variable declaration.
*
* @param name The name of the variable.
* @param value The value of the variable's initializer.
* @param location The source map location for the assignment.
* @param isExportedDeclaration A value indicating whether the variable is exported.
*/
function createVariableAssignment(name: Identifier, value: Expression, location: TextRange, isExportedDeclaration: boolean) {
hoistVariableDeclaration(getSynthesizedClone(name));
return isExportedDeclaration
? createExportExpression(name, preventSubstitution(setTextRange(createAssignment(name, value), location)))
: preventSubstitution(setTextRange(createAssignment(name, value), location));
}
/**
* Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
* and transformed declaration.
*
* @param node The node to visit.
*/
function visitMergeDeclarationMarker(node: MergeDeclarationMarker): VisitResult<Statement> {
// For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
// declaration we do not emit a leading variable declaration. To preserve the
// begin/end semantics of the declararation and to properly handle exports
// we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
//
// To balance the declaration, we defer the exports of the elided variable
// statement until we visit this declaration's `EndOfDeclarationMarker`.
if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === SyntaxKind.VariableStatement) {
const id = getOriginalNodeId(node);
const isExportedDeclaration = hasModifier(node.original, ModifierFlags.Export);
deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], <VariableStatement>node.original, isExportedDeclaration);
}
return node;
}
/**
* Determines whether a node has an associated EndOfDeclarationMarker.
*
* @param node The node to test.
*/
function hasAssociatedEndOfDeclarationMarker(node: Node) {
return (getEmitFlags(node) & EmitFlags.HasEndOfDeclarationMarker) !== 0;
}
/**
* Visits a DeclarationMarker used as a placeholder for the end of a transformed
* declaration.
*
* @param node The node to visit.
*/
function visitEndOfDeclarationMarker(node: EndOfDeclarationMarker): VisitResult<Statement> {
// For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
// end of the transformed declaration. We use this marker to emit any deferred exports
// of the declaration.
const id = getOriginalNodeId(node);
const statements = deferredExports[id];
if (statements) {
delete deferredExports[id];
return append(statements, node);
}
return node;
}
/**
* Appends the exports of an ImportDeclaration to a statement list, returning the
* statement list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param decl The declaration whose exports are to be recorded.
*/
function appendExportsOfImportDeclaration(statements: Statement[], decl: ImportDeclaration) {
if (moduleInfo.exportEquals) {
return statements;
}
const importClause = decl.importClause;
if (!importClause) {
return statements;
}
if (importClause.name) {
statements = appendExportsOfDeclaration(statements, importClause);
}
const namedBindings = importClause.namedBindings;
if (namedBindings) {
switch (namedBindings.kind) {
case SyntaxKind.NamespaceImport:
statements = appendExportsOfDeclaration(statements, namedBindings);
break;
case SyntaxKind.NamedImports:
for (const importBinding of namedBindings.elements) {
statements = appendExportsOfDeclaration(statements, importBinding);
}
break;
}
}
return statements;
}
/**
* Appends the export of an ImportEqualsDeclaration to a statement list, returning the
* statement list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param decl The declaration whose exports are to be recorded.
*/
function appendExportsOfImportEqualsDeclaration(statements: Statement[], decl: ImportEqualsDeclaration): Statement[] | undefined {
if (moduleInfo.exportEquals) {
return statements;
}
return appendExportsOfDeclaration(statements, decl);
}
/**
* Appends the exports of a VariableStatement to a statement list, returning the statement
* list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param node The VariableStatement whose exports are to be recorded.
* @param exportSelf A value indicating whether to also export each VariableDeclaration of
* `nodes` declaration list.
*/
function appendExportsOfVariableStatement(statements: Statement[] | undefined, node: VariableStatement, exportSelf: boolean): Statement[] | undefined {
if (moduleInfo.exportEquals) {
return statements;
}
for (const decl of node.declarationList.declarations) {
if (decl.initializer || exportSelf) {
statements = appendExportsOfBindingElement(statements, decl, exportSelf);
}
}
return statements;
}
/**
* Appends the exports of a VariableDeclaration or BindingElement to a statement list,
* returning the statement list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param decl The declaration whose exports are to be recorded.
* @param exportSelf A value indicating whether to also export the declaration itself.
*/
function appendExportsOfBindingElement(statements: Statement[] | undefined, decl: VariableDeclaration | BindingElement, exportSelf: boolean): Statement[] | undefined {
if (moduleInfo.exportEquals) {
return statements;
}
if (isBindingPattern(decl.name)) {
for (const element of decl.name.elements) {
if (!isOmittedExpression(element)) {
statements = appendExportsOfBindingElement(statements, element, exportSelf);
}
}
}
else if (!isGeneratedIdentifier(decl.name)) {
let excludeName: string;
if (exportSelf) {
statements = appendExportStatement(statements, decl.name, getLocalName(decl));
excludeName = decl.name.text;
}
statements = appendExportsOfDeclaration(statements, decl, excludeName);
}
return statements;
}
/**
* Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
* returning the statement list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param decl The declaration whose exports are to be recorded.
*/
function appendExportsOfHoistedDeclaration(statements: Statement[] | undefined, decl: ClassDeclaration | FunctionDeclaration): Statement[] | undefined {
if (moduleInfo.exportEquals) {
return statements;
}
let excludeName: string;
if (hasModifier(decl, ModifierFlags.Export)) {
const exportName = hasModifier(decl, ModifierFlags.Default) ? createLiteral("default") : decl.name;
statements = appendExportStatement(statements, exportName, getLocalName(decl));
excludeName = exportName.text;
}
if (decl.name) {
statements = appendExportsOfDeclaration(statements, decl, excludeName);
}
return statements;
}
/**
* Appends the exports of a declaration to a statement list, returning the statement list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param decl The declaration to export.
* @param excludeName An optional name to exclude from exports.
*/
function appendExportsOfDeclaration(statements: Statement[] | undefined, decl: Declaration, excludeName?: string): Statement[] | undefined {
if (moduleInfo.exportEquals) {
return statements;
}
const name = getDeclarationName(decl);
const exportSpecifiers = moduleInfo.exportSpecifiers.get(name.text);
if (exportSpecifiers) {
for (const exportSpecifier of exportSpecifiers) {
if (exportSpecifier.name.text !== excludeName) {
statements = appendExportStatement(statements, exportSpecifier.name, name);
}
}
}
return statements;
}
/**
* Appends the down-level representation of an export to a statement list, returning the
* statement list.
*
* @param statements A statement list to which the down-level export statements are to be
* appended. If `statements` is `undefined`, a new array is allocated if statements are
* appended.
* @param exportName The name of the export.
* @param expression The expression to export.
* @param allowComments Whether to allow comments on the export.
*/
function appendExportStatement(statements: Statement[] | undefined, exportName: Identifier | StringLiteral, expression: Expression, allowComments?: boolean): Statement[] | undefined {
statements = append(statements, createExportStatement(exportName, expression, allowComments));
return statements;
}
/**
* Creates a call to the current file's export function to export a value.
*
* @param name The bound name of the export.
* @param value The exported value.
* @param allowComments An optional value indicating whether to emit comments for the statement.
*/
function createExportStatement(name: Identifier | StringLiteral, value: Expression, allowComments?: boolean) {
const statement = createStatement(createExportExpression(name, value));
startOnNewLine(statement);
if (!allowComments) {
setEmitFlags(statement, EmitFlags.NoComments);
}
return statement;
}
/**
* Creates a call to the current file's export function to export a value.
*
* @param name The bound name of the export.
* @param value The exported value.
*/
function createExportExpression(name: Identifier | StringLiteral, value: Expression) {
const exportName = isIdentifier(name) ? createLiteral(name) : name;
return createCall(exportFunction, /*typeArguments*/ undefined, [exportName, value]);
}
//
// Top-Level or Nested Source Element Visitors
//
/**
* Visit nested elements at the top-level of a module.
*
* @param node The node to visit.
*/
function nestedElementVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.VariableStatement:
return visitVariableStatement(<VariableStatement>node);
case SyntaxKind.FunctionDeclaration:
return visitFunctionDeclaration(<FunctionDeclaration>node);
case SyntaxKind.ClassDeclaration:
return visitClassDeclaration(<ClassDeclaration>node);
case SyntaxKind.ForStatement:
return visitForStatement(<ForStatement>node);
case SyntaxKind.ForInStatement:
return visitForInStatement(<ForInStatement>node);
case SyntaxKind.ForOfStatement:
return visitForOfStatement(<ForOfStatement>node);
case SyntaxKind.DoStatement:
return visitDoStatement(<DoStatement>node);
case SyntaxKind.WhileStatement:
return visitWhileStatement(<WhileStatement>node);
case SyntaxKind.LabeledStatement:
return visitLabeledStatement(<LabeledStatement>node);
case SyntaxKind.WithStatement:
return visitWithStatement(<WithStatement>node);
case SyntaxKind.SwitchStatement:
return visitSwitchStatement(<SwitchStatement>node);
case SyntaxKind.CaseBlock:
return visitCaseBlock(<CaseBlock>node);
case SyntaxKind.CaseClause:
return visitCaseClause(<CaseClause>node);
case SyntaxKind.DefaultClause:
return visitDefaultClause(<DefaultClause>node);
case SyntaxKind.TryStatement:
return visitTryStatement(<TryStatement>node);
case SyntaxKind.CatchClause:
return visitCatchClause(<CatchClause>node);
case SyntaxKind.Block:
return visitBlock(<Block>node);
case SyntaxKind.MergeDeclarationMarker:
return visitMergeDeclarationMarker(<MergeDeclarationMarker>node);
case SyntaxKind.EndOfDeclarationMarker:
return visitEndOfDeclarationMarker(<EndOfDeclarationMarker>node);
default:
return destructuringAndImportCallVisitor(node);
}
}
/**
* Visits the body of a ForStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitForStatement(node: ForStatement): VisitResult<Statement> {
const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
enclosingBlockScopedContainer = node;
node = updateFor(
node,
visitForInitializer(node.initializer),
visitNode(node.condition, destructuringAndImportCallVisitor, isExpression),
visitNode(node.incrementor, destructuringAndImportCallVisitor, isExpression),
visitNode(node.statement, nestedElementVisitor, isStatement)
);
enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
return node;
}
/**
* Visits the body of a ForInStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitForInStatement(node: ForInStatement): VisitResult<Statement> {
const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
enclosingBlockScopedContainer = node;
node = updateForIn(
node,
visitForInitializer(node.initializer),
visitNode(node.expression, destructuringAndImportCallVisitor, isExpression),
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock)
);
enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
return node;
}
/**
* Visits the body of a ForOfStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitForOfStatement(node: ForOfStatement): VisitResult<Statement> {
const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
enclosingBlockScopedContainer = node;
node = updateForOf(
node,
node.awaitModifier,
visitForInitializer(node.initializer),
visitNode(node.expression, destructuringAndImportCallVisitor, isExpression),
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock)
);
enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
return node;
}
/**
* Determines whether to hoist the initializer of a ForStatement, ForInStatement, or
* ForOfStatement.
*
* @param node The node to test.
*/
function shouldHoistForInitializer(node: ForInitializer): node is VariableDeclarationList {
return isVariableDeclarationList(node)
&& shouldHoistVariableDeclarationList(node);
}
/**
* Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement
*
* @param node The node to visit.
*/
function visitForInitializer(node: ForInitializer): ForInitializer {
if (!node) {
return node;
}
if (shouldHoistForInitializer(node)) {
let expressions: Expression[];
for (const variable of node.declarations) {
expressions = append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
}
return expressions ? inlineExpressions(expressions) : createOmittedExpression();
}
else {
return visitEachChild(node, nestedElementVisitor, context);
}
}
/**
* Visits the body of a DoStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitDoStatement(node: DoStatement): VisitResult<Statement> {
return updateDo(
node,
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock),
visitNode(node.expression, destructuringAndImportCallVisitor, isExpression)
);
}
/**
* Visits the body of a WhileStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitWhileStatement(node: WhileStatement): VisitResult<Statement> {
return updateWhile(
node,
visitNode(node.expression, destructuringAndImportCallVisitor, isExpression),
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock)
);
}
/**
* Visits the body of a LabeledStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitLabeledStatement(node: LabeledStatement): VisitResult<Statement> {
return updateLabel(
node,
node.label,
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock)
);
}
/**
* Visits the body of a WithStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitWithStatement(node: WithStatement): VisitResult<Statement> {
return updateWith(
node,
visitNode(node.expression, destructuringAndImportCallVisitor, isExpression),
visitNode(node.statement, nestedElementVisitor, isStatement, liftToBlock)
);
}
/**
* Visits the body of a SwitchStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitSwitchStatement(node: SwitchStatement): VisitResult<Statement> {
return updateSwitch(
node,
visitNode(node.expression, destructuringAndImportCallVisitor, isExpression),
visitNode(node.caseBlock, nestedElementVisitor, isCaseBlock)
);
}
/**
* Visits the body of a CaseBlock to hoist declarations.
*
* @param node The node to visit.
*/
function visitCaseBlock(node: CaseBlock): CaseBlock {
const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
enclosingBlockScopedContainer = node;
node = updateCaseBlock(
node,
visitNodes(node.clauses, nestedElementVisitor, isCaseOrDefaultClause)
);
enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
return node;
}
/**
* Visits the body of a CaseClause to hoist declarations.
*
* @param node The node to visit.
*/
function visitCaseClause(node: CaseClause): VisitResult<CaseOrDefaultClause> {
return updateCaseClause(
node,
visitNode(node.expression, destructuringAndImportCallVisitor, isExpression),
visitNodes(node.statements, nestedElementVisitor, isStatement)
);
}
/**
* Visits the body of a DefaultClause to hoist declarations.
*
* @param node The node to visit.
*/
function visitDefaultClause(node: DefaultClause): VisitResult<CaseOrDefaultClause> {
return visitEachChild(node, nestedElementVisitor, context);
}
/**
* Visits the body of a TryStatement to hoist declarations.
*
* @param node The node to visit.
*/
function visitTryStatement(node: TryStatement): VisitResult<Statement> {
return visitEachChild(node, nestedElementVisitor, context);
}
/**
* Visits the body of a CatchClause to hoist declarations.
*
* @param node The node to visit.
*/
function visitCatchClause(node: CatchClause): CatchClause {
const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
enclosingBlockScopedContainer = node;
node = updateCatchClause(
node,
node.variableDeclaration,
visitNode(node.block, nestedElementVisitor, isBlock)
);
enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
return node;
}
/**
* Visits the body of a Block to hoist declarations.
*
* @param node The node to visit.
*/
function visitBlock(node: Block): Block {
const savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
enclosingBlockScopedContainer = node;
node = visitEachChild(node, nestedElementVisitor, context);
enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
return node;
}
//
// Destructuring Assignment Visitors
//
/**
* Visit nodes to flatten destructuring assignments to exported symbols.
*
* @param node The node to visit.
*/
function destructuringAndImportCallVisitor(node: Node): VisitResult<Node> {
if (node.transformFlags & TransformFlags.DestructuringAssignment
&& node.kind === SyntaxKind.BinaryExpression) {
return visitDestructuringAssignment(<DestructuringAssignment>node);
}
else if (isImportCall(node)) {
return visitImportCallExpression(node);
}
else if ((node.transformFlags & TransformFlags.ContainsDestructuringAssignment) || (node.transformFlags & TransformFlags.ContainsDynamicImport)) {
return visitEachChild(node, destructuringAndImportCallVisitor, context);
}
else {
return node;
}
}
function visitImportCallExpression(node: ImportCall): Expression {
// import("./blah")
// emit as
// System.register([], function (_export, _context) {
// return {
// setters: [],
// execute: () => {
// _context.import('./blah');
// }
// };
// });
return createCall(
createPropertyAccess(
contextObject,
createIdentifier("import")
),
/*typeArguments*/ undefined,
node.arguments
);
}
/**
* Visits a DestructuringAssignment to flatten destructuring to exported symbols.
*
* @param node The node to visit.
*/
function visitDestructuringAssignment(node: DestructuringAssignment): VisitResult<Expression> {
if (hasExportedReferenceInDestructuringTarget(node.left)) {
return flattenDestructuringAssignment(
node,
destructuringAndImportCallVisitor,
context,
FlattenLevel.All,
/*needsValue*/ true
);
}
return visitEachChild(node, destructuringAndImportCallVisitor, context);
}
/**
* Determines whether the target of a destructuring assigment refers to an exported symbol.
*
* @param node The destructuring target.
*/
function hasExportedReferenceInDestructuringTarget(node: Expression | ObjectLiteralElementLike): boolean {
if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
return hasExportedReferenceInDestructuringTarget(node.left);
}
else if (isSpreadElement(node)) {
return hasExportedReferenceInDestructuringTarget(node.expression);
}
else if (isObjectLiteralExpression(node)) {
return some(node.properties, hasExportedReferenceInDestructuringTarget);
}
else if (isArrayLiteralExpression(node)) {
return some(node.elements, hasExportedReferenceInDestructuringTarget);
}
else if (isShorthandPropertyAssignment(node)) {
return hasExportedReferenceInDestructuringTarget(node.name);
}
else if (isPropertyAssignment(node)) {
return hasExportedReferenceInDestructuringTarget(node.initializer);
}
else if (isIdentifier(node)) {
const container = resolver.getReferencedExportContainer(node);
return container !== undefined && container.kind === SyntaxKind.SourceFile;
}
else {
return false;
}
}
//
// Modifier Visitors
//
/**
* Visit nodes to elide module-specific modifiers.
*
* @param node The node to visit.
*/
function modifierVisitor(node: Node): VisitResult<Node> {
switch (node.kind) {
case SyntaxKind.ExportKeyword:
case SyntaxKind.DefaultKeyword:
return undefined;
}
return node;
}
//
// Emit Notification
//
/**
* Hook for node emit notifications.
*
* @param hint A hint as to the intended usage of the node.
* @param node The node to emit.
* @param emitCallback A callback used to emit the node in the printer.
*/
function onEmitNode(hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void): void {
if (node.kind === SyntaxKind.SourceFile) {
const id = getOriginalNodeId(node);
currentSourceFile = <SourceFile>node;
moduleInfo = moduleInfoMap[id];
exportFunction = exportFunctionsMap[id];
noSubstitution = noSubstitutionMap[id];
if (noSubstitution) {
delete noSubstitutionMap[id];
}
previousOnEmitNode(hint, node, emitCallback);
currentSourceFile = undefined;
moduleInfo = undefined;
exportFunction = undefined;
noSubstitution = undefined;
}
else {
previousOnEmitNode(hint, node, emitCallback);
}
}
//
// Substitutions
//
/**
* Hooks node substitutions.
*
* @param hint A hint as to the intended usage of the node.
* @param node The node to substitute.
*/
function onSubstituteNode(hint: EmitHint, node: Node) {
node = previousOnSubstituteNode(hint, node);
if (isSubstitutionPrevented(node)) {
return node;
}
if (hint === EmitHint.Expression) {
return substituteExpression(<Expression>node);
}
return node;
}
/**
* Substitute the expression, if necessary.
*
* @param node The node to substitute.
*/
function substituteExpression(node: Expression) {
switch (node.kind) {
case SyntaxKind.Identifier:
return substituteExpressionIdentifier(<Identifier>node);
case SyntaxKind.BinaryExpression:
return substituteBinaryExpression(<BinaryExpression>node);
case SyntaxKind.PrefixUnaryExpression:
case SyntaxKind.PostfixUnaryExpression:
return substituteUnaryExpression(<PrefixUnaryExpression | PostfixUnaryExpression>node);
}
return node;
}
/**
* Substitution for an Identifier expression that may contain an imported or exported symbol.
*
* @param node The node to substitute.
*/
function substituteExpressionIdentifier(node: Identifier): Expression {
if (getEmitFlags(node) & EmitFlags.HelperName) {
const externalHelpersModuleName = getExternalHelpersModuleName(currentSourceFile);
if (externalHelpersModuleName) {
return createPropertyAccess(externalHelpersModuleName, node);
}
return node;
}
// When we see an identifier in an expression position that
// points to an imported symbol, we should substitute a qualified
// reference to the imported symbol if one is needed.
//
// - We do not substitute generated identifiers for any reason.
// - We do not substitute identifiers tagged with the LocalName flag.
if (!isGeneratedIdentifier(node) && !isLocalName(node)) {
const importDeclaration = resolver.getReferencedImportDeclaration(node);
if (importDeclaration) {
if (isImportClause(importDeclaration)) {
return setTextRange(
createPropertyAccess(
getGeneratedNameForNode(importDeclaration.parent),
createIdentifier("default")
),
/*location*/ node
);
}
else if (isImportSpecifier(importDeclaration)) {
return setTextRange(
createPropertyAccess(
getGeneratedNameForNode(importDeclaration.parent.parent.parent),
getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name)
),
/*location*/ node
);
}
}
}
return node;
}
/**
* Substitution for a BinaryExpression that may contain an imported or exported symbol.
*
* @param node The node to substitute.
*/
function substituteBinaryExpression(node: BinaryExpression): Expression {
// When we see an assignment expression whose left-hand side is an exported symbol,
// we should ensure all exports of that symbol are updated with the correct value.
//
// - We do not substitute generated identifiers for any reason.
// - We do not substitute identifiers tagged with the LocalName flag.
// - We do not substitute identifiers that were originally the name of an enum or
// namespace due to how they are transformed in TypeScript.
// - We only substitute identifiers that are exported at the top level.
if (isAssignmentOperator(node.operatorToken.kind)
&& isIdentifier(node.left)
&& !isGeneratedIdentifier(node.left)
&& !isLocalName(node.left)
&& !isDeclarationNameOfEnumOrNamespace(node.left)) {
const exportedNames = getExports(node.left);
if (exportedNames) {
// For each additional export of the declaration, apply an export assignment.
let expression: Expression = node;
for (const exportName of exportedNames) {
expression = createExportExpression(exportName, preventSubstitution(expression));
}
return expression;
}
}
return node;
}
/**
* Substitution for a UnaryExpression that may contain an imported or exported symbol.
*
* @param node The node to substitute.
*/
function substituteUnaryExpression(node: PrefixUnaryExpression | PostfixUnaryExpression): Expression {
// When we see a prefix or postfix increment expression whose operand is an exported
// symbol, we should ensure all exports of that symbol are updated with the correct
// value.
//
// - We do not substitute generated identifiers for any reason.
// - We do not substitute identifiers tagged with the LocalName flag.
// - We do not substitute identifiers that were originally the name of an enum or
// namespace due to how they are transformed in TypeScript.
// - We only substitute identifiers that are exported at the top level.
if ((node.operator === SyntaxKind.PlusPlusToken || node.operator === SyntaxKind.MinusMinusToken)
&& isIdentifier(node.operand)
&& !isGeneratedIdentifier(node.operand)
&& !isLocalName(node.operand)
&& !isDeclarationNameOfEnumOrNamespace(node.operand)) {
const exportedNames = getExports(node.operand);
if (exportedNames) {
let expression: Expression = node.kind === SyntaxKind.PostfixUnaryExpression
? setTextRange(
createPrefix(
node.operator,
node.operand
),
node
)
: node;
for (const exportName of exportedNames) {
expression = createExportExpression(exportName, preventSubstitution(expression));
}
if (node.kind === SyntaxKind.PostfixUnaryExpression) {
expression = node.operator === SyntaxKind.PlusPlusToken
? createSubtract(preventSubstitution(expression), createLiteral(1))
: createAdd(preventSubstitution(expression), createLiteral(1));
}
return expression;
}
}
return node;
}
/**
* Gets the exports of a name.
*
* @param name The name.
*/
function getExports(name: Identifier) {
let exportedNames: Identifier[];
if (!isGeneratedIdentifier(name)) {
const valueDeclaration = resolver.getReferencedImportDeclaration(name)
|| resolver.getReferencedValueDeclaration(name);
if (valueDeclaration) {
const exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
if (exportContainer && exportContainer.kind === SyntaxKind.SourceFile) {
exportedNames = append(exportedNames, getDeclarationName(valueDeclaration));
}
exportedNames = addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[getOriginalNodeId(valueDeclaration)]);
}
}
return exportedNames;
}
/**
* Prevent substitution of a node for this transformer.
*
* @param node The node which should not be substituted.
*/
function preventSubstitution<T extends Node>(node: T): T {
if (noSubstitution === undefined) noSubstitution = [];
noSubstitution[getNodeId(node)] = true;
return node;
}
/**
* Determines whether a node should not be substituted.
*
* @param node The node to test.
*/
function isSubstitutionPrevented(node: Node) {
return noSubstitution && node.id && noSubstitution[node.id];
}
}
}
| mihailik/TypeScript | src/compiler/transformers/module/system.ts | TypeScript | apache-2.0 | 80,422 |
package com.gemii.lizcloud.api.group.admin.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gemii.lizcloud.api.group.admin.clients.AdUserMgmtClient;
import com.gemii.lizcloud.api.group.admin.service.AdUserMgmtService;
import com.gemii.lizcloud.common.data.GeneralContentResult;
import com.gemii.lizcloud.common.data.GeneralPagingResult;
import com.gemii.lizcloud.common.data.dto.accountcenter.AdUserProfile;
import com.gemii.lizcloud.common.data.dto.accountcenter.LdapUserCriteriaQuery;
import lombok.extern.slf4j.Slf4j;
/**
* ClassName: AdUserMgmtServiceImpl <br/>
* Function: TODO <br/>
* Reason: TODO <br/>
* date: 2016年11月21日 <br/>
*
* @author chenxj
* @version
* @since JDK 1.8
*/
@Service
@Slf4j
public class AdUserMgmtServiceImpl implements AdUserMgmtService {
@Autowired
private AdUserMgmtClient adUserMgmtClient;
@Override
public GeneralContentResult<String> createAdUser(AdUserProfile profile) {
GeneralContentResult<String> result = adUserMgmtClient.createAdUser(profile);
return result;
}
@Override
public GeneralPagingResult<List<AdUserProfile>> getLdapUserList(String id, Integer page, Integer size,
LdapUserCriteriaQuery criteriaQuery) {
return adUserMgmtClient.getLdapUserList(id, page, size, criteriaQuery);
}
}
| YY-ORG/yycloud | yy-api/yy-portal-api/src/main/java/com/gemii/lizcloud/api/group/admin/service/impl/AdUserMgmtServiceImpl.java | Java | apache-2.0 | 1,379 |
package cn.felord.wepay.ali.sdk.api.request;
import java.util.Map;
import cn.felord.wepay.ali.sdk.api.AlipayRequest;
import cn.felord.wepay.ali.sdk.api.internal.util.AlipayHashMap;
import cn.felord.wepay.ali.sdk.api.response.AlipayMarketingCashlessvoucherTemplateModifyResponse;
import cn.felord.wepay.ali.sdk.api.AlipayObject;
/**
* ALIPAY API: alipay.marketing.cashlessvoucher.template.modify request
*
* @author auto create
* @version $Id: $Id
*/
public class AlipayMarketingCashlessvoucherTemplateModifyRequest implements AlipayRequest<AlipayMarketingCashlessvoucherTemplateModifyResponse> {
private AlipayHashMap udfParams; // add user-defined text parameters
private String apiVersion="1.0";
/**
* 商户券模板修改接口
*/
private String bizContent;
/**
* <p>Setter for the field <code>bizContent</code>.</p>
*
* @param bizContent a {@link java.lang.String} object.
*/
public void setBizContent(String bizContent) {
this.bizContent = bizContent;
}
/**
* <p>Getter for the field <code>bizContent</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getBizContent() {
return this.bizContent;
}
private String terminalType;
private String terminalInfo;
private String prodCode;
private String notifyUrl;
private String returnUrl;
private boolean needEncrypt=false;
private AlipayObject bizModel=null;
/**
* <p>Getter for the field <code>notifyUrl</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getNotifyUrl() {
return this.notifyUrl;
}
/** {@inheritDoc} */
public void setNotifyUrl(String notifyUrl) {
this.notifyUrl = notifyUrl;
}
/**
* <p>Getter for the field <code>returnUrl</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getReturnUrl() {
return this.returnUrl;
}
/** {@inheritDoc} */
public void setReturnUrl(String returnUrl) {
this.returnUrl = returnUrl;
}
/**
* <p>Getter for the field <code>apiVersion</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getApiVersion() {
return this.apiVersion;
}
/** {@inheritDoc} */
public void setApiVersion(String apiVersion) {
this.apiVersion = apiVersion;
}
/** {@inheritDoc} */
public void setTerminalType(String terminalType){
this.terminalType=terminalType;
}
/**
* <p>Getter for the field <code>terminalType</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getTerminalType(){
return this.terminalType;
}
/** {@inheritDoc} */
public void setTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
/**
* <p>Getter for the field <code>terminalInfo</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getTerminalInfo(){
return this.terminalInfo;
}
/** {@inheritDoc} */
public void setProdCode(String prodCode) {
this.prodCode=prodCode;
}
/**
* <p>Getter for the field <code>prodCode</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getProdCode() {
return this.prodCode;
}
/**
* <p>getApiMethodName.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getApiMethodName() {
return "alipay.marketing.cashlessvoucher.template.modify";
}
/**
* <p>getTextParams.</p>
*
* @return a {@link java.util.Map} object.
*/
public Map<String, String> getTextParams() {
AlipayHashMap txtParams = new AlipayHashMap();
txtParams.put("biz_content", this.bizContent);
if(udfParams != null) {
txtParams.putAll(this.udfParams);
}
return txtParams;
}
/**
* <p>putOtherTextParam.</p>
*
* @param key a {@link java.lang.String} object.
* @param value a {@link java.lang.String} object.
*/
public void putOtherTextParam(String key, String value) {
if(this.udfParams == null) {
this.udfParams = new AlipayHashMap();
}
this.udfParams.put(key, value);
}
/**
* <p>getResponseClass.</p>
*
* @return a {@link java.lang.Class} object.
*/
public Class<AlipayMarketingCashlessvoucherTemplateModifyResponse> getResponseClass() {
return AlipayMarketingCashlessvoucherTemplateModifyResponse.class;
}
/**
* <p>isNeedEncrypt.</p>
*
* @return a boolean.
*/
public boolean isNeedEncrypt() {
return this.needEncrypt;
}
/** {@inheritDoc} */
public void setNeedEncrypt(boolean needEncrypt) {
this.needEncrypt=needEncrypt;
}
/**
* <p>Getter for the field <code>bizModel</code>.</p>
*
* @return a {@link cn.felord.wepay.ali.sdk.api.AlipayObject} object.
*/
public AlipayObject getBizModel() {
return this.bizModel;
}
/** {@inheritDoc} */
public void setBizModel(AlipayObject bizModel) {
this.bizModel=bizModel;
}
}
| NotFound403/WePay | src/main/java/cn/felord/wepay/ali/sdk/api/request/AlipayMarketingCashlessvoucherTemplateModifyRequest.java | Java | apache-2.0 | 4,902 |
#!/usr/bin/env python
#
# 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.
from lexer import RqlLexer, RqlSyntaxError
import random
import math
DEFAULT_CONSTANTS = {
'PI': 3.1415926535897932384,
'NULL': None,
'FALSE': False,
'TRUE': True,
}
DEFAULT_FUNCTIONS = {
'abs': abs,
'min': min,
'max': max,
'sum': lambda *args: sum(args),
'acos': math.acos,
'asin': math.asin,
'atan': math.atan,
'ceil': math.ceil,
'cos': math.cos,
'exp': math.exp,
'floor': math.floor,
'log': math.log,
'random': random.random,
'sin': math.sin,
'sqrt': math.sqrt,
'tan': math.tan
}
# http://technet.microsoft.com/en-us/library/ms190276.aspx
EXPRESSION_OPERATORS = [
{'+', '-', '&', '^', '|'},
{'*', '/', '%'},
{'~'},
]
PREDICATE_OPERATORS = [
{'OR'},
{'AND'},
{'LIKE'},
{'==', '<', '>', '<=', '>=', '<>', '==', '!=', '!>', '!<'},
]
PREDICATE_EXPRESSION_OPERATORS = PREDICATE_OPERATORS + EXPRESSION_OPERATORS
def get_binary_precedence(operators, token):
if token:
tvalue = token.value
precedence = 0
for oplist in operators:
if tvalue in oplist:
return precedence
precedence += 1
return -1
def get_expr_identifiers(expression):
identifiers = set()
for key in expression.__slots__:
expr = getattr(expression, key)
if isinstance(expr, RqlIdentifier):
identifiers.add(expr)
else:
identifiers |= get_identifiers(expression)
return identifiers
class RqlFunctionCall(object):
__slots__ = ('name', 'args')
def __init__(self, name, args):
self.name = name
self.args = args
def __str__(self):
return '%s(%s)' % (self.name, self.args)
def __repr__(self):
return 'RqlFunctionCall(%r, %r)' % (self.name, self.args)
def is_constant(self, context ):
return False
def resolve(self, context):
# TODO: If args are const
return self
def evaluate(self, context):
func = context.functions.get(self.name)
if not func:
raise RqlSyntaxError("Unknown function '%s'" % self.name)
args = []
for arg in self.args:
args.append(arg.evaluate(context))
return func(*args)
class RqlIdentifier(object):
__slots__ = ('name')
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return 'RqlIdentifier(%r)' % (self.name)
def __cmp__(self, other):
return cmp(self.name, other)
def __hash__(self):
return hash(self.name)
def is_constant(self, context):
return False
def resolve(self, context):
return self
def evaluate(self, context):
return context.get_identifier(self.name)
class RqlBaseDataType(object):
__slots__ = ('value')
def __init__(self, value):
self.value = value
def __str__(self):
return '%s' % self.value
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.value)
def is_constant(self, context):
return True
def resolve(self, context):
return self
def evaluate(self, context):
return self.value
class RqlNumber(RqlBaseDataType):
def __init__(self, value):
super(RqlNumber, self).__init__(float(value))
class RqlBoolean(RqlBaseDataType):
def __init__(self, value):
super(RqlBoolean, self).__init__(bool(value))
class RqlString(RqlBaseDataType):
def __init__(self, value):
super(RqlString, self).__init__(value)
def __str__(self):
return '"%s"' % self.value
class RqlWildcard(RqlBaseDataType):
def __init__(self, value):
super(RqlWildcard, self).__init__(value)
class RqlUnary(object):
__slots__ = ('operator', 'expression')
def __init__(self, operator, expression):
self.operator = operator
self.expression = expression
def __str__(self):
return '%s %s' % (self.operator, self.expression)
def __repr__(self):
return 'RqlUnary(%r, %r)' % (self.operator, self.expression)
def is_constant(self, context):
return self.expression.is_constant(context)
def resolve(self, context):
self.expression = self.expression.resolve(context)
if self.is_constant(context):
return RqlNumber(self.evaluate(context))
return self
def evaluate(self, context):
expr = self.expression.evaluate(context)
if self.operator == '+': return expr
if self.operator == '-': return -expr
if self.operator == '~': return ~expr
if self.operator == 'NOT': return not expr
raise RqlSyntaxError("Unknown operator '%s'" % self.operator)
class RqlBinary(object):
__slots__ = ('operator', 'left', 'right')
def __init__(self, operator, left, right):
self.operator = operator
self.left = left
self.right = right
def __str__(self):
return '(%s %s %s)' % (self.left, self.operator, self.right)
def __repr__(self):
return 'RqlBinary(%r, %r, %r)' % (self.operator, self.left, self.right)
def is_constant(self, context):
return self.left.is_constant(context) and self.right.is_constant(context)
def resolve(self, context):
self.left = self.left.resolve(context)
self.right = self.right.resolve(context)
if self.is_constant(context):
result = self.evaluate(context)
if isinstance(result, basestring):
return RqlString(result)
if isinstance(result, (int, float)):
return RqlNumber(result)
if isinstance(result, bool):
return RqlBoolean(result)
raise RqlSyntaxError("Unexpected type %s %r" % (type(result), result))
return self
def evaluate(self, context):
left = self.left.evaluate(context)
right = self.right.evaluate(context)
# Expression
if self.operator == '+': return left + right
if self.operator == '-': return left - right
if self.operator == '&': return left & right
if self.operator == '|': return left | right
if self.operator == '^': return left ^ right
if self.operator == '*': return left * right
if self.operator == '/': return left / right
if self.operator == '%': return left % right
# Predicate
if self.operator == '=': return left == right
if self.operator == '<': return left < right
if self.operator == '>': return left > right
if self.operator == '<=': return left <= right
if self.operator == '>=': return left >= right
if self.operator == '==': return left == right
if self.operator == '!=': return left != right
if self.operator == 'IS': return left is right
if self.operator == 'OR': return left or right
if self.operator == 'AND': return left and right
# LIKE
raise RqlSyntaxError("Unknown operator '%s'" % self)
class RqlAssignment(object):
__slots__ = ('name', 'expression')
def __init__(self, name, expression):
self.name = name
self.expression = expression
def __repr__(self):
return 'RqlAssignment(%r, %r)' % (self.name, self.expression)
def is_constant(self, context):
return self.expression.is_constant(context)
def resolve(self):
self.expression = self.expression.resolve()
if self.is_constant(context):
return RqlNumber(self.evaluate(context))
return self
def evaluate(self, context):
right = self.expression.evaluate(context)
context.variables[self.name] = right
return right
class RqlParser(object):
__slots__ = ('lexer')
def __init__(self, lexer):
self.lexer = lexer
def parse_identifier(self):
items = self.parse_dot_list(self.lexer.expect_string_or_identifier)
return RqlIdentifier('.'.join(items))
# <List> ::= <Item> '.' <List> | <Item>
def parse_dot_list(self, item_parse_func):
return self.parse_list('.', item_parse_func)
# <List> ::= <Item> ',' <List> | <Item>
def parse_comma_list(self, item_parse_func):
return self.parse_list(',', item_parse_func)
# <List> ::= <Item> <separator> <List> | <Item>
def parse_list(self, separator, item_parse_func):
def_list = []
while True:
item_def = item_parse_func()
if not item_def:
raise Exception("Invalid list item definition")
def_list.append(item_def)
if not self.lexer.match_seq(separator):
break
return def_list
def _call_method(self, name, *args, **kwargs):
return getattr(self, name)(*args, **kwargs)
# =============================================================================
# Expression
# =============================================================================
class RqlExprParser(RqlParser):
# FunctionCall ::= Identifier '(' ')' ||
# Identifier '(' ArgumentList ')'
def parse_function_call(self):
args = []
name = self.lexer.expect_identifier().lower()
self.lexer.expect_seq('(')
if not self.lexer.peek_seq(')'):
args = self.parse_comma_list(self.parse_expression)
self.lexer.expect_seq(')')
return RqlFunctionCall(name, args)
# Primary ::= Identifier |
# Number |
# '(' Assignment ')' |
# FunctionCall
def parse_primary(self):
token = self.lexer.peek()
if not token:
raise RqlSyntaxError("Unexpected termination of expression")
if self.lexer.match_seq('('):
expr = self.parse_assignment()
self.lexer.expect_seq(')')
elif token.is_identifier():
if self.lexer.peek_seq(None, '('):
return self.parse_function_call()
expr = self.parse_identifier()
elif token.is_number():
token = self.lexer.next()
expr = RqlNumber(token.value)
elif token.is_string():
token = self.lexer.next()
expr = RqlString(token.value)
elif token.is_boolean():
token = self.lexer.next()
expr = RqlBoolean(token.value)
elif token.value == '*':
token = self.lexer.next()
expr = RqlWildcard(token.value)
else:
raise RqlSyntaxError("Parse error, can not process token %r" % token)
if self.lexer.match_seq('BETWEEN'):
return self.parse_between(expr)
elif self.lexer.match_seq('NOT', 'BETWEEN'):
return RqlUnary('NOT', self.parse_between(expr))
return expr
# Unary ::= Primary |
# '-' Unary |
# '~' Unary
def parse_unary(self):
operator = self.lexer.match_operator('-', '+', '~', 'NOT')
if operator:
expr = self.parse_unary()
return RqlUnary(operator, expr)
return self.parse_primary()
def parse_between(self, expr):
# expr >= min_expr AND expr <= max_expr
min_expr = self.parse_expression()
self.lexer.expect_seq('AND')
max_expr = self.parse_expression()
return RqlBinary('AND', RqlBinary('>=', expr, min_expr), RqlBinary('<=', expr, min_expr))
def parse_binary(self, operators, lhs, min_precedence):
while get_binary_precedence(operators, self.lexer.peek()) >= min_precedence:
operation = self.lexer.next()
rhs = self.parse_unary()
in_precedence = min_precedence
prec = get_binary_precedence(operators, self.lexer.peek())
while prec > in_precedence:
rhs = self.parse_binary(operators, rhs, prec)
in_precedence = prec
prec = get_binary_precedence(operators, self.lexer.peek())
lhs = RqlBinary(operation.value, lhs, rhs)
return lhs
def parse_expression(self):
return self.parse_binary(EXPRESSION_OPERATORS, self.parse_unary(), 0)
def parse_predicate(self):
return self.parse_binary(PREDICATE_EXPRESSION_OPERATORS, self.parse_unary(), 0)
# Assignment ::= Identifier '=' Assignment |
# Additive
def parse_assignment(self):
expr = self.parse_binary(PREDICATE_EXPRESSION_OPERATORS, self.parse_unary(), 0)
if isinstance(expr, RqlIdentifier):
if self.lexer.match_seq('='):
return RqlAssignment(expr, self.parse_assignment())
return expr
return expr
@staticmethod
def parse(expression):
lexer = RqlLexer(expression)
parser = RqlExprParser(lexer)
expr = parser.parse_assignment()
if lexer.has_next():
raise RqlSyntaxError("Unexpected token '%s'" % lexer.peek())
return expr
class RqlContext:
NULL = object()
def __init__(self):
self.constants = dict(DEFAULT_CONSTANTS)
self.functions = dict(DEFAULT_FUNCTIONS)
self.variables = {}
def get_identifier(self, name):
value = self.constants.get(name.upper(), self.NULL)
if value is not self.NULL: return value
value = self.variables.get(name.lower(), self.NULL)
if value is not self.NULL: return value
raise RqlSyntaxError("Unknown identifier '%s' - %r" % (name, self.variables))
def get_qualified_identifier(self, qualifier, name):
return self.get_identifier('%s.%s' % (qualifier, name))
def resolve(self, root):
return root.resolve(root)
def evaluate(self, root):
if 0 and __debug__:
print
print root
print self.resolve(root)
if not root:
raise RqlSyntaxError("Unknown syntax node")
return root.evaluate(self)
if __name__ == '__main__':
ctx = RqlContext()
ctx.variables['table.field'] = 20
print ctx.evaluate(RqlExprParser.parse("1"))
print ctx.evaluate(RqlExprParser.parse("1 + 2"))
print ctx.evaluate(RqlExprParser.parse("FALSE"))
print ctx.evaluate(RqlExprParser.parse("'foo'"))
print ctx.evaluate(RqlExprParser.parse("'foo' + \"-\" + 'bar'"))
print ctx.evaluate(RqlExprParser.parse("NOT 1 + NOT 0"))
print ctx.evaluate(RqlExprParser.parse("(NOT 1) + (NOT 0)"))
print ctx.evaluate(RqlExprParser.parse("1 + 2 * 3"))
print ctx.evaluate(RqlExprParser.parse("1 + (2 * 3)"))
print ctx.evaluate(RqlExprParser.parse("1 OR 2 AND 3"))
print ctx.evaluate(RqlExprParser.parse("1 OR (2 AND 3)"))
print ctx.evaluate(RqlExprParser.parse("sum(1, 2, 3) + 5 * 2 + min(5 / 10, 2 * -3)"))
print ctx.evaluate(RqlExprParser.parse("table.field + 1 + PI"))
print ctx.evaluate(RqlExprParser.parse("(15 + 2) != (- 14 + 3)"))
print ctx.evaluate(RqlExprParser.parse("(15 + 2) <= (14 + 3)"))
print ctx.evaluate(RqlExprParser.parse("(10 > 0 AND 20 < 2)"))
print ctx.evaluate(RqlExprParser.parse("(10 > 0 OR 20 < 2)"))
print RqlExprParser.parse("1 + 10 BETWEEN 1 AND 20 + 2")
print RqlExprParser.parse("1 + 10 NOT BETWEEN 1 AND 20 + 2")
print ctx.evaluate(RqlExprParser.parse("11 * 20 / 3"))
print ctx.evaluate(RqlExprParser.parse("11 * 21 / 2"))
| matteobertozzi/RaleighSL | src/raleigh-client/pyraleigh/sql/expr.py | Python | apache-2.0 | 14,678 |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
*
*/
/**
* @author antonio081014
* @since Feb 25, 2012, 4:08:20 PM
*/
class Main {
public List<List<String>> cards;
public static void main(String[] args) throws Exception {
Main main = new Main();
main.solve();
System.exit(0);
}
public void solve() throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String strLine = br.readLine();
while (strLine.compareTo("#") != 0) {
cards = new ArrayList<List<String>>();
solveLine(strLine.split("\\s"));
strLine = br.readLine();
solveLine(strLine.split("\\s"));
print();
strLine = br.readLine();
}
}
public void print() {
if (cards.size() > 1) {
System.out.print("" + cards.size() + " piles remaining:");
}
else {
System.out.print("" + cards.size() + " pile remaining:");
}
for (int i = 0; i < cards.size(); i++) {
System.out.print(" " + cards.get(i).size());
}
System.out.println();
}
public void solveLine(String[] strs) {
for (int i = 0; i < strs.length; i++) {
List<String> tmp = new ArrayList<String>();
tmp.add(strs[i]);
cards.add(tmp);
for (int j = cards.size() - 1; j < cards.size();) {
String s = cards.get(j).get(0);
if (j >= 3 && match(s, cards.get(j - 3).get(0))) {
cards.get(j - 3).add(0, s);
if (cards.get(j).size() == 1)
cards.remove(j);
else
cards.get(j).remove(0);
j -= 3;
}
else if (j >= 1 && match(s, cards.get(j - 1).get(0))) {
cards.get(j - 1).add(0, s);
if (cards.get(j).size() == 1)
cards.remove(j);
else
cards.get(j).remove(0);
j--;
}
else
j++;
}
}
}
public boolean match(String a, String b) {
if (a.charAt(0) == b.charAt(0) || a.charAt(1) == b.charAt(1))
return true;
return false;
}
}
| antonio081014/ACM-UVa-CodeBase | Volumn001/UVa_00127_Accordian_Patience.java | Java | apache-2.0 | 2,466 |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft Azure Powershell - SiteRecovery Commands")]
[assembly: AssemblyCompany(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCompany)]
[assembly: AssemblyProduct(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyProduct)]
[assembly: AssemblyCopyright(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.AssemblyCopyright)]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("666ec982-0673-4d9f-8f31-da7534c183bb")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.1.9")]
[assembly: AssemblyFileVersion("1.1.9")]
| akurmi/azure-powershell | src/ResourceManager/SiteRecovery/Commands.SiteRecovery/Properties/AssemblyInfo.cs | C# | apache-2.0 | 2,200 |
/*******************************************************************************
* Copyright 2013 Thomas Letsch (contact@thomas-letsch.de)
*
* 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.
******************************************************************************/
package org.moserp.common.converter;
import org.moserp.common.domain.BigDecimalWrapper;
public class BigDecimalWrapperToStringConverter extends SafeConverter<BigDecimalWrapper, String> {
@Override
protected String doConvert(BigDecimalWrapper source) throws Exception {
return source.stringValue();
}
}
| thomasletsch/moserp | backend/common/common-base/src/main/java/org/moserp/common/converter/BigDecimalWrapperToStringConverter.java | Java | apache-2.0 | 1,104 |
(function() {
'use strict';
angular
.module('woodstock24App')
.controller('ModuleMySuffixDetailController', ModuleMySuffixDetailController);
ModuleMySuffixDetailController.$inject = ['$scope', '$rootScope', '$stateParams', 'previousState', 'entity', 'Module', 'Unit', 'Reference', 'Question'];
function ModuleMySuffixDetailController($scope, $rootScope, $stateParams, previousState, entity, Module, Unit, Reference, Question) {
var vm = this;
vm.module = entity;
vm.previousState = previousState.name;
var unsubscribe = $rootScope.$on('woodstock24App:moduleUpdate', function(event, result) {
vm.module = result;
});
$scope.$on('$destroy', unsubscribe);
}
})();
| solairerove/woodstock | src/main/webapp/app/entities/module/module-my-suffix-detail.controller.js | JavaScript | apache-2.0 | 762 |
module RubyQC
VERSION = '0.0.4'
end
| godfat/rubyqc | lib/rubyqc/version.rb | Ruby | apache-2.0 | 39 |
/*
* Copyright 2016 RedRoma, Inc..
*
* 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.
*/
package tech.redroma.yelp.oauth;
import com.google.common.base.Strings;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import java.net.URL;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.redroma.yelp.exceptions.YelpAuthenticationException;
import tech.redroma.yelp.exceptions.YelpBadArgumentException;
import tech.redroma.yelp.exceptions.YelpOperationFailedException;
import tech.sirwellington.alchemy.annotations.access.Internal;
import tech.sirwellington.alchemy.annotations.concurrency.ThreadUnsafe;
import tech.sirwellington.alchemy.http.AlchemyHttp;
import tech.sirwellington.alchemy.http.HttpResponse;
import tech.sirwellington.alchemy.http.exceptions.AlchemyHttpException;
import static tech.sirwellington.alchemy.arguments.Arguments.checkThat;
import static tech.sirwellington.alchemy.arguments.assertions.Assertions.notNull;
import static tech.sirwellington.alchemy.arguments.assertions.BooleanAssertions.trueStatement;
import static tech.sirwellington.alchemy.arguments.assertions.StringAssertions.nonEmptyString;
import static tech.sirwellington.alchemy.arguments.assertions.StringAssertions.stringWithLengthGreaterThan;
/**
* This {@link OAuthTokenProvider} retrieves an OAuth Token from the Yelp Authentication API
* using the given client_id and client_secret, ensuring it is never expired.
*
* @author SirWellington
*/
@Internal
final class RenewingProvider implements OAuthTokenProvider
{
private static final Logger LOG = LoggerFactory.getLogger(RenewingProvider.class);
private final AlchemyHttp http;
private final URL authenticationURL;
private final String clientId;
private final String clientSecret;
private static final int BAD_REQUEST = 400;
/*
* TODO: Make this thread-safe by adding a Lock.
*/
@ThreadUnsafe
private String oauthToken;
RenewingProvider(AlchemyHttp http, URL authenticationURL, String clientId, String clientSecret)
{
checkThat(http, authenticationURL)
.are(notNull());
checkThat(clientId, clientSecret)
.are(nonEmptyString())
.are(stringWithLengthGreaterThan(2));
this.http = http;
this.authenticationURL = authenticationURL;
this.clientId = clientId;
this.clientSecret = clientSecret;
}
@Override
public String getToken()
{
if (!Strings.isNullOrEmpty(oauthToken))
{
return oauthToken;
}
JsonObject response = null;
try
{
response = http
.go()
.post()
.nothing()
.usingQueryParam(Keys.GRANT_TYPE, "client_credentials")
.usingQueryParam(Keys.CLIENT_ID, clientId)
.usingQueryParam(Keys.CLIENT_SECRET, clientSecret)
.usingHeader(Keys.CONTENT_TYPE, Keys.URL_ENCODED)
.expecting(JsonObject.class)
.at(authenticationURL);
}
catch (AlchemyHttpException ex)
{
LOG.error("Failed to obtain a OAuth Token from Yelp", ex);
if (ex.hasResponse())
{
HttpResponse yelpResponse = ex.getResponse();
int status = yelpResponse.statusCode();
if (status == BAD_REQUEST)
{
throw new YelpAuthenticationException("Client ID or Secret are incorrect: " + yelpResponse.body());
}
}
throw new YelpOperationFailedException("Failed to get access token.", ex);
}
checkResponse(response);
printExpiration(response);
this.oauthToken = tryToGetTokenFrom(response);
return this.oauthToken;
}
@Override
public int hashCode()
{
int hash = 5;
hash = 47 * hash + Objects.hashCode(this.http);
hash = 47 * hash + Objects.hashCode(this.authenticationURL);
hash = 47 * hash + Objects.hashCode(this.clientId);
hash = 47 * hash + Objects.hashCode(this.clientSecret);
return hash;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final RenewingProvider other = (RenewingProvider) obj;
if (!Objects.equals(this.clientId, other.clientId))
{
return false;
}
if (!Objects.equals(this.clientSecret, other.clientSecret))
{
return false;
}
if (!Objects.equals(this.http, other.http))
{
return false;
}
if (!Objects.equals(this.authenticationURL, other.authenticationURL))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "OAuthTokenProviderRenewing{" + "http=" + http + ", authenticationURL=" + authenticationURL + ", clientId=" + clientId + ", clientSecret=" + "<redacted>" + '}';
}
private void printExpiration(JsonObject response)
{
JsonElement expiration = response.get(Keys.EXPIRATION);
if (expiration.isJsonPrimitive())
{
JsonPrimitive expirationValue = expiration.getAsJsonPrimitive();
if (expirationValue.isNumber())
{
int expirationSeconds = expirationValue.getAsInt();
long expirationDays = TimeUnit.SECONDS.toDays(expirationSeconds);
long expirationMinutes = TimeUnit.SECONDS.toMinutes(expirationSeconds);
LOG.debug("Yelp Token expires in {} days or {} minutes", expirationDays, expirationMinutes);
}
else
{
LOG.warn("Received unexpected token expiration: " + expirationValue);
}
}
}
private void checkResponse(JsonObject response)
{
checkThat(response)
.throwing(YelpOperationFailedException.class)
.usingMessage("Received unexpected null response")
.is(notNull());
checkThat(response.has(Keys.EXPIRATION))
.usingMessage("OAuth response is missing expiration information: " + response)
.is(trueStatement());
checkThat(response.has(Keys.TOKEN)).usingMessage("OAUth response is missing access token: " + response)
.throwing(YelpOperationFailedException.class)
.is(trueStatement());
}
private String tryToGetTokenFrom(JsonObject response)
{
checkThat(response.has(Keys.TOKEN))
.usingMessage("Yelp AUTH response is missing the token")
.throwing(YelpBadArgumentException.class)
.is(trueStatement());
return response.get(Keys.TOKEN).getAsString();
}
static class Keys
{
static final String GRANT_TYPE = "grant_type";
static final String CLIENT_ID = "client_id";
static final String CLIENT_SECRET = "client_secret";
static final String CONTENT_TYPE = "Content-Type";
static final String URL_ENCODED = "application/x-www-form-urlencoded";
//Response Keys
static final String EXPIRATION = "expires_in";
static final String TOKEN = "access_token";
}
}
| RedRoma/YelpJavaClient | src/main/java/tech/redroma/yelp/oauth/RenewingProvider.java | Java | apache-2.0 | 8,219 |
<!doctype html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="A front-end template that helps you build fast, modern mobile web apps.">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Billy Hayes Mega BadAss</title>
<!-- Add to homescreen for Chrome on Android -->
<meta name="mobile-web-app-capable" content="yes">
<link rel="icon" sizes="192x192" href="images/touch/chrome-touch-icon-192x192.png">
<!-- Add to homescreen for Safari on iOS -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Web Starter Kit">
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">
<!-- Tile icon for Win8 (144x144 + tile color) -->
<meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">
<meta name="msapplication-TileColor" content="#3372DF">
<!-- SEO: If your mobile URL is different from the desktop URL, add a canonical link to the desktop page https://developers.google.com/webmasters/smartphone-sites/feature-phones -->
<!--
<link rel="canonical" href="http://www.example.com/">
-->
<!-- Page styles -->
<link rel="stylesheet" href="styles/main.css">
</head>
<body>
<header class="app-bar promote-layer">
<div class="app-bar-container">
<button class="menu"><img src="images/hamburger.svg" alt="Menu"></button>
<h1 class="logo">Billy Hayes <strong>Mega BadAss Starter Kit</strong></h1>
<section class="app-bar-actions">
<!-- Put App Bar Buttons Here -->
<!-- e.g <button><i class="icon icon-star"></i></button> -->
</section>
</div>
</header>
<nav class="navdrawer-container promote-layer">
<h4>Navigation</h4>
<ul>
<li><a href="#hello">Hello</a></li>
<li><a href="#get-started">Get Started</a></li>
<li><a href="styleguide.html">Style Guide</a></li>
</ul>
</nav>
<main>
<h1 id="hello">Ain't nobody care but gahd</h1>
<p>My main goto bro JC.</p>
<h2 id="get-started">Get Bored and BREAK YO-SELF fool.</h2>
<p>Don't tell me how to code mahn.</p>
</main>
<!-- build:js scripts/main.min.js -->
<script src="scripts/main.js"></script>
<!-- endbuild -->
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXX-X', 'auto');
ga('send', 'pageview');
</script>
<!-- Built with love using Web Starter Kit -->
</body>
</html>
| charliekuldip/web-starter-kit | app/index-original.html | HTML | apache-2.0 | 3,092 |
# Leontice microrrhyncha S.Moore SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Ranunculales/Berberidaceae/Leontice/Leontice microrrhyncha/README.md | Markdown | apache-2.0 | 180 |
/*
* Copyright (C) 2013 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.
*/
package com.constantinnovationsinc.livemultimedia.surfaces;
import android.graphics.SurfaceTexture;
import android.opengl.EGL14;
import android.util.Log;
import android.view.Surface;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import com.constantinnovationsinc.livemultimedia.renders.TextureRender;
/**
* Holds state associated with a Surface used for MediaCodec decoder output.
* <p>
* The (width,height) constructor for this class will prepare GL, create a SurfaceTexture,
* and then create a Surface for that SurfaceTexture. The Surface can be passed to
* MediaCodec.configure() to receive decoder output. When a frame arrives, we latch the
* texture with updateTexImage, then render the texture with GL to a pbuffer.
* <p>
* The no-arg constructor skips the GL preparation step and doesn't allocate a pbuffer.
* Instead, it just creates the Surface and SurfaceTexture, and when a frame arrives
* we just draw it on whatever surface is current.
* <p>
* By default, the Surface will be using a BufferQueue in asynchronous mode, so we
* can potentially drop frames.
*/
public class OutputSurface implements SurfaceTexture.OnFrameAvailableListener {
private static final String TAG = OutputSurface.class.getCanonicalName();
private static final boolean VERBOSE = false;
private static final int EGL_OPENGL_ES2_BIT = 4;
private EGL10 mEGL;
private EGLDisplay mEGLDisplay;
private EGLContext mEGLContext;
private EGLSurface mEGLSurface;
private SurfaceTexture mSurfaceTexture;
private Surface mSurface;
private Object mFrameSyncObject = new Object(); // guards mFrameAvailable
private boolean mFrameAvailable;
private TextureRender mTextureRender;
/**
* Creates an OutputSurface backed by a pbuffer with the specifed dimensions. The new
* EGL context and surface will be made current. Creates a Surface that can be passed
* to MediaCodec.configure().
*/
public OutputSurface(int width, int height) {
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException();
}
eglSetup(width, height);
makeCurrent();
setup();
}
/**
* Creates an OutputSurface using the current EGL context. Creates a Surface that can be
* passed to MediaCodec.configure().
*/
public OutputSurface() {
setup();
}
/**
* Creates instances of TextureRender and SurfaceTexture, and a Surface associated
* with the SurfaceTexture.
*/
private void setup() {
mTextureRender = new TextureRender();
mTextureRender.surfaceCreated();
// Even if we don't access the SurfaceTexture after the constructor returns, we
// still need to keep a reference to it. The Surface doesn't retain a reference
// at the Java level, so if we don't either then the object can get GCed, which
// causes the native finalizer to run.
if (VERBOSE) Log.d(TAG, "textureID=" + mTextureRender.getTextureId());
mSurfaceTexture = new SurfaceTexture(mTextureRender.getTextureId());
// This doesn't work if OutputSurface is created on the thread that CTS started for
// these test cases.
//
// The CTS-created thread has a Looper, and the SurfaceTexture constructor will
// create a Handler that uses it. The "frame available" message is delivered
// there, but since we're not a Looper-based thread we'll never see it. For
// this to do anything useful, OutputSurface must be created on a thread without
// a Looper, so that SurfaceTexture uses the main application Looper instead.
//
// Java language note: passing "this" out of a constructor is generally unwise,
// but we should be able to get away with it here.
mSurfaceTexture.setOnFrameAvailableListener(this);
mSurface = new Surface(mSurfaceTexture);
}
/**
* Prepares EGL. We want a GLES 2.0 context and a surface that supports pbuffer.
*/
private void eglSetup(int width, int height) {
mEGL = (EGL10)EGLContext.getEGL();
mEGLDisplay = mEGL.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
if (!mEGL.eglInitialize(mEGLDisplay, null)) {
throw new RuntimeException("unable to initialize EGL10");
}
// Configure EGL for pbuffer and OpenGL ES 2.0. We want enough RGB bits
// to be able to tell if the frame is reasonable.
int[] attribList = {
EGL10.EGL_RED_SIZE, 8,
EGL10.EGL_GREEN_SIZE, 8,
EGL10.EGL_BLUE_SIZE, 8,
EGL10.EGL_SURFACE_TYPE, EGL10.EGL_PBUFFER_BIT,
EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL10.EGL_NONE
};
EGLConfig[] configs = new EGLConfig[1];
int[] numConfigs = new int[1];
if (!mEGL.eglChooseConfig(mEGLDisplay, attribList, configs, 1, numConfigs)) {
throw new RuntimeException("unable to find RGB888+pbuffer EGL config");
}
// Configure context for OpenGL ES 2.0.
int[] attrib_list = {
EGL14.EGL_CONTEXT_CLIENT_VERSION, 2,
EGL10.EGL_NONE
};
mEGLContext = mEGL.eglCreateContext(mEGLDisplay, configs[0], EGL10.EGL_NO_CONTEXT,
attrib_list);
checkEglError("eglCreateContext");
if (mEGLContext == null) {
throw new RuntimeException("null context");
}
// Create a pbuffer surface. By using this for output, we can use glReadPixels
// to test values in the output.
int[] surfaceAttribs = {
EGL10.EGL_WIDTH, width,
EGL10.EGL_HEIGHT, height,
EGL10.EGL_NONE
};
mEGLSurface = mEGL.eglCreatePbufferSurface(mEGLDisplay, configs[0], surfaceAttribs);
checkEglError("eglCreatePbufferSurface");
if (mEGLSurface == null) {
throw new RuntimeException("surface was null");
}
}
/**
* Discard all resources held by this class, notably the EGL context.
*/
public void release() {
if (mEGL != null) {
if (mEGL.eglGetCurrentContext().equals(mEGLContext)) {
// Clear the current context and surface to ensure they are discarded immediately.
mEGL.eglMakeCurrent(mEGLDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_CONTEXT);
}
mEGL.eglDestroySurface(mEGLDisplay, mEGLSurface);
mEGL.eglDestroyContext(mEGLDisplay, mEGLContext);
//mEGL.eglTerminate(mEGLDisplay);
}
mSurface.release();
// this causes a bunch of warnings that appear harmless but might confuse someone:
// W BufferQueue: [unnamed-3997-2] cancelBuffer: BufferQueue has been abandoned!
//mSurfaceTexture.release();
// null everything out so future attempts to use this object will cause an NPE
mEGLDisplay = null;
mEGLContext = null;
mEGLSurface = null;
mEGL = null;
mTextureRender = null;
mSurface = null;
mSurfaceTexture = null;
}
/**
* Makes our EGL context and surface current.
*/
public void makeCurrent() {
if (mEGL == null) {
throw new RuntimeException("not configured for makeCurrent");
}
checkEglError("before makeCurrent");
if (!mEGL.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext)) {
throw new RuntimeException("eglMakeCurrent failed");
}
}
/**
* Returns the Surface that we draw onto.
*/
public Surface getSurface() {
return mSurface;
}
/**
* Replaces the fragment shader.
*/
public void changeFragmentShader(String fragmentShader) {
mTextureRender.changeFragmentShader(fragmentShader);
}
/**
* Latches the next buffer into the texture. Must be called from the thread that created
* the OutputSurface object, after the onFrameAvailable callback has signaled that new
* data is available.
*/
public void awaitNewImage() {
final int TIMEOUT_MS = 500;
synchronized (mFrameSyncObject) {
while (!mFrameAvailable) {
try {
// Wait for onFrameAvailable() to signal us. Use a timeout to avoid
// stalling the test if it doesn't arrive.
mFrameSyncObject.wait(TIMEOUT_MS);
if (!mFrameAvailable) {
// TODO: if "spurious wakeup", continue while loop
throw new RuntimeException("Surface frame wait timed out");
}
} catch (InterruptedException ie) {
// shouldn't happen
throw new RuntimeException(ie);
}
}
mFrameAvailable = false;
}
// Latch the data.
mTextureRender.checkGlError("before updateTexImage");
mSurfaceTexture.updateTexImage();
}
/**
* Draws the data from SurfaceTexture onto the current EGL surface.
*/
public void drawImage() {
mTextureRender.drawFrame(mSurfaceTexture);
}
@Override
public void onFrameAvailable(SurfaceTexture st) {
if (VERBOSE) Log.d(TAG, "new frame available");
synchronized (mFrameSyncObject) {
if (mFrameAvailable) {
throw new RuntimeException("mFrameAvailable already set, frame could be dropped");
}
mFrameAvailable = true;
mFrameSyncObject.notifyAll();
}
}
/**
* Checks for EGL errors.
*/
private void checkEglError(String msg) {
boolean failed = false;
int error;
while ((error = mEGL.eglGetError()) != EGL10.EGL_SUCCESS) {
Log.e(TAG, msg + ": EGL error: 0x" + Integer.toHexString(error));
failed = true;
}
if (failed) {
throw new RuntimeException("EGL error encountered (see log)");
}
}
}
| tonyconstantinides/LiveMultimedia | app/src/main/java/com/constantinnovationsinc/livemultimedia/surfaces/OutputSurface.java | Java | apache-2.0 | 11,014 |
IRIDA Uploader
==============
## NOTICE!
### This repo will be deprecated as of January 1st 2020, as Python 2 will be End of Life.
### Please use our new uploader https://github.com/phac-nml/irida-uploader
Windows Installation
--------------------
Download the installer from https://github.com/phac-nml/irida-miseq-uploader/releases
Running in Linux
----------------
Install pip and wxpython:
$ sudo apt-get install python-pip python-wxgtk3.0
### virtualenv usage
Install virtualenv and setuptools
$ pip install virtualenv
$ pip install setuptools
If you already have these packages installed, ensure they are up to date
$ pip install virtualenv -U
$ pip install setuptools -U
Build a virtualenv and install the dependencies:
$ git clone https://github.com/phac-nml/irida-miseq-uploader
$ cd irida-miseq-uploader
$ make requirements
$ source .virtualenv/bin/activate
You can then run the uploader by running:
$ ./run_IRIDA_Uploader.py
Deactivate when finished:
$ deactivate
Creating the Windows installer
------------------------------
### Requirements
You must install several packages to build the Windows installer:
sudo apt-get install innoextract nsis python-pip python-virtualenv
### Building the Windows installer
From inside the `irida-miseq-uploader` directory, you can simply run:
make windows
This will build a Windows installer inside the `build/nsis/` directory, named something like `IRIDA_Uploader_1.0.0.exe`.
Running Tests
-------------
You can run all tests (unit and integration) by running:
$ echo "grant all privileges on irida_uploader_test.* to 'test'@'localhost' identified by 'test';" | mysql -u mysql_user -p
$ make test
You can verify PEP8 conformity by running:
$ ./scripts/verifyPEP8.sh
Note: No output is produced (other than `pip`-related output) if the PEP8 verification succeeds.
| phac-nml/irida-miseq-uploader | README.md | Markdown | apache-2.0 | 1,910 |
"""Plugin common functions."""
import logging
import os
import re
import shutil
import tempfile
import OpenSSL
import pkg_resources
import zope.interface
from acme.jose import util as jose_util
from certbot import constants
from certbot import crypto_util
from certbot import errors
from certbot import interfaces
from certbot import reverter
from certbot import util
logger = logging.getLogger(__name__)
def option_namespace(name):
"""ArgumentParser options namespace (prefix of all options)."""
return name + "-"
def dest_namespace(name):
"""ArgumentParser dest namespace (prefix of all destinations)."""
return name.replace("-", "_") + "_"
private_ips_regex = re.compile(
r"(^127\.0\.0\.1)|(^10\.)|(^172\.1[6-9]\.)|"
r"(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)")
hostname_regex = re.compile(
r"^(([a-z0-9]|[a-z0-9][a-z0-9\-]*[a-z0-9])\.)*[a-z]+$", re.IGNORECASE)
@zope.interface.implementer(interfaces.IPlugin)
class Plugin(object):
"""Generic plugin."""
# provider is not inherited, subclasses must define it on their own
# @zope.interface.provider(interfaces.IPluginFactory)
def __init__(self, config, name):
self.config = config
self.name = name
@jose_util.abstractclassmethod
def add_parser_arguments(cls, add):
"""Add plugin arguments to the CLI argument parser.
NOTE: If some of your flags interact with others, you can
use cli.report_config_interaction to register this to ensure
values are correctly saved/overridable during renewal.
:param callable add: Function that proxies calls to
`argparse.ArgumentParser.add_argument` prepending options
with unique plugin name prefix.
"""
@classmethod
def inject_parser_options(cls, parser, name):
"""Inject parser options.
See `~.IPlugin.inject_parser_options` for docs.
"""
# dummy function, doesn't check if dest.startswith(self.dest_namespace)
def add(arg_name_no_prefix, *args, **kwargs):
# pylint: disable=missing-docstring
return parser.add_argument(
"--{0}{1}".format(option_namespace(name), arg_name_no_prefix),
*args, **kwargs)
return cls.add_parser_arguments(add)
@property
def option_namespace(self):
"""ArgumentParser options namespace (prefix of all options)."""
return option_namespace(self.name)
def option_name(self, name):
"""Option name (include plugin namespace)."""
return self.option_namespace + name
@property
def dest_namespace(self):
"""ArgumentParser dest namespace (prefix of all destinations)."""
return dest_namespace(self.name)
def dest(self, var):
"""Find a destination for given variable ``var``."""
# this should do exactly the same what ArgumentParser(arg),
# does to "arg" to compute "dest"
return self.dest_namespace + var.replace("-", "_")
def conf(self, var):
"""Find a configuration value for variable ``var``."""
return getattr(self.config, self.dest(var))
# other
class Installer(Plugin):
"""An installer base class with reverter and ssl_dhparam methods defined.
Installer plugins do not have to inherit from this class.
"""
def __init__(self, *args, **kwargs):
super(Installer, self).__init__(*args, **kwargs)
self.reverter = reverter.Reverter(self.config)
def add_to_checkpoint(self, save_files, save_notes, temporary=False):
"""Add files to a checkpoint.
:param set save_files: set of filepaths to save
:param str save_notes: notes about changes during the save
:param bool temporary: True if the files should be added to a
temporary checkpoint rather than a permanent one. This is
usually used for changes that will soon be reverted.
:raises .errors.PluginError: when unable to add to checkpoint
"""
if temporary:
checkpoint_func = self.reverter.add_to_temp_checkpoint
else:
checkpoint_func = self.reverter.add_to_checkpoint
try:
checkpoint_func(save_files, save_notes)
except errors.ReverterError as err:
raise errors.PluginError(str(err))
def finalize_checkpoint(self, title):
"""Timestamp and save changes made through the reverter.
:param str title: Title describing checkpoint
:raises .errors.PluginError: when an error occurs
"""
try:
self.reverter.finalize_checkpoint(title)
except errors.ReverterError as err:
raise errors.PluginError(str(err))
def recovery_routine(self):
"""Revert all previously modified files.
Reverts all modified files that have not been saved as a checkpoint
:raises .errors.PluginError: If unable to recover the configuration
"""
try:
self.reverter.recovery_routine()
except errors.ReverterError as err:
raise errors.PluginError(str(err))
def revert_temporary_config(self):
"""Rollback temporary checkpoint.
:raises .errors.PluginError: when unable to revert config
"""
try:
self.reverter.revert_temporary_config()
except errors.ReverterError as err:
raise errors.PluginError(str(err))
def rollback_checkpoints(self, rollback=1):
"""Rollback saved checkpoints.
:param int rollback: Number of checkpoints to revert
:raises .errors.PluginError: If there is a problem with the input or
the function is unable to correctly revert the configuration
"""
try:
self.reverter.rollback_checkpoints(rollback)
except errors.ReverterError as err:
raise errors.PluginError(str(err))
def view_config_changes(self):
"""Show all of the configuration changes that have taken place.
:raises .errors.PluginError: If there is a problem while processing
the checkpoints directories.
"""
try:
self.reverter.view_config_changes()
except errors.ReverterError as err:
raise errors.PluginError(str(err))
@property
def ssl_dhparams(self):
"""Full absolute path to ssl_dhparams file."""
return os.path.join(self.config.config_dir, constants.SSL_DHPARAMS_DEST)
@property
def updated_ssl_dhparams_digest(self):
"""Full absolute path to digest of updated ssl_dhparams file."""
return os.path.join(self.config.config_dir, constants.UPDATED_SSL_DHPARAMS_DIGEST)
def install_ssl_dhparams(self):
"""Copy Certbot's ssl_dhparams file into the system's config dir if required."""
return install_version_controlled_file(
self.ssl_dhparams,
self.updated_ssl_dhparams_digest,
constants.SSL_DHPARAMS_SRC,
constants.ALL_SSL_DHPARAMS_HASHES)
class Addr(object):
r"""Represents an virtual host address.
:param str addr: addr part of vhost address
:param str port: port number or \*, or ""
"""
def __init__(self, tup, ipv6=False):
self.tup = tup
self.ipv6 = ipv6
@classmethod
def fromstring(cls, str_addr):
"""Initialize Addr from string."""
if str_addr.startswith('['):
# ipv6 addresses starts with [
endIndex = str_addr.rfind(']')
host = str_addr[:endIndex + 1]
port = ''
if len(str_addr) > endIndex + 2 and str_addr[endIndex + 1] == ':':
port = str_addr[endIndex + 2:]
return cls((host, port), ipv6=True)
else:
tup = str_addr.partition(':')
return cls((tup[0], tup[2]))
def __str__(self):
if self.tup[1]:
return "%s:%s" % self.tup
return self.tup[0]
def normalized_tuple(self):
"""Normalized representation of addr/port tuple
"""
if self.ipv6:
return (self.get_ipv6_exploded(), self.tup[1])
return self.tup
def __eq__(self, other):
if isinstance(other, self.__class__):
# compare normalized to take different
# styles of representation into account
return self.normalized_tuple() == other.normalized_tuple()
return False
def __hash__(self):
return hash(self.tup)
def get_addr(self):
"""Return addr part of Addr object."""
return self.tup[0]
def get_port(self):
"""Return port."""
return self.tup[1]
def get_addr_obj(self, port):
"""Return new address object with same addr and new port."""
return self.__class__((self.tup[0], port), self.ipv6)
def _normalize_ipv6(self, addr):
"""Return IPv6 address in normalized form, helper function"""
addr = addr.lstrip("[")
addr = addr.rstrip("]")
return self._explode_ipv6(addr)
def get_ipv6_exploded(self):
"""Return IPv6 in normalized form"""
if self.ipv6:
return ":".join(self._normalize_ipv6(self.tup[0]))
return ""
def _explode_ipv6(self, addr):
"""Explode IPv6 address for comparison"""
result = ['0', '0', '0', '0', '0', '0', '0', '0']
addr_list = addr.split(":")
if len(addr_list) > len(result):
# too long, truncate
addr_list = addr_list[0:len(result)]
append_to_end = False
for i in range(0, len(addr_list)):
block = addr_list[i]
if len(block) == 0:
# encountered ::, so rest of the blocks should be
# appended to the end
append_to_end = True
continue
elif len(block) > 1:
# remove leading zeros
block = block.lstrip("0")
if not append_to_end:
result[i] = str(block)
else:
# count the location from the end using negative indices
result[i-len(addr_list)] = str(block)
return result
class TLSSNI01(object):
"""Abstract base for TLS-SNI-01 challenge performers"""
def __init__(self, configurator):
self.configurator = configurator
self.achalls = []
self.indices = []
self.challenge_conf = os.path.join(
configurator.config.config_dir, "le_tls_sni_01_cert_challenge.conf")
# self.completed = 0
def add_chall(self, achall, idx=None):
"""Add challenge to TLSSNI01 object to perform at once.
:param .KeyAuthorizationAnnotatedChallenge achall: Annotated
TLSSNI01 challenge.
:param int idx: index to challenge in a larger array
"""
self.achalls.append(achall)
if idx is not None:
self.indices.append(idx)
def get_cert_path(self, achall):
"""Returns standardized name for challenge certificate.
:param .KeyAuthorizationAnnotatedChallenge achall: Annotated
tls-sni-01 challenge.
:returns: certificate file name
:rtype: str
"""
return os.path.join(self.configurator.config.work_dir,
achall.chall.encode("token") + ".crt")
def get_key_path(self, achall):
"""Get standardized path to challenge key."""
return os.path.join(self.configurator.config.work_dir,
achall.chall.encode("token") + '.pem')
def get_z_domain(self, achall):
"""Returns z_domain (SNI) name for the challenge."""
return achall.response(achall.account_key).z_domain.decode("utf-8")
def _setup_challenge_cert(self, achall, cert_key=None):
"""Generate and write out challenge certificate."""
cert_path = self.get_cert_path(achall)
key_path = self.get_key_path(achall)
# Register the path before you write out the file
self.configurator.reverter.register_file_creation(True, key_path)
self.configurator.reverter.register_file_creation(True, cert_path)
response, (cert, key) = achall.response_and_validation(
cert_key=cert_key)
cert_pem = OpenSSL.crypto.dump_certificate(
OpenSSL.crypto.FILETYPE_PEM, cert)
key_pem = OpenSSL.crypto.dump_privatekey(
OpenSSL.crypto.FILETYPE_PEM, key)
# Write out challenge cert and key
with open(cert_path, "wb") as cert_chall_fd:
cert_chall_fd.write(cert_pem)
with util.safe_open(key_path, 'wb', chmod=0o400) as key_file:
key_file.write(key_pem)
return response
def install_version_controlled_file(dest_path, digest_path, src_path, all_hashes):
"""Copy a file into an active location (likely the system's config dir) if required.
:param str dest_path: destination path for version controlled file
:param str digest_path: path to save a digest of the file in
:param str src_path: path to version controlled file found in distribution
:param list all_hashes: hashes of every released version of the file
"""
current_hash = crypto_util.sha256sum(src_path)
def _write_current_hash():
with open(digest_path, "w") as f:
f.write(current_hash)
def _install_current_file():
shutil.copyfile(src_path, dest_path)
_write_current_hash()
# Check to make sure options-ssl.conf is installed
if not os.path.isfile(dest_path):
_install_current_file()
return
# there's already a file there. if it's up to date, do nothing. if it's not but
# it matches a known file hash, we can update it.
# otherwise, print a warning once per new version.
active_file_digest = crypto_util.sha256sum(dest_path)
if active_file_digest == current_hash: # already up to date
return
elif active_file_digest in all_hashes: # safe to update
_install_current_file()
else: # has been manually modified, not safe to update
# did they modify the current version or an old version?
if os.path.isfile(digest_path):
with open(digest_path, "r") as f:
saved_digest = f.read()
# they modified it after we either installed or told them about this version, so return
if saved_digest == current_hash:
return
# there's a new version but we couldn't update the file, or they deleted the digest.
# save the current digest so we only print this once, and print a warning
_write_current_hash()
logger.warning("%s has been manually modified; updated file "
"saved to %s. We recommend updating %s for security purposes.",
dest_path, src_path, dest_path)
# test utils used by certbot_apache/certbot_nginx (hence
# "pragma: no cover") TODO: this might quickly lead to dead code (also
# c.f. #383)
def dir_setup(test_dir, pkg): # pragma: no cover
"""Setup the directories necessary for the configurator."""
def expanded_tempdir(prefix):
"""Return the real path of a temp directory with the specified prefix
Some plugins rely on real paths of symlinks for working correctly. For
example, certbot-apache uses real paths of configuration files to tell
a virtual host from another. On systems where TMP itself is a symbolic
link, (ex: OS X) such plugins will be confused. This function prevents
such a case.
"""
return os.path.realpath(tempfile.mkdtemp(prefix))
temp_dir = expanded_tempdir("temp")
config_dir = expanded_tempdir("config")
work_dir = expanded_tempdir("work")
os.chmod(temp_dir, constants.CONFIG_DIRS_MODE)
os.chmod(config_dir, constants.CONFIG_DIRS_MODE)
os.chmod(work_dir, constants.CONFIG_DIRS_MODE)
test_configs = pkg_resources.resource_filename(
pkg, os.path.join("testdata", test_dir))
shutil.copytree(
test_configs, os.path.join(temp_dir, test_dir), symlinks=True)
return temp_dir, config_dir, work_dir
| jsha/letsencrypt | certbot/plugins/common.py | Python | apache-2.0 | 16,182 |
package com.appacitive.khelkund.model.events;
/**
* Created by sathley on 4/1/2015.
*/
public class LogoSelectedEvent {
public int Position;
}
| randhika/khelkund | app/src/main/java/com/appacitive/khelkund/model/events/LogoSelectedEvent.java | Java | apache-2.0 | 150 |
/*
* Copyright © 2015-2016
*
* This file is part of Spoofax for IntelliJ.
*
* 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.
*/
package org.metaborg.intellij.idea.projects;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.metaborg.core.project.IProject;
import org.metaborg.core.project.IProjectService;
import org.metaborg.intellij.logging.InjectLogger;
import org.metaborg.intellij.resources.FileNameUtils;
import org.metaborg.util.log.ILogger;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
// TODO: Move to Spoofax core?
/**
* Project service for language artifacts.
*/
public final class ArtifactProjectService implements IProjectService {
private final IArtifactProjectFactory artifactProjectFactory;
private final Map<FileName, ArtifactProject> projects = new HashMap<>();
@InjectLogger
private ILogger logger;
@Inject
public ArtifactProjectService(final IArtifactProjectFactory artifactProjectFactory) {
this.artifactProjectFactory = artifactProjectFactory;
}
/**
* {@inheritDoc}
*/
@Nullable
@Override
public IProject get(final FileObject resource) {
Preconditions.checkNotNull(resource);
@Nullable final FileObject artifactRoot = getArtifactRoot(resource);
if (artifactRoot == null)
return null;
final FileName artifactName = artifactRoot.getName();
@Nullable ArtifactProject project = this.projects.get(artifactName);
if (project == null) {
project = this.artifactProjectFactory.create(artifactRoot, null);
this.projects.put(artifactName, project);
}
return project;
}
/**
* Determines the language artifact root of the specified file.
*
* @param file The file.
* @return The language artifact root; or <code>null</code> when there is none.
*/
@Nullable
private FileObject getArtifactRoot(final FileObject file) {
@Nullable FileObject current = getRoot(file);
while (current != null && !isArtifactRoot(current.getName())) {
current = getParentRoot(current);
}
return current;
}
/**
* Gets the root file of the specified layer.
*
* @param layer The layer; or <code>null</code>.
* @return The root file; or <code>null</code>.
*/
@Nullable
private FileObject getRoot(@Nullable final FileObject layer) {
if (layer == null)
return null;
try {
return layer.getFileSystem().getRoot();
} catch (final FileSystemException e) {
this.logger.error("Ignored exception.", e);
return null;
}
}
/**
* Determines whether the specified file name points to a language artifact root.
* <p>
* For example, <code>zip:file:///dir/archive.spoofax-language!/</code> is a language artifact root.
*
* @param fileName The file name to check.
* @return <code>true</code> when the file is a language artifact root;
* otherwise, <code>false</code>.
*/
private boolean isArtifactRoot(final FileName fileName) {
@Nullable final FileName outerFileName = FileNameUtils.getOuterFileName(fileName);
if (outerFileName == null)
return false;
return "spoofax-language".equals(outerFileName.getExtension());
}
/**
* Gets the parent root of the specified file.
*
* @param file The file.
* @return The parent root; or <code>null</code>.
*/
@Nullable
private FileObject getParentRoot(final FileObject file) {
try {
return getRoot(file.getFileSystem().getParentLayer());
} catch (final FileSystemException e) {
this.logger.error("Ignored exception.", e);
return null;
}
}
}
| metaborg/spoofax-intellij | src/main/java/org/metaborg/intellij/idea/projects/ArtifactProjectService.java | Java | apache-2.0 | 4,542 |
// Copyright (c) rubicon IT GmbH, www.rubicon.eu
//
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership. rubicon 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.
//
using System;
using System.Linq.Expressions;
namespace TITcs.SharePoint.Query.LinqProvider.Clauses.Expressions
{
/// <summary>
/// This interface should be implemented by visitors that handle the <see cref="PartialEvaluationExceptionExpression"/> instances.
/// </summary>
public interface IPartialEvaluationExceptionExpressionVisitor
{
Expression VisitPartialEvaluationExceptionExpression (PartialEvaluationExceptionExpression partialEvaluationExceptionExpression);
}
} | TITcs/TITcs.SharePoint | src/TITcs.SharePoint/Query/LinqProvider/Clauses/Expressions/IPartialEvaluationExceptionExpressionVisitor.cs | C# | apache-2.0 | 1,244 |
package com.itracker.android.sync;
import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SyncResult;
import android.os.Bundle;
import android.os.Process;
import com.itracker.android.BuildConfig;
import com.itracker.android.utils.LogUtils;
import java.util.regex.Pattern;
import static com.itracker.android.utils.LogUtils.LOGI;
public class SyncAdapter extends AbstractThreadedSyncAdapter {
private static final String TAG = LogUtils.makeLogTag(SyncAdapter.class);
private static final Pattern sSanitizeAccountNamePattern = Pattern.compile("(.).*?(.?)@");
private final Context mContext;
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
mContext = context;
// noinspection ConstantConditions, PointlessBooleanExpression
if (!BuildConfig.DEBUG) {
Thread.setDefaultUncaughtExceptionHandler((thread, throwable) ->
LogUtils.LOGE(TAG, "Uncaught sync exception, suppressing UI in release build.", throwable));
}
}
@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
final ContentProviderClient provider, final SyncResult syncResult) {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false);
final String logSanitizedAccountName = sSanitizeAccountNamePattern.matcher(account.name).replaceAll("$1...$2@");
LOGI(TAG, "Beginning sync for account " + logSanitizedAccountName + "," +
" uploadOnly=" + uploadOnly +
" manualSync=" + manualSync +
" initialize=" + initialize);
// Sync from bootstrap and remote data, as needed
new SyncHelper(mContext).performSync(syncResult, account, extras);
}
} | bigbugbb/iTracker | app/src/main/java/com/itracker/android/sync/SyncAdapter.java | Java | apache-2.0 | 2,276 |
//===----------------------------------------------------------------------===//
//
// Peloton
//
// abstract_executor.cpp
//
// Identification: src/executor/abstract_executor.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "common/value.h"
#include "common/logger.h"
#include "executor/abstract_executor.h"
#include "executor/executor_context.h"
#include "planner/abstract_plan.h"
namespace peloton {
namespace executor {
/**
* @brief Constructor for AbstractExecutor.
* @param node Abstract plan node corresponding to this executor.
*/
AbstractExecutor::AbstractExecutor(const planner::AbstractPlan *node,
ExecutorContext *executor_context)
: node_(node), executor_context_(executor_context) {}
void AbstractExecutor::SetOutput(LogicalTile *table) { output.reset(table); }
// Transfers ownership
LogicalTile *AbstractExecutor::GetOutput() {
// PL_ASSERT(output.get() != nullptr);
return output.release();
}
/**
* @brief Add child executor to this executor node.
* @param child Child executor to add.
*/
void AbstractExecutor::AddChild(AbstractExecutor *child) {
children_.push_back(child);
}
const std::vector<AbstractExecutor *> &AbstractExecutor::GetChildren() const {
return children_;
}
/**
* @brief Initializes the executor.
*
* This function executes any initialization code common to all executors.
* It recursively initializes all children of this executor in the execution
* tree. It calls SubInit() which is implemented by the subclass.
*
* @return true on success, false otherwise.
*/
bool AbstractExecutor::Init() {
bool status = false;
for (auto child : children_) {
status = child->Init();
if (status == false) {
LOG_ERROR("Initialization failed in child executor with plan id : %s",
child->node_->GetInfo().c_str());
return false;
}
}
status = DInit();
if (status == false) {
LOG_ERROR("Initialization failed in executor with plan id : %s",
node_->GetInfo().c_str());
return false;
}
return true;
}
/**
* @brief Returns next tile processed by this executor.
*
* This function is the backbone of the tile-based volcano-style execution
* model we are using.
*
* @return Pointer to the logical tile processed by this executor.
*/
bool AbstractExecutor::Execute() {
// TODO In the future, we might want to pass some kind of executor state to
// GetNextTile. e.g. params for prepared plans.
bool status = DExecute();
return status;
}
void AbstractExecutor::SetContext(Value value) {
executor_context_->SetParams(value);
}
void AbstractExecutor::ClearContext() {
executor_context_->ClearParams();
}
} // namespace executor
} // namespace peloton
| ranxian/peloton | src/executor/abstract_executor.cpp | C++ | apache-2.0 | 2,878 |
import com.charlesahunt.proteus.config.ProteusConfig
package object proteus {
val testConfig = ProteusConfig(
user = "root",
password = "openSesame"
)
}
| CharlesAHunt/proteus | src/test/scala/proteus/package.scala | Scala | apache-2.0 | 172 |
/**
* Copyright 2004-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.
*/
package org.kuali.kpme.tklm.leave.summary;
import org.joda.time.LocalDateTime;
import org.junit.Assert;
import org.junit.Test;
import org.kuali.kpme.core.IntegrationTest;
import org.kuali.kpme.core.api.calendar.entry.CalendarEntry;
import org.kuali.kpme.core.service.HrServiceLocator;
import org.kuali.kpme.tklm.TKLMIntegrationTestCase;
import org.kuali.kpme.tklm.api.leave.summary.LeaveSummaryContract;
import org.kuali.kpme.tklm.api.leave.summary.LeaveSummaryRowContract;
import org.kuali.kpme.tklm.leave.service.LmServiceLocator;
import java.math.BigDecimal;
import java.util.List;
@IntegrationTest
public class LeaveSummaryServiceImplTest extends TKLMIntegrationTestCase {
@Test
public void testGetLeaveSummary() throws Exception {
// selected calendar entry is 03/15/2012 - 04/01/2012
CalendarEntry ce = HrServiceLocator.getCalendarEntryService().getCalendarEntry("56");
LeaveSummaryContract ls = LmServiceLocator.getLeaveSummaryService().getLeaveSummary("testUser", ce);
Assert.assertTrue("There ytd dates String should be 'March 1 - March 14 2012', not " + ls.getYtdDatesString(), ls.getYtdDatesString().equals("March 1 - March 14 2012"));
Assert.assertTrue("There pending dates String should be 'March 15 - March 31 2012', not " + ls.getPendingDatesString(), ls.getPendingDatesString().equals("March 15 - March 31 2012"));
List<? extends LeaveSummaryRowContract> rows = ls.getLeaveSummaryRows();
Assert.assertTrue("There should be 1 leave summary rows for emplyee 'testUser', not " + rows.size(), rows.size()== 1);
LeaveSummaryRowContract aRow = rows.get(0);
Assert.assertTrue("Accrual cateogry for Row should be 'testAC', not " + aRow.getAccrualCategory(), aRow.getAccrualCategory().equals("testAC"));
Assert.assertTrue("Carry over for Row should be '0', not " + aRow.getCarryOver(), aRow.getCarryOver().compareTo(BigDecimal.ZERO) == 0);
Assert.assertTrue("YTD accrualed balance for Row should be '8', not " + aRow.getYtdAccruedBalance(), aRow.getYtdAccruedBalance().compareTo(new BigDecimal(8)) == 0);
Assert.assertTrue("YTD approved usage for Row should be '-3', not " + aRow.getYtdApprovedUsage(), aRow.getYtdApprovedUsage().compareTo(new BigDecimal(-3)) == 0);
Assert.assertTrue("Leave Balance for Row should be '11', not " + aRow.getLeaveBalance(), aRow.getLeaveBalance().compareTo(new BigDecimal(11)) == 0);
Assert.assertTrue("Pending Leave Accrual for Row should be '10', not " + aRow.getPendingLeaveAccrual(), aRow.getPendingLeaveAccrual().compareTo(new BigDecimal(10)) == 0);
Assert.assertTrue("Pending Leave requests for Row should be '0', not " + aRow.getPendingLeaveRequests(), aRow.getPendingLeaveRequests().compareTo(new BigDecimal(0)) == 0);
//Assert.assertTrue("Pending Leave Balance for Row should be '3', not " + aRow.getPendingLeaveBalance(), aRow.getPendingLeaveBalance().equals(new BigDecimal(3)));
//Assert.assertTrue("Pending Available usage for Row should be '198', not " + aRow.getPendingAvailableUsage(), aRow.getPendingAvailableUsage().equals(new BigDecimal(198)));
Assert.assertTrue("Usage Limit for Row should be '200', not " + aRow.getUsageLimit(), aRow.getUsageLimit().compareTo(new BigDecimal(200)) == 0);
Assert.assertTrue("FMLA usage for Row should be '-3', not " + aRow.getFmlaUsage(), aRow.getFmlaUsage().compareTo(new BigDecimal(-3)) == 0);
// selected calendar entry is 04/01/2012 - 04/30/2012
ce = HrServiceLocator.getCalendarEntryService().getCalendarEntry("58");
ls = LmServiceLocator.getLeaveSummaryService().getLeaveSummary("testUser", ce);
Assert.assertTrue("There ytd dates String should be 'March 1 - March 14 2012', not " + ls.getYtdDatesString(), ls.getYtdDatesString().equals("March 1 - March 14 2012"));
Assert.assertTrue("There pending dates String should be 'April 15 - April 30 2012', not " + ls.getPendingDatesString(), ls.getPendingDatesString().equals("April 15 - April 30 2012"));
rows = ls.getLeaveSummaryRows();
Assert.assertTrue("There should be 1 leave summary rows for emplyee 'testUser', not " + rows.size(), rows.size()== 1);
aRow = rows.get(0);
Assert.assertTrue("Accrual cateogry for Row should be 'testAC', not " + aRow.getAccrualCategory(), aRow.getAccrualCategory().equals("testAC"));
Assert.assertTrue("Carry over for Row should be '0', not " + aRow.getCarryOver(), aRow.getCarryOver().compareTo(BigDecimal.ZERO)==0);
Assert.assertTrue("YTD accrual balance for Row should be '8', not " + aRow.getYtdAccruedBalance(), aRow.getYtdAccruedBalance().compareTo(new BigDecimal(8))==0);
Assert.assertTrue("YTD approved usage for Row should be '-13', not " + aRow.getYtdApprovedUsage(), aRow.getYtdApprovedUsage().compareTo(new BigDecimal(-13))==0);
Assert.assertTrue("Leave Balance for Row should be '21', not " + aRow.getLeaveBalance(), aRow.getLeaveBalance().compareTo(new BigDecimal(21))==0);
Assert.assertTrue("Pending Leave Accrual for Row should be '0', not " + aRow.getPendingLeaveAccrual(), aRow.getPendingLeaveAccrual().compareTo(BigDecimal.ZERO)==0);
Assert.assertTrue("Pending Leave requests for Row should be '0', not " + aRow.getPendingLeaveRequests(), aRow.getPendingLeaveRequests().compareTo(new BigDecimal(0))==0);
//Assert.assertTrue("Pending Leave Balance for Row should be '13', not " + aRow.getPendingLeaveBalance(), aRow.getPendingLeaveBalance().equals(new BigDecimal(13)));
//Assert.assertTrue("Pending Available usage for Row should be '198', not " + aRow.getPendingAvailableUsage(), aRow.getPendingAvailableUsage().equals(new BigDecimal(198)));
Assert.assertTrue("Usage Limit for Row should be '200', not " + aRow.getUsageLimit(), aRow.getUsageLimit().compareTo(new BigDecimal(200)) == 0);
Assert.assertTrue("FMLA usage for Row should be '-3', not " + aRow.getFmlaUsage(), aRow.getFmlaUsage().compareTo(new BigDecimal(-3)) == 0);
// selected calendar entry is 05/01/2012 - 05/31/2012
ce = HrServiceLocator.getCalendarEntryService().getCalendarEntry("59");
ls = LmServiceLocator.getLeaveSummaryService().getLeaveSummary("testUser", ce);
Assert.assertTrue("There ytd dates String should be 'March 1 - March 14 2012', not " + ls.getYtdDatesString(), ls.getYtdDatesString().equals("March 1 - March 14 2012"));
Assert.assertTrue("There pending dates String should be 'May 1 - May 14 2012', not " + ls.getPendingDatesString(), ls.getPendingDatesString().equals("May 1 - May 14 2012"));
rows = ls.getLeaveSummaryRows();
Assert.assertTrue("There should be 2 leave summary rows for employee 'testUser', not " + rows.size(), rows.size()== 2);
for(LeaveSummaryRowContract lsRow : rows ) {
if(lsRow.getAccrualCategory().equals("testAC")) {
Assert.assertTrue("Carry over for Row should be '0', not " + lsRow.getCarryOver(), lsRow.getCarryOver().compareTo(BigDecimal.ZERO) == 0);
Assert.assertTrue("YTD accrualed balance for Row should be '8', not " + lsRow.getYtdAccruedBalance(), lsRow.getYtdAccruedBalance().compareTo(new BigDecimal(8)) == 0);
Assert.assertTrue("YTD approved usage for Row should be '-13', not " + lsRow.getYtdApprovedUsage(), lsRow.getYtdApprovedUsage().compareTo(new BigDecimal(-13)) == 0);
Assert.assertTrue("Leave Balance for Row should be '21', not " + lsRow.getLeaveBalance(), lsRow.getLeaveBalance().compareTo(new BigDecimal(21)) == 0);
Assert.assertTrue("Pending Leave Accrual for Row should be '0', not " + lsRow.getPendingLeaveAccrual(), lsRow.getPendingLeaveAccrual().compareTo(BigDecimal.ZERO) == 0);
Assert.assertTrue("Pending Leave requests for Row should be '0', not " + lsRow.getPendingLeaveRequests(), lsRow.getPendingLeaveRequests().compareTo(new BigDecimal(0)) == 0);
//Assert.assertTrue("Pending Leave Balance for Row should be '13', not " + lsRow.getPendingLeaveBalance(), lsRow.getPendingLeaveBalance().equals(new BigDecimal(13)));
//Assert.assertTrue("Pending Available usage for Row should be '198', not " + lsRow.getPendingAvailableUsage(), lsRow.getPendingAvailableUsage().equals(new BigDecimal(198)));
Assert.assertTrue("Usage Limit for Row should be '200', not " + lsRow.getUsageLimit(), lsRow.getUsageLimit().compareTo(new BigDecimal(200)) == 0);
Assert.assertTrue("FMLA usage for Row should be '-3', not " + lsRow.getFmlaUsage(), lsRow.getFmlaUsage().compareTo(new BigDecimal(-3)) == 0);
} else if(lsRow.getAccrualCategory().equals("testAC1")) {
Assert.assertTrue("Carry over for Row should be '0', not " + lsRow.getCarryOver(), lsRow.getCarryOver().compareTo(BigDecimal.ZERO) == 0);
Assert.assertTrue("YTD accrualed balance for Row should be '0', not " + lsRow.getYtdAccruedBalance(), lsRow.getYtdAccruedBalance().compareTo(new BigDecimal(0)) == 0);
Assert.assertTrue("YTD approved usage for Row should be '-8', not " + lsRow.getYtdApprovedUsage(), lsRow.getYtdApprovedUsage().compareTo(new BigDecimal(-8)) == 0);
Assert.assertTrue("Leave Balance for Row should be '8', not " + lsRow.getLeaveBalance(), lsRow.getLeaveBalance().compareTo(new BigDecimal(8)) == 0);
Assert.assertTrue("Pending Leave Accrual for Row should be '0', not " + lsRow.getPendingLeaveAccrual(), lsRow.getPendingLeaveAccrual().compareTo(BigDecimal.ZERO) == 0);
Assert.assertTrue("Pending Leave requests for Row should be '0', not " + lsRow.getPendingLeaveRequests(), lsRow.getPendingLeaveRequests().compareTo(new BigDecimal(0)) == 0);
//Assert.assertTrue("Pending Leave Balance for Row should be '8', not " + lsRow.getPendingLeaveBalance(), lsRow.getPendingLeaveBalance().equals(new BigDecimal(8)));
//Assert.assertTrue("Pending Available usage for Row should be '300', not " + lsRow.getPendingAvailableUsage(), lsRow.getPendingAvailableUsage().equals(new BigDecimal(300)));
Assert.assertTrue("Usage Limit for Row should be '300', not " + lsRow.getUsageLimit(), lsRow.getUsageLimit().compareTo(new BigDecimal(300)) == 0);
Assert.assertTrue("FMLA usage for Row should be '0', not " + lsRow.getFmlaUsage(), lsRow.getFmlaUsage().compareTo(new BigDecimal(0)) == 0);
} else {
Assert.fail("Accrual category for Row should either be 'testAC' or 'testAC1', not " + lsRow.getAccrualCategory());
}
}
// selected calendar entry is 02/1/2012 - 02/15/2012
// principal HR attribute does not exist on 02/01/2012, it becomes active on 02/05/2012
// this is testing null principalHrAttributes with beginning date of Calendar entry
ce = HrServiceLocator.getCalendarEntryService().getCalendarEntry("53");
ls = LmServiceLocator.getLeaveSummaryService().getLeaveSummary("testUser", ce);
rows = ls.getLeaveSummaryRows();
Assert.assertTrue("There should be 1 leave summary rows for emplyee 'testUser', not " + rows.size(), rows.size()== 1);
}
@Test
public void testGetHeaderForSummary() throws Exception {
CalendarEntry ce = HrServiceLocator.getCalendarEntryService().getCalendarEntry("56");
List<LocalDateTime> leaveSummaryDates = LmServiceLocator.getLeaveSummaryService().getLeaveSummaryDates(ce);
Assert.assertTrue("The number of leave summary dates should be 17, not " + leaveSummaryDates.size(), leaveSummaryDates.size()== 17);
}
}
| kuali/kpme | tk-lm/impl/src/test/java/org/kuali/kpme/tklm/leave/summary/LeaveSummaryServiceImplTest.java | Java | apache-2.0 | 11,824 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AleaMapper.Tests.Models.EmitMapperModels
{
public class BenchSource
{
public class Int1
{
public string str1 = "1";
public string str2 = null;
public int i = 10;
}
public class Int2
{
public Int1 i1 = new Int1();
public Int1 i2 = new Int1();
public Int1 i3 = new Int1();
public Int1 i4 = new Int1();
public Int1 i5 = new Int1();
public Int1 i6 = new Int1();
public Int1 i7 = new Int1();
}
public Int2 i1 = new Int2();
public Int2 i2 = new Int2();
public Int2 i3 = new Int2();
public Int2 i4 = new Int2();
public Int2 i5 = new Int2();
public Int2 i6 = new Int2();
public Int2 i7 = new Int2();
public Int2 i8 = new Int2();
public int n2;
public int n3;
public int n4;
public int n5;
public int n6;
public int n7;
public int n8;
public int n9;
public string s1 = "1";
public string s2 = "2";
public string s3 = "3";
public string s4 = "4";
public string s5 = "5";
public string s6 = "6";
public string s7 = "7";
}
public class BenchDestination
{
public class Int1
{
public string str1;
public string str2;
public int i;
}
public class Int2
{
public Int1 i1;
public Int1 i2;
public Int1 i3;
public Int1 i4;
public Int1 i5;
public Int1 i6;
public Int1 i7;
}
public Int2 i1 { get; set; }
public Int2 i2 { get; set; }
public Int2 i3 { get; set; }
public Int2 i4 { get; set; }
public Int2 i5 { get; set; }
public Int2 i6 { get; set; }
public Int2 i7 { get; set; }
public Int2 i8 { get; set; }
public int n2 = 2;
public int n3 = 3;
public int n4 = 4;
public int n5 = 5;
public int n6 = 6;
public int n7 = 7;
public int n8 = 8;
public int n9 = 9;
public string s1;
public string s2;
public string s3;
public string s4;
public string s5;
public string s6;
public string s7;
}
}
| day01/AleaMapper | AleaMapper.Tests/Models/EmitMapperModels/Bench.cs | C# | apache-2.0 | 1,990 |
// Copyright 2005 The Apache Software Foundation
//
// 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.
package org.apache.tapestry.services.impl;
import org.apache.hivemind.Location;
import org.apache.hivemind.internal.Module;
import org.apache.hivemind.schema.Translator;
/**
* An encapsulation of an invocation of
* {@link org.apache.hivemind.schema.Translator#translate(org.apache.hivemind.internal.Module, java.lang.Class, java.lang.String, org.apache.hivemind.Location)},
* allowing the actual invocation (and all the object creation, etc., that entails) to be deferred,
* or even avoided all together.
*
* @author Howard M. Lewis Ship
* @since 4.0
*/
public class DeferredObjectImpl implements DeferredObject
{
private final Module _module;
private final Translator _objectTranslator;
private final String _objectReference;
private final Location _location;
private Object _object;
public DeferredObjectImpl(final Translator objectTranslator, final Module module,
final String objectReference, final Location location)
{
_objectTranslator = objectTranslator;
_module = module;
_objectReference = objectReference;
_location = location;
}
public synchronized Object getObject()
{
if (_object == null)
_object = _objectTranslator.translate(
_module,
Object.class,
_objectReference,
_location);
return _object;
}
public Location getLocation()
{
return _location;
}
} | apache/tapestry4 | framework/src/java/org/apache/tapestry/services/impl/DeferredObjectImpl.java | Java | apache-2.0 | 2,108 |
package com.dgrid.plugin;
public interface PluginContext {
public static final String NAME = "pluginContext";
public Object getBean(String name);
}
| samtingleff/dgrid | java/src/api/com/dgrid/plugin/PluginContext.java | Java | apache-2.0 | 152 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.