<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestVariantComparison.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkVariant.h"
#include "vtkObject.h"

#include <vtksys/stl/map>
#include <cstdio>

int
TestVariantComparison(int, char *[])
{
  signed char positiveChar = 100;
  signed char negativeChar = -100;
  short positiveShort = 10000;
  short negativeShort = -10000;
  int positiveInt = 100000;
  int negativeInt = -100000;
  long positiveLong = 1000000;
  long negativeLong = -1000000;

  int shiftAmount64 = 8 * sizeof(vtkTypeInt64) - 2;
  int shiftAmountInt = 8 * sizeof(int) - 2;
  int shiftAmountLong = 8 * sizeof(long) - 2;

  vtkTypeInt64 positive64 = static_cast<vtkTypeInt64>(1) << shiftAmount64;
  vtkTypeInt64 negative64 = -positive64;

  // There is nothing inherently magical about these values.  I just
  // happen to like them and they're outside the range of signed
  // integers.
  unsigned char unsignedChar = 192;
  unsigned short unsignedShort = 49152;
  unsigned int unsignedInt = (static_cast<unsigned int>(1)<<shiftAmountInt) * 3;
  unsigned long unsignedLong = 1<<shiftAmountLong * 3;
  vtkTypeUInt64 unsigned64 = 3 * (static_cast<vtkTypeUInt64>(1) << shiftAmount64);

  vtkStdString numberString("100000");
  vtkStdString alphaString("ABCDEFG");

  float positiveFloat = 12345.678;
  float negativeFloat = -12345.678;
  double positiveDouble = 123456789.012345;
  double negativeDouble = -123456789.012345;

  vtkObject *fooObject = vtkObject::New();

  vtkVariant invalidVariant;

  // Now we need variants for all of those
  vtkVariant positiveCharVariant(positiveChar);
  vtkVariant unsignedCharVariant(unsignedChar);
  vtkVariant negativeCharVariant(negativeChar);

  vtkVariant positiveShortVariant(positiveShort);
  vtkVariant unsignedShortVariant(unsignedShort);
  vtkVariant negativeShortVariant(negativeShort);

  vtkVariant positiveIntVariant(positiveInt);
  vtkVariant unsignedIntVariant(unsignedInt);
  vtkVariant negativeIntVariant(negativeInt);

  vtkVariant positiveLongVariant(positiveLong);
  vtkVariant unsignedLongVariant(unsignedLong);
  vtkVariant negativeLongVariant(negativeLong);

  vtkVariant positive64Variant(positive64);
  vtkVariant unsigned64Variant(unsigned64);
  vtkVariant negative64Variant(negative64);

  vtkVariant positiveFloatVariant(positiveFloat);
  vtkVariant negativeFloatVariant(negativeFloat);
  vtkVariant positiveDoubleVariant(positiveDouble);
  vtkVariant negativeDoubleVariant(negativeDouble);

  vtkVariant numberStringVariant(numberString);
  vtkVariant alphaStringVariant(alphaString);

  vtkVariant fooObjectVariant(fooObject);

  int errorCount = 0;
  int overallErrorCount = 0;

#define CHECK_EXPRESSION_FALSE(expr) { if ((expr)) { ++errorCount; cerr << "TEST FAILED: " << #expr << " should have been false\n\n"; } }

#define CHECK_EXPRESSION_TRUE(expr) { if (!(expr)) { ++errorCount; cerr << "TEST FAILED: " << #expr << " should have been true\n\n"; } }

  cerr << "Testing same-type comparisons... ";
  CHECK_EXPRESSION_FALSE(positiveCharVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(unsignedCharVariant < positiveCharVariant);
  CHECK_EXPRESSION_FALSE(unsignedCharVariant < negativeCharVariant);

  CHECK_EXPRESSION_FALSE(positiveShortVariant < negativeShortVariant);
  CHECK_EXPRESSION_FALSE(unsignedShortVariant < positiveShortVariant);
  CHECK_EXPRESSION_FALSE(unsignedShortVariant < negativeShortVariant);

  cerr << "DEBUG: positiveInt " << positiveInt << ", "
       << "negativeInt " << negativeInt << ", "
       << "unsignedInt " << unsignedInt << "\n";

  CHECK_EXPRESSION_FALSE(positiveIntVariant < negativeIntVariant);
  CHECK_EXPRESSION_FALSE(unsignedIntVariant < positiveIntVariant);
  CHECK_EXPRESSION_FALSE(unsignedIntVariant < negativeIntVariant);

  CHECK_EXPRESSION_FALSE(positiveLongVariant < negativeLongVariant);
  CHECK_EXPRESSION_FALSE(unsignedLongVariant < positiveLongVariant);
  CHECK_EXPRESSION_FALSE(unsignedLongVariant < negativeLongVariant);

  CHECK_EXPRESSION_FALSE(positive64Variant < negative64Variant);
  CHECK_EXPRESSION_FALSE(unsigned64Variant < positive64Variant);
  CHECK_EXPRESSION_FALSE(unsigned64Variant < negative64Variant);

  CHECK_EXPRESSION_FALSE(positiveFloat < negativeFloat);
  CHECK_EXPRESSION_FALSE(positiveDouble < negativeDouble);

  CHECK_EXPRESSION_FALSE(alphaString < numberString);

  if (errorCount == 0)
    {
    cerr << "Test succeeded.\n";
    }
  else
    {
    cerr << errorCount << " error(s) found!\n";
    }
  overallErrorCount += errorCount;
  errorCount = 0;

  cerr << "Testing cross-type comparisons... ";

  CHECK_EXPRESSION_FALSE(positiveShortVariant < positiveCharVariant);
  CHECK_EXPRESSION_FALSE(positiveIntVariant < positiveCharVariant);
  CHECK_EXPRESSION_FALSE(positiveLongVariant < positiveCharVariant);
  CHECK_EXPRESSION_FALSE(positive64Variant < positiveCharVariant);

  CHECK_EXPRESSION_FALSE(positiveShortVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(positiveIntVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(positiveLongVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(positive64Variant < negativeCharVariant);

  CHECK_EXPRESSION_FALSE(positiveShortVariant < unsignedCharVariant);
  CHECK_EXPRESSION_FALSE(positiveIntVariant < unsignedCharVariant);
  CHECK_EXPRESSION_FALSE(positiveLongVariant < unsignedCharVariant);
  CHECK_EXPRESSION_FALSE(positive64Variant < unsignedCharVariant);

  CHECK_EXPRESSION_FALSE(negativeCharVariant < negativeShortVariant);
  CHECK_EXPRESSION_FALSE(negativeCharVariant < negativeIntVariant);
  CHECK_EXPRESSION_FALSE(negativeCharVariant < negativeLongVariant);
  CHECK_EXPRESSION_FALSE(negativeCharVariant < negative64Variant);

  CHECK_EXPRESSION_FALSE(unsignedShortVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(unsignedIntVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(unsignedLongVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(unsigned64Variant < negativeCharVariant);

  CHECK_EXPRESSION_FALSE(positiveFloatVariant < positiveCharVariant);
  CHECK_EXPRESSION_FALSE(positiveFloatVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(positiveFloatVariant < unsignedCharVariant);

  CHECK_EXPRESSION_FALSE(positiveDoubleVariant < positiveCharVariant);
  CHECK_EXPRESSION_FALSE(positiveDoubleVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(positiveDoubleVariant < unsignedCharVariant);

  CHECK_EXPRESSION_FALSE(alphaStringVariant < positiveIntVariant);
  CHECK_EXPRESSION_FALSE(numberStringVariant != positiveIntVariant);
  CHECK_EXPRESSION_FALSE(positiveDoubleVariant < fooObjectVariant);
  CHECK_EXPRESSION_FALSE(positiveFloatVariant < invalidVariant);

  if (errorCount == 0)
    {
    cerr << "Test succeeded.\n";
    }
  else
    {
    cerr << errorCount << " error(s) found!\n";
    }
  overallErrorCount += errorCount;
  errorCount = 0;

  cerr << "Testing cross-type equality...";

  char c = 100;
  short s = 100;
  int i = 100;
  long l = 100;
  vtkTypeInt64 i64 = 100;
  float f = 100;
  double d = 100;
  vtkStdString str("100");

  CHECK_EXPRESSION_TRUE(vtkVariant(c) == vtkVariant(s));
  CHECK_EXPRESSION_TRUE(vtkVariant(c) == vtkVariant(i));
  CHECK_EXPRESSION_TRUE(vtkVariant(c) == vtkVariant(l));
  CHECK_EXPRESSION_TRUE(vtkVariant(c) == vtkVariant(i64));
  CHECK_EXPRESSION_TRUE(vtkVariant(c) == vtkVariant(f));
  CHECK_EXPRESSION_TRUE(vtkVariant(c) == vtkVariant(d));

  CHECK_EXPRESSION_TRUE(vtkVariant(s) == vtkVariant(i));
  CHECK_EXPRESSION_TRUE(vtkVariant(s) == vtkVariant(l));
  CHECK_EXPRESSION_TRUE(vtkVariant(s) == vtkVariant(i64));
  CHECK_EXPRESSION_TRUE(vtkVariant(s) == vtkVariant(f));
  CHECK_EXPRESSION_TRUE(vtkVariant(s) == vtkVariant(d));
  CHECK_EXPRESSION_TRUE(vtkVariant(s) == vtkVariant(str));

  CHECK_EXPRESSION_TRUE(vtkVariant(i) == vtkVariant(l));
  CHECK_EXPRESSION_TRUE(vtkVariant(i) == vtkVariant(i64));
  CHECK_EXPRESSION_TRUE(vtkVariant(i) == vtkVariant(f));
  CHECK_EXPRESSION_TRUE(vtkVariant(i) == vtkVariant(d));
  CHECK_EXPRESSION_TRUE(vtkVariant(i) == vtkVariant(str));

  CHECK_EXPRESSION_TRUE(vtkVariant(l) == vtkVariant(i64));
  CHECK_EXPRESSION_TRUE(vtkVariant(l) == vtkVariant(f));
  CHECK_EXPRESSION_TRUE(vtkVariant(l) == vtkVariant(d));
  CHECK_EXPRESSION_TRUE(vtkVariant(l) == vtkVariant(str));

  CHECK_EXPRESSION_TRUE(vtkVariant(i64) == vtkVariant(f));
  CHECK_EXPRESSION_TRUE(vtkVariant(i64) == vtkVariant(d));
  CHECK_EXPRESSION_TRUE(vtkVariant(i64) == vtkVariant(str));

  CHECK_EXPRESSION_TRUE(vtkVariant(f) == vtkVariant(d));
  CHECK_EXPRESSION_TRUE(vtkVariant(f) == vtkVariant(str));

  CHECK_EXPRESSION_TRUE(vtkVariant(d) == vtkVariant(str));

  if (errorCount == 0)
    {
    cerr << " Test succeeded.\n";
    }
  else
    {
    cerr << errorCount << " error(s) found!\n";
    }
  overallErrorCount += errorCount;
  errorCount = 0;

  cerr << "Testing vtkVariant as STL map key... ";

  vtksys_stl::map<vtkVariant, vtkStdString> TestMap;

  TestMap[vtkVariant(s)] = "short";
  TestMap[vtkVariant(i)] = "int";
  TestMap[vtkVariant(l)] = "long";
  TestMap[vtkVariant(i64)] = "int64";
  TestMap[vtkVariant(f)] = "float";
  TestMap[vtkVariant(d)] = "double";
  TestMap[vtkVariant(str)] = "string";

  CHECK_EXPRESSION_TRUE(TestMap.find(vtkVariant(100)) != TestMap.end());
  CHECK_EXPRESSION_TRUE(TestMap[vtkVariant(100)] == "string");
  CHECK_EXPRESSION_TRUE(TestMap.size() == 1);

  if (errorCount == 0)
    {
    cerr << " Test succeeded.\n";
    }
  else
    {
    cerr << errorCount << " error(s) found!\n";
    }
  overallErrorCount += errorCount;
  errorCount = 0;

  cerr << "Testing vtkVariant as STL map key with strict weak ordering (fast comparator)...";

  // This one should treat variants containing different types as
  // unequal.
  vtksys_stl::map<vtkVariant, vtkStdString, vtkVariantStrictWeakOrder> TestMap2;
  TestMap2[vtkVariant()] = "invalid";
  TestMap2[vtkVariant(s)] = "short";
  TestMap2[vtkVariant(i)] = "int";
  TestMap2[vtkVariant(l)] = "long";
  TestMap2[vtkVariant(i64)] = "int64";
  TestMap2[vtkVariant(f)] = "float";
  TestMap2[vtkVariant(d)] = "double";
  TestMap2[vtkVariant(str)] = "string";

  CHECK_EXPRESSION_TRUE(TestMap2.find(vtkVariant()) != TestMap2.end());
  CHECK_EXPRESSION_TRUE(TestMap2[vtkVariant()] == "invalid");

  CHECK_EXPRESSION_TRUE(TestMap2.find(vtkVariant(s)) != TestMap2.end());
  CHECK_EXPRESSION_TRUE(TestMap2[vtkVariant(s)] == "short");

  CHECK_EXPRESSION_TRUE(TestMap2.find(vtkVariant(i)) != TestMap2.end());
  CHECK_EXPRESSION_TRUE(TestMap2[vtkVariant(i)] == "int");

  CHECK_EXPRESSION_TRUE(TestMap2.find(vtkVariant(l)) != TestMap2.end());
  CHECK_EXPRESSION_TRUE(TestMap2[vtkVariant(l)] == "long");

  CHECK_EXPRESSION_TRUE(TestMap2.find(vtkVariant(i64)) != TestMap2.end());
  CHECK_EXPRESSION_TRUE(TestMap2[vtkVariant(i64)] == "int64");

  CHECK_EXPRESSION_TRUE(TestMap2.find(vtkVariant(f)) != TestMap2.end());
  CHECK_EXPRESSION_TRUE(TestMap2[vtkVariant(f)] == "float");

  CHECK_EXPRESSION_TRUE(TestMap2.find(vtkVariant(d)) != TestMap2.end());
  CHECK_EXPRESSION_TRUE(TestMap2[vtkVariant(d)] == "double");

  CHECK_EXPRESSION_TRUE(TestMap2.find(vtkVariant(str)) != TestMap2.end());
  CHECK_EXPRESSION_TRUE(TestMap2[vtkVariant("100")] == "string");

  CHECK_EXPRESSION_TRUE(TestMap2.size() == 8);

  if (errorCount == 0)
    {
    cerr << " Test succeeded.\n";
    }
  else
    {
    cerr << errorCount << " error(s) found!\n";
    }
  overallErrorCount += errorCount;
  errorCount = 0;

  if (overallErrorCount == 0)
    {
    cerr << "All tests succeeded.\n";
    }
  else
    {
    cerr << "Some tests failed!  Overall error count: " << overallErrorCount
         << "\n";
    }

  fooObject->Delete();
  return (overallErrorCount > 0);
}
<commit_msg>BUG: Note to self: sizeof(long) may be larger than 4 depending on platform and compiler.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestVariantComparison.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkVariant.h"
#include "vtkObject.h"

#include <vtksys/stl/map>
#include <cstdio>

int
TestVariantComparison(int, char *[])
{
  signed char positiveChar = 100;
  signed char negativeChar = -100;
  short positiveShort = 10000;
  short negativeShort = -10000;
  int positiveInt = 100000;
  int negativeInt = -100000;
  long positiveLong = 1000000;
  long negativeLong = -1000000;

  int shiftAmount64 = 8 * sizeof(vtkTypeInt64) - 2;
  int shiftAmountInt = 8 * sizeof(int) - 2;
  int shiftAmountLong = 8 * sizeof(long) - 2;

  vtkTypeInt64 positive64 = static_cast<vtkTypeInt64>(1) << shiftAmount64;
  vtkTypeInt64 negative64 = -positive64;

  // There is nothing inherently magical about these values.  I just
  // happen to like them and they're outside the range of signed
  // integers.
  unsigned char unsignedChar = 192;
  unsigned short unsignedShort = 49152;
  unsigned int unsignedInt = (static_cast<unsigned int>(1)<<shiftAmountInt) * 3;
  unsigned long unsignedLong = (static_cast<unsigned int>(1)<<shiftAmountLong) * 3;
  vtkTypeUInt64 unsigned64 = 3 * (static_cast<vtkTypeUInt64>(1) << shiftAmount64);

  vtkStdString numberString("100000");
  vtkStdString alphaString("ABCDEFG");

  float positiveFloat = 12345.678;
  float negativeFloat = -12345.678;
  double positiveDouble = 123456789.012345;
  double negativeDouble = -123456789.012345;

  vtkObject *fooObject = vtkObject::New();

  vtkVariant invalidVariant;

  // Now we need variants for all of those
  vtkVariant positiveCharVariant(positiveChar);
  vtkVariant unsignedCharVariant(unsignedChar);
  vtkVariant negativeCharVariant(negativeChar);

  vtkVariant positiveShortVariant(positiveShort);
  vtkVariant unsignedShortVariant(unsignedShort);
  vtkVariant negativeShortVariant(negativeShort);

  vtkVariant positiveIntVariant(positiveInt);
  vtkVariant unsignedIntVariant(unsignedInt);
  vtkVariant negativeIntVariant(negativeInt);

  vtkVariant positiveLongVariant(positiveLong);
  vtkVariant unsignedLongVariant(unsignedLong);
  vtkVariant negativeLongVariant(negativeLong);

  vtkVariant positive64Variant(positive64);
  vtkVariant unsigned64Variant(unsigned64);
  vtkVariant negative64Variant(negative64);

  vtkVariant positiveFloatVariant(positiveFloat);
  vtkVariant negativeFloatVariant(negativeFloat);
  vtkVariant positiveDoubleVariant(positiveDouble);
  vtkVariant negativeDoubleVariant(negativeDouble);

  vtkVariant numberStringVariant(numberString);
  vtkVariant alphaStringVariant(alphaString);

  vtkVariant fooObjectVariant(fooObject);

  int errorCount = 0;
  int overallErrorCount = 0;

#define CHECK_EXPRESSION_FALSE(expr) { if ((expr)) { ++errorCount; cerr << "TEST FAILED: " << #expr << " should have been false\n\n"; } }

#define CHECK_EXPRESSION_TRUE(expr) { if (!(expr)) { ++errorCount; cerr << "TEST FAILED: " << #expr << " should have been true\n\n"; } }

  cerr << "Testing same-type comparisons... ";
  CHECK_EXPRESSION_FALSE(positiveCharVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(unsignedCharVariant < positiveCharVariant);
  CHECK_EXPRESSION_FALSE(unsignedCharVariant < negativeCharVariant);

  CHECK_EXPRESSION_FALSE(positiveShortVariant < negativeShortVariant);
  CHECK_EXPRESSION_FALSE(unsignedShortVariant < positiveShortVariant);
  CHECK_EXPRESSION_FALSE(unsignedShortVariant < negativeShortVariant);

  cerr << "DEBUG: positiveInt " << positiveInt << ", "
       << "negativeInt " << negativeInt << ", "
       << "unsignedInt " << unsignedInt << "\n";

  CHECK_EXPRESSION_FALSE(positiveIntVariant < negativeIntVariant);
  CHECK_EXPRESSION_FALSE(unsignedIntVariant < positiveIntVariant);
  CHECK_EXPRESSION_FALSE(unsignedIntVariant < negativeIntVariant);

  CHECK_EXPRESSION_FALSE(positiveLongVariant < negativeLongVariant);
  CHECK_EXPRESSION_FALSE(unsignedLongVariant < positiveLongVariant);
  CHECK_EXPRESSION_FALSE(unsignedLongVariant < negativeLongVariant);

  CHECK_EXPRESSION_FALSE(positive64Variant < negative64Variant);
  CHECK_EXPRESSION_FALSE(unsigned64Variant < positive64Variant);
  CHECK_EXPRESSION_FALSE(unsigned64Variant < negative64Variant);

  CHECK_EXPRESSION_FALSE(positiveFloat < negativeFloat);
  CHECK_EXPRESSION_FALSE(positiveDouble < negativeDouble);

  CHECK_EXPRESSION_FALSE(alphaString < numberString);

  if (errorCount == 0)
    {
    cerr << "Test succeeded.\n";
    }
  else
    {
    cerr << errorCount << " error(s) found!\n";
    }
  overallErrorCount += errorCount;
  errorCount = 0;

  cerr << "Testing cross-type comparisons... ";

  CHECK_EXPRESSION_FALSE(positiveShortVariant < positiveCharVariant);
  CHECK_EXPRESSION_FALSE(positiveIntVariant < positiveCharVariant);
  CHECK_EXPRESSION_FALSE(positiveLongVariant < positiveCharVariant);
  CHECK_EXPRESSION_FALSE(positive64Variant < positiveCharVariant);

  CHECK_EXPRESSION_FALSE(positiveShortVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(positiveIntVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(positiveLongVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(positive64Variant < negativeCharVariant);

  CHECK_EXPRESSION_FALSE(positiveShortVariant < unsignedCharVariant);
  CHECK_EXPRESSION_FALSE(positiveIntVariant < unsignedCharVariant);
  CHECK_EXPRESSION_FALSE(positiveLongVariant < unsignedCharVariant);
  CHECK_EXPRESSION_FALSE(positive64Variant < unsignedCharVariant);

  CHECK_EXPRESSION_FALSE(negativeCharVariant < negativeShortVariant);
  CHECK_EXPRESSION_FALSE(negativeCharVariant < negativeIntVariant);
  CHECK_EXPRESSION_FALSE(negativeCharVariant < negativeLongVariant);
  CHECK_EXPRESSION_FALSE(negativeCharVariant < negative64Variant);

  CHECK_EXPRESSION_FALSE(unsignedShortVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(unsignedIntVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(unsignedLongVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(unsigned64Variant < negativeCharVariant);

  CHECK_EXPRESSION_FALSE(positiveFloatVariant < positiveCharVariant);
  CHECK_EXPRESSION_FALSE(positiveFloatVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(positiveFloatVariant < unsignedCharVariant);

  CHECK_EXPRESSION_FALSE(positiveDoubleVariant < positiveCharVariant);
  CHECK_EXPRESSION_FALSE(positiveDoubleVariant < negativeCharVariant);
  CHECK_EXPRESSION_FALSE(positiveDoubleVariant < unsignedCharVariant);

  CHECK_EXPRESSION_FALSE(alphaStringVariant < positiveIntVariant);
  CHECK_EXPRESSION_FALSE(numberStringVariant != positiveIntVariant);
  CHECK_EXPRESSION_FALSE(positiveDoubleVariant < fooObjectVariant);
  CHECK_EXPRESSION_FALSE(positiveFloatVariant < invalidVariant);

  if (errorCount == 0)
    {
    cerr << "Test succeeded.\n";
    }
  else
    {
    cerr << errorCount << " error(s) found!\n";
    }
  overallErrorCount += errorCount;
  errorCount = 0;

  cerr << "Testing cross-type equality...";

  char c = 100;
  short s = 100;
  int i = 100;
  long l = 100;
  vtkTypeInt64 i64 = 100;
  float f = 100;
  double d = 100;
  vtkStdString str("100");

  CHECK_EXPRESSION_TRUE(vtkVariant(c) == vtkVariant(s));
  CHECK_EXPRESSION_TRUE(vtkVariant(c) == vtkVariant(i));
  CHECK_EXPRESSION_TRUE(vtkVariant(c) == vtkVariant(l));
  CHECK_EXPRESSION_TRUE(vtkVariant(c) == vtkVariant(i64));
  CHECK_EXPRESSION_TRUE(vtkVariant(c) == vtkVariant(f));
  CHECK_EXPRESSION_TRUE(vtkVariant(c) == vtkVariant(d));

  CHECK_EXPRESSION_TRUE(vtkVariant(s) == vtkVariant(i));
  CHECK_EXPRESSION_TRUE(vtkVariant(s) == vtkVariant(l));
  CHECK_EXPRESSION_TRUE(vtkVariant(s) == vtkVariant(i64));
  CHECK_EXPRESSION_TRUE(vtkVariant(s) == vtkVariant(f));
  CHECK_EXPRESSION_TRUE(vtkVariant(s) == vtkVariant(d));
  CHECK_EXPRESSION_TRUE(vtkVariant(s) == vtkVariant(str));

  CHECK_EXPRESSION_TRUE(vtkVariant(i) == vtkVariant(l));
  CHECK_EXPRESSION_TRUE(vtkVariant(i) == vtkVariant(i64));
  CHECK_EXPRESSION_TRUE(vtkVariant(i) == vtkVariant(f));
  CHECK_EXPRESSION_TRUE(vtkVariant(i) == vtkVariant(d));
  CHECK_EXPRESSION_TRUE(vtkVariant(i) == vtkVariant(str));

  CHECK_EXPRESSION_TRUE(vtkVariant(l) == vtkVariant(i64));
  CHECK_EXPRESSION_TRUE(vtkVariant(l) == vtkVariant(f));
  CHECK_EXPRESSION_TRUE(vtkVariant(l) == vtkVariant(d));
  CHECK_EXPRESSION_TRUE(vtkVariant(l) == vtkVariant(str));

  CHECK_EXPRESSION_TRUE(vtkVariant(i64) == vtkVariant(f));
  CHECK_EXPRESSION_TRUE(vtkVariant(i64) == vtkVariant(d));
  CHECK_EXPRESSION_TRUE(vtkVariant(i64) == vtkVariant(str));

  CHECK_EXPRESSION_TRUE(vtkVariant(f) == vtkVariant(d));
  CHECK_EXPRESSION_TRUE(vtkVariant(f) == vtkVariant(str));

  CHECK_EXPRESSION_TRUE(vtkVariant(d) == vtkVariant(str));

  if (errorCount == 0)
    {
    cerr << " Test succeeded.\n";
    }
  else
    {
    cerr << errorCount << " error(s) found!\n";
    }
  overallErrorCount += errorCount;
  errorCount = 0;

  cerr << "Testing vtkVariant as STL map key... ";

  vtksys_stl::map<vtkVariant, vtkStdString> TestMap;

  TestMap[vtkVariant(s)] = "short";
  TestMap[vtkVariant(i)] = "int";
  TestMap[vtkVariant(l)] = "long";
  TestMap[vtkVariant(i64)] = "int64";
  TestMap[vtkVariant(f)] = "float";
  TestMap[vtkVariant(d)] = "double";
  TestMap[vtkVariant(str)] = "string";

  CHECK_EXPRESSION_TRUE(TestMap.find(vtkVariant(100)) != TestMap.end());
  CHECK_EXPRESSION_TRUE(TestMap[vtkVariant(100)] == "string");
  CHECK_EXPRESSION_TRUE(TestMap.size() == 1);

  if (errorCount == 0)
    {
    cerr << " Test succeeded.\n";
    }
  else
    {
    cerr << errorCount << " error(s) found!\n";
    }
  overallErrorCount += errorCount;
  errorCount = 0;

  cerr << "Testing vtkVariant as STL map key with strict weak ordering (fast comparator)...";

  // This one should treat variants containing different types as
  // unequal.
  vtksys_stl::map<vtkVariant, vtkStdString, vtkVariantStrictWeakOrder> TestMap2;
  TestMap2[vtkVariant()] = "invalid";
  TestMap2[vtkVariant(s)] = "short";
  TestMap2[vtkVariant(i)] = "int";
  TestMap2[vtkVariant(l)] = "long";
  TestMap2[vtkVariant(i64)] = "int64";
  TestMap2[vtkVariant(f)] = "float";
  TestMap2[vtkVariant(d)] = "double";
  TestMap2[vtkVariant(str)] = "string";

  CHECK_EXPRESSION_TRUE(TestMap2.find(vtkVariant()) != TestMap2.end());
  CHECK_EXPRESSION_TRUE(TestMap2[vtkVariant()] == "invalid");

  CHECK_EXPRESSION_TRUE(TestMap2.find(vtkVariant(s)) != TestMap2.end());
  CHECK_EXPRESSION_TRUE(TestMap2[vtkVariant(s)] == "short");

  CHECK_EXPRESSION_TRUE(TestMap2.find(vtkVariant(i)) != TestMap2.end());
  CHECK_EXPRESSION_TRUE(TestMap2[vtkVariant(i)] == "int");

  CHECK_EXPRESSION_TRUE(TestMap2.find(vtkVariant(l)) != TestMap2.end());
  CHECK_EXPRESSION_TRUE(TestMap2[vtkVariant(l)] == "long");

  CHECK_EXPRESSION_TRUE(TestMap2.find(vtkVariant(i64)) != TestMap2.end());
  CHECK_EXPRESSION_TRUE(TestMap2[vtkVariant(i64)] == "int64");

  CHECK_EXPRESSION_TRUE(TestMap2.find(vtkVariant(f)) != TestMap2.end());
  CHECK_EXPRESSION_TRUE(TestMap2[vtkVariant(f)] == "float");

  CHECK_EXPRESSION_TRUE(TestMap2.find(vtkVariant(d)) != TestMap2.end());
  CHECK_EXPRESSION_TRUE(TestMap2[vtkVariant(d)] == "double");

  CHECK_EXPRESSION_TRUE(TestMap2.find(vtkVariant(str)) != TestMap2.end());
  CHECK_EXPRESSION_TRUE(TestMap2[vtkVariant("100")] == "string");

  CHECK_EXPRESSION_TRUE(TestMap2.size() == 8);

  if (errorCount == 0)
    {
    cerr << " Test succeeded.\n";
    }
  else
    {
    cerr << errorCount << " error(s) found!\n";
    }
  overallErrorCount += errorCount;
  errorCount = 0;

  if (overallErrorCount == 0)
    {
    cerr << "All tests succeeded.\n";
    }
  else
    {
    cerr << "Some tests failed!  Overall error count: " << overallErrorCount
         << "\n";
    }

  fooObject->Delete();
  return (overallErrorCount > 0);
}
<|endoftext|>


<commit_before><commit_msg>Remove old migration code, as users should have been migrated by now.<commit_after><|endoftext|>


<commit_before>/*
    kopeteglobal.cpp - Kopete Globals

    Copyright (c) 2004      by Richard Smith         <kde@metafoo.co.uk>

    Kopete    (c) 2004      by the Kopete developers <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This library is free software; you can redistribute it and/or         *
    * modify it under the terms of the GNU Lesser General Public            *
    * License as published by the Free Software Foundation; either          *
    * version 2 of the License, or (at your option) any later version.      *
    *                                                                       *
    *************************************************************************
*/

#include "kopeteglobal.h"
#include "kopeteuiglobal.h"

#include <QtCore/QLatin1String>
#include <QtGui/QApplication>

#include <kdebug.h>
#include <klocale.h>
#include <kio/netaccess.h>
#include <kmimetype.h>
#include <kmessagebox.h>
#include <kprogressdialog.h>

#include <kstandarddirs.h>
#include <ktar.h>
#include <kzip.h>

namespace Kopete
{

namespace Global
{

class PropertiesPrivate
{
	public:
		PropertyTmpl::Map mTemplates;
};

Properties *Properties::mSelf = 0L;

Properties *Properties::self()
{
	if(!mSelf)
	{
		//kDebug(14000) ;
		mSelf = new Properties();
		// create the templates
		mSelf->fullName();
		mSelf->idleTime();
		mSelf->onlineSince();
		mSelf->lastSeen();
		mSelf->statusMessage();
		mSelf->firstName();
		mSelf->lastName();
		mSelf->emailAddress();
		mSelf->privatePhone();
		mSelf->privateMobilePhone();
		mSelf->workPhone();
		mSelf->workMobilePhone();
		mSelf->nickName();
		mSelf->photo();

	}
	return mSelf;
}

Properties::Properties()
{
	kDebug(14000) ;
	d = new PropertiesPrivate();
}

Properties::~Properties()
{
	kDebug(14000) ;
	delete d;
}

const PropertyTmpl &Properties::tmpl(const QString &key) const
{
	if(d->mTemplates.contains(key))
	{
		/*kDebug(14000) <<
			"Found template for key = '" << key << "'" << endl;*/
		return d->mTemplates[key];
	}
	else
		return PropertyTmpl::null;
}

bool Properties::registerTemplate(const QString &key,
	const PropertyTmpl &tmpl)
{
	if(d->mTemplates.contains(key))
	{
		kDebug(14000) <<
			"Called for EXISTING key = '" << key << "'" << endl;
		return false;
	}
	else
	{
		d->mTemplates.insert(key, tmpl);
		return true;
	}
}

void Properties::unregisterTemplate(const QString &key)
{
	kDebug(14000) << "called for key: '" << key << "'";
	d->mTemplates.remove(key);
}

bool Properties::isRegistered(const QString &key)
{
	return d->mTemplates.contains(key);
}

const PropertyTmpl &Properties::fullName() const
{
	return createProp(QLatin1String("FormattedName"),
		i18n("Full Name"));
}

const PropertyTmpl &Properties::idleTime() const
{
	return createProp(QLatin1String("idleTime"),
		i18n("Idle Time"));
}

const PropertyTmpl &Properties::onlineSince() const
{
	return createProp(QLatin1String("onlineSince"),
		i18n("Online Since"));
}

const PropertyTmpl &Properties::lastSeen() const
{
	return createProp(QLatin1String("lastSeen"),
		i18n("Last Seen"), QString(), true);
}

const PropertyTmpl &Properties::statusTitle() const
{
	return createProp(QLatin1String("statusTitle"),
	                  i18n("Status Title"));
}

const PropertyTmpl &Properties::statusMessage() const
{
	return createProp(QLatin1String("statusMessage"),
		i18n("Status Message"));
}

const PropertyTmpl &Properties::firstName() const
{
	return createProp(QLatin1String("firstName"),
		i18n("First Name"), QString(), true);
}

const PropertyTmpl &Properties::lastName() const
{
	return createProp(QLatin1String("lastName"),
		i18n("Last Name"), QString(), true);
}

const PropertyTmpl &Properties::privatePhone() const
{
	return createProp(QLatin1String("privatePhoneNumber"),
		i18n("Private Phone"), QString(), true);
}

const PropertyTmpl &Properties::privateMobilePhone() const
{
	return createProp(QLatin1String("privateMobilePhoneNumber"),
		i18n("Private Mobile Phone"), QString(), true);
}

const PropertyTmpl &Properties::workPhone() const
{
	return createProp(QLatin1String("workPhoneNumber"),
		i18n("Work Phone"), QString(), true);
}

const PropertyTmpl &Properties::workMobilePhone() const
{
	return createProp(QLatin1String("workMobilePhoneNumber"),
		i18n("Work Mobile Phone"), QString(), true);
}

const PropertyTmpl &Properties::emailAddress() const
{
	return createProp(QLatin1String("emailAddress"),
		i18n("Email Address"), QLatin1String("mail"), true);
}

const PropertyTmpl &Properties::nickName() const
{
	return createProp(QLatin1String("nickName"),
		i18n("Nick Name"), QString(), true);
}

const PropertyTmpl &Properties::isAlwaysVisible() const
{
	return createProp(QLatin1String("isAlwaysVisible"),
		i18n("Shown even if offline"), bool(), true);
}

const PropertyTmpl &Properties::photo() const
{
	return createProp(QLatin1String("photo"),
					  i18n("Photo"), QString(), true);
}

const PropertyTmpl &Properties::createProp(const QString &key,
	const QString &label, const QString &icon, bool persistent) const
{
	/*kDebug(14000) <<
		"key = " << key  << ", label = " << label << endl;*/

	if(!d->mTemplates.contains(key))
	{
/*		kDebug(14000) <<
			"CREATING NEW PropertyTmpl WITH key = " << key  <<
			", label = " << label << ", persisten = " << persistent << endl;*/
		d->mTemplates.insert(key,  PropertyTmpl(key, label, icon, persistent ? PropertyTmpl::PersistentProperty : PropertyTmpl::NoProperty));
	}
	return tmpl(key);
}

const PropertyTmpl::Map &Properties::templateMap() const
{
	return d->mTemplates;
}

} // END namespace Global

} // END namespace Kopete

// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>Fix warning<commit_after>/*
    kopeteglobal.cpp - Kopete Globals

    Copyright (c) 2004      by Richard Smith         <kde@metafoo.co.uk>

    Kopete    (c) 2004      by the Kopete developers <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This library is free software; you can redistribute it and/or         *
    * modify it under the terms of the GNU Lesser General Public            *
    * License as published by the Free Software Foundation; either          *
    * version 2 of the License, or (at your option) any later version.      *
    *                                                                       *
    *************************************************************************
*/

#include "kopeteglobal.h"
#include "kopeteuiglobal.h"

#include <QtCore/QLatin1String>
#include <QtGui/QApplication>

#include <kdebug.h>
#include <klocale.h>
#include <kio/netaccess.h>
#include <kmimetype.h>
#include <kmessagebox.h>
#include <kprogressdialog.h>

#include <kstandarddirs.h>
#include <ktar.h>
#include <kzip.h>

namespace Kopete
{

namespace Global
{

class PropertiesPrivate
{
	public:
		PropertyTmpl::Map mTemplates;
};

Properties *Properties::mSelf = 0L;

Properties *Properties::self()
{
	if(!mSelf)
	{
		//kDebug(14000) ;
		mSelf = new Properties();
		// create the templates
		mSelf->fullName();
		mSelf->idleTime();
		mSelf->onlineSince();
		mSelf->lastSeen();
		mSelf->statusMessage();
		mSelf->firstName();
		mSelf->lastName();
		mSelf->emailAddress();
		mSelf->privatePhone();
		mSelf->privateMobilePhone();
		mSelf->workPhone();
		mSelf->workMobilePhone();
		mSelf->nickName();
		mSelf->photo();

	}
	return mSelf;
}

Properties::Properties()
{
	kDebug(14000) ;
	d = new PropertiesPrivate();
}

Properties::~Properties()
{
	kDebug(14000) ;
	delete d;
}

const PropertyTmpl &Properties::tmpl(const QString &key) const
{
	if(d->mTemplates.contains(key))
	{
		/*kDebug(14000) <<
			"Found template for key = '" << key << "'" << endl;*/
		return d->mTemplates[key];
	}
	else
		return PropertyTmpl::null;
}

bool Properties::registerTemplate(const QString &key,
	const PropertyTmpl &tmpl)
{
	if(d->mTemplates.contains(key))
	{
		kDebug(14000) <<
			"Called for EXISTING key = '" << key << "'" << endl;
		return false;
	}
	else
	{
		d->mTemplates.insert(key, tmpl);
		return true;
	}
}

void Properties::unregisterTemplate(const QString &key)
{
	kDebug(14000) << "called for key: '" << key << "'";
	d->mTemplates.remove(key);
}

bool Properties::isRegistered(const QString &key)
{
	return d->mTemplates.contains(key);
}

const PropertyTmpl &Properties::fullName() const
{
	return createProp(QLatin1String("FormattedName"),
		i18n("Full Name"));
}

const PropertyTmpl &Properties::idleTime() const
{
	return createProp(QLatin1String("idleTime"),
		i18n("Idle Time"));
}

const PropertyTmpl &Properties::onlineSince() const
{
	return createProp(QLatin1String("onlineSince"),
		i18n("Online Since"));
}

const PropertyTmpl &Properties::lastSeen() const
{
	return createProp(QLatin1String("lastSeen"),
		i18n("Last Seen"), QString(), true);
}

const PropertyTmpl &Properties::statusTitle() const
{
	return createProp(QLatin1String("statusTitle"),
	                  i18n("Status Title"));
}

const PropertyTmpl &Properties::statusMessage() const
{
	return createProp(QLatin1String("statusMessage"),
		i18n("Status Message"));
}

const PropertyTmpl &Properties::firstName() const
{
	return createProp(QLatin1String("firstName"),
		i18n("First Name"), QString(), true);
}

const PropertyTmpl &Properties::lastName() const
{
	return createProp(QLatin1String("lastName"),
		i18n("Last Name"), QString(), true);
}

const PropertyTmpl &Properties::privatePhone() const
{
	return createProp(QLatin1String("privatePhoneNumber"),
		i18n("Private Phone"), QString(), true);
}

const PropertyTmpl &Properties::privateMobilePhone() const
{
	return createProp(QLatin1String("privateMobilePhoneNumber"),
		i18n("Private Mobile Phone"), QString(), true);
}

const PropertyTmpl &Properties::workPhone() const
{
	return createProp(QLatin1String("workPhoneNumber"),
		i18n("Work Phone"), QString(), true);
}

const PropertyTmpl &Properties::workMobilePhone() const
{
	return createProp(QLatin1String("workMobilePhoneNumber"),
		i18n("Work Mobile Phone"), QString(), true);
}

const PropertyTmpl &Properties::emailAddress() const
{
	return createProp(QLatin1String("emailAddress"),
		i18n("Email Address"), QLatin1String("mail"), true);
}

const PropertyTmpl &Properties::nickName() const
{
	return createProp(QLatin1String("nickName"),
		i18n("Nick Name"), QString(), true);
}

const PropertyTmpl &Properties::isAlwaysVisible() const
{
	return createProp(QLatin1String("isAlwaysVisible"),
		i18n("Shown even if offline"), QString(), true);
}

const PropertyTmpl &Properties::photo() const
{
	return createProp(QLatin1String("photo"),
					  i18n("Photo"), QString(), true);
}

const PropertyTmpl &Properties::createProp(const QString &key,
	const QString &label, const QString &icon, bool persistent) const
{
	/*kDebug(14000) <<
		"key = " << key  << ", label = " << label << endl;*/

	if(!d->mTemplates.contains(key))
	{
/*		kDebug(14000) <<
			"CREATING NEW PropertyTmpl WITH key = " << key  <<
			", label = " << label << ", persisten = " << persistent << endl;*/
		d->mTemplates.insert(key,  PropertyTmpl(key, label, icon, persistent ? PropertyTmpl::PersistentProperty : PropertyTmpl::NoProperty));
	}
	return tmpl(key);
}

const PropertyTmpl::Map &Properties::templateMap() const
{
	return d->mTemplates;
}

} // END namespace Global

} // END namespace Kopete

// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|>


<commit_before>#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

#define VERSION "1.0.0"

enum ArgMode
{
    AM_NONE,
    AM_SOURCE_DIR,
    AM_INTUICIO_PATH,
    AM_JAEGER_PREPROCESSOR_PATH
};

std::string string_replace( const std::string& val, const std::string& oldval, const std::string& newval )
{
    if( val.empty() )
        return val;
    std::string r( val );
    size_t oldlen = oldval.length();
    size_t newlen = newval.length();
    size_t pos = r.find( oldval );
    while( pos != std::string::npos )
    {
        r = r.replace( pos, oldlen, newval );
        pos = r.find( oldval, pos + newlen );
    }
    return r;
}

int main( int argc, char* argv[] )
{
    ArgMode argMode = AM_NONE;
    std::string arg;
    std::vector< std::string > sourceDirs;
    std::string intuicioPath = "intuicio";
    std::string jaegerPreprocessorPath = "I4Jaeger";
    bool profile = false;
    std::vector< std::string > a;
    for( int i = 1; i < argc; ++i )
    {
        arg = argv[i];
        if( argMode == AM_NONE )
        {
            if( arg == "-v" || arg == "--version" )
            {
                std::cout << "Jaeger v" << VERSION << std::endl;
                system( "intuicio -v" );
                return 0;
            }
            else if( arg == "-sd" || arg == "--source-dir" )
                argMode = AM_SOURCE_DIR;
            else if( arg == "-ip" || arg == "--intuicio-path" )
                argMode = AM_INTUICIO_PATH;
            else if( arg == "-jpp" || arg == "--jaeger-preprocessor-path" )
                argMode = AM_JAEGER_PREPROCESSOR_PATH;
            else if( arg == "-p" || arg == "--profile" )
                profile = true;
            else
                a.push_back( arg );
        }
        else if( argMode == AM_SOURCE_DIR )
        {
            sourceDirs.push_back( arg );
            argMode = AM_NONE;
        }
        else if( argMode == AM_INTUICIO_PATH )
        {
            intuicioPath = arg;
            argMode = AM_NONE;
        }
        else if( argMode == AM_JAEGER_PREPROCESSOR_PATH )
        {
            jaegerPreprocessorPath = arg;
            argMode = AM_NONE;
        }
    }
    std::string stdPath = getenv( "JAEGER_STD" );
    if( stdPath.empty() )
    {
        std::cout << "There is no registered JAEGER_STD environment variable that specify Jaeger standard libraries path!" << std::endl;
        return 1;
    }
    #ifdef BUILD_WIN
    intuicioPath = string_replace( intuicioPath, "\\", "\\\\" );
    jaegerPreprocessorPath = string_replace( jaegerPreprocessorPath, "\\", "\\\\" );
    stdPath = string_replace( stdPath, "\\", "\\\\" );
    #endif
    std::stringstream ss;
    ss << intuicioPath;
    for( auto& v : a )
        ss << " " << v;
    ss << ( profile ? " --profile" : "" ) << " -epp " << jaegerPreprocessorPath << ( profile ? " --profile" : "" ) << " -sd \"" << stdPath << "\"";
    for( auto& sd : sourceDirs )
        ss << " -sd \"" << sd << "\"";
    ss << " -- -ep I4Run -mcs 8" << ( profile ? " --profile" : "" );
    #ifdef DEBUG
    std::cout << ss.str() << std::endl;
    #endif
    return system( ss.str().c_str() );
}
<commit_msg>jaeger cli tool - getting jaeger std path from env vars fixed<commit_after>#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

#define VERSION "1.0.0"

enum ArgMode
{
    AM_NONE,
    AM_SOURCE_DIR,
    AM_INTUICIO_PATH,
    AM_JAEGER_PREPROCESSOR_PATH
};

std::string string_replace( const std::string& val, const std::string& oldval, const std::string& newval )
{
    if( val.empty() )
        return val;
    std::string r( val );
    size_t oldlen = oldval.length();
    size_t newlen = newval.length();
    size_t pos = r.find( oldval );
    while( pos != std::string::npos )
    {
        r = r.replace( pos, oldlen, newval );
        pos = r.find( oldval, pos + newlen );
    }
    return r;
}

int main( int argc, char* argv[] )
{
    ArgMode argMode = AM_NONE;
    std::string arg;
    std::vector< std::string > sourceDirs;
    std::string intuicioPath = "intuicio";
    std::string jaegerPreprocessorPath = "I4Jaeger";
    bool profile = false;
    std::vector< std::string > a;
    for( int i = 1; i < argc; ++i )
    {
        arg = argv[i];
        if( argMode == AM_NONE )
        {
            if( arg == "-v" || arg == "--version" )
            {
                std::cout << "Jaeger v" << VERSION << std::endl;
                system( "intuicio -v" );
                return 0;
            }
            else if( arg == "-sd" || arg == "--source-dir" )
                argMode = AM_SOURCE_DIR;
            else if( arg == "-ip" || arg == "--intuicio-path" )
                argMode = AM_INTUICIO_PATH;
            else if( arg == "-jpp" || arg == "--jaeger-preprocessor-path" )
                argMode = AM_JAEGER_PREPROCESSOR_PATH;
            else if( arg == "-p" || arg == "--profile" )
                profile = true;
            else
                a.push_back( arg );
        }
        else if( argMode == AM_SOURCE_DIR )
        {
            sourceDirs.push_back( arg );
            argMode = AM_NONE;
        }
        else if( argMode == AM_INTUICIO_PATH )
        {
            intuicioPath = arg;
            argMode = AM_NONE;
        }
        else if( argMode == AM_JAEGER_PREPROCESSOR_PATH )
        {
            jaegerPreprocessorPath = arg;
            argMode = AM_NONE;
        }
    }
    auto cstdPath = getenv( "JAEGER_STD" );
    std::string stdPath = cstdPath ? cstdPath : "";
    if( stdPath.empty() )
    {
        std::cout << "There is no registered JAEGER_STD environment variable that specify Jaeger standard libraries path!" << std::endl;
        return 1;
    }
    #ifdef BUILD_WIN
    intuicioPath = string_replace( intuicioPath, "\\", "\\\\" );
    jaegerPreprocessorPath = string_replace( jaegerPreprocessorPath, "\\", "\\\\" );
    stdPath = string_replace( stdPath, "\\", "\\\\" );
    #endif
    std::stringstream ss;
    ss << intuicioPath;
    for( auto& v : a )
        ss << " " << v;
    ss << ( profile ? " --profile" : "" ) << " -epp " << jaegerPreprocessorPath << ( profile ? " --profile" : "" ) << " -sd \"" << stdPath << "\"";
    for( auto& sd : sourceDirs )
        ss << " -sd \"" << sd << "\"";
    ss << " -- -ep I4Run -mcs 8" << ( profile ? " --profile" : "" );
    #ifdef DEBUG
    std::cout << ss.str() << std::endl;
    #endif
    return system( ss.str().c_str() );
}
<|endoftext|>


<commit_before>//===-- AMDGPUAsmPrinter.cpp - AMDGPU Assebly printer  --------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
///
/// The AMDGPUAsmPrinter is used to print both assembly string and also binary
/// code.  When passed an MCAsmStreamer it prints assembly and when passed
/// an MCObjectStreamer it outputs binary code.
//
//===----------------------------------------------------------------------===//
//

#include "AMDGPUAsmPrinter.h"
#include "AMDGPU.h"
#include "R600Defines.h"
#include "R600MachineFunctionInfo.h"
#include "R600RegisterInfo.h"
#include "SIDefines.h"
#include "SIMachineFunctionInfo.h"
#include "SIRegisterInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Target/TargetLoweringObjectFile.h"

using namespace llvm;

static AsmPrinter *createAMDGPUAsmPrinterPass(TargetMachine &tm,
                                              MCStreamer &Streamer) {
  return new AMDGPUAsmPrinter(tm, Streamer);
}

extern "C" void LLVMInitializeR600AsmPrinter() {
  TargetRegistry::RegisterAsmPrinter(TheAMDGPUTarget, createAMDGPUAsmPrinterPass);
}

AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
    : AsmPrinter(TM, Streamer) {
  DisasmEnabled = TM.getSubtarget<AMDGPUSubtarget>().dumpCode() &&
                  ! Streamer.hasRawTextSupport();
}

/// We need to override this function so we can avoid
/// the call to EmitFunctionHeader(), which the MCPureStreamer can't handle.
bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
  SetupMachineFunction(MF);

  if (OutStreamer.hasRawTextSupport()) {
    OutStreamer.EmitRawText("@" + MF.getName() + ":");
  }

  MCContext &Context = getObjFileLowering().getContext();
  const MCSectionELF *ConfigSection = Context.getELFSection(".AMDGPU.config",
                                              ELF::SHT_PROGBITS, 0,
                                              SectionKind::getReadOnly());
  OutStreamer.SwitchSection(ConfigSection);

  const AMDGPUSubtarget &STM = TM.getSubtarget<AMDGPUSubtarget>();
  SIProgramInfo KernelInfo;
  if (STM.getGeneration() > AMDGPUSubtarget::NORTHERN_ISLANDS) {
    findNumUsedRegistersSI(MF, KernelInfo.NumSGPR, KernelInfo.NumVGPR);
    EmitProgramInfoSI(MF, KernelInfo);
  } else {
    EmitProgramInfoR600(MF);
  }

  DisasmLines.clear();
  HexLines.clear();
  DisasmLineMaxLen = 0;

  OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
  EmitFunctionBody();

  if (isVerbose() && OutStreamer.hasRawTextSupport()) {
    const MCSectionELF *CommentSection
      = Context.getELFSection(".AMDGPU.csdata",
                              ELF::SHT_PROGBITS, 0,
                              SectionKind::getReadOnly());
    OutStreamer.SwitchSection(CommentSection);

    if (STM.getGeneration() > AMDGPUSubtarget::NORTHERN_ISLANDS) {
      OutStreamer.emitRawComment("Kernel info:", false);
      OutStreamer.emitRawComment("NumSgprs: " + Twine(KernelInfo.NumSGPR),
                                 false);
      OutStreamer.emitRawComment("NumVgprs: " + Twine(KernelInfo.NumVGPR),
                                 false);
    } else {
      R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
      OutStreamer.EmitRawText(
        Twine("SQ_PGM_RESOURCES:STACK_SIZE = " + Twine(MFI->StackSize)));
    }
  }

  if (STM.dumpCode()) {
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
    MF.dump();
#endif

    if (DisasmEnabled) {
      OutStreamer.SwitchSection(Context.getELFSection(".AMDGPU.disasm",
                                                  ELF::SHT_NOTE, 0,
                                                  SectionKind::getReadOnly()));

      for (size_t i = 0; i < DisasmLines.size(); ++i) {
        std::string Comment(DisasmLineMaxLen - DisasmLines[i].size(), ' ');
        Comment += " ; " + HexLines[i] + "\n";

        OutStreamer.EmitBytes(StringRef(DisasmLines[i]));
        OutStreamer.EmitBytes(StringRef(Comment));
      }
    }
  }

  return false;
}

void AMDGPUAsmPrinter::EmitProgramInfoR600(MachineFunction &MF) {
  unsigned MaxGPR = 0;
  bool killPixel = false;
  const R600RegisterInfo * RI =
                static_cast<const R600RegisterInfo*>(TM.getRegisterInfo());
  R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
  const AMDGPUSubtarget &STM = TM.getSubtarget<AMDGPUSubtarget>();

  for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end();
                                                  BB != BB_E; ++BB) {
    MachineBasicBlock &MBB = *BB;
    for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
                                                    I != E; ++I) {
      MachineInstr &MI = *I;
      if (MI.getOpcode() == AMDGPU::KILLGT)
        killPixel = true;
      unsigned numOperands = MI.getNumOperands();
      for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) {
        MachineOperand & MO = MI.getOperand(op_idx);
        if (!MO.isReg())
          continue;
        unsigned HWReg = RI->getEncodingValue(MO.getReg()) & 0xff;

        // Register with value > 127 aren't GPR
        if (HWReg > 127)
          continue;
        MaxGPR = std::max(MaxGPR, HWReg);
      }
    }
  }

  unsigned RsrcReg;
  if (STM.getGeneration() >= AMDGPUSubtarget::EVERGREEN) {
    // Evergreen / Northern Islands
    switch (MFI->ShaderType) {
    default: // Fall through
    case ShaderType::COMPUTE:  RsrcReg = R_0288D4_SQ_PGM_RESOURCES_LS; break;
    case ShaderType::GEOMETRY: RsrcReg = R_028878_SQ_PGM_RESOURCES_GS; break;
    case ShaderType::PIXEL:    RsrcReg = R_028844_SQ_PGM_RESOURCES_PS; break;
    case ShaderType::VERTEX:   RsrcReg = R_028860_SQ_PGM_RESOURCES_VS; break;
    }
  } else {
    // R600 / R700
    switch (MFI->ShaderType) {
    default: // Fall through
    case ShaderType::GEOMETRY: // Fall through
    case ShaderType::COMPUTE:  // Fall through
    case ShaderType::VERTEX:   RsrcReg = R_028868_SQ_PGM_RESOURCES_VS; break;
    case ShaderType::PIXEL:    RsrcReg = R_028850_SQ_PGM_RESOURCES_PS; break;
    }
  }

  OutStreamer.EmitIntValue(RsrcReg, 4);
  OutStreamer.EmitIntValue(S_NUM_GPRS(MaxGPR + 1) |
                           S_STACK_SIZE(MFI->StackSize), 4);
  OutStreamer.EmitIntValue(R_02880C_DB_SHADER_CONTROL, 4);
  OutStreamer.EmitIntValue(S_02880C_KILL_ENABLE(killPixel), 4);

  if (MFI->ShaderType == ShaderType::COMPUTE) {
    OutStreamer.EmitIntValue(R_0288E8_SQ_LDS_ALLOC, 4);
    OutStreamer.EmitIntValue(RoundUpToAlignment(MFI->LDSSize, 4) >> 2, 4);
  }
}

void AMDGPUAsmPrinter::findNumUsedRegistersSI(MachineFunction &MF,
                                              unsigned &NumSGPR,
                                              unsigned &NumVGPR) const {
  unsigned MaxSGPR = 0;
  unsigned MaxVGPR = 0;
  bool VCCUsed = false;
  const SIRegisterInfo * RI =
                static_cast<const SIRegisterInfo*>(TM.getRegisterInfo());

  for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end();
                                                  BB != BB_E; ++BB) {
    MachineBasicBlock &MBB = *BB;
    for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
                                                    I != E; ++I) {
      MachineInstr &MI = *I;

      unsigned numOperands = MI.getNumOperands();
      for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) {
        MachineOperand &MO = MI.getOperand(op_idx);
        unsigned width = 0;
        bool isSGPR = false;

        if (!MO.isReg()) {
          continue;
        }
        unsigned reg = MO.getReg();
        if (reg == AMDGPU::VCC) {
          VCCUsed = true;
          continue;
        }

        switch (reg) {
        default: break;
        case AMDGPU::SCC:
        case AMDGPU::EXEC:
        case AMDGPU::M0:
          continue;
        }

        if (AMDGPU::SReg_32RegClass.contains(reg)) {
          isSGPR = true;
          width = 1;
        } else if (AMDGPU::VReg_32RegClass.contains(reg)) {
          isSGPR = false;
          width = 1;
        } else if (AMDGPU::SReg_64RegClass.contains(reg)) {
          isSGPR = true;
          width = 2;
        } else if (AMDGPU::VReg_64RegClass.contains(reg)) {
          isSGPR = false;
          width = 2;
        } else if (AMDGPU::VReg_96RegClass.contains(reg)) {
          isSGPR = false;
          width = 3;
        } else if (AMDGPU::SReg_128RegClass.contains(reg)) {
          isSGPR = true;
          width = 4;
        } else if (AMDGPU::VReg_128RegClass.contains(reg)) {
          isSGPR = false;
          width = 4;
        } else if (AMDGPU::SReg_256RegClass.contains(reg)) {
          isSGPR = true;
          width = 8;
        } else if (AMDGPU::VReg_256RegClass.contains(reg)) {
          isSGPR = false;
          width = 8;
        } else if (AMDGPU::SReg_512RegClass.contains(reg)) {
          isSGPR = true;
          width = 16;
        } else if (AMDGPU::VReg_512RegClass.contains(reg)) {
          isSGPR = false;
          width = 16;
        } else {
          llvm_unreachable("Unknown register class");
        }
        unsigned hwReg = RI->getEncodingValue(reg) & 0xff;
        unsigned maxUsed = hwReg + width - 1;
        if (isSGPR) {
          MaxSGPR = maxUsed > MaxSGPR ? maxUsed : MaxSGPR;
        } else {
          MaxVGPR = maxUsed > MaxVGPR ? maxUsed : MaxVGPR;
        }
      }
    }
  }

  if (VCCUsed)
    MaxSGPR += 2;

  NumSGPR = MaxSGPR;
  NumVGPR = MaxVGPR;
}

void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &Out,
                                        MachineFunction &MF) const {
  findNumUsedRegistersSI(MF, Out.NumSGPR, Out.NumVGPR);
}

void AMDGPUAsmPrinter::EmitProgramInfoSI(MachineFunction &MF,
                                         const SIProgramInfo &KernelInfo) {
  const AMDGPUSubtarget &STM = TM.getSubtarget<AMDGPUSubtarget>();

  SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
  unsigned RsrcReg;
  switch (MFI->ShaderType) {
  default: // Fall through
  case ShaderType::COMPUTE:  RsrcReg = R_00B848_COMPUTE_PGM_RSRC1; break;
  case ShaderType::GEOMETRY: RsrcReg = R_00B228_SPI_SHADER_PGM_RSRC1_GS; break;
  case ShaderType::PIXEL:    RsrcReg = R_00B028_SPI_SHADER_PGM_RSRC1_PS; break;
  case ShaderType::VERTEX:   RsrcReg = R_00B128_SPI_SHADER_PGM_RSRC1_VS; break;
  }

  OutStreamer.EmitIntValue(RsrcReg, 4);
  OutStreamer.EmitIntValue(S_00B028_VGPRS(KernelInfo.NumVGPR / 4) |
                           S_00B028_SGPRS(KernelInfo.NumSGPR / 8), 4);

  unsigned LDSAlignShift;
  if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) {
    // LDS is allocated in 64 dword blocks
    LDSAlignShift = 8;
  } else {
    // LDS is allocated in 128 dword blocks
    LDSAlignShift = 9;
  }
  unsigned LDSBlocks =
          RoundUpToAlignment(MFI->LDSSize, 1 << LDSAlignShift) >> LDSAlignShift;

  if (MFI->ShaderType == ShaderType::COMPUTE) {
    OutStreamer.EmitIntValue(R_00B84C_COMPUTE_PGM_RSRC2, 4);
    OutStreamer.EmitIntValue(S_00B84C_LDS_SIZE(LDSBlocks), 4);
  }
  if (MFI->ShaderType == ShaderType::PIXEL) {
    OutStreamer.EmitIntValue(R_00B02C_SPI_SHADER_PGM_RSRC2_PS, 4);
    OutStreamer.EmitIntValue(S_00B02C_EXTRA_LDS_SIZE(LDSBlocks), 4);
    OutStreamer.EmitIntValue(R_0286CC_SPI_PS_INPUT_ENA, 4);
    OutStreamer.EmitIntValue(MFI->PSInputAddr, 4);
  }
}
<commit_msg>Add back spaces I missed in the conversion to emitRawComments.<commit_after>//===-- AMDGPUAsmPrinter.cpp - AMDGPU Assebly printer  --------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
///
/// The AMDGPUAsmPrinter is used to print both assembly string and also binary
/// code.  When passed an MCAsmStreamer it prints assembly and when passed
/// an MCObjectStreamer it outputs binary code.
//
//===----------------------------------------------------------------------===//
//

#include "AMDGPUAsmPrinter.h"
#include "AMDGPU.h"
#include "R600Defines.h"
#include "R600MachineFunctionInfo.h"
#include "R600RegisterInfo.h"
#include "SIDefines.h"
#include "SIMachineFunctionInfo.h"
#include "SIRegisterInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Target/TargetLoweringObjectFile.h"

using namespace llvm;

static AsmPrinter *createAMDGPUAsmPrinterPass(TargetMachine &tm,
                                              MCStreamer &Streamer) {
  return new AMDGPUAsmPrinter(tm, Streamer);
}

extern "C" void LLVMInitializeR600AsmPrinter() {
  TargetRegistry::RegisterAsmPrinter(TheAMDGPUTarget, createAMDGPUAsmPrinterPass);
}

AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
    : AsmPrinter(TM, Streamer) {
  DisasmEnabled = TM.getSubtarget<AMDGPUSubtarget>().dumpCode() &&
                  ! Streamer.hasRawTextSupport();
}

/// We need to override this function so we can avoid
/// the call to EmitFunctionHeader(), which the MCPureStreamer can't handle.
bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
  SetupMachineFunction(MF);

  if (OutStreamer.hasRawTextSupport()) {
    OutStreamer.EmitRawText("@" + MF.getName() + ":");
  }

  MCContext &Context = getObjFileLowering().getContext();
  const MCSectionELF *ConfigSection = Context.getELFSection(".AMDGPU.config",
                                              ELF::SHT_PROGBITS, 0,
                                              SectionKind::getReadOnly());
  OutStreamer.SwitchSection(ConfigSection);

  const AMDGPUSubtarget &STM = TM.getSubtarget<AMDGPUSubtarget>();
  SIProgramInfo KernelInfo;
  if (STM.getGeneration() > AMDGPUSubtarget::NORTHERN_ISLANDS) {
    findNumUsedRegistersSI(MF, KernelInfo.NumSGPR, KernelInfo.NumVGPR);
    EmitProgramInfoSI(MF, KernelInfo);
  } else {
    EmitProgramInfoR600(MF);
  }

  DisasmLines.clear();
  HexLines.clear();
  DisasmLineMaxLen = 0;

  OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
  EmitFunctionBody();

  if (isVerbose() && OutStreamer.hasRawTextSupport()) {
    const MCSectionELF *CommentSection
      = Context.getELFSection(".AMDGPU.csdata",
                              ELF::SHT_PROGBITS, 0,
                              SectionKind::getReadOnly());
    OutStreamer.SwitchSection(CommentSection);

    if (STM.getGeneration() > AMDGPUSubtarget::NORTHERN_ISLANDS) {
      OutStreamer.emitRawComment(" Kernel info:", false);
      OutStreamer.emitRawComment(" NumSgprs: " + Twine(KernelInfo.NumSGPR),
                                 false);
      OutStreamer.emitRawComment(" NumVgprs: " + Twine(KernelInfo.NumVGPR),
                                 false);
    } else {
      R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
      OutStreamer.EmitRawText(
        Twine("SQ_PGM_RESOURCES:STACK_SIZE = " + Twine(MFI->StackSize)));
    }
  }

  if (STM.dumpCode()) {
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
    MF.dump();
#endif

    if (DisasmEnabled) {
      OutStreamer.SwitchSection(Context.getELFSection(".AMDGPU.disasm",
                                                  ELF::SHT_NOTE, 0,
                                                  SectionKind::getReadOnly()));

      for (size_t i = 0; i < DisasmLines.size(); ++i) {
        std::string Comment(DisasmLineMaxLen - DisasmLines[i].size(), ' ');
        Comment += " ; " + HexLines[i] + "\n";

        OutStreamer.EmitBytes(StringRef(DisasmLines[i]));
        OutStreamer.EmitBytes(StringRef(Comment));
      }
    }
  }

  return false;
}

void AMDGPUAsmPrinter::EmitProgramInfoR600(MachineFunction &MF) {
  unsigned MaxGPR = 0;
  bool killPixel = false;
  const R600RegisterInfo * RI =
                static_cast<const R600RegisterInfo*>(TM.getRegisterInfo());
  R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
  const AMDGPUSubtarget &STM = TM.getSubtarget<AMDGPUSubtarget>();

  for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end();
                                                  BB != BB_E; ++BB) {
    MachineBasicBlock &MBB = *BB;
    for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
                                                    I != E; ++I) {
      MachineInstr &MI = *I;
      if (MI.getOpcode() == AMDGPU::KILLGT)
        killPixel = true;
      unsigned numOperands = MI.getNumOperands();
      for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) {
        MachineOperand & MO = MI.getOperand(op_idx);
        if (!MO.isReg())
          continue;
        unsigned HWReg = RI->getEncodingValue(MO.getReg()) & 0xff;

        // Register with value > 127 aren't GPR
        if (HWReg > 127)
          continue;
        MaxGPR = std::max(MaxGPR, HWReg);
      }
    }
  }

  unsigned RsrcReg;
  if (STM.getGeneration() >= AMDGPUSubtarget::EVERGREEN) {
    // Evergreen / Northern Islands
    switch (MFI->ShaderType) {
    default: // Fall through
    case ShaderType::COMPUTE:  RsrcReg = R_0288D4_SQ_PGM_RESOURCES_LS; break;
    case ShaderType::GEOMETRY: RsrcReg = R_028878_SQ_PGM_RESOURCES_GS; break;
    case ShaderType::PIXEL:    RsrcReg = R_028844_SQ_PGM_RESOURCES_PS; break;
    case ShaderType::VERTEX:   RsrcReg = R_028860_SQ_PGM_RESOURCES_VS; break;
    }
  } else {
    // R600 / R700
    switch (MFI->ShaderType) {
    default: // Fall through
    case ShaderType::GEOMETRY: // Fall through
    case ShaderType::COMPUTE:  // Fall through
    case ShaderType::VERTEX:   RsrcReg = R_028868_SQ_PGM_RESOURCES_VS; break;
    case ShaderType::PIXEL:    RsrcReg = R_028850_SQ_PGM_RESOURCES_PS; break;
    }
  }

  OutStreamer.EmitIntValue(RsrcReg, 4);
  OutStreamer.EmitIntValue(S_NUM_GPRS(MaxGPR + 1) |
                           S_STACK_SIZE(MFI->StackSize), 4);
  OutStreamer.EmitIntValue(R_02880C_DB_SHADER_CONTROL, 4);
  OutStreamer.EmitIntValue(S_02880C_KILL_ENABLE(killPixel), 4);

  if (MFI->ShaderType == ShaderType::COMPUTE) {
    OutStreamer.EmitIntValue(R_0288E8_SQ_LDS_ALLOC, 4);
    OutStreamer.EmitIntValue(RoundUpToAlignment(MFI->LDSSize, 4) >> 2, 4);
  }
}

void AMDGPUAsmPrinter::findNumUsedRegistersSI(MachineFunction &MF,
                                              unsigned &NumSGPR,
                                              unsigned &NumVGPR) const {
  unsigned MaxSGPR = 0;
  unsigned MaxVGPR = 0;
  bool VCCUsed = false;
  const SIRegisterInfo * RI =
                static_cast<const SIRegisterInfo*>(TM.getRegisterInfo());

  for (MachineFunction::iterator BB = MF.begin(), BB_E = MF.end();
                                                  BB != BB_E; ++BB) {
    MachineBasicBlock &MBB = *BB;
    for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
                                                    I != E; ++I) {
      MachineInstr &MI = *I;

      unsigned numOperands = MI.getNumOperands();
      for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) {
        MachineOperand &MO = MI.getOperand(op_idx);
        unsigned width = 0;
        bool isSGPR = false;

        if (!MO.isReg()) {
          continue;
        }
        unsigned reg = MO.getReg();
        if (reg == AMDGPU::VCC) {
          VCCUsed = true;
          continue;
        }

        switch (reg) {
        default: break;
        case AMDGPU::SCC:
        case AMDGPU::EXEC:
        case AMDGPU::M0:
          continue;
        }

        if (AMDGPU::SReg_32RegClass.contains(reg)) {
          isSGPR = true;
          width = 1;
        } else if (AMDGPU::VReg_32RegClass.contains(reg)) {
          isSGPR = false;
          width = 1;
        } else if (AMDGPU::SReg_64RegClass.contains(reg)) {
          isSGPR = true;
          width = 2;
        } else if (AMDGPU::VReg_64RegClass.contains(reg)) {
          isSGPR = false;
          width = 2;
        } else if (AMDGPU::VReg_96RegClass.contains(reg)) {
          isSGPR = false;
          width = 3;
        } else if (AMDGPU::SReg_128RegClass.contains(reg)) {
          isSGPR = true;
          width = 4;
        } else if (AMDGPU::VReg_128RegClass.contains(reg)) {
          isSGPR = false;
          width = 4;
        } else if (AMDGPU::SReg_256RegClass.contains(reg)) {
          isSGPR = true;
          width = 8;
        } else if (AMDGPU::VReg_256RegClass.contains(reg)) {
          isSGPR = false;
          width = 8;
        } else if (AMDGPU::SReg_512RegClass.contains(reg)) {
          isSGPR = true;
          width = 16;
        } else if (AMDGPU::VReg_512RegClass.contains(reg)) {
          isSGPR = false;
          width = 16;
        } else {
          llvm_unreachable("Unknown register class");
        }
        unsigned hwReg = RI->getEncodingValue(reg) & 0xff;
        unsigned maxUsed = hwReg + width - 1;
        if (isSGPR) {
          MaxSGPR = maxUsed > MaxSGPR ? maxUsed : MaxSGPR;
        } else {
          MaxVGPR = maxUsed > MaxVGPR ? maxUsed : MaxVGPR;
        }
      }
    }
  }

  if (VCCUsed)
    MaxSGPR += 2;

  NumSGPR = MaxSGPR;
  NumVGPR = MaxVGPR;
}

void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &Out,
                                        MachineFunction &MF) const {
  findNumUsedRegistersSI(MF, Out.NumSGPR, Out.NumVGPR);
}

void AMDGPUAsmPrinter::EmitProgramInfoSI(MachineFunction &MF,
                                         const SIProgramInfo &KernelInfo) {
  const AMDGPUSubtarget &STM = TM.getSubtarget<AMDGPUSubtarget>();

  SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
  unsigned RsrcReg;
  switch (MFI->ShaderType) {
  default: // Fall through
  case ShaderType::COMPUTE:  RsrcReg = R_00B848_COMPUTE_PGM_RSRC1; break;
  case ShaderType::GEOMETRY: RsrcReg = R_00B228_SPI_SHADER_PGM_RSRC1_GS; break;
  case ShaderType::PIXEL:    RsrcReg = R_00B028_SPI_SHADER_PGM_RSRC1_PS; break;
  case ShaderType::VERTEX:   RsrcReg = R_00B128_SPI_SHADER_PGM_RSRC1_VS; break;
  }

  OutStreamer.EmitIntValue(RsrcReg, 4);
  OutStreamer.EmitIntValue(S_00B028_VGPRS(KernelInfo.NumVGPR / 4) |
                           S_00B028_SGPRS(KernelInfo.NumSGPR / 8), 4);

  unsigned LDSAlignShift;
  if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) {
    // LDS is allocated in 64 dword blocks
    LDSAlignShift = 8;
  } else {
    // LDS is allocated in 128 dword blocks
    LDSAlignShift = 9;
  }
  unsigned LDSBlocks =
          RoundUpToAlignment(MFI->LDSSize, 1 << LDSAlignShift) >> LDSAlignShift;

  if (MFI->ShaderType == ShaderType::COMPUTE) {
    OutStreamer.EmitIntValue(R_00B84C_COMPUTE_PGM_RSRC2, 4);
    OutStreamer.EmitIntValue(S_00B84C_LDS_SIZE(LDSBlocks), 4);
  }
  if (MFI->ShaderType == ShaderType::PIXEL) {
    OutStreamer.EmitIntValue(R_00B02C_SPI_SHADER_PGM_RSRC2_PS, 4);
    OutStreamer.EmitIntValue(S_00B02C_EXTRA_LDS_SIZE(LDSBlocks), 4);
    OutStreamer.EmitIntValue(R_0286CC_SPI_PS_INPUT_ENA, 4);
    OutStreamer.EmitIntValue(MFI->PSInputAddr, 4);
  }
}
<|endoftext|>


<commit_before>#include <qfile.h>
#include <qdir.h>

#include <kglobal.h>
#include <ksimpleconfig.h>
#include <kstddirs.h>
#include <knotifyclient.h>
#include <klocale.h>
#include <kurl.h>
#include <kdebug.h>

#include <plugin.h>
#include <pluginloader.h>
#include <kopete.h>
#include <kparts/componentfactory.h>
class KopeteLibraryInfo;

bool operator ==(const KopeteLibraryInfo &a, const KopeteLibraryInfo &b)
{
	// Feels like cheating, doesn't it?
	return a.specfile == b.specfile;
}

LibraryLoader::LibraryLoader()
{
}

LibraryLoader::~LibraryLoader()
{
	QValueList<KopeteLibraryInfo> l;

	l = loaded();
	for(QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)
	{
		if((*i).type != "protocol" && (*i).type != "ui" && (*i).type != "dock")
		{
			removeNow((*i).specfile);
		}
	}
	/*
	l = loaded();
	for(QValueList<NoatunLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)
	{
		if((*i).type == "userinterface")
		{
			removeNow((*i).specfile);
		}
	}
	*/
	l = loaded();
	for(QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)
	{
		removeNow((*i).specfile);
	}
}

QValueList<KopeteLibraryInfo> LibraryLoader::available() const
{
	QValueList<KopeteLibraryInfo> items;
	QStringList files=KGlobal::dirs()->findAllResources("appdata", "*.plugin", false, true);
	for (QStringList::Iterator i=files.begin(); i!=files.end(); ++i)
		items.append(getInfo(*i));

	return items;
}

QList<Plugin> LibraryLoader::plugins() const
{
	QList<Plugin> list;
	for (QDictIterator<LibraryLoader::PluginLibrary> i(mLibHash); i.current(); ++i)
		list.append(i.current()->plugin);
	return list;
}

bool LibraryLoader::loadAll(void)
{
	KConfig *config=KGlobal::config();
	config->setGroup("");
	QStringList modules = config->readListEntry("Modules");
	return loadAll(modules);
}

bool LibraryLoader::loadAll(const QStringList &modules)
{
	// Session management...
/*
	for(QStringList::ConstIterator i=modules.begin(); i!=modules.end(); ++i)
	{
		KopeteLibraryInfo info=getInfo(*i);
		if (!info.type.contains("sm"))
			continue;
		loadSO(*i);
	}
*/
	// load all the protocols in the first
	for(QStringList::ConstIterator i=modules.begin(); i!=modules.end(); ++i)
	{
		KopeteLibraryInfo info=getInfo(*i);
		if (!info.type.contains("protocol"))
			continue;

		if ( !loadSO(*i) )
			kdDebug() << "[LibraryLoader] loading " << (*i) << " failed!" << endl;
	}

	// load all misc plugins
	for(QStringList::ConstIterator i=modules.begin(); i!=modules.end(); ++i)
	{
		KopeteLibraryInfo info=getInfo(*i);
		if (!info.type.contains("other"))
			continue;

		if ( !loadSO(*i) )
			kdDebug() << "[LibraryLoader] loading " << (*i) << " failed!" << endl;
	}

	return true;
}

KopeteLibraryInfo LibraryLoader::getInfo(const QString &spec) const
{
	KopeteLibraryInfo info;
	QString specPath = (spec[0]=='/') ? spec : KGlobal::dirs()->findResource("appdata", spec);
	if (!QFile::exists(specPath))
		return info;
	KSimpleConfig file(specPath);
	if (spec.find('/')>=0)
		info.specfile=KURL(spec).fileName();
	else
		info.specfile=spec;
	info.filename=file.readEntry("Filename");
	info.author=file.readEntry("Author");
	info.site=file.readEntry("Site");
	info.email=file.readEntry("Email");
	info.type=file.readEntry("Type");
	info.name=file.readEntry("Name");
	info.comment=file.readEntry("Comment");
	info.require=file.readListEntry("Require");
	info.license=file.readEntry("License");
	return info;
}

bool LibraryLoader::isLoaded(const QString &spec) const
{
	PluginLibrary *lib=mLibHash[spec];
	if (!lib) return false;
	return lib->plugin;
}

bool LibraryLoader::loadSO(const QString &spec)
{
	if( !isLoaded(spec) )
	{
		KopeteLibraryInfo info = getInfo(spec);
		if (info.specfile != spec)
			return false;

		for (QStringList::ConstIterator it = info.require.begin(); it != info.require.end(); ++it)
			loadSO(*it);

		// get the library loader instance
		KLibLoader *loader = KLibLoader::self();

		PluginLibrary *listitem=mLibHash[spec];

		if (!listitem)
		{
			KLibrary *lib = loader->library( QFile::encodeName(info.filename) );
			if (!lib)
			{
				kdDebug() << "[LibraryLoader] loadSO(), error while loading library: " << loader->lastErrorMessage() << endl;
				return false;
			}
			listitem = new PluginLibrary;
			listitem->library = lib;
			mLibHash.insert(spec, listitem);
		}

#if KDE_VERSION < 305
		// This code works with KDE 3.0.x, but will generate a warning on
		// stderr if the symbol is not found. For later KDE versions use
		// the new hasSymbol() method instead
		if( listitem->library->symbol( "create_plugin" ) == 0 &&
			listitem->library->factory() )
#else
		if( !listitem->library->hasSymbol( "create_plugin" ) &&
			listitem->library->factory() )
#endif
		{
			listitem->plugin =
				KParts::ComponentFactory::createInstanceFromFactory<Plugin>
				( listitem->library->factory(), 0L /* FIXME: parent object */ );
		}
		else
		{
			kdDebug() << "LibraryLoader::loadSO old plugin" << endl;
			void *create = listitem->library->symbol("create_plugin");
			Plugin* (*plugInStart)();
			plugInStart = (Plugin* (*)()) create;
			listitem->plugin = plugInStart();
		}

		// Automatically load the i18n catalogue for the plugin
		KGlobal::locale()->insertCatalogue( info.filename );

		listitem->plugin->init();
		kdDebug() << "[LibraryLoader] loadSO(), loading " << spec << " successful"<< endl;
		return true;
	}
	else
	{
		kdDebug() << "[LibraryLoader] loadSO(), " << spec << " is already loaded!" << endl;
		return false;
	}
}

void LibraryLoader::add(const QString &spec)
{
	PluginLibrary *lib=mLibHash[spec];
	if (lib)
		if (lib->plugin) return;

	loadSO(spec);
}

void LibraryLoader::setModules(const QStringList &mods)
{
	KConfig *config=KGlobal::config();
	config->setGroup("");
	config->writeEntry("Modules", mods);
	KGlobal::config()->sync();
}

bool LibraryLoader::remove(const QString &spec)
{
	removeNow(spec);

	// exit if this is the last UI
	/*
	if (getInfo(spec).type=="userinterface")
	{
		QValueList<NoatunLibraryInfo> l=loaded();
		bool isanotherui=false;
		for (QValueList<NoatunLibraryInfo>::Iterator i=l.begin(); i!=l.end(); ++i)
		{
			if ((*i).specfile!=spec && (*i).type=="userinterface")
				isanotherui=true;
		}
		if (!isanotherui)
			kapp->exit();
	}
  */
	return true;
}

bool LibraryLoader::remove(const PluginLibrary *pl)
{
	for (QDictIterator<PluginLibrary> i(mLibHash); i.current(); ++i)
	{
		if (i.current()==pl)
			return remove(i.currentKey());
	}
	return false;
}

bool LibraryLoader::remove(const Plugin *plugin)
{
	for (QDictIterator<PluginLibrary> i(mLibHash); i.current(); ++i)
	{
		if (i.current()->plugin==plugin)
			return remove(i.currentKey());
	}
	return false;

}

/*
Playlist *LibraryLoader::playlist() const
{
        return mPlaylist;
}
*/

QValueList<KopeteLibraryInfo> LibraryLoader::loaded() const
{
	QValueList<KopeteLibraryInfo> items;

	for (QDictIterator<PluginLibrary> i(mLibHash); i.current(); ++i)
		if (isLoaded(i.currentKey()))
			items.append(getInfo(i.currentKey()));

	return items;
}

void LibraryLoader::removeNow(const QString &spec)
{
	KopeteLibraryInfo info = getInfo(spec);
	if (info.specfile == spec)
	{
		QValueList<KopeteLibraryInfo> l = loaded();
		for (QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)
		{
			for (QStringList::ConstIterator it = (*i).require.begin(); it != (*i).require.end(); ++it)
				if (*it == spec)
				removeNow((*i).specfile);
		}
	}

	PluginLibrary *lib=mLibHash[spec];

	if (!lib)
		return;

	// Added by Duncan 20/01/2002
	// We need to call unload function for the plugin
	lib->plugin->unload();

	delete lib->plugin;
	lib->plugin=0;

	mLibHash.remove(spec);
//	delete lib->library;
//	delete lib;
}

Plugin* LibraryLoader::searchByID( QString &Id )
{
	QValueList<KopeteLibraryInfo> l = loaded();

	for (QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)
	{
		kdDebug() << "[Kopete] slotSetAwayAll() for plugin: " << (*i).name << endl;
		Plugin *tmp_plug = mLibHash[(*i).specfile]->plugin;
		if ( tmp_plug->id() == Id )
		{
			return tmp_plug;
		}
	}
	return NULL;
}

<commit_msg>Removed an wrong kdDebug<commit_after>#include <qfile.h>
#include <qdir.h>

#include <kglobal.h>
#include <ksimpleconfig.h>
#include <kstddirs.h>
#include <knotifyclient.h>
#include <klocale.h>
#include <kurl.h>
#include <kdebug.h>

#include <plugin.h>
#include <pluginloader.h>
#include <kopete.h>
#include <kparts/componentfactory.h>
class KopeteLibraryInfo;

bool operator ==(const KopeteLibraryInfo &a, const KopeteLibraryInfo &b)
{
	// Feels like cheating, doesn't it?
	return a.specfile == b.specfile;
}

LibraryLoader::LibraryLoader()
{
}

LibraryLoader::~LibraryLoader()
{
	QValueList<KopeteLibraryInfo> l;

	l = loaded();
	for(QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)
	{
		if((*i).type != "protocol" && (*i).type != "ui" && (*i).type != "dock")
		{
			removeNow((*i).specfile);
		}
	}
	/*
	l = loaded();
	for(QValueList<NoatunLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)
	{
		if((*i).type == "userinterface")
		{
			removeNow((*i).specfile);
		}
	}
	*/
	l = loaded();
	for(QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)
	{
		removeNow((*i).specfile);
	}
}

QValueList<KopeteLibraryInfo> LibraryLoader::available() const
{
	QValueList<KopeteLibraryInfo> items;
	QStringList files=KGlobal::dirs()->findAllResources("appdata", "*.plugin", false, true);
	for (QStringList::Iterator i=files.begin(); i!=files.end(); ++i)
		items.append(getInfo(*i));

	return items;
}

QList<Plugin> LibraryLoader::plugins() const
{
	QList<Plugin> list;
	for (QDictIterator<LibraryLoader::PluginLibrary> i(mLibHash); i.current(); ++i)
		list.append(i.current()->plugin);
	return list;
}

bool LibraryLoader::loadAll(void)
{
	KConfig *config=KGlobal::config();
	config->setGroup("");
	QStringList modules = config->readListEntry("Modules");
	return loadAll(modules);
}

bool LibraryLoader::loadAll(const QStringList &modules)
{
	// Session management...
/*
	for(QStringList::ConstIterator i=modules.begin(); i!=modules.end(); ++i)
	{
		KopeteLibraryInfo info=getInfo(*i);
		if (!info.type.contains("sm"))
			continue;
		loadSO(*i);
	}
*/
	// load all the protocols in the first
	for(QStringList::ConstIterator i=modules.begin(); i!=modules.end(); ++i)
	{
		KopeteLibraryInfo info=getInfo(*i);
		if (!info.type.contains("protocol"))
			continue;

		if ( !loadSO(*i) )
			kdDebug() << "[LibraryLoader] loading " << (*i) << " failed!" << endl;
	}

	// load all misc plugins
	for(QStringList::ConstIterator i=modules.begin(); i!=modules.end(); ++i)
	{
		KopeteLibraryInfo info=getInfo(*i);
		if (!info.type.contains("other"))
			continue;

		if ( !loadSO(*i) )
			kdDebug() << "[LibraryLoader] loading " << (*i) << " failed!" << endl;
	}

	return true;
}

KopeteLibraryInfo LibraryLoader::getInfo(const QString &spec) const
{
	KopeteLibraryInfo info;
	QString specPath = (spec[0]=='/') ? spec : KGlobal::dirs()->findResource("appdata", spec);
	if (!QFile::exists(specPath))
		return info;
	KSimpleConfig file(specPath);
	if (spec.find('/')>=0)
		info.specfile=KURL(spec).fileName();
	else
		info.specfile=spec;
	info.filename=file.readEntry("Filename");
	info.author=file.readEntry("Author");
	info.site=file.readEntry("Site");
	info.email=file.readEntry("Email");
	info.type=file.readEntry("Type");
	info.name=file.readEntry("Name");
	info.comment=file.readEntry("Comment");
	info.require=file.readListEntry("Require");
	info.license=file.readEntry("License");
	return info;
}

bool LibraryLoader::isLoaded(const QString &spec) const
{
	PluginLibrary *lib=mLibHash[spec];
	if (!lib) return false;
	return lib->plugin;
}

bool LibraryLoader::loadSO(const QString &spec)
{
	if( !isLoaded(spec) )
	{
		KopeteLibraryInfo info = getInfo(spec);
		if (info.specfile != spec)
			return false;

		for (QStringList::ConstIterator it = info.require.begin(); it != info.require.end(); ++it)
			loadSO(*it);

		// get the library loader instance
		KLibLoader *loader = KLibLoader::self();

		PluginLibrary *listitem=mLibHash[spec];

		if (!listitem)
		{
			KLibrary *lib = loader->library( QFile::encodeName(info.filename) );
			if (!lib)
			{
				kdDebug() << "[LibraryLoader] loadSO(), error while loading library: " << loader->lastErrorMessage() << endl;
				return false;
			}
			listitem = new PluginLibrary;
			listitem->library = lib;
			mLibHash.insert(spec, listitem);
		}

#if KDE_VERSION < 305
		// This code works with KDE 3.0.x, but will generate a warning on
		// stderr if the symbol is not found. For later KDE versions use
		// the new hasSymbol() method instead
		if( listitem->library->symbol( "create_plugin" ) == 0 &&
			listitem->library->factory() )
#else
		if( !listitem->library->hasSymbol( "create_plugin" ) &&
			listitem->library->factory() )
#endif
		{
			listitem->plugin =
				KParts::ComponentFactory::createInstanceFromFactory<Plugin>
				( listitem->library->factory(), 0L /* FIXME: parent object */ );
		}
		else
		{
			kdDebug() << "LibraryLoader::loadSO old plugin" << endl;
			void *create = listitem->library->symbol("create_plugin");
			Plugin* (*plugInStart)();
			plugInStart = (Plugin* (*)()) create;
			listitem->plugin = plugInStart();
		}

		// Automatically load the i18n catalogue for the plugin
		KGlobal::locale()->insertCatalogue( info.filename );

		listitem->plugin->init();
		kdDebug() << "[LibraryLoader] loadSO(), loading " << spec << " successful"<< endl;
		return true;
	}
	else
	{
		kdDebug() << "[LibraryLoader] loadSO(), " << spec << " is already loaded!" << endl;
		return false;
	}
}

void LibraryLoader::add(const QString &spec)
{
	PluginLibrary *lib=mLibHash[spec];
	if (lib)
		if (lib->plugin) return;

	loadSO(spec);
}

void LibraryLoader::setModules(const QStringList &mods)
{
	KConfig *config=KGlobal::config();
	config->setGroup("");
	config->writeEntry("Modules", mods);
	KGlobal::config()->sync();
}

bool LibraryLoader::remove(const QString &spec)
{
	removeNow(spec);

	// exit if this is the last UI
	/*
	if (getInfo(spec).type=="userinterface")
	{
		QValueList<NoatunLibraryInfo> l=loaded();
		bool isanotherui=false;
		for (QValueList<NoatunLibraryInfo>::Iterator i=l.begin(); i!=l.end(); ++i)
		{
			if ((*i).specfile!=spec && (*i).type=="userinterface")
				isanotherui=true;
		}
		if (!isanotherui)
			kapp->exit();
	}
  */
	return true;
}

bool LibraryLoader::remove(const PluginLibrary *pl)
{
	for (QDictIterator<PluginLibrary> i(mLibHash); i.current(); ++i)
	{
		if (i.current()==pl)
			return remove(i.currentKey());
	}
	return false;
}

bool LibraryLoader::remove(const Plugin *plugin)
{
	for (QDictIterator<PluginLibrary> i(mLibHash); i.current(); ++i)
	{
		if (i.current()->plugin==plugin)
			return remove(i.currentKey());
	}
	return false;

}

/*
Playlist *LibraryLoader::playlist() const
{
        return mPlaylist;
}
*/

QValueList<KopeteLibraryInfo> LibraryLoader::loaded() const
{
	QValueList<KopeteLibraryInfo> items;

	for (QDictIterator<PluginLibrary> i(mLibHash); i.current(); ++i)
		if (isLoaded(i.currentKey()))
			items.append(getInfo(i.currentKey()));

	return items;
}

void LibraryLoader::removeNow(const QString &spec)
{
	KopeteLibraryInfo info = getInfo(spec);
	if (info.specfile == spec)
	{
		QValueList<KopeteLibraryInfo> l = loaded();
		for (QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)
		{
			for (QStringList::ConstIterator it = (*i).require.begin(); it != (*i).require.end(); ++it)
				if (*it == spec)
				removeNow((*i).specfile);
		}
	}

	PluginLibrary *lib=mLibHash[spec];

	if (!lib)
		return;

	// Added by Duncan 20/01/2002
	// We need to call unload function for the plugin
	lib->plugin->unload();

	delete lib->plugin;
	lib->plugin=0;

	mLibHash.remove(spec);
//	delete lib->library;
//	delete lib;
}

Plugin* LibraryLoader::searchByID( QString &Id )
{
	QValueList<KopeteLibraryInfo> l = loaded();

	for (QValueList<KopeteLibraryInfo>::Iterator i = l.begin(); i != l.end(); ++i)
	{
		Plugin *tmp_plug = mLibHash[(*i).specfile]->plugin;
		if ( tmp_plug->id() == Id )
		{
			return tmp_plug;
		}
	}
	return NULL;
}

<|endoftext|>