blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
e7dd87df73befa2ddd1873d40d3dbabb0c73472c
0b5c6d6576e0313f55146b9fba4728de29da29f9
/fuzz/FuzzCanvas.cpp
7cfcc132d54fcef44a9c494e975b6b094ee32aa4
[ "BSD-3-Clause" ]
permissive
hoangpq/skia
948f29ac8d834c5ab466e0fb3ecdc53dc1abaacc
a2b1ed5e9d2852bad5d8e1bddc299e920e73d6e0
refs/heads/master
2020-03-11T19:13:14.066759
2018-04-19T08:38:18
2018-04-19T09:16:13
130,200,668
1
0
null
2018-04-19T10:42:12
2018-04-19T10:42:12
null
UTF-8
C++
false
false
71,597
cpp
/* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Fuzz.h" #include "FuzzCommon.h" // CORE #include "SkCanvas.h" #include "SkColorFilter.h" #include "SkDebugCanvas.h" #include "SkDocument.h" #include "SkFontMgr.h" #include "SkImageFilter.h" #include "SkMaskFilter.h" #include "SkNullCanvas.h" #include "SkPathEffect.h" #include "SkPictureRecorder.h" #include "SkPoint3.h" #include "SkRSXform.h" #include "SkRegion.h" #include "SkSurface.h" #include "SkTypeface.h" #include "SkOSFile.h" // EFFECTS #include "Sk1DPathEffect.h" #include "Sk2DPathEffect.h" #include "SkAlphaThresholdFilter.h" #include "SkArithmeticImageFilter.h" #include "SkBlurImageFilter.h" #include "SkBlurMaskFilter.h" #include "SkColorFilterImageFilter.h" #include "SkColorMatrixFilter.h" #include "SkComposeImageFilter.h" #include "SkCornerPathEffect.h" #include "SkDashPathEffect.h" #include "SkDiscretePathEffect.h" #include "SkDisplacementMapEffect.h" #include "SkDropShadowImageFilter.h" #include "SkGradientShader.h" #include "SkHighContrastFilter.h" #include "SkImageSource.h" #include "SkLightingImageFilter.h" #include "SkLumaColorFilter.h" #include "SkMagnifierImageFilter.h" #include "SkMatrixConvolutionImageFilter.h" #include "SkMergeImageFilter.h" #include "SkMorphologyImageFilter.h" #include "SkOffsetImageFilter.h" #include "SkPaintImageFilter.h" #include "SkPerlinNoiseShader.h" #include "SkPictureImageFilter.h" #include "SkReadBuffer.h" #include "SkRRectsGaussianEdgeMaskFilter.h" #include "SkTableColorFilter.h" #include "SkTextBlob.h" #include "SkTileImageFilter.h" #include "SkXfermodeImageFilter.h" // SRC #include "SkUtils.h" #if SK_SUPPORT_GPU #include "GrContextFactory.h" #endif // MISC #include <iostream> // TODO: // SkTextBlob with Unicode // SkImage: more types // be careful: `foo(make_fuzz_t<T>(f), make_fuzz_t<U>(f))` is undefined. // In fact, all make_fuzz_foo() functions have this potential problem. // Use sequence points! template <typename T> inline T make_fuzz_t(Fuzz* fuzz) { T t; fuzz->next(&t); return t; } template <> inline void Fuzz::next(SkShader::TileMode* m) { fuzz_enum_range(this, m, 0, SkShader::kTileModeCount - 1); } template <> inline void Fuzz::next(SkFilterQuality* q) { fuzz_enum_range(this, q, SkFilterQuality::kNone_SkFilterQuality, SkFilterQuality::kLast_SkFilterQuality); } template <> inline void Fuzz::next(SkMatrix* m) { constexpr int kArrayLength = 9; SkScalar buffer[kArrayLength]; int matrixType; this->nextRange(&matrixType, 0, 4); switch (matrixType) { case 0: // identity *m = SkMatrix::I(); return; case 1: // translate this->nextRange(&buffer[0], -4000.0f, 4000.0f); this->nextRange(&buffer[1], -4000.0f, 4000.0f); *m = SkMatrix::MakeTrans(buffer[0], buffer[1]); return; case 2: // translate + scale this->nextRange(&buffer[0], -400.0f, 400.0f); this->nextRange(&buffer[1], -400.0f, 400.0f); this->nextRange(&buffer[2], -4000.0f, 4000.0f); this->nextRange(&buffer[3], -4000.0f, 4000.0f); *m = SkMatrix::MakeScale(buffer[0], buffer[1]); m->postTranslate(buffer[2], buffer[3]); return; case 3: // affine this->nextN(buffer, 6); m->setAffine(buffer); return; case 4: // perspective this->nextN(buffer, kArrayLength); m->set9(buffer); return; default: SkASSERT(false); return; } } template <> inline void Fuzz::next(SkRRect* rr) { SkRect r; SkVector radii[4]; this->next(&r); r.sort(); for (SkVector& vec : radii) { this->nextRange(&vec.fX, 0.0f, 1.0f); vec.fX *= 0.5f * r.width(); this->nextRange(&vec.fY, 0.0f, 1.0f); vec.fY *= 0.5f * r.height(); } rr->setRectRadii(r, radii); } template <> inline void Fuzz::next(SkBlendMode* mode) { fuzz_enum_range(this, mode, 0, SkBlendMode::kLastMode); } static sk_sp<SkImage> make_fuzz_image(Fuzz*); static SkBitmap make_fuzz_bitmap(Fuzz*); static sk_sp<SkPicture> make_fuzz_picture(Fuzz*, int depth); static sk_sp<SkColorFilter> make_fuzz_colorfilter(Fuzz* fuzz, int depth) { if (depth <= 0) { return nullptr; } int colorFilterType; fuzz->nextRange(&colorFilterType, 0, 8); switch (colorFilterType) { case 0: return nullptr; case 1: { SkColor color; SkBlendMode mode; fuzz->next(&color, &mode); return SkColorFilter::MakeModeFilter(color, mode); } case 2: { sk_sp<SkColorFilter> outer = make_fuzz_colorfilter(fuzz, depth - 1); if (!outer) { return nullptr; } sk_sp<SkColorFilter> inner = make_fuzz_colorfilter(fuzz, depth - 1); // makeComposed should be able to handle nullptr. return outer->makeComposed(std::move(inner)); } case 3: { SkScalar array[20]; fuzz->nextN(array, SK_ARRAY_COUNT(array)); return SkColorFilter::MakeMatrixFilterRowMajor255(array); } case 4: { SkColor mul, add; fuzz->next(&mul, &add); return SkColorMatrixFilter::MakeLightingFilter(mul, add); } case 5: { bool grayscale; int invertStyle; float contrast; fuzz->next(&grayscale); fuzz->nextRange(&invertStyle, 0, 2); fuzz->nextRange(&contrast, -1.0f, 1.0f); return SkHighContrastFilter::Make(SkHighContrastConfig( grayscale, SkHighContrastConfig::InvertStyle(invertStyle), contrast)); } case 6: return SkLumaColorFilter::Make(); case 7: { uint8_t table[256]; fuzz->nextN(table, SK_ARRAY_COUNT(table)); return SkTableColorFilter::Make(table); } case 8: { uint8_t tableA[256]; uint8_t tableR[256]; uint8_t tableG[256]; uint8_t tableB[256]; fuzz->nextN(tableA, SK_ARRAY_COUNT(tableA)); fuzz->nextN(tableR, SK_ARRAY_COUNT(tableR)); fuzz->nextN(tableG, SK_ARRAY_COUNT(tableG)); fuzz->nextN(tableB, SK_ARRAY_COUNT(tableB)); return SkTableColorFilter::MakeARGB(tableA, tableR, tableG, tableB); } default: SkASSERT(false); break; } return nullptr; } static void fuzz_gradient_stops(Fuzz* fuzz, SkScalar* pos, int colorCount) { SkScalar totalPos = 0; for (int i = 0; i < colorCount; ++i) { fuzz->nextRange(&pos[i], 1.0f, 1024.0f); totalPos += pos[i]; } totalPos = 1.0f / totalPos; for (int i = 0; i < colorCount; ++i) { pos[i] *= totalPos; } // SkASSERT(fabs(pos[colorCount - 1] - 1.0f) < 0.00001f); pos[colorCount - 1] = 1.0f; } static sk_sp<SkShader> make_fuzz_shader(Fuzz* fuzz, int depth) { sk_sp<SkShader> shader1(nullptr), shader2(nullptr); sk_sp<SkColorFilter> colorFilter(nullptr); SkBitmap bitmap; sk_sp<SkImage> img; SkShader::TileMode tmX, tmY; bool useMatrix; SkColor color; SkMatrix matrix; SkBlendMode blendMode; int shaderType; if (depth <= 0) { return nullptr; } fuzz->nextRange(&shaderType, 0, 14); switch (shaderType) { case 0: return nullptr; case 1: return SkShader::MakeEmptyShader(); case 2: fuzz->next(&color); return SkShader::MakeColorShader(color); case 3: img = make_fuzz_image(fuzz); fuzz->next(&tmX, &tmY, &useMatrix); if (useMatrix) { fuzz->next(&matrix); } return img->makeShader(tmX, tmY, useMatrix ? &matrix : nullptr); case 4: bitmap = make_fuzz_bitmap(fuzz); fuzz->next(&tmX, &tmY, &useMatrix); if (useMatrix) { fuzz->next(&matrix); } return SkShader::MakeBitmapShader(bitmap, tmX, tmY, useMatrix ? &matrix : nullptr); case 5: shader1 = make_fuzz_shader(fuzz, depth - 1); // limit recursion. fuzz->next(&matrix); return shader1 ? shader1->makeWithLocalMatrix(matrix) : nullptr; case 6: shader1 = make_fuzz_shader(fuzz, depth - 1); // limit recursion. colorFilter = make_fuzz_colorfilter(fuzz, depth - 1); return shader1 ? shader1->makeWithColorFilter(std::move(colorFilter)) : nullptr; case 7: shader1 = make_fuzz_shader(fuzz, depth - 1); // limit recursion. shader2 = make_fuzz_shader(fuzz, depth - 1); fuzz->next(&blendMode); return SkShader::MakeComposeShader(std::move(shader1), std::move(shader2), blendMode); case 8: { auto pic = make_fuzz_picture(fuzz, depth - 1); bool useTile; SkRect tile; fuzz->next(&tmX, &tmY, &useMatrix, &useTile); if (useMatrix) { fuzz->next(&matrix); } if (useTile) { fuzz->next(&tile); } return SkShader::MakePictureShader(std::move(pic), tmX, tmY, useMatrix ? &matrix : nullptr, useTile ? &tile : nullptr); } // EFFECTS: case 9: // Deprecated SkGaussianEdgeShader return nullptr; case 10: { constexpr int kMaxColors = 12; SkPoint pts[2]; SkColor colors[kMaxColors]; SkScalar pos[kMaxColors]; int colorCount; bool usePos; fuzz->nextN(pts, 2); fuzz->nextRange(&colorCount, 2, kMaxColors); fuzz->nextN(colors, colorCount); fuzz->next(&tmX, &useMatrix, &usePos); if (useMatrix) { fuzz->next(&matrix); } if (usePos) { fuzz_gradient_stops(fuzz, pos, colorCount); } return SkGradientShader::MakeLinear(pts, colors, usePos ? pos : nullptr, colorCount, tmX, 0, useMatrix ? &matrix : nullptr); } case 11: { constexpr int kMaxColors = 12; SkPoint center; SkScalar radius; int colorCount; bool usePos; SkColor colors[kMaxColors]; SkScalar pos[kMaxColors]; fuzz->next(&tmX, &useMatrix, &usePos, &center, &radius); fuzz->nextRange(&colorCount, 2, kMaxColors); fuzz->nextN(colors, colorCount); if (useMatrix) { fuzz->next(&matrix); } if (usePos) { fuzz_gradient_stops(fuzz, pos, colorCount); } return SkGradientShader::MakeRadial(center, radius, colors, usePos ? pos : nullptr, colorCount, tmX, 0, useMatrix ? &matrix : nullptr); } case 12: { constexpr int kMaxColors = 12; SkPoint start, end; SkScalar startRadius, endRadius; int colorCount; bool usePos; SkColor colors[kMaxColors]; SkScalar pos[kMaxColors]; fuzz->next(&tmX, &useMatrix, &usePos, &startRadius, &endRadius, &start, &end); fuzz->nextRange(&colorCount, 2, kMaxColors); fuzz->nextN(colors, colorCount); if (useMatrix) { fuzz->next(&matrix); } if (usePos) { fuzz_gradient_stops(fuzz, pos, colorCount); } return SkGradientShader::MakeTwoPointConical(start, startRadius, end, endRadius, colors, usePos ? pos : nullptr, colorCount, tmX, 0, useMatrix ? &matrix : nullptr); } case 13: { constexpr int kMaxColors = 12; SkScalar cx, cy; int colorCount; bool usePos; SkColor colors[kMaxColors]; SkScalar pos[kMaxColors]; fuzz->next(&cx, &cy, &useMatrix, &usePos); fuzz->nextRange(&colorCount, 2, kMaxColors); fuzz->nextN(colors, colorCount); if (useMatrix) { fuzz->next(&matrix); } if (usePos) { fuzz_gradient_stops(fuzz, pos, colorCount); } return SkGradientShader::MakeSweep(cx, cy, colors, usePos ? pos : nullptr, colorCount, 0, useMatrix ? &matrix : nullptr); } case 14: { SkScalar baseFrequencyX, baseFrequencyY, seed; int numOctaves; SkISize tileSize; bool useTileSize, turbulence; fuzz->next(&baseFrequencyX, &baseFrequencyY, &seed, &useTileSize, &turbulence); if (useTileSize) { fuzz->next(&tileSize); } fuzz->nextRange(&numOctaves, 2, 7); if (turbulence) { return SkPerlinNoiseShader::MakeTurbulence(baseFrequencyX, baseFrequencyY, numOctaves, seed, useTileSize ? &tileSize : nullptr); } else { return SkPerlinNoiseShader::MakeFractalNoise(baseFrequencyX, baseFrequencyY, numOctaves, seed, useTileSize ? &tileSize : nullptr); } } default: SkASSERT(false); break; } return nullptr; } static sk_sp<SkPathEffect> make_fuzz_patheffect(Fuzz* fuzz, int depth) { if (depth <= 0) { return nullptr; } uint8_t pathEffectType; fuzz->nextRange(&pathEffectType, 0, 8); switch (pathEffectType) { case 0: { return nullptr; } case 1: { sk_sp<SkPathEffect> first = make_fuzz_patheffect(fuzz, depth - 1); sk_sp<SkPathEffect> second = make_fuzz_patheffect(fuzz, depth - 1); return SkPathEffect::MakeSum(std::move(first), std::move(second)); } case 2: { sk_sp<SkPathEffect> first = make_fuzz_patheffect(fuzz, depth - 1); sk_sp<SkPathEffect> second = make_fuzz_patheffect(fuzz, depth - 1); return SkPathEffect::MakeCompose(std::move(first), std::move(second)); } case 3: { SkPath path; FuzzPath(fuzz, &path, 20); SkScalar advance, phase; fuzz->next(&advance, &phase); SkPath1DPathEffect::Style style; fuzz_enum_range(fuzz, &style, 0, SkPath1DPathEffect::kLastEnum_Style); return SkPath1DPathEffect::Make(path, advance, phase, style); } case 4: { SkScalar width; SkMatrix matrix; fuzz->next(&width, &matrix); return SkLine2DPathEffect::Make(width, matrix); } case 5: { SkPath path; FuzzPath(fuzz, &path, 20); SkMatrix matrix; fuzz->next(&matrix); return SkPath2DPathEffect::Make(matrix, path); } case 6: { SkScalar radius; fuzz->next(&radius); return SkCornerPathEffect::Make(radius); } case 7: { SkScalar phase; fuzz->next(&phase); SkScalar intervals[20]; int count; fuzz->nextRange(&count, 0, (int)SK_ARRAY_COUNT(intervals)); fuzz->nextN(intervals, count); return SkDashPathEffect::Make(intervals, count, phase); } case 8: { SkScalar segLength, dev; uint32_t seed; fuzz->next(&segLength, &dev, &seed); return SkDiscretePathEffect::Make(segLength, dev, seed); } default: SkASSERT(false); return nullptr; } } static sk_sp<SkMaskFilter> make_fuzz_maskfilter(Fuzz* fuzz) { int maskfilterType; fuzz->nextRange(&maskfilterType, 0, 2); switch (maskfilterType) { case 0: return nullptr; case 1: { SkBlurStyle blurStyle; fuzz_enum_range(fuzz, &blurStyle, 0, kLastEnum_SkBlurStyle); SkScalar sigma; fuzz->next(&sigma); SkRect occluder{0.0f, 0.0f, 0.0f, 0.0f}; if (make_fuzz_t<bool>(fuzz)) { fuzz->next(&occluder); } uint32_t flags; fuzz->nextRange(&flags, 0, 1); bool respectCTM = flags != 0; return SkMaskFilter::MakeBlur(blurStyle, sigma, occluder, respectCTM); } case 2: { SkRRect first, second; SkScalar radius; fuzz->next(&first, &second, &radius); return SkRRectsGaussianEdgeMaskFilter::Make(first, second, radius); } default: SkASSERT(false); return nullptr; } } static sk_sp<SkTypeface> make_fuzz_typeface(Fuzz* fuzz) { if (make_fuzz_t<bool>(fuzz)) { return nullptr; } auto fontMugger = SkFontMgr::RefDefault(); SkASSERT(fontMugger); int familyCount = fontMugger->countFamilies(); int i, j; fuzz->nextRange(&i, 0, familyCount - 1); sk_sp<SkFontStyleSet> family(fontMugger->createStyleSet(i)); int styleCount = family->count(); fuzz->nextRange(&j, 0, styleCount - 1); return sk_sp<SkTypeface>(family->createTypeface(j)); } template <> inline void Fuzz::next(SkImageFilter::CropRect* cropRect) { SkRect rect; uint8_t flags; this->next(&rect); this->nextRange(&flags, 0, 0xF); *cropRect = SkImageFilter::CropRect(rect, flags); } static sk_sp<SkImageFilter> make_fuzz_imageFilter(Fuzz* fuzz, int depth); static sk_sp<SkImageFilter> make_fuzz_lighting_imagefilter(Fuzz* fuzz, int depth) { if (depth <= 0) { return nullptr; } uint8_t imageFilterType; fuzz->nextRange(&imageFilterType, 1, 6); SkPoint3 p, q; SkColor lightColor; SkScalar surfaceScale, k, specularExponent, cutoffAngle, shininess; sk_sp<SkImageFilter> input; SkImageFilter::CropRect cropRect; bool useCropRect; fuzz->next(&useCropRect); if (useCropRect) { fuzz->next(&cropRect); } switch (imageFilterType) { case 1: fuzz->next(&p, &lightColor, &surfaceScale, &k); input = make_fuzz_imageFilter(fuzz, depth - 1); return SkLightingImageFilter::MakeDistantLitDiffuse(p, lightColor, surfaceScale, k, std::move(input), useCropRect ? &cropRect : nullptr); case 2: fuzz->next(&p, &lightColor, &surfaceScale, &k); input = make_fuzz_imageFilter(fuzz, depth - 1); return SkLightingImageFilter::MakePointLitDiffuse(p, lightColor, surfaceScale, k, std::move(input), useCropRect ? &cropRect : nullptr); case 3: fuzz->next(&p, &q, &specularExponent, &cutoffAngle, &lightColor, &surfaceScale, &k); input = make_fuzz_imageFilter(fuzz, depth - 1); return SkLightingImageFilter::MakeSpotLitDiffuse( p, q, specularExponent, cutoffAngle, lightColor, surfaceScale, k, std::move(input), useCropRect ? &cropRect : nullptr); case 4: fuzz->next(&p, &lightColor, &surfaceScale, &k, &shininess); input = make_fuzz_imageFilter(fuzz, depth - 1); return SkLightingImageFilter::MakeDistantLitSpecular(p, lightColor, surfaceScale, k, shininess, std::move(input), useCropRect ? &cropRect : nullptr); case 5: fuzz->next(&p, &lightColor, &surfaceScale, &k, &shininess); input = make_fuzz_imageFilter(fuzz, depth - 1); return SkLightingImageFilter::MakePointLitSpecular(p, lightColor, surfaceScale, k, shininess, std::move(input), useCropRect ? &cropRect : nullptr); case 6: fuzz->next(&p, &q, &specularExponent, &cutoffAngle, &lightColor, &surfaceScale, &k, &shininess); input = make_fuzz_imageFilter(fuzz, depth - 1); return SkLightingImageFilter::MakeSpotLitSpecular( p, q, specularExponent, cutoffAngle, lightColor, surfaceScale, k, shininess, std::move(input), useCropRect ? &cropRect : nullptr); default: SkASSERT(false); return nullptr; } } static void fuzz_paint(Fuzz* fuzz, SkPaint* paint, int depth); static sk_sp<SkImageFilter> make_fuzz_imageFilter(Fuzz* fuzz, int depth) { if (depth <= 0) { return nullptr; } uint8_t imageFilterType; fuzz->nextRange(&imageFilterType, 0, 23); switch (imageFilterType) { case 0: return nullptr; case 1: { SkScalar sigmaX, sigmaY; sk_sp<SkImageFilter> input = make_fuzz_imageFilter(fuzz, depth - 1); bool useCropRect; fuzz->next(&sigmaX, &sigmaY, &useCropRect); SkImageFilter::CropRect cropRect; if (useCropRect) { fuzz->next(&cropRect); } return SkBlurImageFilter::Make(sigmaX, sigmaY, std::move(input), useCropRect ? &cropRect : nullptr); } case 2: { SkMatrix matrix; SkFilterQuality quality; fuzz->next(&matrix, &quality); sk_sp<SkImageFilter> input = make_fuzz_imageFilter(fuzz, depth - 1); return SkImageFilter::MakeMatrixFilter(matrix, quality, std::move(input)); } case 3: { SkRegion region; SkScalar innerMin, outerMax; sk_sp<SkImageFilter> input = make_fuzz_imageFilter(fuzz, depth - 1); bool useCropRect; fuzz->next(&region, &innerMin, &outerMax, &useCropRect); SkImageFilter::CropRect cropRect; if (useCropRect) { fuzz->next(&cropRect); } return SkAlphaThresholdFilter::Make(region, innerMin, outerMax, std::move(input), useCropRect ? &cropRect : nullptr); } case 4: { float k1, k2, k3, k4; bool enforcePMColor; bool useCropRect; fuzz->next(&k1, &k2, &k3, &k4, &enforcePMColor, &useCropRect); sk_sp<SkImageFilter> background = make_fuzz_imageFilter(fuzz, depth - 1); sk_sp<SkImageFilter> foreground = make_fuzz_imageFilter(fuzz, depth - 1); SkImageFilter::CropRect cropRect; if (useCropRect) { fuzz->next(&cropRect); } return SkArithmeticImageFilter::Make(k1, k2, k3, k4, enforcePMColor, std::move(background), std::move(foreground), useCropRect ? &cropRect : nullptr); } case 5: { sk_sp<SkColorFilter> cf = make_fuzz_colorfilter(fuzz, depth - 1); sk_sp<SkImageFilter> input = make_fuzz_imageFilter(fuzz, depth - 1); bool useCropRect; SkImageFilter::CropRect cropRect; fuzz->next(&useCropRect); if (useCropRect) { fuzz->next(&cropRect); } return SkColorFilterImageFilter::Make(std::move(cf), std::move(input), useCropRect ? &cropRect : nullptr); } case 6: { sk_sp<SkImageFilter> ifo = make_fuzz_imageFilter(fuzz, depth - 1); sk_sp<SkImageFilter> ifi = make_fuzz_imageFilter(fuzz, depth - 1); return SkComposeImageFilter::Make(std::move(ifo), std::move(ifi)); } case 7: { SkDisplacementMapEffect::ChannelSelectorType xChannelSelector, yChannelSelector; fuzz_enum_range(fuzz, &xChannelSelector, 1, 4); fuzz_enum_range(fuzz, &yChannelSelector, 1, 4); SkScalar scale; bool useCropRect; fuzz->next(&scale, &useCropRect); SkImageFilter::CropRect cropRect; if (useCropRect) { fuzz->next(&cropRect); } sk_sp<SkImageFilter> displacement = make_fuzz_imageFilter(fuzz, depth - 1); sk_sp<SkImageFilter> color = make_fuzz_imageFilter(fuzz, depth - 1); return SkDisplacementMapEffect::Make(xChannelSelector, yChannelSelector, scale, std::move(displacement), std::move(color), useCropRect ? &cropRect : nullptr); } case 8: { SkScalar dx, dy, sigmaX, sigmaY; SkColor color; SkDropShadowImageFilter::ShadowMode shadowMode; fuzz_enum_range(fuzz, &shadowMode, 0, 1); bool useCropRect; fuzz->next(&dx, &dy, &sigmaX, &sigmaY, &color, &useCropRect); SkImageFilter::CropRect cropRect; if (useCropRect) { fuzz->next(&cropRect); } sk_sp<SkImageFilter> input = make_fuzz_imageFilter(fuzz, depth - 1); return SkDropShadowImageFilter::Make(dx, dy, sigmaX, sigmaY, color, shadowMode, std::move(input), useCropRect ? &cropRect : nullptr); } case 9: return SkImageSource::Make(make_fuzz_image(fuzz)); case 10: { sk_sp<SkImage> image = make_fuzz_image(fuzz); SkRect srcRect, dstRect; SkFilterQuality filterQuality; fuzz->next(&srcRect, &dstRect, &filterQuality); return SkImageSource::Make(std::move(image), srcRect, dstRect, filterQuality); } case 11: return make_fuzz_lighting_imagefilter(fuzz, depth - 1); case 12: { SkRect srcRect; SkScalar inset; bool useCropRect; SkImageFilter::CropRect cropRect; fuzz->next(&srcRect, &inset, &useCropRect); if (useCropRect) { fuzz->next(&cropRect); } sk_sp<SkImageFilter> input = make_fuzz_imageFilter(fuzz, depth - 1); return SkMagnifierImageFilter::Make(srcRect, inset, std::move(input), useCropRect ? &cropRect : nullptr); } case 13: { constexpr int kMaxKernelSize = 5; int32_t n, m; fuzz->nextRange(&n, 1, kMaxKernelSize); fuzz->nextRange(&m, 1, kMaxKernelSize); SkScalar kernel[kMaxKernelSize * kMaxKernelSize]; fuzz->nextN(kernel, n * m); int32_t offsetX, offsetY; fuzz->nextRange(&offsetX, 0, n - 1); fuzz->nextRange(&offsetY, 0, m - 1); SkScalar gain, bias; bool convolveAlpha, useCropRect; fuzz->next(&gain, &bias, &convolveAlpha, &useCropRect); SkMatrixConvolutionImageFilter::TileMode tileMode; fuzz_enum_range(fuzz, &tileMode, 0, 2); SkImageFilter::CropRect cropRect; if (useCropRect) { fuzz->next(&cropRect); } sk_sp<SkImageFilter> input = make_fuzz_imageFilter(fuzz, depth - 1); return SkMatrixConvolutionImageFilter::Make( SkISize{n, m}, kernel, gain, bias, SkIPoint{offsetX, offsetY}, tileMode, convolveAlpha, std::move(input), useCropRect ? &cropRect : nullptr); } case 14: { sk_sp<SkImageFilter> first = make_fuzz_imageFilter(fuzz, depth - 1); sk_sp<SkImageFilter> second = make_fuzz_imageFilter(fuzz, depth - 1); bool useCropRect; fuzz->next(&useCropRect); SkImageFilter::CropRect cropRect; if (useCropRect) { fuzz->next(&cropRect); } return SkMergeImageFilter::Make(std::move(first), std::move(second), useCropRect ? &cropRect : nullptr); } case 15: { constexpr int kMaxCount = 4; sk_sp<SkImageFilter> ifs[kMaxCount]; int count; fuzz->nextRange(&count, 1, kMaxCount); for (int i = 0; i < count; ++i) { ifs[i] = make_fuzz_imageFilter(fuzz, depth - 1); } bool useCropRect; fuzz->next(&useCropRect); SkImageFilter::CropRect cropRect; if (useCropRect) { fuzz->next(&cropRect); } return SkMergeImageFilter::Make(ifs, count, useCropRect ? &cropRect : nullptr); } case 16: { int rx, ry; fuzz->next(&rx, &ry); bool useCropRect; fuzz->next(&useCropRect); SkImageFilter::CropRect cropRect; if (useCropRect) { fuzz->next(&cropRect); } sk_sp<SkImageFilter> input = make_fuzz_imageFilter(fuzz, depth - 1); return SkDilateImageFilter::Make(rx, ry, std::move(input), useCropRect ? &cropRect : nullptr); } case 17: { int rx, ry; fuzz->next(&rx, &ry); bool useCropRect; fuzz->next(&useCropRect); SkImageFilter::CropRect cropRect; if (useCropRect) { fuzz->next(&cropRect); } sk_sp<SkImageFilter> input = make_fuzz_imageFilter(fuzz, depth - 1); return SkErodeImageFilter::Make(rx, ry, std::move(input), useCropRect ? &cropRect : nullptr); } case 18: { SkScalar dx, dy; fuzz->next(&dx, &dy); bool useCropRect; fuzz->next(&useCropRect); SkImageFilter::CropRect cropRect; if (useCropRect) { fuzz->next(&cropRect); } sk_sp<SkImageFilter> input = make_fuzz_imageFilter(fuzz, depth - 1); return SkOffsetImageFilter::Make(dx, dy, std::move(input), useCropRect ? &cropRect : nullptr); } case 19: { SkPaint paint; fuzz_paint(fuzz, &paint, depth - 1); bool useCropRect; fuzz->next(&useCropRect); SkImageFilter::CropRect cropRect; if (useCropRect) { fuzz->next(&cropRect); } return SkPaintImageFilter::Make(paint, useCropRect ? &cropRect : nullptr); } case 20: { sk_sp<SkPicture> picture = make_fuzz_picture(fuzz, depth - 1); return SkPictureImageFilter::Make(std::move(picture)); } case 21: { SkRect cropRect; fuzz->next(&cropRect); sk_sp<SkPicture> picture = make_fuzz_picture(fuzz, depth - 1); return SkPictureImageFilter::Make(std::move(picture), cropRect); } case 22: { SkRect src, dst; fuzz->next(&src, &dst); sk_sp<SkImageFilter> input = make_fuzz_imageFilter(fuzz, depth - 1); return SkTileImageFilter::Make(src, dst, std::move(input)); } case 23: { SkBlendMode blendMode; bool useCropRect; fuzz->next(&useCropRect, &blendMode); SkImageFilter::CropRect cropRect; if (useCropRect) { fuzz->next(&cropRect); } sk_sp<SkImageFilter> bg = make_fuzz_imageFilter(fuzz, depth - 1); sk_sp<SkImageFilter> fg = make_fuzz_imageFilter(fuzz, depth - 1); return SkXfermodeImageFilter::Make(blendMode, std::move(bg), std::move(fg), useCropRect ? &cropRect : nullptr); } default: SkASSERT(false); return nullptr; } } static sk_sp<SkImage> make_fuzz_image(Fuzz* fuzz) { int w, h; fuzz->nextRange(&w, 1, 1024); fuzz->nextRange(&h, 1, 1024); SkAutoTMalloc<SkPMColor> data(w * h); SkPixmap pixmap(SkImageInfo::MakeN32Premul(w, h), data.get(), w * sizeof(SkPMColor)); int n = w * h; for (int i = 0; i < n; ++i) { SkColor c; fuzz->next(&c); data[i] = SkPreMultiplyColor(c); } (void)data.release(); return SkImage::MakeFromRaster(pixmap, [](const void* p, void*) { sk_free((void*)p); }, nullptr); } static SkBitmap make_fuzz_bitmap(Fuzz* fuzz) { SkBitmap bitmap; int w, h; fuzz->nextRange(&w, 1, 1024); fuzz->nextRange(&h, 1, 1024); if (!bitmap.tryAllocN32Pixels(w, h)) { SkDEBUGF(("Could not allocate pixels %d x %d", w, h)); return bitmap; } for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { SkColor c; fuzz->next(&c); *bitmap.getAddr32(x, y) = SkPreMultiplyColor(c); } } return bitmap; } template <typename T, typename Min, typename Max> inline T make_fuzz_t_range(Fuzz* fuzz, Min minv, Max maxv) { T value; fuzz_enum_range(fuzz, &value, minv, maxv); return value; } static void fuzz_paint(Fuzz* fuzz, SkPaint* paint, int depth) { if (!fuzz || !paint || depth <= 0) { return; } paint->setAntiAlias( make_fuzz_t<bool>(fuzz)); paint->setDither( make_fuzz_t<bool>(fuzz)); paint->setColor( make_fuzz_t<SkColor>(fuzz)); paint->setBlendMode( make_fuzz_t_range<SkBlendMode>(fuzz, 0, SkBlendMode::kLastMode)); paint->setFilterQuality(make_fuzz_t_range<SkFilterQuality>(fuzz, 0, kLast_SkFilterQuality)); paint->setStyle( make_fuzz_t_range<SkPaint::Style>(fuzz, 0, 2)); paint->setShader( make_fuzz_shader(fuzz, depth - 1)); paint->setPathEffect( make_fuzz_patheffect(fuzz, depth - 1)); paint->setMaskFilter( make_fuzz_maskfilter(fuzz)); paint->setImageFilter( make_fuzz_imageFilter(fuzz, depth - 1)); paint->setColorFilter( make_fuzz_colorfilter(fuzz, depth - 1)); if (paint->getStyle() != SkPaint::kFill_Style) { paint->setStrokeWidth(make_fuzz_t<SkScalar>(fuzz)); paint->setStrokeMiter(make_fuzz_t<SkScalar>(fuzz)); paint->setStrokeCap( make_fuzz_t_range<SkPaint::Cap>(fuzz, 0, SkPaint::kLast_Cap)); paint->setStrokeJoin( make_fuzz_t_range<SkPaint::Join>(fuzz, 0, SkPaint::kLast_Join)); } } static void fuzz_paint_text(Fuzz* fuzz, SkPaint* paint) { paint->setTypeface( make_fuzz_typeface(fuzz)); paint->setTextSize( make_fuzz_t<SkScalar>(fuzz)); paint->setTextScaleX( make_fuzz_t<SkScalar>(fuzz)); paint->setTextSkewX( make_fuzz_t<SkScalar>(fuzz)); paint->setLinearText( make_fuzz_t<bool>(fuzz)); paint->setSubpixelText( make_fuzz_t<bool>(fuzz)); paint->setLCDRenderText( make_fuzz_t<bool>(fuzz)); paint->setEmbeddedBitmapText(make_fuzz_t<bool>(fuzz)); paint->setAutohinted( make_fuzz_t<bool>(fuzz)); paint->setVerticalText( make_fuzz_t<bool>(fuzz)); paint->setFakeBoldText( make_fuzz_t<bool>(fuzz)); paint->setDevKernText( make_fuzz_t<bool>(fuzz)); paint->setHinting( make_fuzz_t_range<SkPaint::Hinting>(fuzz, 0, SkPaint::kFull_Hinting)); paint->setTextAlign( make_fuzz_t_range<SkPaint::Align>(fuzz, 0, 2)); } static void fuzz_paint_text_encoding(Fuzz* fuzz, SkPaint* paint) { paint->setTextEncoding(make_fuzz_t_range<SkPaint::TextEncoding>(fuzz, 0, 3)); } constexpr int kMaxGlyphCount = 30; static SkTDArray<uint8_t> make_fuzz_text(Fuzz* fuzz, const SkPaint& paint) { SkTDArray<uint8_t> array; if (SkPaint::kGlyphID_TextEncoding == paint.getTextEncoding()) { int glyphRange = paint.getTypeface() ? paint.getTypeface()->countGlyphs() : SkTypeface::MakeDefault()->countGlyphs(); if (glyphRange == 0) { // Some fuzzing environments have no fonts, so empty array is the best // we can do. return array; } int glyphCount; fuzz->nextRange(&glyphCount, 1, kMaxGlyphCount); SkGlyphID* glyphs = (SkGlyphID*)array.append(glyphCount * sizeof(SkGlyphID)); for (int i = 0; i < glyphCount; ++i) { fuzz->nextRange(&glyphs[i], 0, glyphRange - 1); } return array; } static const SkUnichar ranges[][2] = { {0x0020, 0x007F}, {0x00A1, 0x0250}, {0x0400, 0x0500}, }; int32_t count = 0; for (size_t i = 0; i < SK_ARRAY_COUNT(ranges); ++i) { count += (ranges[i][1] - ranges[i][0]); } constexpr int kMaxLength = kMaxGlyphCount; SkUnichar buffer[kMaxLength]; int length; fuzz->nextRange(&length, 1, kMaxLength); for (int j = 0; j < length; ++j) { int32_t value; fuzz->nextRange(&value, 0, count - 1); for (size_t i = 0; i < SK_ARRAY_COUNT(ranges); ++i) { if (value + ranges[i][0] < ranges[i][1]) { buffer[j] = value + ranges[i][0]; break; } else { value -= (ranges[i][1] - ranges[i][0]); } } } switch (paint.getTextEncoding()) { case SkPaint::kUTF8_TextEncoding: { size_t utf8len = 0; for (int j = 0; j < length; ++j) { utf8len += SkUTF8_FromUnichar(buffer[j], nullptr); } char* ptr = (char*)array.append(utf8len); for (int j = 0; j < length; ++j) { ptr += SkUTF8_FromUnichar(buffer[j], ptr); } } break; case SkPaint::kUTF16_TextEncoding: { size_t utf16len = 0; for (int j = 0; j < length; ++j) { utf16len += SkUTF16_FromUnichar(buffer[j]); } uint16_t* ptr = (uint16_t*)array.append(utf16len * sizeof(uint16_t)); for (int j = 0; j < length; ++j) { ptr += SkUTF16_FromUnichar(buffer[j], ptr); } } break; case SkPaint::kUTF32_TextEncoding: memcpy(array.append(length * sizeof(SkUnichar)), buffer, length * sizeof(SkUnichar)); break; default: SkASSERT(false); break; } return array; } static sk_sp<SkTextBlob> make_fuzz_textblob(Fuzz* fuzz) { SkTextBlobBuilder textBlobBuilder; int8_t runCount; fuzz->nextRange(&runCount, (int8_t)1, (int8_t)8); while (runCount-- > 0) { SkPaint paint; fuzz_paint_text_encoding(fuzz, &paint); paint.setAntiAlias(make_fuzz_t<bool>(fuzz)); paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding); SkTDArray<uint8_t> text = make_fuzz_text(fuzz, paint); int glyphCount = paint.countText(text.begin(), SkToSizeT(text.count())); SkASSERT(glyphCount <= kMaxGlyphCount); SkScalar x, y; const SkTextBlobBuilder::RunBuffer* buffer; uint8_t runType; fuzz->nextRange(&runType, (uint8_t)0, (uint8_t)2); switch (runType) { case 0: fuzz->next(&x, &y); // TODO: Test other variations of this. buffer = &textBlobBuilder.allocRun(paint, glyphCount, x, y); memcpy(buffer->glyphs, text.begin(), SkToSizeT(text.count())); break; case 1: fuzz->next(&y); // TODO: Test other variations of this. buffer = &textBlobBuilder.allocRunPosH(paint, glyphCount, y); memcpy(buffer->glyphs, text.begin(), SkToSizeT(text.count())); fuzz->nextN(buffer->pos, glyphCount); break; case 2: // TODO: Test other variations of this. buffer = &textBlobBuilder.allocRunPos(paint, glyphCount); memcpy(buffer->glyphs, text.begin(), SkToSizeT(text.count())); fuzz->nextN(buffer->pos, glyphCount * 2); break; default: SkASSERT(false); break; } } return textBlobBuilder.make(); } static void fuzz_canvas(Fuzz* fuzz, SkCanvas* canvas, int depth = 9) { if (!fuzz || !canvas || depth <= 0) { return; } SkAutoCanvasRestore autoCanvasRestore(canvas, false); unsigned N; fuzz->nextRange(&N, 0, 2000); for (unsigned i = 0; i < N; ++i) { if (fuzz->exhausted()) { return; } SkPaint paint; SkMatrix matrix; unsigned drawCommand; fuzz->nextRange(&drawCommand, 0, 53); switch (drawCommand) { case 0: canvas->flush(); break; case 1: canvas->save(); break; case 2: { SkRect bounds; fuzz->next(&bounds); fuzz_paint(fuzz, &paint, depth - 1); canvas->saveLayer(&bounds, &paint); break; } case 3: { SkRect bounds; fuzz->next(&bounds); canvas->saveLayer(&bounds, nullptr); break; } case 4: fuzz_paint(fuzz, &paint, depth - 1); canvas->saveLayer(nullptr, &paint); break; case 5: canvas->saveLayer(nullptr, nullptr); break; case 6: { uint8_t alpha; fuzz->next(&alpha); canvas->saveLayerAlpha(nullptr, (U8CPU)alpha); break; } case 7: { SkRect bounds; uint8_t alpha; fuzz->next(&bounds, &alpha); canvas->saveLayerAlpha(&bounds, (U8CPU)alpha); break; } case 8: { SkCanvas::SaveLayerRec saveLayerRec; SkRect bounds; if (make_fuzz_t<bool>(fuzz)) { fuzz->next(&bounds); saveLayerRec.fBounds = &bounds; } if (make_fuzz_t<bool>(fuzz)) { fuzz_paint(fuzz, &paint, depth - 1); saveLayerRec.fPaint = &paint; } sk_sp<SkImageFilter> imageFilter; if (make_fuzz_t<bool>(fuzz)) { imageFilter = make_fuzz_imageFilter(fuzz, depth - 1); saveLayerRec.fBackdrop = imageFilter.get(); } // _DumpCanvas can't handle this. // if (make_fuzz_t<bool>(fuzz)) { // saveLayerRec.fSaveLayerFlags |= SkCanvas::kPreserveLCDText_SaveLayerFlag; // } canvas->saveLayer(saveLayerRec); break; } case 9: canvas->restore(); break; case 10: { int saveCount; fuzz->next(&saveCount); canvas->restoreToCount(saveCount); break; } case 11: { SkScalar x, y; fuzz->next(&x, &y); canvas->translate(x, y); break; } case 12: { SkScalar x, y; fuzz->next(&x, &y); canvas->scale(x, y); break; } case 13: { SkScalar v; fuzz->next(&v); canvas->rotate(v); break; } case 14: { SkScalar x, y, v; fuzz->next(&x, &y, &v); canvas->rotate(v, x, y); break; } case 15: { SkScalar x, y; fuzz->next(&x, &y); canvas->skew(x, y); break; } case 16: { SkMatrix mat; fuzz->next(&mat); canvas->concat(mat); break; } case 17: { SkMatrix mat; fuzz->next(&mat); canvas->setMatrix(mat); break; } case 18: canvas->resetMatrix(); break; case 19: { SkRect r; int op; bool doAntiAlias; fuzz->next(&r, &doAntiAlias); fuzz->nextRange(&op, 0, 1); r.sort(); canvas->clipRect(r, (SkClipOp)op, doAntiAlias); break; } case 20: { SkRRect rr; int op; bool doAntiAlias; fuzz->next(&rr); fuzz->next(&doAntiAlias); fuzz->nextRange(&op, 0, 1); canvas->clipRRect(rr, (SkClipOp)op, doAntiAlias); break; } case 21: { SkPath path; FuzzPath(fuzz, &path, 30); int op; bool doAntiAlias; fuzz->next(&doAntiAlias); fuzz->nextRange(&op, 0, 1); canvas->clipPath(path, (SkClipOp)op, doAntiAlias); break; } case 22: { SkRegion region; int op; fuzz->next(&region); fuzz->nextRange(&op, 0, 1); canvas->clipRegion(region, (SkClipOp)op); break; } case 23: fuzz_paint(fuzz, &paint, depth - 1); canvas->drawPaint(paint); break; case 24: { fuzz_paint(fuzz, &paint, depth - 1); SkCanvas::PointMode pointMode; fuzz_enum_range(fuzz, &pointMode, SkCanvas::kPoints_PointMode, SkCanvas::kPolygon_PointMode); size_t count; constexpr int kMaxCount = 30; fuzz->nextRange(&count, 0, kMaxCount); SkPoint pts[kMaxCount]; fuzz->nextN(pts, count); canvas->drawPoints(pointMode, count, pts, paint); break; } case 25: { fuzz_paint(fuzz, &paint, depth - 1); SkRect r; fuzz->next(&r); if (!r.isFinite()) { break; } canvas->drawRect(r, paint); break; } case 26: { fuzz_paint(fuzz, &paint, depth - 1); SkRegion region; fuzz->next(&region); canvas->drawRegion(region, paint); break; } case 27: { fuzz_paint(fuzz, &paint, depth - 1); SkRect r; fuzz->next(&r); if (!r.isFinite()) { break; } canvas->drawOval(r, paint); break; } case 28: break; // must have deleted this some time earlier case 29: { fuzz_paint(fuzz, &paint, depth - 1); SkRRect rr; fuzz->next(&rr); canvas->drawRRect(rr, paint); break; } case 30: { fuzz_paint(fuzz, &paint, depth - 1); SkRRect orr, irr; fuzz->next(&orr); fuzz->next(&irr); if (orr.getBounds().contains(irr.getBounds())) { canvas->drawDRRect(orr, irr, paint); } break; } case 31: { fuzz_paint(fuzz, &paint, depth - 1); SkRect r; SkScalar start, sweep; bool useCenter; fuzz->next(&r, &start, &sweep, &useCenter); canvas->drawArc(r, start, sweep, useCenter, paint); break; } case 32: { SkPath path; FuzzPath(fuzz, &path, 60); canvas->drawPath(path, paint); break; } case 33: { sk_sp<SkImage> img = make_fuzz_image(fuzz); SkScalar left, top; bool usePaint; fuzz->next(&left, &top, &usePaint); if (usePaint) { fuzz_paint(fuzz, &paint, depth - 1); } canvas->drawImage(img.get(), left, top, usePaint ? &paint : nullptr); break; } case 34: { auto img = make_fuzz_image(fuzz); SkRect src, dst; bool usePaint; fuzz->next(&src, &dst, &usePaint); if (usePaint) { fuzz_paint(fuzz, &paint, depth - 1); } SkCanvas::SrcRectConstraint constraint = make_fuzz_t<bool>(fuzz) ? SkCanvas::kStrict_SrcRectConstraint : SkCanvas::kFast_SrcRectConstraint; canvas->drawImageRect(img, src, dst, usePaint ? &paint : nullptr, constraint); break; } case 35: { auto img = make_fuzz_image(fuzz); SkIRect src; SkRect dst; bool usePaint; fuzz->next(&src, &dst, &usePaint); if (usePaint) { fuzz_paint(fuzz, &paint, depth - 1); } SkCanvas::SrcRectConstraint constraint = make_fuzz_t<bool>(fuzz) ? SkCanvas::kStrict_SrcRectConstraint : SkCanvas::kFast_SrcRectConstraint; canvas->drawImageRect(img, src, dst, usePaint ? &paint : nullptr, constraint); break; } case 36: { bool usePaint; auto img = make_fuzz_image(fuzz); SkRect dst; fuzz->next(&dst, &usePaint); if (usePaint) { fuzz_paint(fuzz, &paint, depth - 1); } SkCanvas::SrcRectConstraint constraint = make_fuzz_t<bool>(fuzz) ? SkCanvas::kStrict_SrcRectConstraint : SkCanvas::kFast_SrcRectConstraint; canvas->drawImageRect(img, dst, usePaint ? &paint : nullptr, constraint); break; } case 37: { auto img = make_fuzz_image(fuzz); SkIRect center; SkRect dst; bool usePaint; fuzz->next(&usePaint); if (usePaint) { fuzz_paint(fuzz, &paint, depth - 1); } if (make_fuzz_t<bool>(fuzz)) { fuzz->next(&center); } else { // Make valid center, see SkLatticeIter::Valid(). fuzz->nextRange(&center.fLeft, 0, img->width() - 1); fuzz->nextRange(&center.fTop, 0, img->height() - 1); fuzz->nextRange(&center.fRight, center.fLeft + 1, img->width()); fuzz->nextRange(&center.fBottom, center.fTop + 1, img->height()); } fuzz->next(&dst); canvas->drawImageNine(img, center, dst, usePaint ? &paint : nullptr); break; } case 38: { SkBitmap bitmap = make_fuzz_bitmap(fuzz); SkScalar left, top; bool usePaint; fuzz->next(&left, &top, &usePaint); if (usePaint) { fuzz_paint(fuzz, &paint, depth - 1); } canvas->drawBitmap(bitmap, left, top, usePaint ? &paint : nullptr); break; } case 39: { SkBitmap bitmap = make_fuzz_bitmap(fuzz); SkRect src, dst; bool usePaint; fuzz->next(&src, &dst, &usePaint); if (usePaint) { fuzz_paint(fuzz, &paint, depth - 1); } SkCanvas::SrcRectConstraint constraint = make_fuzz_t<bool>(fuzz) ? SkCanvas::kStrict_SrcRectConstraint : SkCanvas::kFast_SrcRectConstraint; canvas->drawBitmapRect(bitmap, src, dst, usePaint ? &paint : nullptr, constraint); break; } case 40: { SkBitmap img = make_fuzz_bitmap(fuzz); SkIRect src; SkRect dst; bool usePaint; fuzz->next(&src, &dst, &usePaint); if (usePaint) { fuzz_paint(fuzz, &paint, depth - 1); } SkCanvas::SrcRectConstraint constraint = make_fuzz_t<bool>(fuzz) ? SkCanvas::kStrict_SrcRectConstraint : SkCanvas::kFast_SrcRectConstraint; canvas->drawBitmapRect(img, src, dst, usePaint ? &paint : nullptr, constraint); break; } case 41: { SkBitmap img = make_fuzz_bitmap(fuzz); SkRect dst; bool usePaint; fuzz->next(&dst, &usePaint); if (usePaint) { fuzz_paint(fuzz, &paint, depth - 1); } SkCanvas::SrcRectConstraint constraint = make_fuzz_t<bool>(fuzz) ? SkCanvas::kStrict_SrcRectConstraint : SkCanvas::kFast_SrcRectConstraint; canvas->drawBitmapRect(img, dst, usePaint ? &paint : nullptr, constraint); break; } case 42: { SkBitmap img = make_fuzz_bitmap(fuzz); SkIRect center; SkRect dst; bool usePaint; fuzz->next(&usePaint); if (usePaint) { fuzz_paint(fuzz, &paint, depth - 1); } if (make_fuzz_t<bool>(fuzz)) { fuzz->next(&center); } else { // Make valid center, see SkLatticeIter::Valid(). if (img.width() == 0 || img.height() == 0) { // bitmap may not have had its pixels initialized. break; } fuzz->nextRange(&center.fLeft, 0, img.width() - 1); fuzz->nextRange(&center.fTop, 0, img.height() - 1); fuzz->nextRange(&center.fRight, center.fLeft + 1, img.width()); fuzz->nextRange(&center.fBottom, center.fTop + 1, img.height()); } fuzz->next(&dst); canvas->drawBitmapNine(img, center, dst, usePaint ? &paint : nullptr); break; } case 43: { SkBitmap img = make_fuzz_bitmap(fuzz); bool usePaint; SkRect dst; fuzz->next(&usePaint, &dst); if (usePaint) { fuzz_paint(fuzz, &paint, depth - 1); } constexpr int kMax = 6; int xDivs[kMax], yDivs[kMax]; SkCanvas::Lattice lattice{xDivs, yDivs, nullptr, 0, 0, nullptr, nullptr}; fuzz->nextRange(&lattice.fXCount, 2, kMax); fuzz->nextRange(&lattice.fYCount, 2, kMax); fuzz->nextN(xDivs, lattice.fXCount); fuzz->nextN(yDivs, lattice.fYCount); canvas->drawBitmapLattice(img, lattice, dst, usePaint ? &paint : nullptr); break; } case 44: { auto img = make_fuzz_image(fuzz); bool usePaint; SkRect dst; fuzz->next(&usePaint, &dst); if (usePaint) { fuzz_paint(fuzz, &paint, depth - 1); } constexpr int kMax = 6; int xDivs[kMax], yDivs[kMax]; SkCanvas::Lattice lattice{xDivs, yDivs, nullptr, 0, 0, nullptr, nullptr}; fuzz->nextRange(&lattice.fXCount, 2, kMax); fuzz->nextRange(&lattice.fYCount, 2, kMax); fuzz->nextN(xDivs, lattice.fXCount); fuzz->nextN(yDivs, lattice.fYCount); canvas->drawImageLattice(img.get(), lattice, dst, usePaint ? &paint : nullptr); break; } case 45: { fuzz_paint(fuzz, &paint, depth - 1); fuzz_paint_text(fuzz, &paint); fuzz_paint_text_encoding(fuzz, &paint); SkScalar x, y; fuzz->next(&x, &y); SkTDArray<uint8_t> text = make_fuzz_text(fuzz, paint); canvas->drawText(text.begin(), SkToSizeT(text.count()), x, y, paint); break; } case 46: { fuzz_paint(fuzz, &paint, depth - 1); fuzz_paint_text(fuzz, &paint); fuzz_paint_text_encoding(fuzz, &paint); SkTDArray<uint8_t> text = make_fuzz_text(fuzz, paint); int glyphCount = paint.countText(text.begin(), SkToSizeT(text.count())); if (glyphCount < 1) { break; } SkAutoTMalloc<SkPoint> pos(glyphCount); SkAutoTMalloc<SkScalar> widths(glyphCount); paint.getTextWidths(text.begin(), SkToSizeT(text.count()), widths.get()); pos[0] = {0, 0}; for (int i = 1; i < glyphCount; ++i) { float y; fuzz->nextRange(&y, -0.5f * paint.getTextSize(), 0.5f * paint.getTextSize()); pos[i] = {pos[i - 1].x() + widths[i - 1], y}; } canvas->drawPosText(text.begin(), SkToSizeT(text.count()), pos.get(), paint); break; } case 47: { fuzz_paint(fuzz, &paint, depth - 1); fuzz_paint_text(fuzz, &paint); fuzz_paint_text_encoding(fuzz, &paint); SkTDArray<uint8_t> text = make_fuzz_text(fuzz, paint); int glyphCount = paint.countText(text.begin(), SkToSizeT(text.count())); SkAutoTMalloc<SkScalar> widths(glyphCount); if (glyphCount < 1) { break; } paint.getTextWidths(text.begin(), SkToSizeT(text.count()), widths.get()); SkScalar x = widths[0]; for (int i = 0; i < glyphCount; ++i) { SkTSwap(x, widths[i]); x += widths[i]; SkScalar offset; fuzz->nextRange(&offset, -0.125f * paint.getTextSize(), 0.125f * paint.getTextSize()); widths[i] += offset; } SkScalar y; fuzz->next(&y); canvas->drawPosTextH(text.begin(), SkToSizeT(text.count()), widths.get(), y, paint); break; } case 48: { fuzz_paint(fuzz, &paint, depth - 1); fuzz_paint_text(fuzz, &paint); fuzz_paint_text_encoding(fuzz, &paint); SkTDArray<uint8_t> text = make_fuzz_text(fuzz, paint); SkPath path; FuzzPath(fuzz, &path, 20); SkScalar hOffset, vOffset; fuzz->next(&hOffset, &vOffset); canvas->drawTextOnPathHV(text.begin(), SkToSizeT(text.count()), path, hOffset, vOffset, paint); break; } case 49: { SkMatrix matrix; bool useMatrix = make_fuzz_t<bool>(fuzz); if (useMatrix) { fuzz->next(&matrix); } fuzz_paint(fuzz, &paint, depth - 1); fuzz_paint_text(fuzz, &paint); fuzz_paint_text_encoding(fuzz, &paint); SkTDArray<uint8_t> text = make_fuzz_text(fuzz, paint); SkPath path; FuzzPath(fuzz, &path, 20); canvas->drawTextOnPath(text.begin(), SkToSizeT(text.count()), path, useMatrix ? &matrix : nullptr, paint); break; } case 50: { fuzz_paint(fuzz, &paint, depth - 1); fuzz_paint_text(fuzz, &paint); fuzz_paint_text_encoding(fuzz, &paint); SkTDArray<uint8_t> text = make_fuzz_text(fuzz, paint); SkRSXform rSXform[kMaxGlyphCount]; int glyphCount = paint.countText(text.begin(), SkToSizeT(text.count())); SkASSERT(glyphCount <= kMaxGlyphCount); fuzz->nextN(rSXform, glyphCount); SkRect cullRect; bool useCullRect; fuzz->next(&useCullRect); if (useCullRect) { fuzz->next(&cullRect); } canvas->drawTextRSXform(text.begin(), SkToSizeT(text.count()), rSXform, useCullRect ? &cullRect : nullptr, paint); break; } case 51: { sk_sp<SkTextBlob> blob = make_fuzz_textblob(fuzz); fuzz_paint(fuzz, &paint, depth - 1); SkScalar x, y; fuzz->next(&x, &y); canvas->drawTextBlob(blob, x, y, paint); break; } case 52: { bool usePaint, useMatrix; fuzz->next(&usePaint, &useMatrix); if (usePaint) { fuzz_paint(fuzz, &paint, depth - 1); } if (useMatrix) { fuzz->next(&matrix); } auto pic = make_fuzz_picture(fuzz, depth - 1); canvas->drawPicture(pic, useMatrix ? &matrix : nullptr, usePaint ? &paint : nullptr); break; } case 53: { fuzz_paint(fuzz, &paint, depth - 1); SkVertices::VertexMode vertexMode; SkBlendMode blendMode; fuzz_enum_range(fuzz, &vertexMode, 0, SkVertices::kTriangleFan_VertexMode); fuzz->next(&blendMode); constexpr int kMaxCount = 100; int vertexCount; SkPoint vertices[kMaxCount]; SkPoint texs[kMaxCount]; SkColor colors[kMaxCount]; fuzz->nextRange(&vertexCount, 3, kMaxCount); fuzz->nextN(vertices, vertexCount); bool useTexs, useColors; fuzz->next(&useTexs, &useColors); if (useTexs) { fuzz->nextN(texs, vertexCount); } if (useColors) { fuzz->nextN(colors, vertexCount); } int indexCount = 0; uint16_t indices[kMaxCount * 2]; if (make_fuzz_t<bool>(fuzz)) { fuzz->nextRange(&indexCount, vertexCount, vertexCount + kMaxCount); for (int i = 0; i < indexCount; ++i) { fuzz->nextRange(&indices[i], 0, vertexCount - 1); } } canvas->drawVertices(SkVertices::MakeCopy(vertexMode, vertexCount, vertices, useTexs ? texs : nullptr, useColors ? colors : nullptr, indexCount, indices), blendMode, paint); break; } default: SkASSERT(false); break; } } } static sk_sp<SkPicture> make_fuzz_picture(Fuzz* fuzz, int depth) { SkScalar w, h; fuzz->next(&w, &h); SkPictureRecorder pictureRecorder; fuzz_canvas(fuzz, pictureRecorder.beginRecording(w, h), depth - 1); return pictureRecorder.finishRecordingAsPicture(); } DEF_FUZZ(NullCanvas, fuzz) { fuzz_canvas(fuzz, SkMakeNullCanvas().get()); } constexpr SkISize kCanvasSize = {128, 160}; DEF_FUZZ(RasterN32Canvas, fuzz) { auto surface = SkSurface::MakeRasterN32Premul(kCanvasSize.width(), kCanvasSize.height()); if (!surface || !surface->getCanvas()) { fuzz->signalBug(); } fuzz_canvas(fuzz, surface->getCanvas()); } DEF_FUZZ(RasterN32CanvasViaSerialization, fuzz) { SkPictureRecorder recorder; fuzz_canvas(fuzz, recorder.beginRecording(SkIntToScalar(kCanvasSize.width()), SkIntToScalar(kCanvasSize.height()))); sk_sp<SkPicture> pic(recorder.finishRecordingAsPicture()); if (!pic) { fuzz->signalBug(); } sk_sp<SkData> data = pic->serialize(); if (!data) { fuzz->signalBug(); } SkReadBuffer rb(data->data(), data->size()); auto deserialized = SkPicture::MakeFromBuffer(rb); if (!deserialized) { fuzz->signalBug(); } auto surface = SkSurface::MakeRasterN32Premul(kCanvasSize.width(), kCanvasSize.height()); SkASSERT(surface && surface->getCanvas()); surface->getCanvas()->drawPicture(deserialized); } DEF_FUZZ(ImageFilter, fuzz) { auto fil = make_fuzz_imageFilter(fuzz, 20); SkPaint paint; paint.setImageFilter(fil); SkBitmap bitmap; SkCanvas canvas(bitmap); canvas.saveLayer(SkRect::MakeWH(500, 500), &paint); } //SkRandom _rand; #define SK_ADD_RANDOM_BIT_FLIPS DEF_FUZZ(SerializedImageFilter, fuzz) { auto filter = make_fuzz_imageFilter(fuzz, 20); auto data = filter->serialize(); const unsigned char* ptr = static_cast<const unsigned char*>(data->data()); size_t len = data->size(); #ifdef SK_ADD_RANDOM_BIT_FLIPS unsigned char* p = const_cast<unsigned char*>(ptr); for (size_t i = 0; i < len; ++i, ++p) { uint8_t j; fuzz->nextRange(&j, 1, 250); if (j == 1) { // 0.4% of the time, flip a bit or byte uint8_t k; fuzz->nextRange(&k, 1, 10); if (k == 1) { // Then 10% of the time, change a whole byte uint8_t s; fuzz->nextRange(&s, 0, 2); switch(s) { case 0: *p ^= 0xFF; // Flip entire byte break; case 1: *p = 0xFF; // Set all bits to 1 break; case 2: *p = 0x00; // Set all bits to 0 break; } } else { uint8_t s; fuzz->nextRange(&s, 0, 7); *p ^= (1 << 7); } } } #endif // SK_ADD_RANDOM_BIT_FLIPS auto deserializedFil = SkImageFilter::Deserialize(ptr, len); // uncomment below to write out a serialized image filter (to make corpus // for -t filter_fuzz) // SkString s("./serialized_filters/sf"); // s.appendU32(_rand.nextU()); // auto file = sk_fopen(s.c_str(), SkFILE_Flags::kWrite_SkFILE_Flag); // sk_fwrite(data->bytes(), data->size(), file); // sk_fclose(file); SkPaint paint; paint.setImageFilter(deserializedFil); SkBitmap bitmap; SkCanvas canvas(bitmap); canvas.saveLayer(SkRect::MakeWH(500, 500), &paint); } #if SK_SUPPORT_GPU static void fuzz_ganesh(Fuzz* fuzz, GrContext* context) { SkASSERT(context); auto surface = SkSurface::MakeRenderTarget( context, SkBudgeted::kNo, SkImageInfo::Make(kCanvasSize.width(), kCanvasSize.height(), kRGBA_8888_SkColorType, kPremul_SkAlphaType)); SkASSERT(surface && surface->getCanvas()); fuzz_canvas(fuzz, surface->getCanvas()); } DEF_FUZZ(NativeGLCanvas, fuzz) { sk_gpu_test::GrContextFactory f; GrContext* context = f.get(sk_gpu_test::GrContextFactory::kGL_ContextType); if (!context) { context = f.get(sk_gpu_test::GrContextFactory::kGLES_ContextType); } fuzz_ganesh(fuzz, context); } // This target is deprecated, NullGLContext is not well maintained. // Please use MockGPUCanvas instead. DEF_FUZZ(NullGLCanvas, fuzz) { sk_gpu_test::GrContextFactory f; fuzz_ganesh(fuzz, f.get(sk_gpu_test::GrContextFactory::kNullGL_ContextType)); } // This target is deprecated, DebugGLContext is not well maintained. // Please use MockGPUCanvas instead. DEF_FUZZ(DebugGLCanvas, fuzz) { sk_gpu_test::GrContextFactory f; fuzz_ganesh(fuzz, f.get(sk_gpu_test::GrContextFactory::kDebugGL_ContextType)); } DEF_FUZZ(MockGPUCanvas, fuzz) { sk_gpu_test::GrContextFactory f; fuzz_ganesh(fuzz, f.get(sk_gpu_test::GrContextFactory::kMock_ContextType)); } #endif DEF_FUZZ(PDFCanvas, fuzz) { SkNullWStream stream; auto doc = SkDocument::MakePDF(&stream); fuzz_canvas(fuzz, doc->beginPage(SkIntToScalar(kCanvasSize.width()), SkIntToScalar(kCanvasSize.height()))); } // not a "real" thing to fuzz, used to debug errors found while fuzzing. DEF_FUZZ(_DumpCanvas, fuzz) { SkDebugCanvas debugCanvas(kCanvasSize.width(), kCanvasSize.height()); fuzz_canvas(fuzz, &debugCanvas); std::unique_ptr<SkCanvas> nullCanvas = SkMakeNullCanvas(); UrlDataManager dataManager(SkString("data")); Json::Value json = debugCanvas.toJSON(dataManager, debugCanvas.getSize(), nullCanvas.get()); Json::StyledStreamWriter(" ").write(std::cout, json); }
[ "skia-commit-bot@chromium.org" ]
skia-commit-bot@chromium.org
122b106c621da984504aaaa27b8e51518a818112
37b06470bea58c0e17e1e2f8cbfed105f02c09b3
/src/SPH/grid/gridSph.cpp
b75efd87a07b83d3b0c8976af97a7c7422a81752
[]
no_license
edarles/Grain
7e56bc6962380a9dce9b6f17a2eca0f6027a49fc
e197672b637e2de7c14aa188d2abf1b87961454f
refs/heads/master
2020-03-23T13:06:17.628516
2018-07-19T15:33:44
2018-07-19T15:33:44
141,600,131
0
0
null
null
null
null
UTF-8
C++
false
false
5,911
cpp
#include <gridSph.h> #include <sphParticle.h> #include <iostream> /****************************************************************************/ /****************************************************************************/ GridSPH::GridSPH():GridFluid(Vector3f(-1,-1,-1),Vector3f(1,1,1),0.05,0.05,0.05) { init(); } /****************************************************************************/ GridSPH::GridSPH(Vector3f min, Vector3f max, float dx, float dy, float dz):GridFluid(min,max,dx,dy,dz) { init(); } /****************************************************************************/ GridSPH::GridSPH(Vector3f min, Vector3f max, float dx, float dy, float dz, float intensity) :GridFluid(min,max,dx,dy,dz,intensity) { init(); } /****************************************************************************/ GridSPH::~GridSPH() { } /*************************************************/ /*************************************************/ void GridSPH::computeNeighborhood(vector<SPHParticle*> particles) { vector< vector<int> > indexs; // Store particles into cells for(int ix=0; ix<m_nx; ix++){ for(int iy=0; iy<m_ny; iy++){ for(int iz=0; iz<m_nz; iz++){ int indexCell = ix + iy*m_nx + iz*m_nx*m_ny; indexs.push_back(vector<int>()); } } } for(unsigned int i=0;i<particles.size();i++){ Vector3f pos = particles[i]->getPos(); int iC = (int) floor((double)(pos[0]-m_min[0])/m_dx); int jC = (int) floor((double)(pos[1]-m_min[1])/m_dy); int kC = (int) floor((double)(pos[2]-m_min[2])/m_dz); int indexCell = iC + jC*m_nx + kC*m_nx*m_ny; if(indexCell>=0 && indexCell<m_n){ indexs[indexCell].push_back(i); } } // Compute neighboorhood for each particle for(unsigned int iP=0;iP<particles.size();iP++) { particles[iP]->clearVois(); Vector3f pos = particles[iP]->getPos(); // à rajouter dans omega //particles[iP]->setVois(iP); //*********************** float h1 = particles[iP]->getRadius(); float x = pos[0]; float y = pos[1]; float z = pos[2]; int ix = (int)floor((double)(x-m_min[0])/m_dx); int iy = (int)floor((double)(y-m_min[1])/m_dy); int iz = (int)floor((double)(z-m_min[2])/m_dz); int nbcx = floor(h1/m_dx); int nbcy = floor(h1/m_dy); int nbcz = floor(h1/m_dz); int nbP = 0; if(ix>=0 && iy>=0 && iz>=0 && ix < m_nx && iy < m_ny && iz < m_nz){ for(int i=ix-nbcx; i<=ix+nbcx; i++){ for(int j=iy-nbcy; j<=iy+nbcy; j++){ for(int k=iz-nbcz; k<=iz+nbcz; k++){ if(i>=0 && j>=0 && k>=0 && i<m_nx && j<m_ny && k<m_nz){ int indexCell = i + j*m_nx + k*m_nx*m_ny; if(indexCell>=0 && indexCell<m_n){ if(indexs[indexCell].size()>0){ for(unsigned int n=0;n<indexs[indexCell].size();n++) { int iP2 = indexs[indexCell][n]; if(iP2>particles.size()) cout << "Pb: index: " << iP2 << " size: " << particles.size() << endl; else { Vector3f pos2 = particles[iP2]->getPos(); Vector3f PP = pos - pos2; float h2 = particles[iP2]->getRadius(); float r = max(h1,h2); if(PP.norm()<=r) particles[iP]->setVois(iP2); } } } } } } } } } } for(unsigned int i=0;i<indexs.size();i++){ indexs[i].clear(); vector<int>().swap(indexs[i]); indexs[i].shrink_to_fit(); } indexs.clear(); vector<vector<int>>().swap(indexs); indexs.shrink_to_fit(); } /****************************************************************************/ /****************************************************************************/ void GridSPH::computeNeighborhood2D(vector<SPHParticle*> particles) { vector< vector<int> > indexs; // Store particles into cells for(int ix=0; ix<=m_nx; ix++){ for(int iy=0; iy<=m_ny; iy++){ int indexCell = ix + iy*m_nx; indexs.push_back(vector<int>()); } } for(unsigned int i=0;i<particles.size();i++){ Vector3f pos = particles[i]->getPos(); int iC = (int) floor((double)(pos[0]-m_min[0])/m_dx); int jC = (int) floor((double)(pos[1]-m_min[1])/m_dy); int indexCell = iC + jC*m_nx ; if(indexCell>=0 && indexCell<=m_n){ indexs[indexCell].push_back(i); } } // Compute neighboorhood for each particle for(unsigned int iP=0;iP<particles.size();iP++){ particles[iP]->clearVois(); Vector3f pos = particles[iP]->getPos(); //particles[iP]->setVois(iP); float h1 = particles[iP]->getRadius(); float x = pos[0]; float y = pos[1]; int ix = (int)floor((double)(x-m_min[0])/m_dx); int iy = (int)floor((double)(y-m_min[1])/m_dy); int nbcx = floor(h1/m_dx)+1; int nbcy = floor(h1/m_dy)+1; int nbP = 0; if(ix>=0 && iy>=0 && ix <= m_nx && iy <= m_ny){ for(int i=ix-nbcx; i<=ix+nbcx; i++){ for(int j=iy-nbcy; j<=iy+nbcy; j++){ if(i>=0 && j>=0 && i<=m_nx && j<=m_ny ){ int indexCell = i + j*m_nx ; if(indexCell>=0 && indexCell<=m_n){ if(indexs[indexCell].size()>0){ for(unsigned int n=0;n<indexs[indexCell].size();n++) { int iP2 = indexs[indexCell][n]; if(iP2>particles.size()) cout << "Pb: index: " << iP2 << " size: " << particles.size() << endl; else { Vector3f pos2 = particles[iP2]->getPos(); Vector3f PP = pos - pos2; float h2 = particles[iP2]->getRadius(); float r = max(h1,h2); if(PP.norm()<=r) particles[iP]->setVois(iP2); } } } } } } } } } for(unsigned int i=0;i<indexs.size();i++){ indexs[i].clear(); vector<int>().swap(indexs[i]); indexs[i].shrink_to_fit(); } indexs.clear(); vector<vector<int>>().swap(indexs); indexs.shrink_to_fit(); } /****************************************************************************/ /****************************************************************************/
[ "emmanuelle.darles@univ-poitiers.fr" ]
emmanuelle.darles@univ-poitiers.fr
2b7d9242e51e420364968f3cadd53f7f99c340b9
884d8fd8d4e2bc5a71852de7131a7a6476bf9c48
/grid-test/export/macos/obj/include/openfl/display/Application.h
c8d8399a3d492de4dc5725139ae4de31c6707c93
[ "Apache-2.0" ]
permissive
VehpuS/learning-haxe-and-haxeflixel
69655276f504748347decfea66b91a117a722f6c
cb18c074720656797beed7333eeaced2cf323337
refs/heads/main
2023-02-16T07:45:59.795832
2021-01-07T03:01:46
2021-01-07T03:01:46
324,458,421
0
0
null
null
null
null
UTF-8
C++
false
true
1,790
h
// Generated by Haxe 4.1.4 #ifndef INCLUDED_openfl_display_Application #define INCLUDED_openfl_display_Application #ifndef HXCPP_H #include <hxcpp.h> #endif #ifndef INCLUDED_lime_app_Application #include <lime/app/Application.h> #endif HX_DECLARE_CLASS2(lime,app,Application) HX_DECLARE_CLASS2(lime,app,IModule) HX_DECLARE_CLASS2(lime,app,Module) HX_DECLARE_CLASS2(lime,ui,Window) HX_DECLARE_CLASS2(openfl,display,Application) namespace openfl{ namespace display{ class HXCPP_CLASS_ATTRIBUTES Application_obj : public ::lime::app::Application_obj { public: typedef ::lime::app::Application_obj super; typedef Application_obj OBJ_; Application_obj(); public: enum { _hx_ClassId = 0x169c11fe }; void __construct(); inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="openfl.display.Application") { return ::hx::Object::operator new(inSize,inContainer,inName); } inline void *operator new(size_t inSize, int extra) { return ::hx::Object::operator new(inSize+extra,true,"openfl.display.Application"); } static ::hx::ObjectPtr< Application_obj > __new(); static ::hx::ObjectPtr< Application_obj > __alloc(::hx::Ctx *_hx_ctx); static void * _hx_vtable; static Dynamic __CreateEmpty(); static Dynamic __Create(::hx::DynamicArray inArgs); //~Application_obj(); HX_DO_RTTI_ALL; ::hx::Val __Field(const ::String &inString, ::hx::PropertyAccess inCallProp); static void __register(); bool _hx_isInstanceOf(int inClassId); ::String __ToString() const { return HX_("Application",30,43,71,0e); } static void __boot(); static ::Dynamic __meta__; ::lime::ui::Window createWindow( ::Dynamic attributes); }; } // end namespace openfl } // end namespace display #endif /* INCLUDED_openfl_display_Application */
[ "vehpus@gmail.com" ]
vehpus@gmail.com
2d1b88e84453f04843225c0feb386803ee455edb
349fe789ab1e4e46aae6812cf60ada9423c0b632
/ComClasses/DLL/PrintPrice/UPrintPriceNumber6.cpp
6ac890c50b9ab05e2d02f5001d6dc86f4b8a7c60
[]
no_license
presscad/ERP
a6acdaeb97b3a53f776677c3a585ca860d4de980
18ecc6c8664ed7fc3f01397d587cce91fc3ac78b
refs/heads/master
2020-08-22T05:24:15.449666
2019-07-12T12:59:13
2019-07-12T12:59:13
216,326,440
1
0
null
2019-10-20T07:52:26
2019-10-20T07:52:26
null
WINDOWS-1251
C++
false
false
10,515
cpp
//--------------------------------------------------------------------------- #pragma hdrstop #include "UPrintPriceNumber6.h" #include "IDMSprNom.h" //--------------------------------------------------------------------------- #pragma package(smart_init) //------------------------------------------------------------------- TPrintPriceNumber6::TPrintPriceNumber6() { } //----------------------------------------------------------------------------- TPrintPriceNumber6::~TPrintPriceNumber6() { } //----------------------------------------------------------------------- bool TPrintPriceNumber6::Init(void) { bool result=false; //ПРИВЕЛЕГИИ DM_Connection->GetPrivDM(GCPRIV_DM_NoModule); ExecPriv=DM_Connection->ExecPriv; InsertPriv=DM_Connection->InsertPriv; EditPriv=DM_Connection->EditPriv; DeletePriv=DM_Connection->DeletePriv; result=true; return result; } //---------------------------------------------------------------------------- void TPrintPriceNumber6::CreatePrice(void) { // SE=new TSheetEditor(Application); SE->SS->RowsAutoHeight=false; if (!SE) return; KolNaPage=0; KolNaString=0; x = 1; y = 1; SE->SS->BeginUpdate(); NumberPage=1; SE->SS->ActiveSheet->Caption= "Стр."+IntToStr(NumberPage); PrintPriceNumber_OutputZagolovok(); for (int i=0; i<List->Count;i++) { ElementSpiska=(TElementSpiskaPrintPrice*)List->Items[i]; if (ElementSpiska->Grp==true) { PrintPriceNumber_OutputGrp(); } else { IDMSprNom * DMSprNom; InterfaceGlobalCom->kanCreateObject("Oberon.DMSprNom.1",IID_IDMSprNom, (void**)&DMSprNom); DMSprNom->Init(InterfaceMainObject,0); DMSprNom->IdTypePrice=IdTypePrice; DMSprNom->OpenElement(ElementSpiska->Id); PrintPriceNumber_OutputElement(DMSprNom->ElementNAMENOM->AsString, DMSprNom->ElementCODENOM->AsString, FloatToStrF(DMSprNom->ElementZNACH_PRICE->AsFloat,ffFixed,10,2), ElementSpiska->NameEd, DMSprNom->ElementNAME_SCOUNTRY->AsString); DMSprNom->kanRelease(); } } SE->SS->EndUpdate(); SE->Show(); } //---------------------------------------------------------------------------- void TPrintPriceNumber6::PrintPriceNumber_OutputGrp(void) { IDMSprNom * DMSprNom; InterfaceGlobalCom->kanCreateObject("Oberon.DMSprNom.1",IID_IDMSprNom, (void**)&DMSprNom); DMSprNom->Init(InterfaceMainObject,0); DMSprNom->IdTypePrice=IdTypePrice; DMSprNom->OpenTable(ElementSpiska->Id,false); DMSprNom->Table->First(); while (!DMSprNom->Table->Eof) { DMSprNom->OpenElement(DMSprNom->TableIDNOM->AsInteger); PrintPriceNumber_OutputElement(DMSprNom->TableNAMENOM->AsString, DMSprNom->TableCODENOM->AsString, FloatToStrF(DMSprNom->TableZNACH_PRICE->AsFloat,ffFixed,10,2), DMSprNom->TableNAMEED->AsString, DMSprNom->ElementNAME_SCOUNTRY->AsString); DMSprNom->Table->Next(); } DMSprNom->kanRelease(); } //----------------------------------------------------------------------------- void TPrintPriceNumber6::PrintPriceNumber_OutputZagolovok(void) { TcxSSHeader *cHeader; cHeader = SE->SS->ActiveSheet->Cols; cHeader->Size[0] = 10; cHeader->Size[1] = 58; cHeader->Size[2] = 58; cHeader->Size[3] = 58; cHeader->Size[4] = 10; cHeader->Size[5] = 58; cHeader->Size[6] = 58; cHeader->Size[7] = 58; cHeader->Size[8] = 10; cHeader->Size[9] = 58; cHeader->Size[10] = 58; cHeader->Size[11] = 58; cHeader->Size[12] = 10; cHeader->Size[13] = 58; cHeader->Size[14] = 58; cHeader->Size[15] = 58; } //----------------------------------------------------------------------------- void TPrintPriceNumber6::PrintPriceNumber_OutputElement(AnsiString name, AnsiString code, AnsiString price, AnsiString name_ed, AnsiString country) { if (KolNaString==4) //новая строка { KolNaString=0; x=1; y=y+8; SE->SS->ActiveSheet->Rows->Size[y]=20; y++; } if (KolNaPage==12) //новая страница { NumberPage++; SE->SS->AddSheetPage("Стр."+IntToStr(NumberPage)); SE->SS->ActivePage++; PrintPriceNumber_OutputZagolovok(); KolNaString=0; KolNaPage=0; x = 1; y = 1; } int tek_y=y; SE->SS->ActiveSheet->Rows->Size[y]=60; y++; TRect rect; rect.Left = x; rect.Top = y; rect.Right = x+2; rect.Bottom = y; SE->SS->ActiveSheet->SetMergedState(rect, true); TcxSSCellObject *cell; cell = SE->SS->ActiveSheet->GetCellObject(x, y); cell->Text = NameFirm; cell->Style->HorzTextAlign = haCENTER; cell->Style->VertTextAlign = vaCENTER; cell->Style->Font->Name = "Times New Roman"; cell->Style->Font->Size = 12; cell->Style->Font->Style = TFontStyles() << fsUnderline << fsBold;; cell->Style->Borders->Edges [eTop]->Style=lsThick; cell->Style->Borders->Edges [eLeft]->Style=lsThick; SE->SS->ActiveSheet->Rows->Size[y]=18; cell->Style->Brush->BackgroundColor = 14; delete cell; cell = SE->SS->ActiveSheet->GetCellObject(x+1, y); cell->Style->Borders->Edges [eTop]->Style=lsThick; cell->Style->Brush->BackgroundColor = 14; delete cell; cell = SE->SS->ActiveSheet->GetCellObject(x+2, y); cell->Style->Borders->Edges [eRight]->Style=lsThick; cell->Style->Borders->Edges [eTop]->Style=lsThick; cell->Style->Brush->BackgroundColor = 14; delete cell; y++; //-----------------следующая строка ------------------------------------------ rect.Left = x; rect.Top = y; rect.Right = x+2; rect.Bottom = y+1; SE->SS->ActiveSheet->SetMergedState(rect, true); cell = SE->SS->ActiveSheet->GetCellObject(x, y); cell->Style->Borders->Edges [eLeft]->Style=lsThick; cell->Text = name; cell->Style->HorzTextAlign = haCENTER; cell->Style->VertTextAlign = vaCENTER; cell->Style->Font->Name = "Times New Roman"; cell->Style->Font->Size = 16; cell->Style->WordBreak = true; cell->Style->Font->Style = TFontStyles() << fsBold << fsUnderline; delete cell; cell = SE->SS->ActiveSheet->GetCellObject(x+2, y); cell->Style->Borders->Edges [eRight]->Style=lsThick; delete cell; SE->SS->ActiveSheet->Rows->Size[y]=50; SE->SS->ActiveSheet->Rows->Size[y+1]=50; y++; //-----------------следующая строка ------------------------------------------ cell = SE->SS->ActiveSheet->GetCellObject(x, y); cell->Style->Borders->Edges [eLeft]->Style=lsThick; delete cell; cell = SE->SS->ActiveSheet->GetCellObject(x+2, y); cell->Style->Borders->Edges [eRight]->Style=lsThick; delete cell; y++; //-----------------следующая строка ------------------------------------------ cell = SE->SS->ActiveSheet->GetCellObject(x, y); cell->Style->Borders->Edges [eLeft]->Style=lsThick; cell->Text = "Код: "+code; cell->Style->HorzTextAlign = haLEFT; cell->Style->Font->Size = 14; delete cell; cell = SE->SS->ActiveSheet->GetCellObject(x+2, y); cell->Style->Borders->Edges [eRight]->Style=lsThick; delete cell; cell = SE->SS->ActiveSheet->GetCellObject(x+2, y); cell->Text = name_ed+" "; cell->Style->HorzTextAlign = haRIGHT; // cell->Style->VertTextAlign = vaCENTER; cell->Style->Font->Name = "Times New Roman"; cell->Style->Font->Size = 14; // cell->Style->Font->Style = TFontStyles() << fsBold; SE->SS->ActiveSheet->Rows->Size[y]=20; delete cell; y++; //-----------------следующая строка ------------------------------------------ cell = SE->SS->ActiveSheet->GetCellObject(x, y); cell->Style->Borders->Edges [eLeft]->Style=lsThick; cell->Style->Brush->BackgroundColor = 14; delete cell; cell = SE->SS->ActiveSheet->GetCellObject(x+1, y); AnsiString str=glConvertString(price, ".", "="); cell->Text = glConvertString(str, ",", "="); cell->Style->HorzTextAlign = haCENTER; cell->Style->VertTextAlign = vaCENTER; cell->Style->Font->Name = "Times New Roman"; cell->Style->Font->Size = 30; cell->Style->Font->Style = TFontStyles() << fsBold; cell->Style->Brush->BackgroundColor = 14; delete cell; cell = SE->SS->ActiveSheet->GetCellObject(x+2, y); cell->Style->Borders->Edges [eRight]->Style=lsThick; cell->Style->Brush->BackgroundColor = 14; delete cell; SE->SS->ActiveSheet->Rows->Size[y]=60; y++; //----------------------------- cell = SE->SS->ActiveSheet->GetCellObject(x, y); cell->Style->Borders->Edges [eLeft]->Style=lsThick; // cell->Style->Borders->Edges [eBottom]->Style=lsThick; delete cell; cell = SE->SS->ActiveSheet->GetCellObject(x+1, y); // cell->Style->Borders->Edges [eBottom]->Style=lsThick; cell->Text =country; cell->Style->HorzTextAlign = haCENTER; cell->Style->VertTextAlign = vaCENTER; cell->Style->Font->Name = "Times New Roman"; cell->Style->Font->Size = 12; cell->Style->Font->Style = TFontStyles() << fsBold; delete cell; cell = SE->SS->ActiveSheet->GetCellObject(x+2, y); cell->Style->Borders->Edges [eRight]->Style=lsThick; // cell->Style->Borders->Edges [eBottom]->Style=lsThick; delete cell; SE->SS->ActiveSheet->Rows->Size[y]=18; y++; //-----------------следующая строка ------------------------------------------ cell = SE->SS->ActiveSheet->GetCellObject(x, y); cell->Style->Borders->Edges [eLeft]->Style=lsThick; cell->Style->Borders->Edges [eBottom]->Style=lsThick; delete cell; cell = SE->SS->ActiveSheet->GetCellObject(x+1, y); cell->Style->Borders->Edges [eBottom]->Style=lsThick; cell->Text ="Годен до_______________ "; cell->Style->HorzTextAlign = haCENTER; cell->Style->VertTextAlign = vaBOTTOM; cell->Style->Font->Name = "Times New Roman"; cell->Style->Font->Size = 10; delete cell; cell = SE->SS->ActiveSheet->GetCellObject(x+2, y); cell->Style->Borders->Edges [eRight]->Style=lsThick; cell->Style->Borders->Edges [eBottom]->Style=lsThick; delete cell; SE->SS->ActiveSheet->Rows->Size[y]=18; x=x+4; y=tek_y; KolNaString++; KolNaPage++; } //-----------------------------------------------------------------------------
[ "sasha@kaserv.ru" ]
sasha@kaserv.ru
411ab0f7475c8c88eba917093d2fdbd634d7966e
51fdd27bfe20e60dd726b04850a881be110002e3
/poj/POJ_zyt/3273/3273.cpp
27dea9126ba52ac3da95b5311367e67e337c6446
[]
no_license
MintSummer/TYC
0eb4d04851a6ecc8e2d83475a6f16c6d1c6d8f9b
23700d4d857d0729b2db3b1ef9afc21b040aecbd
refs/heads/master
2020-04-11T16:13:18.035139
2019-03-10T15:18:53
2019-03-10T15:18:53
161,916,623
0
0
null
null
null
null
UTF-8
C++
false
false
776
cpp
#include<cstdio> #include<algorithm> using namespace std; int n,m,high,low; int money[100010]; int main(void) { scanf("%d%d",&n,&m); for(int i=0;i<n;i++) { scanf("%d",money+i); high+=money[i]; low=max(low,money[i]); } int mid=(high+low)/2; while(low<high) { int sum=0,group=0; for(int i=0;i<n;i++) { if(sum+money[i]<=mid)sum+=money[i]; else sum=money[i],group++; } group++; if(group>m)low=mid+1; else high=mid-1; mid=(high+low)/2; } printf("%d",mid); return 0; }
[ "tangyichen0902@126.com" ]
tangyichen0902@126.com
6a8d301f9505aec723b27f5e49622e477ca401e5
164820b0aa546f65741bfaace5c542a8236d4b88
/OOP_Assignment/Task3/Expression.h
d519a5e70d9087f6880fd39d083d16f13844dad0
[]
no_license
dsumler/Java
9c55a44e7995d432bc682d9d133a9bdb230fc57e
20f69142ed7fbe8451fee136da44fb42d46cd467
refs/heads/master
2023-07-06T20:57:43.752163
2021-08-03T20:19:55
2021-08-03T20:19:55
392,442,086
0
0
null
null
null
null
UTF-8
C++
false
false
383
h
// // Created by dsuml on 14-Jan-20. // #ifndef QUESTION3_EXPRESSION_H #define QUESTION3_EXPRESSION_H template <typename A, typename BinOp, typename B> class Expression { const A &l_; const B &r_; public: Expression(const A &l, const B &r) : l_(l), r_(r) {}; double eval() { return BinOp::apply(l_, r_); }; }; #endif //QUESTION3_EXPRESSION_H
[ "d.sumler1@outlook.com" ]
d.sumler1@outlook.com
ebe51cfb01b8169c8cc8b97e5ef6f0dd8e750c3d
0b6530ec3938127f4422815fd01f59b72f0b92d6
/Project 8/Backups/Submiited/ExecutorCommands/eCDUMP.cpp
14b3749f88c99ebeb13ed7629339ae0300ac4b17
[]
no_license
brenthompson2/Compiler-Construction
c9160921b48252b63981388c6fcc82d38af46eb0
1f239285515d49d241c10d3aad42e6e89d9bcd9f
refs/heads/master
2021-08-29T19:05:26.702578
2017-12-14T18:10:36
2017-12-14T18:10:36
107,502,420
0
0
null
null
null
null
UTF-8
C++
false
false
3,628
cpp
/* ============================================================================== File: eCDUMP.cpp Author: Brendan Thompson Updated: 11/13/17 Description: Implementation of Functions for processing CDUMP command for Compiler object made for Transylvania University University Fall Term 2017 Compiler Construction class - NOT BEING USED: EXECUTOR IS HANDLING THIS COMMAND ============================================================================== */ #include "eCDUMP.h" /* ============================================================================== Constructor & Destructor ============================================================================== */ eCDUMP::eCDUMP(){ return; } eCDUMP::~eCDUMP(){ return; } /* ============================================================================== Public Manipulator Methods ============================================================================== */ // Connects local pointer to SymbolTable with the parent's (compiler's) versions void eCDUMP::prepareCDUMP(SymbolTable *parentMemoryManager){ currentMemoryManager = parentMemoryManager; } // calls the functions necessary to parse the line, sync the variables with the SymbolTable, and print the object code to the file while counting errors void eCDUMP::handleCDUMP(ProgramLineObject *currentLine){ globalCurrentLine = currentLine; string startIndexValue_string, endIndexValue_string, startIndexMemLocation_string, endIndexMemLocation_string; int startIndexValue_int, endIndexValue_int, startIndexMemLocation_int, endIndexMemLocation_int; startIndexMemLocation_int = ((*globalCurrentLine).lineOfCodeArray)[1]; endIndexMemLocation_int = ((*globalCurrentLine).lineOfCodeArray)[2]; // cout << "\t\t[CDUMP]: Executing CDUMP command from values at mem locations " << startIndexMemLocation_int << " to " << endIndexMemLocation_int << endl; startIndexValue_string = (*currentMemoryManager).getValue(startIndexMemLocation_int); endIndexValue_string = (*currentMemoryManager).getValue(endIndexMemLocation_int); // cout << "\t\t[CDUMP]: Executing CDUMP command from " << startIndexValue_string << " to " << endIndexValue_string << endl; std::stringstream str0(startIndexValue_string); str0 >> startIndexValue_int; std::stringstream str1(endIndexValue_string); str1 >> endIndexValue_int; // cout << "\t\t[CDUMP]: Executing CDUMP command from " << startIndexValue_int << " to " << endIndexValue_int << endl; coreDump(startIndexValue_int, endIndexValue_int); // cout << "\t\t[CDUMP]: Executed CDUMP command\n"; return; } /* ============================================================================== Private Manipulator Methods ============================================================================== */ /* ============================================================================== Private Accessor Methods ============================================================================== */ // Outputs All Literals between the start and the end indexes void eCDUMP::coreDump(int startIndex, int endIndex){ string currentLiteral; if ((startIndex >= 0) && (endIndex <= MAX_NUM_VARIABLES)){ for (int i = startIndex; i <= endIndex; i++){ currentLiteral = (*currentMemoryManager).getValue(i); cout << i << ": " << currentLiteral << endl; } } else { if (startIndex >= 0){ cout << "\t\t\t[LiteralTable]: Warning: Start Index Must Exceed 0: \"" << startIndex << "\"\n"; } if (endIndex <= MAX_NUM_VARIABLES){ cout << "\t\t\t[LiteralTable]: Warning: End Index Exceeds " << MAX_NUM_VARIABLES << ": \"" << endIndex << "\"\n"; } } return; }
[ "brenthompson2@gmail.com" ]
brenthompson2@gmail.com
535393a00228a04c6b90946897f3bab381739fa7
d0966bf382f0eb739bf59d61ae967e0f83d004cc
/csharp/csharp/shared/makefile.inc
c6d6b43f195746101df9946c7ee51082acb62f63
[]
no_license
mattwarren/GenericsInDotNet
7b6f871808c411cbd05c538c5652618ddf162e20
2714ccac6f18f0f6ff885567b90484013b31e007
refs/heads/master
2021-04-30T04:56:03.409728
2018-02-13T16:09:33
2018-02-13T16:09:33
121,404,138
4
0
null
null
null
null
UTF-8
C++
false
false
499
inc
# # # Copyright (c) 2002 Microsoft Corporation. All rights reserved. # # The use and distribution terms for this software are contained in the file # named license.txt, which can be found in the root of this distribution. # By using this software in any fashion, you are agreeing to be bound by the # terms of this license. # # You must not remove this notice, or any other, from this software. # # # # R E A D T H I S # # ...this is where we can override things in the makefile.def #
[ "matt.warren@live.co.uk" ]
matt.warren@live.co.uk
bd137c2303580759e1672cbde7926ce83c1247e5
7c9966c0a9d853f588fdd8ee91b7a6a4ac83aa65
/stream.h
04abad379da5c95c520e3ce6f09b558c05e2901c
[]
no_license
paxunix/sandbox
1e6d015322531af32033d144571baf75f0c3c4de
4fd728605cdfdd76ec8ccbea5e1ebc0fb67b8bda
refs/heads/master
2016-09-05T20:18:26.866488
2011-05-30T23:35:04
2011-05-30T23:35:04
1,823,835
0
0
null
null
null
null
UTF-8
C++
false
false
1,372
h
/* STREAM.H Copyright (c) 1995 Shawn Halpenny All rights reserved. Input and output stream wrapper classes. Tailored especially for Sandbox. */ #ifndef __STREAM_H #define __STREAM_H #ifndef __STDIO_H #include <stdio.h> #endif class ifstream { FILE *pf; char *pBuf; public: ifstream(); ~ifstream(); void close(); void open(char *, int=16384); int operator!(); friend ifstream& ws(ifstream&); ifstream& operator>>(ifstream& (*f)(ifstream&)); ifstream& operator>>(char*); ifstream& operator>>(char&); ifstream& operator>>(int&); ifstream& operator>>(unsigned int&); ifstream& operator>>(long&); ifstream& operator>>(unsigned long&); ifstream& ignore(int=1, int=EOF); ifstream& putback(char c) { ungetc(c, pf); return *this; } int peek(); int get() { return fgetc(pf); } int good(); ifstream& getline(char *, int, char = '\n'); }; class ofstream { FILE *pf; char *pBuf; public: ofstream(); ~ofstream(); void close(); void open(char *, int, int=16384); int operator!(); ofstream& operator<<(char); ofstream& operator<<(int n) { return *this << (long) n; } ofstream& operator<<(unsigned int n) { return *this << (unsigned long) n; } ofstream& operator<<(long); ofstream& operator<<(unsigned long); ofstream& operator<<(const char *); ofstream& operator<<(ofstream& (*f)(ofstream &)); int good(); }; #endif //__STREAM_H
[ "paxunix@gmail.com" ]
paxunix@gmail.com
8c3c4169968c8552239ce195908b7a0359dfe666
ece0b2cf5a898237f34761030b20016740ba6ec8
/parser/scanner.cpp
f37ee515861e0c8a6eaf9a2e48da49cf50643816
[]
no_license
cchapman94/cs421
20d08f4fdeb81b20dd1cb154352d23d54f6b86d0
1b067b8e66b17cff0bc3b0bca94609d301ee099f
refs/heads/master
2020-04-30T13:22:32.687624
2019-05-17T01:42:37
2019-05-17T01:42:37
176,855,823
1
0
null
null
null
null
UTF-8
C++
false
false
9,631
cpp
#include<iostream> #include<fstream> #include<string> using namespace std; //===================================================== // File scanner.cpp written by: Group Number: **10 //===================================================== // --------- DFAs --------------------------------- //Purpose: check to see if it's a vowel //Done by: Daniel Caballero bool vowelCheck(char c) { switch(c){ case 'a': case 'i': case 'I': case 'u': case 'e': case 'E': case 'o': //cout<<"vowel check"<<endl; return true; break; default: return false; } } //Purpose: Check consonant Pairs //Done by Daniel Caballero bool checkConsPairs(string s, int &charpos, int& state) { char c = s[charpos]; // cout<<s[charpos]<<" ss"<<endl; switch (c) { case 'b': case 'm': case 'k': case 'n': case 'h': case 'p': case 'r': case 'y': case 'g': if (vowelCheck(s[charpos+1])) { state=6; return true; } else if (s[charpos+1]== 'y') { state=4; charpos++; return true; } break; case 's': if (vowelCheck(s[charpos+1])) { // cout<< endl << s[charpos+1]; state=6; return true; } else if (s[charpos+1]== 'h') { state=4; charpos++; return true; } break; case 't': if (vowelCheck(s[charpos+1])) { state=6; return true; } else if (s[charpos+1]== 's') { state=4; charpos++; return true; } break; default: return false; } return false; } // ** MYTOKEN DFA to be replaced by the WORD DFA // ** Done by:Daniel Caballero, Julian Conner // ** RE: (vowel | vowel n | consonant vowel | consonant vowel n | consonant-pair vowel | consonant-pair vowel n)^+ bool word(string s) { int state = 0; int charpos = 0; int tempState=0; while (s[charpos] != '\0') { if ( ( (state== 6) && (s[charpos+1] == 'n')) ) state =6; else if ( state == 6 && s[charpos] == 'n' ) state = 0; else if ( state == 6) { state = 0; } else if (state == 0 && s[charpos] == 't') state = 3; else if (state == 0 && s[charpos] == 's') state = 2; else if (state == 0 && s[charpos] == 'c') state = 1; else if ((state == 0) && (vowelCheck(s[charpos])==true)) { if( s[charpos+1] == 'n'){ // cout<<"\t"<<vowelCheck(s[charpos])<<endl; state=6; } else { state = 0; } } else if ((state == 0) && (checkConsPairs(s,charpos,tempState)==true)) state=tempState; else if (state == 0 && s[charpos] == 'j') state = 5; else if(state == 0 && s[charpos] == 'z') state = 5; else if (state == 0 && s[charpos] == 'd') state = 5; else if (state == 0 && s[charpos] == 'w') state = 5; else if(state == 0 && s[charpos] == 'y') state =5; // q0 to qY(state 4) by bmknhpr else if ( state == 0 && ( s[charpos] == 'b' || s[charpos] == 'm' || s[charpos] == 'k' || s[charpos] == 'n' || s[charpos] == 'h' || s[charpos] == 'p' || s[charpos] == 'r' ) ){ state = 4; } else if (state ==5 && vowelCheck(s[charpos])) { if( s[charpos+1] == 'n'){ state=6; } else { state = 0; } } else if (state ==5 && s[charpos]=='s') state =6; else if (state ==5 && s[charpos]=='a') state=6; else if (state == 4 && vowelCheck(s[charpos])) { if( s[charpos+1] == 'n'){ state=6; } else { state = 0; } } else if (state == 4 && s[charpos]== 'y') state =5; else if (state == 3 && s[charpos] == 's') state=5; else if (state == 3 && vowelCheck(s[charpos])) { if( s[charpos+1] == 'n'){ state=6; } else { state = 0; } } else if (state == 2 && s[charpos] == 'h') state=5; else if (state == 2 && vowelCheck(s[charpos])) { if( s[charpos + 1] == 'n'){ state = 6; } else { state = 0; } } else if (state == 1 && s[charpos] == 'h') state=5; else return(false); charpos++; //cout<<state<<endl; }//end of while // where did I end up???? if ((state == 6) || (state == 0)) return(true); // end in a final state else return(false); } // ** Add the PERIOD DFA here // ** Done by: Chantell Chapman bool periodDFA(string s) { /* if (s[0] == '.') return true; else return false; */ int state = 0; int charpos = 0; while (s[charpos] != '\0') { if (state == 0 && (s[charpos] == '.')) state = 1; else return (false); charpos++; } if (state == 1) return (true); else return (false); } // ----- Tables ------------------------------------- // ** Update the tokentype to be WORD1, WORD2, PERIOD, ERROR, EOFM, etc. enum tokentype { WORD1, WORD2, PERIOD, VERB, VERBNEG, VERBPAST, VERBPASTNEG, IS, WAS, OBJECT, SUBJECT, DESTINATION, PRONOUN, CONNECTOR, EOFM, ERROR };//enum tokentype { ERROR, }; // ** string tokenName[30] = { }; for the display names oftokens - must be in the same order as the tokentype. string tokenName[30] = { "WORD1", "WORD2", "PERIOD", "VERB", "VERBNEG", "VERBPAST", "VERBPASTNEG", "IS", "WAS", "OBJECT", "SUBJECT", "DESTINATION", "PRONOUN", "CONNECTOR", "EOFM", "ERROR" }; // ** Need the reservedwords table to be set up here. // ** Do not require any file input for this. // ** a.out should work without any additional files. const int rIndexA=19; const int rIndexB=2; string reservedWords[rIndexA][rIndexB] = { {"masu", "VERB"}, { "masen", "VERBNEG"}, {"mashita", "VERBPAST"}, { "masendeshita", "VERBPASTNEG"}, {"desu", "IS"}, { "deshita", "WAS"}, {"o", "OBJECT"}, { "wa", "SUBJECT"}, {"ni", "DESTINATION"}, { "watashi", "PRONOUN"}, {"anata", "PRONOUN"}, {"kare", "PRONOUN"}, {"kanojo", "PRONOUN"}, { "sore", "PRONOUN"}, { "mata", "CONNECTOR"}, {"soshite", "CONNECTOR"}, {"shikashi", "CONNECTOR"}, {"dakara", "CONNECTOR"}, {"eofm", "EOFM"} }; // ------------ Scaner and Driver ----------------------- ifstream fin; // global stream for reading from the input file // Scanner processes only one word each time it is called // Gives back the token type and the word itself // ** Done by: Julian Conner, int scanner(tokentype& a, string& w) { string currentWord; // To store the word for readability during processing string endOfFileWord = reservedWords[18][0]; // Used for readability bool isEndOfFile; // ** Grab the next word from the file via fin // 1. If it is eofm, return right now. isEndOfFile = fin.eof(); // Check if the file stream is empty if( isEndOfFile ) { a = EOFM; w = endOfFileWord; return -1; } // Get the next word for processing fin >> currentWord; // To return the word by reference w = currentWord; cout << "Scanner called using word: " << w << endl; // Check if the last word is the end of file message isEndOfFile = currentWord.compare( endOfFileWord) == 0; if( isEndOfFile ){ a = EOFM; return 0; } /* 2. Call the token functions one after another (if-then-else) And generate a lexical error message if both DFAs failed. Let the token_type be ERROR in that case. */ /* 4. Return the token type & string (pass by reference) */ // Check if its a valid word if( word( currentWord ) ) { /* 3. Then, make sure WORDs are checked against the reservedwords list If not reserved, token_type is WORD1 or WORD2. */ // FOR DANIEL : (Note : The test labels all words as errors because there's no implementation here for the word check yet. It works for periods and end of files. ) //START Daniel Section bool reservedFlag=false; for (int i=0;i<rIndexA;i++){ if (currentWord==reservedWords[i][0]){ if (reservedWords[i][1]==tokenName[3]) a=VERB; else if (reservedWords[i][1]==tokenName[4]) a=VERBNEG; else if (reservedWords[i][1]==tokenName[5]) a=VERBPAST; else if (reservedWords[i][1]==tokenName[6]) a=VERBPASTNEG; else if (reservedWords[i][1]==tokenName[7]) a=IS; else if (reservedWords[i][1]==tokenName[8]) a=WAS; else if (reservedWords[i][1]==tokenName[9]) a=OBJECT; else if (reservedWords[i][1]==tokenName[10]) a=SUBJECT; else if (reservedWords[i][1]==tokenName[11]) a=DESTINATION; else if (reservedWords[i][1]==tokenName[12]) a=PRONOUN; else if (reservedWords[i][1]==tokenName[13]) a=CONNECTOR; reservedFlag=true; } } if (((currentWord[currentWord.length()-1] <=90)) && ((currentWord[currentWord.length()-1]>=65)&& reservedFlag==false))//uppercase a=WORD2; else if (reservedFlag==false) a=WORD1; }//end DANIEL SECTION // Check if its a period else if ( periodDFA( currentWord ) ) { a = PERIOD; } // If the word wasn't a valid token, show a lexical error else { a = ERROR; cout << "LEXICAL ERROR : \"" << currentWord << "\" is not a valid token." << endl; } return 0; }//the end of scanner
[ "noreply@github.com" ]
noreply@github.com
bd1f2727557ff3b131f5513b222567269e2e0cd3
3e82a4ac023b160c07e15539949d356108d57b1d
/thirdparty/PEGTL/include/tao/pegtl/internal/file_mapper_posix.hpp
ff58eda141af951eb9e96f24784e885ecb60619a
[ "MIT" ]
permissive
spirit-code/ovf
fe23879b9a57a409346c9efb3ac0c20bf7499695
6e3383eea0a71f78aa1e11dcb5680da980979b1b
refs/heads/master
2021-09-11T03:49:38.585833
2021-08-18T10:23:27
2021-08-18T10:23:27
134,859,062
6
2
MIT
2021-08-19T14:04:18
2018-05-25T13:23:08
C++
UTF-8
C++
false
false
2,531
hpp
// Copyright (c) 2014-2019 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_INTERNAL_FILE_MAPPER_POSIX_HPP #define TAO_PEGTL_INTERNAL_FILE_MAPPER_POSIX_HPP #include <sys/mman.h> #include <unistd.h> #include "../config.hpp" #include "file_opener.hpp" #include "../input_error.hpp" namespace tao { namespace TAO_PEGTL_NAMESPACE { namespace internal { class file_mapper { public: explicit file_mapper( const char* filename ) : file_mapper( file_opener( filename ) ) { } explicit file_mapper( const file_opener& reader ) : m_size( reader.size() ), m_data( static_cast< const char* >( ::mmap( nullptr, m_size, PROT_READ, MAP_PRIVATE, reader.m_fd, 0 ) ) ) { if( ( m_size != 0 ) && ( intptr_t( m_data ) == -1 ) ) { TAO_PEGTL_THROW_INPUT_ERROR( "unable to mmap() file " << reader.m_source << " descriptor " << reader.m_fd ); } } file_mapper( const file_mapper& ) = delete; file_mapper( file_mapper&& ) = delete; ~file_mapper() noexcept { // Legacy C interface requires pointer-to-mutable but does not write through the pointer. ::munmap( const_cast< char* >( m_data ), m_size ); // NOLINT } void operator=( const file_mapper& ) = delete; void operator=( file_mapper&& ) = delete; bool empty() const noexcept { return m_size == 0; } std::size_t size() const noexcept { return m_size; } using iterator = const char*; using const_iterator = const char*; iterator data() const noexcept { return m_data; } iterator begin() const noexcept { return m_data; } iterator end() const noexcept { return m_data + m_size; } std::string string() const { return std::string( m_data, m_size ); } private: const std::size_t m_size; const char* const m_data; }; } // namespace internal } // namespace TAO_PEGTL_NAMESPACE } // namespace tao #endif
[ "g.mueller@fz-juelich.de" ]
g.mueller@fz-juelich.de
78fb61ed5682ff4e447358de2faf8d0a5f8b3106
09e58edccdae392bf9c54bd59c96446e74b5f0a0
/tools/bsnes/lib/ruby/audio/alsa.hpp
bc175eef33226973aaa93d75ec07d3f936360ebd
[]
no_license
optixx/quickdev16
80460b1a01601b5fd31a721a8fafcfd5d7cd0a66
a1e3ef36b4b6aa7afcf77897c4b897c621c799c2
refs/heads/master
2020-05-30T07:13:42.870526
2016-08-20T16:13:08
2016-08-20T16:13:08
199,003
65
11
null
null
null
null
UTF-8
C++
false
false
337
hpp
/* audio.alsa (2008-08-12) authors: Nach, RedDwarf */ class pAudioALSA; class AudioALSA : public Audio { public: bool cap(Setting); uintptr_t get(Setting); bool set(Setting, uintptr_t); void sample(uint16_t left, uint16_t right); bool init(); void term(); AudioALSA(); ~AudioALSA(); private: pAudioALSA &p; };
[ "david@optixx.org" ]
david@optixx.org
63ffe75b0e3b7b70c9d0287f4a89398db95eec60
c9ea4b7d00be3092b91bf157026117bf2c7a77d7
/比赛/luogu.org/20181021_十月月赛II(100)/T44777_force.cpp
b0da261bb30e59196e01e717a4e08ff1e0b1d8b1
[]
no_license
Jerry-Terrasse/Programming
dc39db2259c028d45c58304e8f29b2116eef4bfd
a59a23259d34a14e38a7d4c8c4d6c2b87a91574c
refs/heads/master
2020-04-12T08:31:48.429416
2019-04-20T00:32:55
2019-04-20T00:32:55
162,387,499
3
0
null
null
null
null
UTF-8
C++
false
false
731
cpp
#include<iostream> #define MAXN 32 using namespace std; int a[MAXN],n=0,ans=0,now=0; inline void judge(); int main() { int i=0; cin>>n; for(i=0;i<n;++i) { cin>>a[i]; } for(now=1;now<(1<<n);++now) { judge(); } cout<<ans<<endl; return 0; } inline void judge() { int i=0,pre=0,d=0; for(i=0;;++i) { if(1<<i&now) { pre=a[i]; break; } } for(++i;i<n;++i) { if(1<<i&now) { d=a[i]-pre; pre=a[i]; break; } } if(i==n) { ++ans; return; } for(++i;i<n;++i) { if(1<<i&now) { if(a[i]-pre==d) { pre=a[i]; } else { return; } } } ++ans; return; }
[ "3305049949@qq.com" ]
3305049949@qq.com
af24bb7e39bccbf3307a59af03f59f30bfe60a23
a0604bbb76abbb42cf83e99f673134c80397b92b
/fldserver/base/util/memory_pressure/multi_source_memory_pressure_monitor.cc
5ea4d55fa06f58ed7a65646299828a79991f048f
[ "BSD-3-Clause" ]
permissive
Hussam-Turjman/FLDServer
816910da39b6780cfd540fa1e79c84a03c57a488
ccc6e98d105cfffbf44bfd0a49ee5dcaf47e9ddb
refs/heads/master
2022-07-29T20:59:28.954301
2022-07-03T12:02:42
2022-07-03T12:02:42
461,034,667
2
0
null
null
null
null
UTF-8
C++
false
false
3,876
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "fldserver/base/util/memory_pressure/multi_source_memory_pressure_monitor.h" #include "fldserver/base/bind.h" #include "fldserver/base/check_op.h" #include "fldserver/base/metrics/histogram_functions.h" #include "fldserver/base/metrics/histogram_macros.h" #include "fldserver/base/time/time.h" #include "fldserver/base/util/memory_pressure/system_memory_pressure_evaluator.h" #if 0 #include "fldserver/base/trace_event/memory_pressure_level_proto.h" // no-presubmit-check #endif namespace util { MultiSourceMemoryPressureMonitor::MultiSourceMemoryPressureMonitor() : current_pressure_level_(base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE), dispatch_callback_(base::BindRepeating(&base::MemoryPressureListener::NotifyMemoryPressure)), aggregator_(this), level_reporter_(current_pressure_level_) { } MultiSourceMemoryPressureMonitor::~MultiSourceMemoryPressureMonitor() { // Destroy system evaluator early while the remaining members of this class // still exist. MultiSourceMemoryPressureMonitor implements // MemoryPressureVoteAggregator::Delegate, and // delegate_->OnMemoryPressureLevelChanged() gets indirectly called during // ~SystemMemoryPressureEvaluator(). system_evaluator_.reset(); } void MultiSourceMemoryPressureMonitor::Start() { system_evaluator_ = SystemMemoryPressureEvaluator::CreateDefaultSystemEvaluator(this); StartMetricsTimer(); } void MultiSourceMemoryPressureMonitor::StartMetricsTimer() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Unretained is safe here since this task is running on a timer owned by this // object. metric_timer_.Start(FROM_HERE, MemoryPressureMonitor::kUMAMemoryPressureLevelPeriod, BindRepeating(&MultiSourceMemoryPressureMonitor::RecordCurrentPressureLevel, base::Unretained(this))); } void MultiSourceMemoryPressureMonitor::StopMetricsTimer() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); metric_timer_.Stop(); } void MultiSourceMemoryPressureMonitor::RecordCurrentPressureLevel() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); RecordMemoryPressure(GetCurrentPressureLevel(), /* ticks = */ 1); } base::MemoryPressureListener::MemoryPressureLevel MultiSourceMemoryPressureMonitor::GetCurrentPressureLevel() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return current_pressure_level_; } std::unique_ptr<MemoryPressureVoter> MultiSourceMemoryPressureMonitor::CreateVoter() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return aggregator_.CreateVoter(); } void MultiSourceMemoryPressureMonitor::SetDispatchCallback(const DispatchCallback& callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); dispatch_callback_ = callback; } void MultiSourceMemoryPressureMonitor::OnMemoryPressureLevelChanged( base::MemoryPressureListener::MemoryPressureLevel level) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK_NE(current_pressure_level_, level); level_reporter_.OnMemoryPressureLevelChanged(level); current_pressure_level_ = level; } void MultiSourceMemoryPressureMonitor::OnNotifyListenersRequested() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); dispatch_callback_.Run(current_pressure_level_); } void MultiSourceMemoryPressureMonitor::ResetSystemEvaluatorForTesting() { system_evaluator_.reset(); } void MultiSourceMemoryPressureMonitor::SetSystemEvaluator( std::unique_ptr<SystemMemoryPressureEvaluator> evaluator) { DCHECK(!system_evaluator_); system_evaluator_ = std::move(evaluator); } } // namespace util
[ "hussam.turjman@gmail.com" ]
hussam.turjman@gmail.com
6ba2bfe96fffc6fd0210c57cd95035b8940e45a4
c9098680fb9badde3499217b33619d99eeb9a0c5
/TimeCounter.cpp
0234590ec823008d317fe6fd316609b333d87f0e
[]
no_license
bpaszko/aal
0f1fa48cf91a4218e7261b7cb7e3947f52a5760a
0fd99b5ec203cc1a09ffd35ef4cb16f241833111
refs/heads/master
2021-06-17T01:01:38.020537
2017-01-17T22:50:29
2017-01-17T22:50:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
334
cpp
#include "TimeCounter.h" void TimeCounter::start_timer() { start = std::chrono::system_clock::now(); started = true; } void TimeCounter::stop_timer() { if(started) end = std::chrono::system_clock::now(); } double TimeCounter::getTime() { std::chrono::duration<double> elapsed_time = end-start; return elapsed_time.count(); }
[ "bar.paszko@gmail.com" ]
bar.paszko@gmail.com
773a969409facfc0e4b2c72341e8c3d7162f9e97
38f5842a3c95f404ac697dde6b777a2c86fab4b8
/npccharacterwidget.h
642812f3b0a81dd9c4df2556a5a54c2641b3ddfe
[]
no_license
James-Shultis1/Database_Tester_Qt
17967f25a114abda77252ffabfc37bb135601591
22e59ec3130428be0db03852305c814154c755a3
refs/heads/master
2022-11-22T23:45:17.011363
2020-07-30T07:26:01
2020-07-30T07:26:01
274,486,226
0
0
null
null
null
null
UTF-8
C++
false
false
353
h
#ifndef NPCCHARACTERWIDGET_H #define NPCCHARACTERWIDGET_H #include <QWidget> namespace Ui { class NPCCharacterWidget; } class NPCCharacterWidget : public QWidget { Q_OBJECT public: explicit NPCCharacterWidget(QWidget *parent = nullptr); ~NPCCharacterWidget(); private: Ui::NPCCharacterWidget *ui; }; #endif // NPCCHARACTERWIDGET_H
[ "anthony.shultis@stud.edubs.ch" ]
anthony.shultis@stud.edubs.ch
354fa355f506e08ea38274271bb5293b7a649f48
bfbdd3d6bf4e70aa2aa2df3d01d18c83a30d8033
/day8/code/08zoo/main.cpp
bf635b21a1efeda4509c66c03ec0721de870b1aa
[]
no_license
caiyiming/cppCode
42333b1c052818afdd68d8a47c4e5b648d7a6b6d
dc1b897af0ebd0778159b852112e02b0ade23e78
refs/heads/master
2020-06-15T15:46:48.511108
2016-12-01T08:08:16
2016-12-01T08:08:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
331
cpp
#include <iostream> #include "dog.h" #include "cat.h" using namespace std; int main() { #if 0 Dog dog; dog.voice(); Cat cat; cat.voice(); Animal *ani = &dog; ani->voice(); ani = &cat; ani->voice(); #endif Animal * ani = new Dog; ani->voice(); delete ani; return 0; }
[ "guilin_wang@163.com" ]
guilin_wang@163.com
7155c2ad364a59907f0ff1f6c68119d567864070
926c517f9f4c129e653fb8c21b77ff599847048a
/ImageTracking/Assets/Plugins/EasyAR.bundle/Contents/Headers/cloudrecognizer.hxx
b570f1d890ce37c69e781fdcf85b4f588ecfbc3c
[]
no_license
Swagat47/easyARImageTracking
d1a71e668cace89094ca3284a436410cfcde0776
a24432c4b1ba4f81086f80621af19d3c28452a4b
refs/heads/master
2022-11-28T13:38:58.859477
2020-07-31T19:42:30
2020-07-31T19:42:30
284,109,458
3
0
null
null
null
null
UTF-8
C++
false
false
12,853
hxx
//============================================================================================================================= // // EasyAR Sense 4.1.0.7750-f1413084f // Copyright (c) 2015-2020 VisionStar Information Technology (Shanghai) Co., Ltd. All Rights Reserved. // EasyAR is the registered trademark or trademark of VisionStar Information Technology (Shanghai) Co., Ltd in China // and other countries for the augmented reality technology developed by VisionStar Information Technology (Shanghai) Co., Ltd. // //============================================================================================================================= #ifndef __EASYAR_CLOUDRECOGNIZER_HXX__ #define __EASYAR_CLOUDRECOGNIZER_HXX__ #include "easyar/types.hxx" namespace easyar { class CloudRecognizationResult { protected: easyar_CloudRecognizationResult * cdata_ ; void init_cdata(easyar_CloudRecognizationResult * cdata); virtual CloudRecognizationResult & operator=(const CloudRecognizationResult & data) { return *this; } //deleted public: CloudRecognizationResult(easyar_CloudRecognizationResult * cdata); virtual ~CloudRecognizationResult(); CloudRecognizationResult(const CloudRecognizationResult & data); const easyar_CloudRecognizationResult * get_cdata() const; easyar_CloudRecognizationResult * get_cdata(); /// <summary> /// Returns recognition status. /// </summary> CloudRecognizationStatus getStatus(); /// <summary> /// Returns the recognized target when status is FoundTarget. /// </summary> void getTarget(/* OUT */ ImageTarget * * Return); /// <summary> /// Returns the error message when status is UnknownError. /// </summary> void getUnknownErrorMessage(/* OUT */ String * * Return); }; /// <summary> /// CloudRecognizer implements cloud recognition. It can only be used after created a recognition image library on the cloud. Please refer to EasyAR CRS documentation. /// When the component is not needed anymore, call close function to close it. It shall not be used after calling close. /// Before using a CloudRecognizer, an `ImageTracker`_ must be setup and prepared. Any target returned from cloud should be manually put into the `ImageTracker`_ using `ImageTracker.loadTarget`_ if it need to be tracked. Then the target can be used as same as a local target after loaded into the tracker. When a target is recognized, you can get it from callback, and you should use target uid to distinguish different targets. The target runtimeID is dynamically created and cannot be used as unique identifier in the cloud situation. /// </summary> class CloudRecognizer { protected: easyar_CloudRecognizer * cdata_ ; void init_cdata(easyar_CloudRecognizer * cdata); virtual CloudRecognizer & operator=(const CloudRecognizer & data) { return *this; } //deleted public: CloudRecognizer(easyar_CloudRecognizer * cdata); virtual ~CloudRecognizer(); CloudRecognizer(const CloudRecognizer & data); const easyar_CloudRecognizer * get_cdata() const; easyar_CloudRecognizer * get_cdata(); /// <summary> /// Returns true. /// </summary> static bool isAvailable(); /// <summary> /// Creates an instance and connects to the server. /// </summary> static void create(String * cloudRecognitionServiceServerAddress, String * apiKey, String * apiSecret, String * cloudRecognitionServiceAppId, /* OUT */ CloudRecognizer * * Return); /// <summary> /// Creates an instance and connects to the server with Cloud Secret. /// </summary> static void createByCloudSecret(String * cloudRecognitionServiceServerAddress, String * cloudRecognitionServiceSecret, String * cloudRecognitionServiceAppId, /* OUT */ CloudRecognizer * * Return); /// <summary> /// Send recognition request. The lowest available request interval is 300ms. /// </summary> void resolve(InputFrame * inputFrame, CallbackScheduler * callbackScheduler, FunctorOfVoidFromCloudRecognizationResult callback); /// <summary> /// Stops the recognition and closes connection. The component shall not be used after calling close. /// </summary> void close(); }; #ifndef __EASYAR_OPTIONALOFIMAGETARGET__ #define __EASYAR_OPTIONALOFIMAGETARGET__ struct OptionalOfImageTarget { bool has_value; ImageTarget * value; }; static inline easyar_OptionalOfImageTarget OptionalOfImageTarget_to_c(ImageTarget * o); #endif #ifndef __EASYAR_OPTIONALOFSTRING__ #define __EASYAR_OPTIONALOFSTRING__ struct OptionalOfString { bool has_value; String * value; }; static inline easyar_OptionalOfString OptionalOfString_to_c(String * o); #endif #ifndef __EASYAR_FUNCTOROFVOIDFROMCLOUDRECOGNIZATIONRESULT__ #define __EASYAR_FUNCTOROFVOIDFROMCLOUDRECOGNIZATIONRESULT__ struct FunctorOfVoidFromCloudRecognizationResult { void * _state; void (* func)(void * _state, CloudRecognizationResult *); void (* destroy)(void * _state); FunctorOfVoidFromCloudRecognizationResult(void * _state, void (* func)(void * _state, CloudRecognizationResult *), void (* destroy)(void * _state)); }; static void FunctorOfVoidFromCloudRecognizationResult_func(void * _state, easyar_CloudRecognizationResult *, /* OUT */ easyar_String * * _exception); static void FunctorOfVoidFromCloudRecognizationResult_destroy(void * _state); static inline easyar_FunctorOfVoidFromCloudRecognizationResult FunctorOfVoidFromCloudRecognizationResult_to_c(FunctorOfVoidFromCloudRecognizationResult f); #endif } #endif #ifndef __IMPLEMENTATION_EASYAR_CLOUDRECOGNIZER_HXX__ #define __IMPLEMENTATION_EASYAR_CLOUDRECOGNIZER_HXX__ #include "easyar/cloudrecognizer.h" #include "easyar/imagetarget.hxx" #include "easyar/target.hxx" #include "easyar/image.hxx" #include "easyar/buffer.hxx" #include "easyar/frame.hxx" #include "easyar/cameraparameters.hxx" #include "easyar/vector.hxx" #include "easyar/matrix.hxx" #include "easyar/callbackscheduler.hxx" namespace easyar { inline CloudRecognizationResult::CloudRecognizationResult(easyar_CloudRecognizationResult * cdata) : cdata_(NULL) { init_cdata(cdata); } inline CloudRecognizationResult::~CloudRecognizationResult() { if (cdata_) { easyar_CloudRecognizationResult__dtor(cdata_); cdata_ = NULL; } } inline CloudRecognizationResult::CloudRecognizationResult(const CloudRecognizationResult & data) : cdata_(NULL) { easyar_CloudRecognizationResult * cdata = NULL; easyar_CloudRecognizationResult__retain(data.cdata_, &cdata); init_cdata(cdata); } inline const easyar_CloudRecognizationResult * CloudRecognizationResult::get_cdata() const { return cdata_; } inline easyar_CloudRecognizationResult * CloudRecognizationResult::get_cdata() { return cdata_; } inline void CloudRecognizationResult::init_cdata(easyar_CloudRecognizationResult * cdata) { cdata_ = cdata; } inline CloudRecognizationStatus CloudRecognizationResult::getStatus() { if (cdata_ == NULL) { return CloudRecognizationStatus(); } easyar_CloudRecognizationStatus _return_value_ = easyar_CloudRecognizationResult_getStatus(cdata_); return static_cast<CloudRecognizationStatus>(_return_value_); } inline void CloudRecognizationResult::getTarget(/* OUT */ ImageTarget * * Return) { if (cdata_ == NULL) { *Return = NULL; return; } easyar_OptionalOfImageTarget _return_value_ = {false, NULL}; easyar_CloudRecognizationResult_getTarget(cdata_, &_return_value_); *Return = (_return_value_.has_value ? new ImageTarget(_return_value_.value) : NULL); } inline void CloudRecognizationResult::getUnknownErrorMessage(/* OUT */ String * * Return) { if (cdata_ == NULL) { *Return = NULL; return; } easyar_OptionalOfString _return_value_ = {false, NULL}; easyar_CloudRecognizationResult_getUnknownErrorMessage(cdata_, &_return_value_); *Return = (_return_value_.has_value ? new String(_return_value_.value) : NULL); } inline CloudRecognizer::CloudRecognizer(easyar_CloudRecognizer * cdata) : cdata_(NULL) { init_cdata(cdata); } inline CloudRecognizer::~CloudRecognizer() { if (cdata_) { easyar_CloudRecognizer__dtor(cdata_); cdata_ = NULL; } } inline CloudRecognizer::CloudRecognizer(const CloudRecognizer & data) : cdata_(NULL) { easyar_CloudRecognizer * cdata = NULL; easyar_CloudRecognizer__retain(data.cdata_, &cdata); init_cdata(cdata); } inline const easyar_CloudRecognizer * CloudRecognizer::get_cdata() const { return cdata_; } inline easyar_CloudRecognizer * CloudRecognizer::get_cdata() { return cdata_; } inline void CloudRecognizer::init_cdata(easyar_CloudRecognizer * cdata) { cdata_ = cdata; } inline bool CloudRecognizer::isAvailable() { bool _return_value_ = easyar_CloudRecognizer_isAvailable(); return _return_value_; } inline void CloudRecognizer::create(String * arg0, String * arg1, String * arg2, String * arg3, /* OUT */ CloudRecognizer * * Return) { easyar_CloudRecognizer * _return_value_ = NULL; easyar_CloudRecognizer_create(arg0->get_cdata(), arg1->get_cdata(), arg2->get_cdata(), arg3->get_cdata(), &_return_value_); *Return = new CloudRecognizer(_return_value_); } inline void CloudRecognizer::createByCloudSecret(String * arg0, String * arg1, String * arg2, /* OUT */ CloudRecognizer * * Return) { easyar_CloudRecognizer * _return_value_ = NULL; easyar_CloudRecognizer_createByCloudSecret(arg0->get_cdata(), arg1->get_cdata(), arg2->get_cdata(), &_return_value_); *Return = new CloudRecognizer(_return_value_); } inline void CloudRecognizer::resolve(InputFrame * arg0, CallbackScheduler * arg1, FunctorOfVoidFromCloudRecognizationResult arg2) { if (cdata_ == NULL) { return; } easyar_CloudRecognizer_resolve(cdata_, arg0->get_cdata(), arg1->get_cdata(), FunctorOfVoidFromCloudRecognizationResult_to_c(arg2)); } inline void CloudRecognizer::close() { if (cdata_ == NULL) { return; } easyar_CloudRecognizer_close(cdata_); } #ifndef __IMPLEMENTATION_EASYAR_OPTIONALOFIMAGETARGET__ #define __IMPLEMENTATION_EASYAR_OPTIONALOFIMAGETARGET__ static inline easyar_OptionalOfImageTarget OptionalOfImageTarget_to_c(ImageTarget * o) { if (o != NULL) { easyar_OptionalOfImageTarget _return_value_ = {true, o->get_cdata()}; return _return_value_; } else { easyar_OptionalOfImageTarget _return_value_ = {false, NULL}; return _return_value_; } } #endif #ifndef __IMPLEMENTATION_EASYAR_OPTIONALOFSTRING__ #define __IMPLEMENTATION_EASYAR_OPTIONALOFSTRING__ static inline easyar_OptionalOfString OptionalOfString_to_c(String * o) { if (o != NULL) { easyar_OptionalOfString _return_value_ = {true, o->get_cdata()}; return _return_value_; } else { easyar_OptionalOfString _return_value_ = {false, NULL}; return _return_value_; } } #endif #ifndef __IMPLEMENTATION_EASYAR_FUNCTOROFVOIDFROMCLOUDRECOGNIZATIONRESULT__ #define __IMPLEMENTATION_EASYAR_FUNCTOROFVOIDFROMCLOUDRECOGNIZATIONRESULT__ inline FunctorOfVoidFromCloudRecognizationResult::FunctorOfVoidFromCloudRecognizationResult(void * _state, void (* func)(void * _state, CloudRecognizationResult *), void (* destroy)(void * _state)) { this->_state = _state; this->func = func; this->destroy = destroy; } static void FunctorOfVoidFromCloudRecognizationResult_func(void * _state, easyar_CloudRecognizationResult * arg0, /* OUT */ easyar_String * * _exception) { *_exception = NULL; try { easyar_CloudRecognizationResult__retain(arg0, &arg0); CloudRecognizationResult * cpparg0 = new CloudRecognizationResult(arg0); FunctorOfVoidFromCloudRecognizationResult * f = reinterpret_cast<FunctorOfVoidFromCloudRecognizationResult *>(_state); f->func(f->_state, cpparg0); delete cpparg0; } catch (std::exception & ex) { easyar_String_from_utf8_begin(ex.what(), _exception); } } static void FunctorOfVoidFromCloudRecognizationResult_destroy(void * _state) { FunctorOfVoidFromCloudRecognizationResult * f = reinterpret_cast<FunctorOfVoidFromCloudRecognizationResult *>(_state); if (f->destroy) { f->destroy(f->_state); } delete f; } static inline easyar_FunctorOfVoidFromCloudRecognizationResult FunctorOfVoidFromCloudRecognizationResult_to_c(FunctorOfVoidFromCloudRecognizationResult f) { easyar_FunctorOfVoidFromCloudRecognizationResult _return_value_ = {NULL, NULL, NULL}; _return_value_._state = new FunctorOfVoidFromCloudRecognizationResult(f._state, f.func, f.destroy); _return_value_.func = FunctorOfVoidFromCloudRecognizationResult_func; _return_value_.destroy = FunctorOfVoidFromCloudRecognizationResult_destroy; return _return_value_; } #endif } #endif
[ "swagatraj47@gmail.com" ]
swagatraj47@gmail.com
c4ba649a29a82ee84a518b4747f575d8a430865b
a1e19ec5d28255bf82cdae2bf453e0a609ab2afc
/floor_Element.cpp
ad2891c83da1311492104b8bb4f0f77d6f3b2f19
[]
no_license
shourya9/Binary-Search
68ec31600e383a64c02f5a6e82d80850fb2f5275
2134cee6a0ce919a2bc31e1e046f0747c5a07bb8
refs/heads/master
2022-12-06T08:02:35.392659
2020-09-03T13:56:00
2020-09-03T13:56:00
289,232,726
0
0
null
null
null
null
UTF-8
C++
false
false
650
cpp
#include<bits/stdc++.h> using namespace std; int binarySearch(int arr[],int n,int floor) { int start=0; int end=n-1; int result=0; while(start<=end) { int mid=start+(end-start)/2; if(arr[mid]==floor) { return arr[mid]; } else if(arr[mid]>floor) { end=mid-1; } else if(arr[mid]<floor) { result=arr[mid]; start=mid+1; } } return result; } int main() { int arr[]={1,2,3,4,8,10,10,12,14}; int n=sizeof(arr)/sizeof(int); int floor; cin>>floor; cout<<binarySearch(arr,n,floor); }
[ "shouryamaheshwari09@gmail.com" ]
shouryamaheshwari09@gmail.com
79d92063d0ddd903b96978769b1eed0da75e7aa6
dbf621be39445a9d3e0e24881c5c85b9693c4f4a
/src/Mesh.h
d55856dcef5fda0bf9296e9ef5fa3780793e6e17
[]
no_license
domahony/BrickWall
328d1e39a4da68c4d3a78741934660443a241939
9b5450228f274437e07adf13e8954d049b115787
refs/heads/master
2021-04-26T16:48:06.038976
2015-07-15T00:04:14
2015-07-15T00:04:14
28,065,736
0
0
null
null
null
null
UTF-8
C++
false
false
1,080
h
/* * Mesh.h * * Created on: Jan 26, 2015 * Author: domahony */ #ifndef MESH_H_ #define MESH_H_ /* #include <string> */ #include "types.h" #include <bullet/LinearMath/btMotionState.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <map> #include <vector> #include <memory> #include <iostream> #include "ShaderBase.h" #include "Camera.h" #include "ViewPort.h" namespace app { namespace gl { class Mesh { public: Mesh( std::shared_ptr<ShaderBase> shader, const GLuint& vao, const GLenum& mode, const GLint& first_idx, const GLsizei& count): shader(shader), vao(vao), mode(mode), first_idx(first_idx), count(count), local(btTransform::getIdentity()) { } ~Mesh() { // TODO Auto-generated destructor stub } void render(const app::CameraPtr& c, const app::ViewPort& vp, const btTransform& transform) const; private: std::shared_ptr<app::gl::ShaderBase> shader; GLuint vao; GLenum mode; GLint first_idx; GLsizei count; btTransform local; }; } /* namespace gl */ } /* namespace app */ #endif /* MESH_H_ */
[ "domahony@compusult.net" ]
domahony@compusult.net
ed5b7a5b1f101cd66eb617503fd4323b86a440df
4cc8d3560f64147b18dbd1da0d010de24c23bc22
/advancedcpp/OverloadingPlus/main.cpp
4e08000d1390fefa8db18e92819cac3541b1f9b6
[]
no_license
BAEK-Programming-Languages/cpp-playground
c8e05f53c0bd264a2b3dcbea306ada7226440720
7d8c1c10c028b6a89dd3954de21975d8a70b5fcd
refs/heads/master
2021-10-09T05:32:36.568544
2018-12-05T06:48:56
2018-12-05T06:48:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
533
cpp
/** * Name: main.cpp * * Take-away: * * */ #include <iostream> #include "Complex.h" using namespace std; int main(int argc, char **argv) { Complex c1(3, 4); Complex c2(2, 3); Complex c3 = c1 + c2; cout << c1 << endl; cout << c1 + c2 + c3 << endl; Complex c4(4, 2); Complex c5 = c4 + 7; cout << c5 << endl; Complex c6(1, 7); cout << 3.2 + c6 << endl; // the order matters!! cout << 7 + c1 + c2 + 8 + 9 + c6 << endl; return 0; }
[ "robotpengxu@gmail.com" ]
robotpengxu@gmail.com
72d888c65068be0d62bffa7e598cc9e109c0563f
6de9a67ec29c5a57bf3eb62e74f0b809d5a03d68
/sky/engine/platform/text/PlatformLocale.cpp
ad84c081032ba5c0aa43c6fcefecd9fd4ce421a8
[ "BSD-3-Clause" ]
permissive
kleopatra999/mojo
0b00f1fbcaae2c675992e5a061a2f98594851a27
16917a007d20aaa02aecfd74760a685594229f76
refs/heads/master
2021-01-20T08:54:36.224641
2014-11-05T04:19:09
2014-11-05T04:19:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,376
cpp
/* * Copyright (C) 2011,2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "platform/text/PlatformLocale.h" #include "platform/text/DateTimeFormat.h" #include "public/platform/Platform.h" #include "wtf/MainThread.h" #include "wtf/text/StringBuilder.h" namespace blink { using blink::Platform; using blink::WebLocalizedString; class DateTimeStringBuilder : private DateTimeFormat::TokenHandler { WTF_MAKE_NONCOPYABLE(DateTimeStringBuilder); public: // The argument objects must be alive until this object dies. DateTimeStringBuilder(Locale&, const DateComponents&); bool build(const String&); String toString(); private: // DateTimeFormat::TokenHandler functions. virtual void visitField(DateTimeFormat::FieldType, int) override final; virtual void visitLiteral(const String&) override final; String zeroPadString(const String&, size_t width); void appendNumber(int number, size_t width); StringBuilder m_builder; Locale& m_localizer; const DateComponents& m_date; }; DateTimeStringBuilder::DateTimeStringBuilder(Locale& localizer, const DateComponents& date) : m_localizer(localizer) , m_date(date) { } bool DateTimeStringBuilder::build(const String& formatString) { m_builder.reserveCapacity(formatString.length()); return DateTimeFormat::parse(formatString, *this); } String DateTimeStringBuilder::zeroPadString(const String& string, size_t width) { if (string.length() >= width) return string; StringBuilder zeroPaddedStringBuilder; zeroPaddedStringBuilder.reserveCapacity(width); for (size_t i = string.length(); i < width; ++i) zeroPaddedStringBuilder.append('0'); zeroPaddedStringBuilder.append(string); return zeroPaddedStringBuilder.toString(); } void DateTimeStringBuilder::appendNumber(int number, size_t width) { String zeroPaddedNumberString = zeroPadString(String::number(number), width); m_builder.append(m_localizer.convertToLocalizedNumber(zeroPaddedNumberString)); } void DateTimeStringBuilder::visitField(DateTimeFormat::FieldType fieldType, int numberOfPatternCharacters) { switch (fieldType) { case DateTimeFormat::FieldTypeYear: // Always use padding width of 4 so it matches DateTimeEditElement. appendNumber(m_date.fullYear(), 4); return; case DateTimeFormat::FieldTypeMonth: if (numberOfPatternCharacters == 3) { m_builder.append(m_localizer.shortMonthLabels()[m_date.month()]); } else if (numberOfPatternCharacters == 4) { m_builder.append(m_localizer.monthLabels()[m_date.month()]); } else { // Always use padding width of 2 so it matches DateTimeEditElement. appendNumber(m_date.month() + 1, 2); } return; case DateTimeFormat::FieldTypeMonthStandAlone: if (numberOfPatternCharacters == 3) { m_builder.append(m_localizer.shortStandAloneMonthLabels()[m_date.month()]); } else if (numberOfPatternCharacters == 4) { m_builder.append(m_localizer.standAloneMonthLabels()[m_date.month()]); } else { // Always use padding width of 2 so it matches DateTimeEditElement. appendNumber(m_date.month() + 1, 2); } return; case DateTimeFormat::FieldTypeDayOfMonth: // Always use padding width of 2 so it matches DateTimeEditElement. appendNumber(m_date.monthDay(), 2); return; case DateTimeFormat::FieldTypeWeekOfYear: // Always use padding width of 2 so it matches DateTimeEditElement. appendNumber(m_date.week(), 2); return; case DateTimeFormat::FieldTypePeriod: m_builder.append(m_localizer.timeAMPMLabels()[(m_date.hour() >= 12 ? 1 : 0)]); return; case DateTimeFormat::FieldTypeHour12: { int hour12 = m_date.hour() % 12; if (!hour12) hour12 = 12; appendNumber(hour12, numberOfPatternCharacters); return; } case DateTimeFormat::FieldTypeHour23: appendNumber(m_date.hour(), numberOfPatternCharacters); return; case DateTimeFormat::FieldTypeHour11: appendNumber(m_date.hour() % 12, numberOfPatternCharacters); return; case DateTimeFormat::FieldTypeHour24: { int hour24 = m_date.hour(); if (!hour24) hour24 = 24; appendNumber(hour24, numberOfPatternCharacters); return; } case DateTimeFormat::FieldTypeMinute: appendNumber(m_date.minute(), numberOfPatternCharacters); return; case DateTimeFormat::FieldTypeSecond: if (!m_date.millisecond()) { appendNumber(m_date.second(), numberOfPatternCharacters); } else { double second = m_date.second() + m_date.millisecond() / 1000.0; String zeroPaddedSecondString = zeroPadString(String::format("%.03f", second), numberOfPatternCharacters + 4); m_builder.append(m_localizer.convertToLocalizedNumber(zeroPaddedSecondString)); } return; default: return; } } void DateTimeStringBuilder::visitLiteral(const String& text) { ASSERT(text.length()); m_builder.append(text); } String DateTimeStringBuilder::toString() { return m_builder.toString(); } Locale& Locale::defaultLocale() { static Locale* locale = Locale::create(defaultLanguage()).leakPtr(); ASSERT(isMainThread()); return *locale; } Locale::~Locale() { } String Locale::queryString(WebLocalizedString::Name name) { // FIXME: Returns a string locazlied for this locale. return Platform::current()->queryLocalizedString(name); } String Locale::queryString(WebLocalizedString::Name name, const String& parameter) { // FIXME: Returns a string locazlied for this locale. return Platform::current()->queryLocalizedString(name, parameter); } String Locale::queryString(WebLocalizedString::Name name, const String& parameter1, const String& parameter2) { // FIXME: Returns a string locazlied for this locale. return Platform::current()->queryLocalizedString(name, parameter1, parameter2); } String Locale::validationMessageTooLongText(unsigned valueLength, int maxLength) { return queryString(WebLocalizedString::ValidationTooLong, convertToLocalizedNumber(String::number(valueLength)), convertToLocalizedNumber(String::number(maxLength))); } String Locale::weekFormatInLDML() { String templ = queryString(WebLocalizedString::WeekFormatTemplate); // Converts a string like "Week $2, $1" to an LDML date format pattern like // "'Week 'ww', 'yyyy". StringBuilder builder; unsigned literalStart = 0; unsigned length = templ.length(); for (unsigned i = 0; i + 1 < length; ++i) { if (templ[i] == '$' && (templ[i + 1] == '1' || templ[i + 1] == '2')) { if (literalStart < i) DateTimeFormat::quoteAndAppendLiteral(templ.substring(literalStart, i - literalStart), builder); builder.append(templ[++i] == '1' ? "yyyy" : "ww"); literalStart = i + 1; } } if (literalStart < length) DateTimeFormat::quoteAndAppendLiteral(templ.substring(literalStart, length - literalStart), builder); return builder.toString(); } void Locale::setLocaleData(const Vector<String, DecimalSymbolsSize>& symbols, const String& positivePrefix, const String& positiveSuffix, const String& negativePrefix, const String& negativeSuffix) { for (size_t i = 0; i < symbols.size(); ++i) { ASSERT(!symbols[i].isEmpty()); m_decimalSymbols[i] = symbols[i]; } m_positivePrefix = positivePrefix; m_positiveSuffix = positiveSuffix; m_negativePrefix = negativePrefix; m_negativeSuffix = negativeSuffix; ASSERT(!m_positivePrefix.isEmpty() || !m_positiveSuffix.isEmpty() || !m_negativePrefix.isEmpty() || !m_negativeSuffix.isEmpty()); m_hasLocaleData = true; } String Locale::convertToLocalizedNumber(const String& input) { initializeLocaleData(); if (!m_hasLocaleData || input.isEmpty()) return input; unsigned i = 0; bool isNegative = false; StringBuilder builder; builder.reserveCapacity(input.length()); if (input[0] == '-') { ++i; isNegative = true; builder.append(m_negativePrefix); } else { builder.append(m_positivePrefix); } for (; i < input.length(); ++i) { switch (input[i]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': builder.append(m_decimalSymbols[input[i] - '0']); break; case '.': builder.append(m_decimalSymbols[DecimalSeparatorIndex]); break; default: ASSERT_NOT_REACHED(); } } builder.append(isNegative ? m_negativeSuffix : m_positiveSuffix); return builder.toString(); } static bool matches(const String& text, unsigned position, const String& part) { if (part.isEmpty()) return true; if (position + part.length() > text.length()) return false; for (unsigned i = 0; i < part.length(); ++i) { if (text[position + i] != part[i]) return false; } return true; } bool Locale::detectSignAndGetDigitRange(const String& input, bool& isNegative, unsigned& startIndex, unsigned& endIndex) { startIndex = 0; endIndex = input.length(); if (m_negativePrefix.isEmpty() && m_negativeSuffix.isEmpty()) { if (input.startsWith(m_positivePrefix) && input.endsWith(m_positiveSuffix)) { isNegative = false; startIndex = m_positivePrefix.length(); endIndex -= m_positiveSuffix.length(); } else { isNegative = true; } } else { if (input.startsWith(m_negativePrefix) && input.endsWith(m_negativeSuffix)) { isNegative = true; startIndex = m_negativePrefix.length(); endIndex -= m_negativeSuffix.length(); } else { isNegative = false; if (input.startsWith(m_positivePrefix) && input.endsWith(m_positiveSuffix)) { startIndex = m_positivePrefix.length(); endIndex -= m_positiveSuffix.length(); } else { return false; } } } return true; } unsigned Locale::matchedDecimalSymbolIndex(const String& input, unsigned& position) { for (unsigned symbolIndex = 0; symbolIndex < DecimalSymbolsSize; ++symbolIndex) { if (m_decimalSymbols[symbolIndex].length() && matches(input, position, m_decimalSymbols[symbolIndex])) { position += m_decimalSymbols[symbolIndex].length(); return symbolIndex; } } return DecimalSymbolsSize; } String Locale::convertFromLocalizedNumber(const String& localized) { initializeLocaleData(); String input = localized.removeCharacters(isASCIISpace); if (!m_hasLocaleData || input.isEmpty()) return input; bool isNegative; unsigned startIndex; unsigned endIndex; if (!detectSignAndGetDigitRange(input, isNegative, startIndex, endIndex)) return input; StringBuilder builder; builder.reserveCapacity(input.length()); if (isNegative) builder.append('-'); for (unsigned i = startIndex; i < endIndex;) { unsigned symbolIndex = matchedDecimalSymbolIndex(input, i); if (symbolIndex >= DecimalSymbolsSize) return input; if (symbolIndex == DecimalSeparatorIndex) builder.append('.'); else if (symbolIndex == GroupSeparatorIndex) return input; else builder.append(static_cast<UChar>('0' + symbolIndex)); } return builder.toString(); } String Locale::formatDateTime(const DateComponents& date, FormatType formatType) { if (date.type() == DateComponents::Invalid) return String(); DateTimeStringBuilder builder(*this, date); switch (date.type()) { case DateComponents::Time: builder.build(formatType == FormatTypeShort ? shortTimeFormat() : timeFormat()); break; case DateComponents::Date: builder.build(dateFormat()); break; case DateComponents::Month: builder.build(formatType == FormatTypeShort ? shortMonthFormat() : monthFormat()); break; case DateComponents::Week: builder.build(weekFormatInLDML()); break; case DateComponents::DateTime: case DateComponents::DateTimeLocal: builder.build(formatType == FormatTypeShort ? dateTimeFormatWithoutSeconds() : dateTimeFormatWithSeconds()); break; case DateComponents::Invalid: ASSERT_NOT_REACHED(); break; } return builder.toString(); } }
[ "abarth@chromium.org" ]
abarth@chromium.org
9a86e1dc4c7f82342298dee89c2d9988e0785430
b4a0df6a86d130a3a510a50c6f53bf62cefb408d
/TkrUtil/ITkrBadStripsSvc.h
1b756b4aa77263c8be150d802efc877de63809ae
[ "BSD-3-Clause" ]
permissive
fermi-lat/TkrUtil
8591170ae9306894d29cb3424b38a3ae5616bb34
194d4e1501b3d3583d5c794c04e094382c672eb2
refs/heads/master
2022-03-03T12:26:11.518695
2019-08-27T17:28:52
2019-08-27T17:28:52
103,186,929
0
0
null
null
null
null
UTF-8
C++
false
false
3,054
h
/** @file ITkrBadStripsSvc.h @brief Abstract interface to TkrBadStripsSvc (q.v.) @author Leon Rochester $Header: /nfs/slac/g/glast/ground/cvs/TkrUtil/TkrUtil/ITkrBadStripsSvc.h,v 1.9 2005/12/20 02:35:57 lsrea Exp $ */ #ifndef __ITKRBADSTRIPSSVC_H #define __ITKRBADSTRIPSSVC_H 1 #include "GaudiKernel/IInterface.h" #include "idents/GlastAxis.h" #include "GaudiKernel/IDataProviderSvc.h" #include "Event/Digi/TkrDigi.h" #include "Event/Recon/TkrRecon/TkrCluster.h" #include <vector> //---------------------------------------------- // // TkrBadStripsSvc // // Tracker BadStrips Service. Supplies the bad strips // for use by SiClustersAlg, for example //---------------------------------------------- // Leon Rochester, 3-June-2001 //---------------------------------------------- static const InterfaceID IID_ITkrBadStripsSvc("ITkrBadStripsSvc", 5 , 0); /// A small class to define tagged strips class TaggedStrip { public: enum {tagShift = 12, stripMask = 0xFFF, BIG = stripMask}; TaggedStrip(int stripNumber = 0, int tag = 0) { m_stripNumber = (stripNumber & stripMask); m_tag = (tag & stripMask); } ~TaggedStrip() {} int getStripNumber() const { return m_stripNumber;} int getTag() const { return m_tag;} bool isTaggedBad() const { return getTag()>0;} static TaggedStrip makeLastStrip() { return TaggedStrip(BIG, BIG);} static TaggedStrip makeTaggedStrip(const int &strip) { return TaggedStrip(strip); } operator int() const { return ((m_stripNumber & stripMask) << tagShift) | ((m_tag & stripMask)); } private: int m_stripNumber; int m_tag; }; typedef std::vector<TaggedStrip> stripCol; typedef stripCol::iterator stripCol_it; typedef stripCol::const_iterator stripCon_it; class ITkrBadStripsSvc : public virtual IInterface { public: enum clusterType { STANDARDCLUSTERS, BADCLUSTERS }; //! Constructor of this form must be provided static const InterfaceID& interfaceID() { return IID_ITkrBadStripsSvc; } virtual const stripCol* getBadStrips(int tower, int layer, idents::GlastAxis::axis axis) const = 0; virtual bool isBadStrip(int tower, int layer, idents::GlastAxis::axis axis, int strip) const = 0; virtual bool isBadStrip(const stripCol* v, int strip) const = 0; //! Fill the ASCII output stream virtual std::ostream& fillStream( std::ostream& s ) const = 0; virtual bool empty() const = 0; // for bad clusters virtual void setBadClusterCol(Event::TkrClusterCol* pClus) = 0; virtual void setBadIdClusterMap(Event::TkrIdClusterMap* pMap) = 0; virtual Event::TkrClusterCol* getBadClusterCol() const = 0; virtual Event::TkrIdClusterMap* getBadIdClusterMap() const = 0; virtual StatusCode makeBadDigiCol(Event::TkrDigiCol* pDigis) = 0; //! Fill the ASCII output stream friend std::ostream& operator<<( std::ostream& s , stripCol* v); }; #endif
[ "" ]
ac3210914f5fa6ad32da8fa9780f41b15a49fe8c
b146e1042c8ef3f9d16b7273f6d73a13ae5a79be
/app/src/main/cpp/thirdparty/include/glm/ext/matrix_double2x2.hpp
8f6541dcaa0a73e555405b2ba6a6e47c87752fc6
[]
no_license
Bo007/android_opengl
3efe3be882ff6f9e5d93d4d972f0d1acf8d715ec
ae95b1b58bfc8b142532ef8425e40020cc566b60
refs/heads/master
2020-06-13T03:02:31.136486
2019-07-21T11:10:02
2019-07-21T11:10:02
194,510,556
1
0
null
null
null
null
UTF-8
C++
false
false
748
hpp
/// @ref core /// @file glm/ext/matrix_double2x2.hpp #pragma once #include "../detail/type_mat2x2.hpp" namespace glm { /// @addtogroup core_matrix /// @{ /// 2 columns of 2 components matrix of double-precision floating-point numbers. /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a> typedef mat<2, 2, double, defaultp> dmat2x2; /// 2 columns of 2 components matrix of double-precision floating-point numbers. /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a> typedef mat<2, 2, double, defaultp> dmat2; /// @} }//namespace glm
[ "aleksey.bozhenko@nixsolutions.com" ]
aleksey.bozhenko@nixsolutions.com
3fbaa265ef2d22d405c22e8a8335f0b78fffd4cb
e724239c987c158a59e21486b3a431ec61195c79
/Source/SRPG/UI/NPCWidgetComponent.h
aecc28ff6a336e17726941a7df23e4dd4ec86fee
[]
no_license
MohdAAyyad/SRPG
6608c113b62409c3f688b6c93d8d6e29e1846f5e
f5f63a01e3f5663238a1a308909e2ec55d101720
refs/heads/master
2023-03-23T02:47:36.694002
2021-03-18T17:06:18
2021-03-18T17:06:18
279,445,173
1
0
null
null
null
null
UTF-8
C++
false
false
534
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/WidgetComponent.h" #include "Hub/NPC.h" #include "NPCWidgetComponent.generated.h" /** * */ UCLASS() class SRPG_API UNPCWidgetComponent : public UWidgetComponent { GENERATED_BODY() protected: public: UFUNCTION(BlueprintCallable) void SetNPCRef(ANPC* npc_); UPROPERTY(EditAnywhere, BlueprintReadWrite) FString line; UPROPERTY(EditAnywhere, BlueprintReadWrite) ANPC* npcRef; };
[ "seanfowke@hotmail.com" ]
seanfowke@hotmail.com
0c3bb7089c777f55c123de31a95618453e7d153c
671ef594c3a043b32900864b3f5bf13bbcdab0aa
/src/effectDX7/efpane.h
b4bf14f0e7738eeec5882f141845ce662c67c55c
[ "MIT" ]
permissive
VSitoianu/Allegiance
bae7206b874d02fdbf4c9c746e9834c7ef93154e
6f3213b78f793c6f77fd397c280cd2dd80c46396
refs/heads/master
2021-05-07T17:15:01.811214
2017-10-22T18:18:44
2017-10-22T18:18:44
108,667,678
1
0
null
2017-10-28T17:02:26
2017-10-28T17:02:26
null
UTF-8
C++
false
false
2,945
h
#ifndef _efpane_H_ #define _efpane_H_ ////////////////////////////////////////////////////////////////////////////// // // effect panes // ////////////////////////////////////////////////////////////////////////////// void SetEffectWindow(Window* pwindow); void AddPaneFactories( INameSpace* pns, Modeler* pmodeler, IPopupContainer* ppopupContainer, Number* ptime ); ////////////////////////////////////////////////////////////////////////////// // // Black background // ////////////////////////////////////////////////////////////////////////////// TRef<Pane> CreateBlackPane(Pane* ppane); ////////////////////////////////////////////////////////////////////////////// // // Hover Site // ////////////////////////////////////////////////////////////////////////////// class HoverSite : public IObject { public: virtual void Enter(float id) = 0; virtual void Leave(float id) = 0; virtual Number* GetID() = 0; }; TRef<HoverSite> CreateHoverSite(float id); TRef<Pane> CreateHoverPane(HoverSite* psite, float id, Pane* ppane); ////////////////////////////////////////////////////////////////////////////// // // ThumbPane // ////////////////////////////////////////////////////////////////////////////// class ThumbPane : public Pane { public: static TRef<ThumbPane> Create(Modeler* pmodeler, bool bHorizontal, // false == vertical TRef<Image> pImageThumb // Set this to NULL for default image ); }; ////////////////////////////////////////////////////////////////////////////// // // Trek Scroll Bar // ////////////////////////////////////////////////////////////////////////////// TRef<Pane> CreateTrekScrollPane( unsigned height, Modeler* pmodeler, TRef<IIntegerEventSource>& pevent, TRef<ScrollPane>& pscrollPane ); ///////////////////////////////////////////////////////////////////////////// // // Gauge Pane // ///////////////////////////////////////////////////////////////////////////// class GaugePane : public Pane { private: TRef<Surface> m_psurface; float m_minValue; float m_maxValue; int m_value; int m_valueOld; int m_valueFlash; Time m_timeLastChange; Color m_colorFlash; Color m_colorEmpty; void Paint(Surface* psurface); public: GaugePane(Surface* psurface, const Color& colorFlash = Color::Red(), float minValue = 0.0f, float maxValue = 1.0f, const Color& colorEmpty = Color::Black()); void SetValue(float v, bool fFlash = true); void Update(Time time); }; void ParseIntVector(IObject* pobject, TVector<int>& vec); void ParseFloatVector(IObject* pobject, TVector<int>& vec); void ParseStringVector(IObject* pobject, TVector<ZString>& vec); #endif
[ "nick@zaphop.com" ]
nick@zaphop.com
905f428a7ab7291a9d115b2ac9eedb68f717f4ef
00d71fcdf7962487c1162518d74c9b676053f894
/c++-practice/dfs.cc
f71adf2d82f36ab26b23483b92736e16cd326f50
[ "MIT" ]
permissive
Indefine/algorithm
ddb1c1db9ab99ce08fdd97181b9d5b02f05870d9
ee744daefb1d6b9be0e9025ff2c3c0149eac1a06
refs/heads/master
2021-05-10T11:17:20.752776
2021-01-05T07:06:26
2021-01-05T07:06:26
118,408,635
0
0
null
null
null
null
UTF-8
C++
false
false
460
cc
#include <iostream> int route[10][10] void dfs(int **); void dfs(int **Map, int need, int x, int y) { for (int i = 0; i < 4; i++) { switch (i) case 0: dfs(Map, need, x + 1, y); break; case 1: dfs(Map, need, x -1, y); break; case 2: dfs(Map, need, x, y + 1); case 3: dfs(Map, need, x, y - 1); default: break; } }
[ "q7086935@gmail.com" ]
q7086935@gmail.com
5128f6255b3e2f653dd9c46fddcfef9de372a2ba
52abd2ccd1435421f756514a23c73843ea301a35
/bubble/src/OpType/OpTypeFunctions.cpp
73c06a323966b4ccc017310e0691b5869a6d2790
[ "Apache-2.0" ]
permissive
qfizik/tket
51e684db0f56128a71a18a27d6c660908af391cd
f31cbec63be1a0e08f83494ef7dedb8b7c1dafc8
refs/heads/main
2023-08-13T01:20:01.937544
2021-09-24T08:09:30
2021-09-24T08:09:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,726
cpp
// Copyright 2019-2021 Cambridge Quantum Computing // // 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. #include "OpTypeFunctions.hpp" #include <memory> namespace tket { bool find_in_set(const OpType& val, const OpTypeSet& set) { return set.find(val) != set.cend(); } const OpTypeSet& all_gate_types() { static std::unique_ptr<const OpTypeSet> gates( new OpTypeSet{OpType::Z, OpType::X, OpType::Y, OpType::S, OpType::Sdg, OpType::T, OpType::Tdg, OpType::V, OpType::Vdg, OpType::SX, OpType::SXdg, OpType::H, OpType::Rx, OpType::Ry, OpType::Rz, OpType::U3, OpType::U2, OpType::U1, OpType::tk1, OpType::CX, OpType::CY, OpType::CZ, OpType::CH, OpType::CV, OpType::CVdg, OpType::CSX, OpType::CSXdg, OpType::CRz, OpType::CRx, OpType::CRy, OpType::CU1, OpType::CU3, OpType::PhaseGadget, OpType::CCX, OpType::SWAP, OpType::CSWAP, OpType::noop, OpType::Measure, OpType::Reset, OpType::ECR, OpType::ISWAP, OpType::PhasedX, OpType::ZZMax, OpType::XXPhase, OpType::YYPhase, OpType::ZZPhase, OpType::CnRy, OpType::CnX, OpType::BRIDGE, OpType::Collapse, OpType::ESWAP, OpType::FSim, OpType::Sycamore, OpType::ISWAPMax, OpType::PhasedISWAP, OpType::XXPhase3}); return *gates; } const OpTypeSet& all_multi_qubit_types() { static std::unique_ptr<const OpTypeSet> multi_qubit_gates( new OpTypeSet{OpType::CX, OpType::CY, OpType::CZ, OpType::CH, OpType::CV, OpType::CVdg, OpType::CSX, OpType::CSXdg, OpType::CRz, OpType::CRx, OpType::CRy, OpType::CU1, OpType::CU3, OpType::PhaseGadget, OpType::CCX, OpType::SWAP, OpType::CSWAP, OpType::ECR, OpType::ISWAP, OpType::ZZMax, OpType::XXPhase, OpType::YYPhase, OpType::ZZPhase, OpType::CnRy, OpType::CnX, OpType::BRIDGE, OpType::ESWAP, OpType::FSim, OpType::Sycamore, OpType::ISWAPMax, OpType::PhasedISWAP, OpType::XXPhase3}); return *multi_qubit_gates; } const OpTypeSet& all_single_qubit_types() { static std::unique_ptr<const OpTypeSet> single_qubit_gates(new OpTypeSet{ OpType::Z, OpType::X, OpType::Y, OpType::S, OpType::Sdg, OpType::T, OpType::Tdg, OpType::V, OpType::Vdg, OpType::SX, OpType::SXdg, OpType::H, OpType::Rx, OpType::Ry, OpType::Rz, OpType::U3, OpType::U2, OpType::U1, OpType::tk1, OpType::Measure, OpType::Reset, OpType::Collapse, OpType::PhasedX, OpType::noop}); return *single_qubit_gates; } const OpTypeSet& all_projective_types() { static std::unique_ptr<const OpTypeSet> projective_gates( new OpTypeSet{OpType::Measure, OpType::Collapse, OpType::Reset}); return *projective_gates; } bool is_metaop_type(OpType optype) { static const OpTypeSet metaops = { OpType::Input, OpType::Output, OpType::ClInput, OpType::ClOutput, OpType::Barrier, OpType::Create, OpType::Discard}; return find_in_set(optype, metaops); } bool is_initial_q_type(OpType optype) { return optype == OpType::Input || optype == OpType::Create; } bool is_final_q_type(OpType optype) { return optype == OpType::Output || optype == OpType::Discard; } bool is_boundary_q_type(OpType optype) { return is_initial_q_type(optype) || is_final_q_type(optype); } bool is_boundary_c_type(OpType optype) { return optype == OpType::ClInput || optype == OpType::ClOutput; } bool is_gate_type(OpType optype) { return find_in_set(optype, all_gate_types()); } bool is_box_type(OpType optype) { static const OpTypeSet boxes = { OpType::CircBox, OpType::Unitary1qBox, OpType::Unitary2qBox, OpType::Unitary3qBox, OpType::ExpBox, OpType::PauliExpBox, OpType::Composite, OpType::CliffBox, OpType::PhasePolyBox, OpType::QControlBox, OpType::ClassicalExpBox, OpType::ProjectorAssertionBox, OpType::StabiliserAssertionBox}; return find_in_set(optype, boxes); } bool is_flowop_type(OpType optype) { static const OpTypeSet flowops = { OpType::Label, OpType::Branch, OpType::Goto, OpType::Stop}; return find_in_set(optype, flowops); } bool is_rotation_type(OpType optype) { static const OpTypeSet rotation_gates = { OpType::Rx, OpType::Ry, OpType::Rz, OpType::U1, OpType::CnRy, OpType::CRz, OpType::CRx, OpType::CRy, OpType::CU1, OpType::XXPhase, OpType::YYPhase, OpType::ZZPhase, OpType::ESWAP, OpType::ISWAP, OpType::XXPhase3}; return find_in_set(optype, rotation_gates); } bool is_parameterised_pauli_rotation_type(OpType optype) { static const OpTypeSet parameterised_pauli_rotations = { OpType::Rx, OpType::Ry, OpType::Rz, OpType::U1}; return find_in_set(optype, parameterised_pauli_rotations); } bool is_multi_qubit_type(OpType optype) { return find_in_set(optype, all_multi_qubit_types()); } bool is_single_qubit_type(OpType optype) { return find_in_set(optype, all_single_qubit_types()); } bool is_oneway_type(OpType optype) { // This set should contain only gates for which an dagger is nonsensical // or we do not yet have the dagger gate as an OpType. // If the gate can have an dagger, define it in the dagger() method. static const OpTypeSet no_defined_inverse = { OpType::Input, OpType::Output, OpType::Measure, OpType::ClInput, OpType::ClOutput, OpType::Barrier, OpType::Reset, OpType::Collapse, OpType::Composite, OpType::PhasePolyBox, OpType::Create, OpType::Discard}; return find_in_set(optype, no_defined_inverse); } bool is_clifford_type(OpType optype) { static const OpTypeSet clifford_gates = { OpType::Z, OpType::X, OpType::Y, OpType::S, OpType::Sdg, OpType::V, OpType::Vdg, OpType::SX, OpType::SXdg, OpType::H, OpType::CX, OpType::CY, OpType::CZ, OpType::SWAP, OpType::BRIDGE, OpType::noop, OpType::ZZMax, OpType::ECR, OpType::ISWAPMax}; return find_in_set(optype, clifford_gates); } bool is_projective_type(OpType optype) { return find_in_set(optype, all_projective_types()); } bool is_classical_type(OpType optype) { static const OpTypeSet classical_gates = { OpType::ClassicalTransform, OpType::SetBits, OpType::CopyBits, OpType::RangePredicate, OpType::ExplicitPredicate, OpType::ExplicitModifier, OpType::MultiBit, }; return find_in_set(optype, classical_gates); } } // namespace tket
[ "alec.edgington@cambridgequantum.com" ]
alec.edgington@cambridgequantum.com
c8be23868528885fff04c5e8ec4b69adcc921028
4ef09b833e4682b7c1c205a654874f4b2a7cba82
/ray casting/source files/viewing_ray.cpp
4e7a3b070964c6ab59417de519127521ab8316a5
[]
no_license
GabrielChan1/sample-code
87d9f18d3ee10198753918267cd44e88b77e2685
c344df3a8f3a0f4882a3c2e651552ccf21599fc6
refs/heads/master
2020-06-04T01:46:24.465308
2019-06-13T20:12:08
2019-06-13T20:12:08
191,820,773
0
0
null
null
null
null
UTF-8
C++
false
false
1,097
cpp
#include "viewing_ray.h" /* TODO: - Set 'ray.origin' to 'camera.e' - Find values 'u' and 'v' to determine direction - 'width' and 'height' = pixel width and height = n.x and n.y - 'camera.width' and 'camera.height' = physical image width and height */ void viewing_ray( const Camera & camera, const int i, const int j, const int width, const int height, Ray & ray) { //////////////////////////////////////////////////////////////////////////// // Add your code here // Calculate 'u' and 'v' using formulas from lecture slides (according to the TA, the // positions of 'i' and 'j' in the lecture slides need to be swapped) double u = camera.width * ((j + (0.5)) / width) - (camera.width / 2.0); double v = camera.height * ((height - (i + 0.5)) / height) - (camera.height / 2.0); // Set origin of the ray to the origin of the camera ray.origin = camera.e; // Set direction of the ray using formula from the textbook ray.direction = camera.d * (-1.0) * camera.w + u * camera.u + v * camera.v; //////////////////////////////////////////////////////////////////////////// }
[ "neoco@techie.com" ]
neoco@techie.com
9f694650145f2fbf17c046ad6777ba4c1d5848f4
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/chrome/browser/chromeos/lock_screen_apps/app_window_metrics_tracker.h
a5c95ab6889f2a4f0a11258e30b162e22026d3e8
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
2,538
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_CHROMEOS_LOCK_SCREEN_APPS_APP_WINDOW_METRICS_TRACKER_H_ #define CHROME_BROWSER_CHROMEOS_LOCK_SCREEN_APPS_APP_WINDOW_METRICS_TRACKER_H_ #include <map> #include "base/macros.h" #include "base/optional.h" #include "base/time/time.h" #include "content/public/browser/web_contents_observer.h" namespace base { class TickClock; } namespace extensions { class AppWindow; } namespace lock_screen_apps { // Helper for tracking metrics for lock screen app window launches. class AppWindowMetricsTracker : public content::WebContentsObserver { public: explicit AppWindowMetricsTracker(base::TickClock* clock); ~AppWindowMetricsTracker() override; // Register app launch request. void AppLaunchRequested(); // Registers the app window created for lock screen action - the class // will begin observing the app window state as a result. void AppWindowCreated(extensions::AppWindow* app_window); // Updates metrics state for app window being moved to foreground. void MovedToForeground(); // Updates metrics state for app window being moved to background. void MovedToBackground(); // Stops tracking current app window state, and resets collected timestamps. void Reset(); // content::WebContentsObserver: void RenderViewCreated(content::RenderViewHost* render_view_host) override; void DocumentOnLoadCompletedInMainFrame() override; private: // NOTE: Used in histograms - do not change order, or remove entries. // Also, update LockScreenAppSessionState enum. enum class State { kInitial = 0, kLaunchRequested = 1, kWindowCreated = 2, kWindowShown = 3, kForeground = 4, kBackground = 5, kCount }; void SetState(State state); base::TickClock* clock_; State state_ = State::kInitial; // Maps states to their last occurrence time. std::map<State, base::TimeTicks> time_stamps_; // Number of times app launch was requested during the int app_launch_count_ = 0; // The state to which the metrics tracker should move after // the window contents is loaded. // Should be either kForeground or kBackground. base::Optional<State> state_after_window_contents_load_ = State::kForeground; DISALLOW_COPY_AND_ASSIGN(AppWindowMetricsTracker); }; } // namespace lock_screen_apps #endif // CHROME_BROWSER_CHROMEOS_LOCK_SCREEN_APPS_APP_WINDOW_METRICS_TRACKER_H_
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
f9e89fcd967b836e066ae6c9a030e8ceacc3e0a7
4f6437719a470e6d2c364e6ab9aec5b04596c350
/tests/test_cipher_base.cxx
71a605aeb6933610213f0d2d8bac4781671f5a75
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "BSD-3-Clause" ]
permissive
Scratch-net/virgil-crypto
6b3eae2e223b697d0ab9352b68558b9ed35bb051
7173463be7e192032161f99a8c94bda0e70becab
refs/heads/master
2021-09-07T03:42:58.117858
2018-02-01T18:46:22
2018-02-01T18:46:22
119,807,142
0
0
null
2018-02-01T08:36:32
2018-02-01T08:36:32
null
UTF-8
C++
false
false
16,789
cxx
/** * Copyright (C) 2015-2016 Virgil Security Inc. * * Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com> * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * (1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * (3) Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file test_cipher_base.cxx * @brief Covers class VirgilCipherBase. */ #include "catch.hpp" #include <virgil/crypto/VirgilByteArray.h> #include <virgil/crypto/VirgilByteArrayUtils.h> #include <virgil/crypto/VirgilCipherBase.h> #include <virgil/crypto/VirgilCryptoException.h> #include <virgil/crypto/VirgilKeyPair.h> using virgil::crypto::VirgilByteArray; using virgil::crypto::VirgilByteArrayUtils; using virgil::crypto::VirgilCipherBase; using virgil::crypto::VirgilCryptoException; using virgil::crypto::VirgilKeyPair; constexpr char kPublicKey[] = "-----BEGIN PUBLIC KEY-----\n" "MCowBQYDK2VwAyEAGb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZmE=\n" "-----END PUBLIC KEY-----\n"; constexpr char kPrivateKey[] = "-----BEGIN PRIVATE KEY-----\n" "MC4CAQAwBQYDK2VwBCIEINTuctv5E1hK1bbY8fdp+K06/nwoy/HU++CXqI9EdVhC\n" "-----END PRIVATE KEY-----\n"; constexpr char kUnsupportedPublicKey[] = "-----BEGIN PUBLIC KEY-----\n" "MFswFQYHKoZIzj0CAQYKKwYBBAGXVQEFBQNCAARhEuj2bVQKPe1ZXst7ubob+bVr\n" "9tcjPs7x7mVumQO7YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n" "-----END PUBLIC KEY-----\n"; TEST_CASE("VirgilCipherBase::addKeyRecipient()", "[cipher-base]") { const VirgilByteArray emptyRecipientId = VirgilByteArrayUtils::stringToBytes(""); const VirgilByteArray invalidPublicKey = VirgilByteArrayUtils::stringToBytes("invalid public key"); const VirgilByteArray unsupportedPublicKey = VirgilByteArrayUtils::stringToBytes(kUnsupportedPublicKey); const VirgilByteArray emptyPublicKey = VirgilByteArrayUtils::stringToBytes(""); const VirgilByteArray validRecipientId = VirgilByteArrayUtils::stringToBytes("valid-bob-id"); const VirgilByteArray validPublicKey = VirgilByteArrayUtils::stringToBytes(kPublicKey); VirgilCipherBase cipherBase; SECTION("Add recipient with valid parameters") { REQUIRE_NOTHROW(cipherBase.addKeyRecipient(validRecipientId, validPublicKey)); } SECTION("Add recipient with invalid parameter: recipientId") { REQUIRE_THROWS_AS(cipherBase.addKeyRecipient(emptyRecipientId, validPublicKey), VirgilCryptoException); } SECTION("Add recipient with empty parameter: publicKey") { REQUIRE_THROWS_AS(cipherBase.addKeyRecipient(validRecipientId, emptyPublicKey), VirgilCryptoException); } SECTION("Add recipient with invalid format of parameter: publicKey") { REQUIRE_THROWS_AS(cipherBase.addKeyRecipient(validRecipientId, invalidPublicKey), VirgilCryptoException); } SECTION("Add recipient with unsupported algorithm defined with parameter: publicKey") { REQUIRE_THROWS_AS(cipherBase.addKeyRecipient(validRecipientId, unsupportedPublicKey), VirgilCryptoException); } } TEST_CASE("VirgilCipherBase::removeKeyRecipient()", "[cipher-base]") { const VirgilByteArray emptyRecipientId = VirgilByteArrayUtils::stringToBytes(""); const VirgilByteArray existingRecipientId = VirgilByteArrayUtils::stringToBytes("valid-bob-id"); const VirgilByteArray nonExistingRecipientId = VirgilByteArrayUtils::stringToBytes("valid-alice-id"); const VirgilByteArray validPublicKey = VirgilByteArrayUtils::stringToBytes(kPublicKey); VirgilCipherBase cipherBase; cipherBase.addKeyRecipient(existingRecipientId, validPublicKey); SECTION("Remove existing recipient") { REQUIRE_NOTHROW(cipherBase.removeKeyRecipient(existingRecipientId)); } SECTION("Remove non existing recipient") { REQUIRE_NOTHROW(cipherBase.removeKeyRecipient(nonExistingRecipientId)); } SECTION("Remove empty recipient") { REQUIRE_NOTHROW(cipherBase.removeKeyRecipient(emptyRecipientId)); } } TEST_CASE("VirgilCipherBase::keyRecipientExists()", "[cipher-base]") { const VirgilByteArray emptyRecipientId = VirgilByteArrayUtils::stringToBytes(""); const VirgilByteArray existingRecipientId = VirgilByteArrayUtils::stringToBytes("valid-bob-id"); const VirgilByteArray nonExistingRecipientId = VirgilByteArrayUtils::stringToBytes("valid-alice-id"); const VirgilByteArray validPublicKey = VirgilByteArrayUtils::stringToBytes(kPublicKey); VirgilCipherBase cipherBase; REQUIRE_NOTHROW(cipherBase.addKeyRecipient(existingRecipientId, validPublicKey)); SECTION("Check existing recipient") { REQUIRE(cipherBase.keyRecipientExists(existingRecipientId)); } SECTION("Check non existing recipient") { REQUIRE_FALSE(cipherBase.keyRecipientExists(nonExistingRecipientId)); } SECTION("Check empty recipient") { REQUIRE_FALSE(cipherBase.keyRecipientExists(emptyRecipientId)); } } TEST_CASE("VirgilCipherBase::addPasswordRecipient()", "[cipher-base]") { const VirgilByteArray emptyPassword = VirgilByteArrayUtils::stringToBytes(""); const VirgilByteArray validPassword = VirgilByteArrayUtils::stringToBytes("valid-bob-password"); VirgilCipherBase cipherBase; SECTION("Add non empty password recipient") { REQUIRE_NOTHROW(cipherBase.addPasswordRecipient(validPassword)); } SECTION("Add non empty password recipient twice") { REQUIRE_NOTHROW(cipherBase.addPasswordRecipient(validPassword)); REQUIRE_NOTHROW(cipherBase.addPasswordRecipient(validPassword)); } SECTION("Add empty password recipient") { REQUIRE_THROWS_AS(cipherBase.addPasswordRecipient(emptyPassword), VirgilCryptoException); } } TEST_CASE("VirgilCipherBase::removePasswordRecipient()", "[cipher-base]") { const VirgilByteArray emptyPassword = VirgilByteArrayUtils::stringToBytes(""); const VirgilByteArray existingPassword = VirgilByteArrayUtils::stringToBytes("valid-bob-password"); const VirgilByteArray nonExistingPassword = VirgilByteArrayUtils::stringToBytes("valid-alice-password"); VirgilCipherBase cipherBase; REQUIRE_NOTHROW(cipherBase.addPasswordRecipient(existingPassword)); SECTION("Remove existing password recipient") { REQUIRE_NOTHROW(cipherBase.removePasswordRecipient(existingPassword)); } SECTION("Remove existing password recipient twice") { REQUIRE_NOTHROW(cipherBase.removePasswordRecipient(existingPassword)); REQUIRE_NOTHROW(cipherBase.removePasswordRecipient(existingPassword)); } SECTION("Remove non existing password recipient") { REQUIRE_NOTHROW(cipherBase.removePasswordRecipient(nonExistingPassword)); } SECTION("Remove empty password recipient") { REQUIRE_NOTHROW(cipherBase.removePasswordRecipient(emptyPassword)); } } TEST_CASE("VirgilCipherBase::passwordRecipientExists()", "[cipher-base]") { const VirgilByteArray emptyPassword = VirgilByteArrayUtils::stringToBytes(""); const VirgilByteArray existingPassword = VirgilByteArrayUtils::stringToBytes("valid-bob-password"); const VirgilByteArray nonExistingPassword = VirgilByteArrayUtils::stringToBytes("valid-alice-password"); VirgilCipherBase cipherBase; REQUIRE_NOTHROW(cipherBase.addPasswordRecipient(existingPassword)); SECTION("Check existing recipient") { REQUIRE(cipherBase.passwordRecipientExists(existingPassword)); } SECTION("Check non existing recipient") { REQUIRE_FALSE(cipherBase.passwordRecipientExists(nonExistingPassword)); } SECTION("Check empty recipient") { REQUIRE_FALSE(cipherBase.passwordRecipientExists(emptyPassword)); } } TEST_CASE("VirgilCipherBase::removeAllRecipients()", "[cipher-base]") { const VirgilByteArray existingPassword = VirgilByteArrayUtils::stringToBytes("valid-bob-password"); const VirgilByteArray existingRecipientId = VirgilByteArrayUtils::stringToBytes("valid-bob-id"); const VirgilByteArray validPublicKey = VirgilByteArrayUtils::stringToBytes(kPublicKey); VirgilCipherBase cipherBase; REQUIRE_NOTHROW(cipherBase.addPasswordRecipient(existingPassword)); REQUIRE_NOTHROW(cipherBase.addKeyRecipient(existingRecipientId, validPublicKey)); SECTION("Remove all recipients") { REQUIRE(cipherBase.keyRecipientExists(existingRecipientId)); REQUIRE(cipherBase.passwordRecipientExists(existingPassword)); REQUIRE_NOTHROW(cipherBase.removeAllRecipients()); REQUIRE_FALSE(cipherBase.passwordRecipientExists(existingPassword)); REQUIRE_FALSE(cipherBase.keyRecipientExists(existingPassword)); } SECTION("Remove all recipients twice") { REQUIRE(cipherBase.keyRecipientExists(existingRecipientId)); REQUIRE(cipherBase.passwordRecipientExists(existingPassword)); REQUIRE_NOTHROW(cipherBase.removeAllRecipients()); REQUIRE_NOTHROW(cipherBase.removeAllRecipients()); REQUIRE_FALSE(cipherBase.passwordRecipientExists(existingPassword)); REQUIRE_FALSE(cipherBase.keyRecipientExists(existingPassword)); } } TEST_CASE("VirgilCipherBase::getContentInfo()", "[cipher-base]") { VirgilCipherBase cipherBase; SECTION("Read empty content info") { VirgilByteArray contentInfo; REQUIRE_THROWS_AS(contentInfo = cipherBase.getContentInfo(), VirgilCryptoException); } } TEST_CASE("VirgilCipherBase::setContentInfo()", "[cipher-base]") { const VirgilByteArray emptyContentInfo = VirgilByteArrayUtils::stringToBytes(""); const VirgilByteArray invalidContentInfo = VirgilByteArrayUtils::stringToBytes("invalid content info"); const VirgilByteArray validContentInfo = VirgilByteArrayUtils::hexToBytes( "308201A7020100308201A006092A864886F70D010703A08201913082018D0201" "023182015E3082015A020102A026042437643464396462392D343833382D3462" "33652D393934622D646464613666633035373630301506072A8648CE3D020106" "0A2B0601040197550105010482011430820110020100305B301506072A8648CE" "3D0201060A2B06010401975501050103420004337F20F3E2B4F85B5E02B22A8A" "EB0A02E58436C00906C85B0A11C8B18F85A96D00000000000000000000000000" "000000000000000000000000000000000000003018060728818C71020502300D" "060960864801650304020205003041300D060960864801650304020205000430F" "B28152BC746813659109EFCCA90B0AE44635E82FCF4BA583267AE5FC8717FC098" "EA0C8E0474E938BDE125401B3911DB3051301D060960864801650304012A04102" "6FA3996462ADA0CC36D3ECC850185D704307E43EE0B2451313BC62FC129F7322A" "44E56632F38EE442E841B1ECBD144609F04CE3FAC5879F719A399DBC6E1B84F3C" "2302606092A864886F70D0107013019060960864801650304012E040C2BC53E10" "6C326CF26CD6C572" ); const VirgilByteArray malformedContentInfo = VirgilByteArrayUtils::hexToBytes( "308201A7020100308201A006092A864886F70D010704A08201913082018D0201" "023182015E3082015A020102A026042437643464396462392D343833382D3462" "33652D393934622D646464613666633035373630301506072A8648CE3D020106" "0A2B0601040197550105010482011430820110020100305B301506072A8648CE" "3D0201060A2B06010401975501050103420004337F20F3E2B4F85B5E02B22A8A" "EB0A02E58436C00906C85B0A11C8B18F85A96D00000000000000000000000000" "000000000000000000000000000000000000003018060728818C71020502300D" "060960864801650304020205003041300D060960864801650304020205000430F" "B28152BC746813659109EFCCA90B0AE44635E82FCF4BA583267AE5FC8717FC098" "EA0C8E0474E938BDE125401B3911DB3051301D060960864801650304012A04102" "6FA3996462ADA0CC36D3ECC850185D704307E43EE0B2451313BC62FC129F7322A" "44E56632F38EE442E841B1ECBD144609F04CE3FAC5879F719A399DBC6E1B84F3C" "2302606092A864886F70D0107013019060960864801650304012E040C2BC53E10" "6C326CF26CD6C572" ); VirgilCipherBase cipherBase; SECTION("Write valid content info") { REQUIRE_NOTHROW(cipherBase.setContentInfo(validContentInfo)); } SECTION("Write empty content info") { REQUIRE_THROWS_AS(cipherBase.setContentInfo(emptyContentInfo), VirgilCryptoException); } SECTION("Write invalid content info") { REQUIRE_THROWS_AS(cipherBase.setContentInfo(invalidContentInfo), VirgilCryptoException); } SECTION("Write unsupported content info") { REQUIRE_THROWS_AS(cipherBase.setContentInfo(malformedContentInfo), VirgilCryptoException); } } TEST_CASE("VirgilCipherBase::computeShared()", "[cipher-base]") { VirgilKeyPair bobCurve25519 = VirgilKeyPair::generate(VirgilKeyPair::Type::FAST_EC_X25519); VirgilKeyPair aliceCurve25519 = VirgilKeyPair::generate(VirgilKeyPair::Type::FAST_EC_X25519); VirgilKeyPair bobNist256 = VirgilKeyPair::generate(VirgilKeyPair::Type::EC_SECP256K1); VirgilKeyPair aliceNist256 = VirgilKeyPair::generate(VirgilKeyPair::Type::EC_SECP256K1); VirgilKeyPair bobBrainpool256 = VirgilKeyPair::generate(VirgilKeyPair::Type::EC_BP256R1); VirgilKeyPair aliceBrainpool256 = VirgilKeyPair::generate(VirgilKeyPair::Type::EC_BP256R1); VirgilKeyPair bobRsa2048 = VirgilKeyPair::generate(VirgilKeyPair::Type::RSA_2048); VirgilKeyPair aliceRsa2048 = VirgilKeyPair::generate(VirgilKeyPair::Type::RSA_2048); SECTION("Compute shared key on Elliptic Curve keys of the same group") { REQUIRE_NOTHROW(VirgilCipherBase::computeShared(bobCurve25519.publicKey(), aliceCurve25519.privateKey())); REQUIRE_NOTHROW(VirgilCipherBase::computeShared(aliceCurve25519.publicKey(), bobCurve25519.privateKey())); REQUIRE_NOTHROW(VirgilCipherBase::computeShared(bobNist256.publicKey(), aliceNist256.privateKey())); REQUIRE_NOTHROW(VirgilCipherBase::computeShared(aliceNist256.publicKey(), bobNist256.privateKey())); REQUIRE_NOTHROW(VirgilCipherBase::computeShared(bobBrainpool256.publicKey(), aliceBrainpool256.privateKey())); REQUIRE_NOTHROW(VirgilCipherBase::computeShared(aliceBrainpool256.publicKey(), bobBrainpool256.privateKey())); } SECTION("Compute shared key on Elliptic Curve keys of the different group") { REQUIRE_THROWS_AS(VirgilCipherBase::computeShared(bobCurve25519.publicKey(), aliceNist256.privateKey()), VirgilCryptoException); REQUIRE_THROWS_AS(VirgilCipherBase::computeShared(bobCurve25519.publicKey(), aliceBrainpool256.privateKey()), VirgilCryptoException); REQUIRE_THROWS_AS(VirgilCipherBase::computeShared(bobBrainpool256.publicKey(), aliceNist256.privateKey()), VirgilCryptoException); } SECTION("Compute shared key on RSA keys") { REQUIRE_THROWS_AS(VirgilCipherBase::computeShared(bobRsa2048.publicKey(), aliceRsa2048.privateKey()), VirgilCryptoException); } SECTION("Compute shared key on RSA key and Elliptic Curve key") { REQUIRE_THROWS_AS(VirgilCipherBase::computeShared(bobCurve25519.publicKey(), aliceRsa2048.privateKey()), VirgilCryptoException); } }
[ "sergey.seroshtan@gmail.com" ]
sergey.seroshtan@gmail.com
96fc340847f9988156dff79d69b7fc751bf91ddc
24989c1b490295e44a9c328e38b3f2e43a47e9e0
/RotMG Server/XMLWorld.h
cac8cf0370242f3107504e8bad39ae8e292dd0f6
[]
no_license
Devwarlt/RotMG-Server
d88b6ca89bd8772000d1d76db3f3f0bf2aef9f8a
c8b9e48823c44e8a70a4b46c316e8eca0a172eca
refs/heads/master
2021-01-21T10:51:51.684702
2016-08-20T20:22:10
2016-08-20T20:22:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
631
h
#ifndef XMLWORLD_H_ #define XMLWORLD_H_ #include <string> #include <unordered_map> #include "pugixml.hpp" using std::string; using pugi::xml_node; using pugi::xpath_node; using pugi::xml_attribute; using pugi::xml_node_type; class XMLRoom; class XMLWorld { public: XMLWorld(xml_node worldNode); std::string id; int width; int height; int background; int difficulty; std::string visibility; bool showDisplays; bool allowPlayerTeleport; bool centerStartRoom; int defaultTile; std::unordered_map<std::string, std::vector<XMLRoom*>*>* rooms; XMLRoom* getRoom(const char* type); private: }; #endif // !XMLWORLD_H_
[ "speisewagen96@gmx.de" ]
speisewagen96@gmx.de
07e9e8fbb723c2f1c17d13f07c8f086947c6dd90
23079f7d74476456659ec28c34de950cf4da662c
/aed/aplicacaoRadixSort.cpp
3ab95f3166adc6074a3deab4d2ab22006957c890
[]
no_license
lulumaxde/unifesp
7d77f0e5ad921954a0699c21a3050e6a690c6bd7
597ea1694f7a54975541f61197266002d8efaf29
refs/heads/master
2023-05-15T13:07:36.989696
2021-06-15T13:43:51
2021-06-15T13:43:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,380
cpp
/* Gaspar Andrade – 133633 * UC: AED2 Prof. Dr. Álvaro Luiz Fazenda * UNIFESP – ICT * Atividade 5 */ #include <iostream> #include <stdio.h> #include <cctype> #include <ctype.h> #include <cstring> // pega o maior vetor com caracteres em uma matriz int getMaior(char **a, const int &n) { int ret = 0; for (int i = 0; i < n; i++) if (ret < strlen(a[i])) ret = strlen(a[i]); return ret; // retorna o maior tamanho } // seta todos os caracteres minusculo void setMinuscula(char **a, const int &n) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) a[i][j] = tolower(a[i][j]); } void imprimeVetor(int *c, int n) { for (int i = 0; i < n; i++) std::cout << c[i] << ' '; std::cout << '\n'; } void countingSort(char **a, char **b, int n, int k, int pos) { int c[k]; for (int i = 0; i < k; i++) c[i] = 0; int p0 = 'a' - 1; // p0 posicao inicial no alfabeto for (int j = 0; j < n; j++) if (a[j][pos] == '\0') c[0] += 1; else c[a[j][pos] - p0] += 1; for (int i = 1; i < k; i++) c[i] += c[i - 1]; imprimeVetor(c, 27); // copia vetor na posicao j para a nova posicao ordenada for (int j = n - 1; j >= 0; j--) { if (a[j][pos] == '\0') { c[0]--; // vai antes da copia pois ha diferenca nos indices strncpy(b[c[0]], a[j], 15); } else { c[a[j][pos] - p0]--; // vai antes da copia pois ha diferenca nos indices strncpy(b[c[a[j][pos] - p0]], a[j], 15); } } for (int i = 0; i < n; i++) strncpy(a[i], b[i], 15); } void radixSort(char **a, int n, int d) { char **b = new char*[n]; for (int i = 0; i < n; i++) b[i] = new char[15]; for (int i = d - 1; i >= 0; i--){ countingSort(a, b, n, 27, i); // copia os valores ordenados da matriz auxiliar para a matriz 'a' } for (int i = 0; i < n; i++) delete[] b[i]; delete[] b; } int main() { int n, p, m; std::cin >> n; std::cin.ignore(); // aloca matriz de caracteres char **a = new char*[n]; for (int i = 0; i < n; i++) a[i] = new char[15]; for (int i = 0; i < n; i++) scanf("%s", a[i]); std::cin >> p >> m; int maior = getMaior(a, n); radixSort(a, n, maior); for (int i = p - 1; m > 0; i++, m--) std::cout << a[i] << '\n'; // desaloca matriz de caracteres for (int i = 0; i < n; i++) delete[] a[i]; delete[] a; return 0; }
[ "gaspar_jr@outlook.com" ]
gaspar_jr@outlook.com
5ea977bbd227a39b57ae5c83be23bfb29d5568e1
8f505ac543714ce9383a15e12bd6c909f3c3b48b
/双目视觉测定三维坐标/双目视觉测定三维坐标Dlg.cpp
101ae7922f191f1a5a9206303a2c6a6181cbd968
[]
no_license
chenyutcmn/StereoVision-get-3dPoint
1cf255dad432f9bf0543ea3c8912af39a06da883
d3b146b2928c1fd3b98010f534355da94643ba37
refs/heads/master
2021-09-03T07:37:52.011739
2018-01-07T05:13:54
2018-01-07T05:13:54
null
0
0
null
null
null
null
GB18030
C++
false
false
20,780
cpp
// 双目视觉测定三维坐标Dlg.cpp : 实现文件 // #include "stdafx.h" #include "双目视觉测定三维坐标.h" #include "双目视觉测定三维坐标Dlg.h" #include "afxdialogex.h" #include <iostream> #include <fstream> #include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/calib3d/calib3d.hpp" using namespace cv; using namespace std; #ifdef _DEBUG #define new DEBUG_NEW #endif VideoCapture cap1(2); VideoCapture cap2(1); Mat frame[2]; CString strText = _T(""); // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 void MatToCImage(Mat &mat, CImage &cImage); string DoubleToString(double d); class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // C双目视觉测定三维坐标Dlg 对话框 C双目视觉测定三维坐标Dlg::C双目视觉测定三维坐标Dlg(CWnd* pParent /*=NULL*/) : CDialogEx(IDD_MY_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void C双目视觉测定三维坐标Dlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(C双目视觉测定三维坐标Dlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(btnInit, &C双目视觉测定三维坐标Dlg::OnBnClickedbtninit) ON_WM_TIMER() ON_BN_CLICKED(btnGet3D, &C双目视觉测定三维坐标Dlg::OnBnClickedbtnget3d) ON_BN_CLICKED(btnShowMats, &C双目视觉测定三维坐标Dlg::OnBnClickedbtnshowmats) END_MESSAGE_MAP() // C双目视觉测定三维坐标Dlg 消息处理程序 BOOL C双目视觉测定三维坐标Dlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 cap1.set(CV_CAP_PROP_FRAME_WIDTH, 640); cap1.set(CV_CAP_PROP_FRAME_HEIGHT, 480); cap2.set(CV_CAP_PROP_FRAME_WIDTH, 640); cap2.set(CV_CAP_PROP_FRAME_HEIGHT, 480); //模拟点击初始化按钮 PostMessage(WM_COMMAND, MAKEWPARAM(btnInit, BN_CLICKED), NULL); return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void C双目视觉测定三维坐标Dlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void C双目视觉测定三维坐标Dlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR C双目视觉测定三维坐标Dlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } //初始化按钮 void C双目视觉测定三维坐标Dlg::OnBnClickedbtninit() { // TODO: 在此添加控件通知处理程序代码 Mat frame[2]; CImage myImage[2]; frame[0].setTo(0); frame[1].setTo(0); if (cap1.isOpened() && cap2.isOpened()) { cap1 >> frame[0]; cap2 >> frame[1]; } else { AfxMessageBox(_T("打开摄像头失败")); } MatToCImage(frame[0], myImage[0]); MatToCImage(frame[1], myImage[1]); CRect rect; CWnd *pWnd = GetDlgItem(picRight); CDC *pDC = pWnd->GetDC(); pWnd->GetClientRect(&rect); pDC->SetStretchBltMode(STRETCH_HALFTONE); myImage[0].Draw(pDC->m_hDC, rect); ReleaseDC(pDC); myImage[0].Destroy(); CRect rect1; CWnd *pWnd1 = GetDlgItem(picLeft); CDC *pDC1 = pWnd1->GetDC(); pWnd1->GetClientRect(&rect1); pDC1->SetStretchBltMode(STRETCH_HALFTONE); myImage[1].Draw(pDC1->m_hDC, rect1); ReleaseDC(pDC1); myImage[1].Destroy(); SetTimer(1, 10, NULL); } //Mat转Cimage用于在pic控件上显示 void MatToCImage(Mat &mat, CImage &cImage) { //create new CImage int width = mat.cols; int height = mat.rows; int channels = mat.channels(); //cout << channels << endl; cImage.Destroy(); //clear cImage.Create(width, height, //positive: left-bottom-up or negative: left-top-down 8 * channels); //numbers of bits per pixel //copy values uchar* ps; uchar* pimg = (uchar*)cImage.GetBits(); //A pointer to the bitmap buffer //The pitch is the distance, in bytes. represent the beginning of // one bitmap line and the beginning of the next bitmap line int step = cImage.GetPitch(); for (int i = 0; i < height; ++i) { ps = (mat.ptr<uchar>(i)); for (int j = 0; j < width; ++j) { if (channels == 1) //gray { *(pimg + i*step + j) = ps[j]; } else if (channels == 3) //color { for (int k = 0; k < 3; ++k) { *(pimg + i*step + j * 3 + k) = ps[j * 3 + k]; } } } } } //显示摄像头图像的定时器 void C双目视觉测定三维坐标Dlg::OnTimer(UINT_PTR nIDEvent) { // TODO: 在此添加消息处理程序代码和/或调用默认值 CImage myImage[2]; frame[0].setTo(0); frame[1].setTo(0); if (cap1.isOpened() && cap2.isOpened()) { cap1 >> frame[0]; cap2 >> frame[1]; } else { AfxMessageBox(_T("打开摄像头失败")); } MatToCImage(frame[0], myImage[0]); MatToCImage(frame[1], myImage[1]); CRect rect; CWnd *pWnd = GetDlgItem(picRight); CDC *pDC = pWnd->GetDC(); pWnd->GetClientRect(&rect); pDC->SetStretchBltMode(STRETCH_HALFTONE); myImage[0].Draw(pDC->m_hDC, rect); ReleaseDC(pDC); myImage[0].Destroy(); CRect rect1; CWnd *pWnd1 = GetDlgItem(picLeft); CDC *pDC1 = pWnd1->GetDC(); pWnd1->GetClientRect(&rect1); pDC1->SetStretchBltMode(STRETCH_HALFTONE); myImage[1].Draw(pDC1->m_hDC, rect1); ReleaseDC(pDC1); myImage[1].Destroy(); CDialogEx::OnTimer(nIDEvent); } //求取目标点坐标 void C双目视觉测定三维坐标Dlg::OnBnClickedbtnget3d() { // TODO: 在此添加控件通知处理程序代码 strText = _T(""); FileStorage fsRamp("rmap.yml", FileStorage::READ); Mat rmap[2][2]; fsRamp["ramp00"] >> rmap[0][0]; fsRamp["ramp01"] >> rmap[0][1]; fsRamp["ramp10"] >> rmap[1][0]; fsRamp["ramp11"] >> rmap[1][1]; fsRamp.release(); Mat frameR = frame[0]; Mat frameL = frame[1]; if (frameR.cols!=0 && frameL.cols != 0) { imshow("right", frame[0]); imshow("left", frame[1]); //打印信息 strText += _T("获取图像成功\r\n"); GetDlgItem(showSomething)->SetWindowText(strText); } else { AfxMessageBox(_T("未获取到图像!")); return; } Mat copyR = frameR.clone(); Mat copyL = frameL.clone(); Mat newR = frameR.clone(); Mat newL = frameL.clone(); remap(copyR, newR, rmap[0][0], rmap[0][1], INTER_LINEAR); remap(copyL, newL, rmap[1][0], rmap[1][1], INTER_LINEAR); //打印信息 GetDlgItem(showSomething)->GetWindowText(strText); strText += _T("图像矫正完成\r\n"); GetDlgItem(showSomething)->SetWindowText(strText); Mat newRGry, newLGry; cvtColor(newR, newRGry, CV_RGB2GRAY); cvtColor(newL, newLGry, CV_RGB2GRAY); //erode(newRGry, rGryErode, NULL); int thresh = 200; Mat dst, dst_norm; Mat dst_norm_scaled[2]; dst = Mat::zeros(newRGry.size(), CV_32FC1); vector<Point2f> corners[2]; vector<vector<Point2f>> corCircles1; vector<vector<Point2f>> corCircles2; vector<Point2f> pointCircle[2]; int count; int test; //打印信息 GetDlgItem(showSomething)->GetWindowText(strText); strText += _T("开始获取角点\r\n"); GetDlgItem(showSomething)->SetWindowText(strText); //右图像获取目标点 cornerHarris(newRGry, dst, 7, 5, 0.04, BORDER_DEFAULT); normalize(dst, dst_norm, 0, 255, NORM_MINMAX, CV_32FC1, Mat()); convertScaleAbs(dst_norm, dst_norm_scaled[0]); test = 0; for (int j = 0; j < dst_norm.rows; j++) { for (int i = 0; i < dst_norm.cols; i++) { if ((int)dst_norm.at<float>(j, i) > thresh) { circle(dst_norm_scaled[0], Point(i, j), 5, CV_RGB(255, 0, 0), 1, 8, 0); if (corners[0].size() != 0) { Point2f lastPoint = corners[0].back(); test = (lastPoint.x - i)*(lastPoint.x - i) + (lastPoint.y - j)*(lastPoint.y - j); } if (test > 200 || corners[0].size() == 0) { Point2f corner(i, j); corners[0].push_back(corner); vector<Point2f> corCircle; int r = 10; for (int k = (0 - r); k < r + 1; k++) { Point2f point(i + k, j + r); corCircle.push_back(point); } for (int k = (r - 1); k >(0 - r - 1); k--) { Point2f point(i + r, j + k); corCircle.push_back(point); } for (int k = (r - 1); k > (0 - r - 1); k--) { Point2f point(i + k, j - r); corCircle.push_back(point); } for (int k = (0 - r + 1); k < r; k++) { Point2f point(i - r, j + k); corCircle.push_back(point); } corCircles1.push_back(corCircle); } } } } copyR = newRGry.clone(); for (int i = 0; i < copyR.rows; i++) { for (int j = 0; j < copyR.cols; j++) { int test1 = (int)copyR.at<uchar>(i, j); if (test1 < 125) { copyR.at<uchar>(i, j) = 0; } else { copyR.at<uchar>(i, j) = 255; } } } for (int i = 0; i < corCircles1.size(); i++) { count = 0; for (int j = 0; j < corCircles1[i].size() - 1; j++) { int test1 = (int)copyR.at<uchar>(corCircles1[i][j].y, corCircles1[i][j].x); int test2 = (int)copyR.at<uchar>(corCircles1[i][j + 1].y, corCircles1[i][j + 1].x); if (abs(test1 - test2)>150) { count++; } } cout << "右图像第" << i << "角点超过200个数为:" << count << endl; if (count == 4) { Point2f point(corCircles1[i][0].x + 10, corCircles1[i][0].y - 10); pointCircle[0].push_back(point); } count = 0; } //左图像获取目标点 cornerHarris(newLGry, dst, 7, 5, 0.04, BORDER_DEFAULT); normalize(dst, dst_norm, 0, 255, NORM_MINMAX, CV_32FC1, Mat()); convertScaleAbs(dst_norm, dst_norm_scaled[1]); test = 0; for (int j = 0; j < dst_norm.rows; j++) { for (int i = 0; i < dst_norm.cols; i++) { if ((int)dst_norm.at<float>(j, i) > thresh) { circle(dst_norm_scaled[1], Point(i, j), 5, CV_RGB(255, 0, 0), 1, 8, 0); if (corners[1].size() != 0) { Point2f lastPoint = corners[1].back(); test = (lastPoint.x - i)*(lastPoint.x - i) + (lastPoint.y - j)*(lastPoint.y - j); } if (test > 200 || corners[1].size() == 0) { Point2f corner(i, j); corners[1].push_back(corner); vector<Point2f> corCircle; int r = 10; for (int k = (0 - r); k < r + 1; k++) { Point2f point(i + k, j + r); corCircle.push_back(point); } for (int k = (r - 1); k >(0 - r - 1); k--) { Point2f point(i + r, j + k); corCircle.push_back(point); } for (int k = (r - 1); k > (0 - r - 1); k--) { Point2f point(i + k, j - r); corCircle.push_back(point); } for (int k = (0 - r + 1); k < r; k++) { Point2f point(i - r, j + k); corCircle.push_back(point); } //cout << corCircle; corCircles2.push_back(corCircle); } } } } copyL = newLGry.clone(); for (int i = 0; i < copyL.rows; i++) { for (int j = 0; j < copyL.cols; j++) { int test1 = (int)copyL.at<uchar>(i, j); if (test1 < 125) { copyL.at<uchar>(i, j) = 0; } else { copyL.at<uchar>(i, j) = 255; } } } Mat element = getStructuringElement(0, Size(3, 3), Point(0, 0)); erode(copyL, copyL, element); for (int i = 0; i < corCircles2.size(); i++) { count = 0; for (int j = 0; j < corCircles2[i].size() - 1; j++) { int test1 = (int)copyL.at<uchar>(corCircles2[i][j].y, corCircles2[i][j].x); int test2 = (int)copyL.at<uchar>(corCircles2[i][j + 1].y, corCircles2[i][j + 1].x); if (abs(test1 - test2)>150) { count++; } } cout << "左图像第" << i << "角点超过200个数为:" << count << endl; if (count == 4) { Point2f point(corCircles2[i][0].x + 10, corCircles2[i][0].y - 10); pointCircle[1].push_back(point); } count = 0; } if (pointCircle[0].size() != 1 && pointCircle[1].size() != 1) { AfxMessageBox(_T("提取目标角点失败!")); return; } else { //打印信息 GetDlgItem(showSomething)->GetWindowText(strText); strText += _T("目标角点提取成功\r\n"); GetDlgItem(showSomething)->SetWindowText(strText); } //打印信息 GetDlgItem(showSomething)->GetWindowText(strText); strText += _T("开始计算目标点坐标\r\n"); GetDlgItem(showSomething)->SetWindowText(strText); FileStorage fsMat("intrinsics.yml", FileStorage::READ); Mat p1, p2; fsMat["P1"] >> p1; fsMat["P2"] >> p2; fsMat.release(); //cout << p1 << endl << p2 << endl; double w = 146.0 / 640.0; double h = 110.0 / 480.0; Mat pointRight = Mat(2, 1, 6); Mat pointLeft = Mat(2, 1, 6); pointRight.at<double>(0, 0) = (double)pointCircle[0][0].y * h; pointRight.at<double>(1, 0) = (double)pointCircle[0][0].x * w; pointLeft.at<double>(0, 0) = (double)pointCircle[1][0].y * h; pointLeft.at<double>(1, 0) = (double)pointCircle[1][0].x * w; Mat MA = Mat(4, 3, 6); Mat MB = Mat(4, 1, 6); //CvMat *MA = cvCreateMat(4, 3, 6); //CvMat *MB = cvCreateMat(4, 1, 6); //cout << p1.channels() << endl << pointLeft.channels() << endl << p1.type() << endl << pointLeft.type(); //cout<<p2.at<double>(3, 1)*pointLeft.at<double>(1, 1) - p2.at<double>(1, 1); //初始化A double A11 = p2.at<double>(2, 0)*pointLeft.at<double>(0, 0) - p2.at<double>(0, 0); double A12 = p2.at<double>(2, 1)*pointLeft.at<double>(0, 0) - p2.at<double>(0, 1); double A13 = p2.at<double>(2, 2)*pointLeft.at<double>(0, 0) - p2.at<double>(0, 2); double A21 = p2.at<double>(2, 0)*pointLeft.at<double>(1, 0) - p2.at<double>(1, 0); double A22 = p2.at<double>(2, 1)*pointLeft.at<double>(1, 0) - p2.at<double>(1, 1); double A23 = p2.at<double>(2, 2)*pointLeft.at<double>(1, 0) - p2.at<double>(1, 2); double A31 = p1.at<double>(2, 0)*pointRight.at<double>(0, 0) - p1.at<double>(0, 0); double A32 = p1.at<double>(2, 1)*pointRight.at<double>(0, 0) - p1.at<double>(0, 1); double A33 = p1.at<double>(2, 2)*pointRight.at<double>(0, 0) - p1.at<double>(0, 2); double A41 = p1.at<double>(2, 0)*pointRight.at<double>(1, 0) - p1.at<double>(1, 0); double A42 = p1.at<double>(2, 1)*pointRight.at<double>(1, 0) - p1.at<double>(1, 1); double A43 = p1.at<double>(2, 2)*pointRight.at<double>(1, 0) - p1.at<double>(1, 2); double arrayA[12] = { A11, A12, A13, A21, A22, A23, A31, A32, A33, A41, A42, A43 }; for (int i = 0; i < 4; i++) { for (int j = 0; j < 3; j++) { MA.at<double>(i, j) = arrayA[i * 3 + j]; } } //cvSetData(MA, arrayA, CV_AUTOSTEP); //初始化b double b11 = p2.at<double>(0, 3) - p2.at<double>(2, 3)*pointLeft.at<double>(0, 0); double b21 = p2.at<double>(1, 3) - p2.at<double>(2, 3)*pointLeft.at<double>(1, 0); double b31 = p1.at<double>(0, 3) - p1.at<double>(2, 3)*pointRight.at<double>(0, 0); double b41 = p1.at<double>(1, 3) - p1.at<double>(2, 3)*pointRight.at<double>(1, 0); double arrayb[4] = { b11,b21,b31,b41 }; //cvSetData(MB, arrayb, CV_AUTOSTEP); for (int j = 0; j < 4; j++) { MB.at<double>(j, 0) = arrayb[j]; } Mat MAT; MA.copyTo(MAT); MAT = MAT.t(); Mat MATXA = MAT*MA; MATXA = MATXA.inv(); Mat MATXAA = MATXA*MAT; Mat res = MATXAA*MB; ofstream fout("calibration_result.txt"); fout << "一号相机内参数矩阵:" << endl; fout << res << endl; //打印信息 GetDlgItem(showSomething)->GetWindowText(strText); strText += _T("坐标计算成功\r\n"); GetDlgItem(showSomething)->SetWindowText(strText); string mat00 = DoubleToString(res.at<double>(0, 0)); string mat10 = DoubleToString(res.at<double>(1, 0)); string mat20 = DoubleToString(res.at<double>(2, 0)); //打印信息 GetDlgItem(showSomething)->GetWindowText(strText); strText += mat00.c_str(); strText += _T("\r\n"); strText += mat10.c_str(); strText += _T("\r\n"); strText += mat20.c_str(); strText += _T("\r\n"); GetDlgItem(showSomething)->SetWindowText(strText); } void C双目视觉测定三维坐标Dlg::OnBnClickedbtnshowmats() { // TODO: 在此添加控件通知处理程序代码 strText = _T(""); GetDlgItem(showSomething)->SetWindowText(strText); CString strText = _T("右摄像头内参矩阵\r\n"); FileStorage fsMat("intrinsics.yml", FileStorage::READ); if (!fsMat.isOpened()) { CWnd::MessageBox(_T("打开文件失败!"), _T("error"), MB_OK); } Mat intrinsic_matrix[2], distortion_coeffs[2],R,T,P1,P2; fsMat["C0"] >> intrinsic_matrix[0]; fsMat["D0"] >> distortion_coeffs[0]; fsMat["C1"] >> intrinsic_matrix[1]; fsMat["D1"] >> distortion_coeffs[1]; fsMat["R"] >> R; fsMat["T"] >> T; fsMat["P1"] >> P1; fsMat["P2"] >> P2; fsMat.release(); int nRows = intrinsic_matrix[0].rows; int nCols = intrinsic_matrix[0].cols; int i, j; double* p; for (i = 0; i < nRows; ++i) { p = intrinsic_matrix[0].ptr<double>(i); for (j = 0; j < nCols; j += 1)// { string ss = DoubleToString(p[j]); strText += ss.c_str(); strText += _T("\r\t\r\t"); } strText += _T("\r\n"); } strText += _T("右摄像头畸变矩阵\r\n"); nRows = distortion_coeffs[0].rows; nCols = distortion_coeffs[0].cols; for (i = 0; i < nRows; ++i) { p = distortion_coeffs[0].ptr<double>(i); for (j = 0; j < nCols; j += 1)// { string ss = DoubleToString(p[j]); strText += ss.c_str(); strText += _T("\r\t\r\t"); } strText += _T("\r\n"); } nRows = intrinsic_matrix[1].rows; nCols = intrinsic_matrix[1].cols; strText += _T("左摄像头内参矩阵\r\n"); for (i = 0; i < nRows; ++i) { p = intrinsic_matrix[1].ptr<double>(i); for (j = 0; j < nCols; j += 1)// { string ss = DoubleToString(p[j]); strText += ss.c_str(); strText += _T("\r\t\r\t"); } strText += _T("\r\n"); } strText += _T("左摄像头畸变矩阵\r\n"); nRows = distortion_coeffs[1].rows; nCols = distortion_coeffs[1].cols; for (i = 0; i < nRows; ++i) { p = distortion_coeffs[1].ptr<double>(i); for (j = 0; j < nCols; j += 1)// { string ss = DoubleToString(p[j]); strText += ss.c_str(); strText += _T("\r\t"); } strText += _T("\r\n"); } //系统旋转矩阵 nRows = R.rows; nCols = R.cols; strText += _T("系统旋转矩阵\r\n"); for (i = 0; i < nRows; ++i) { p = R.ptr<double>(i); for (j = 0; j < nCols; j += 1)// { string ss = DoubleToString(p[j]); strText += ss.c_str(); strText += _T("\r\t\r\t"); } strText += _T("\r\n"); } strText += _T("系统平移向量\r\n"); nRows = T.rows; nCols = T.cols; for (i = 0; i < nRows; ++i) { p = T.ptr<double>(i); for (j = 0; j < nCols; j += 1)// { string ss = DoubleToString(p[j]); strText += ss.c_str(); strText += _T("\r\t"); } strText += _T("\r\n"); } nRows = P1.rows; nCols = P1.cols; strText += _T("右摄像机投影矩阵\r\n"); for (i = 0; i < nRows; ++i) { p = P1.ptr<double>(i); for (j = 0; j < nCols; j += 1)// { string ss = DoubleToString(p[j]); strText += ss.c_str(); strText += _T("\r\t\r\t"); } strText += _T("\r\n"); } strText += _T("左摄像机投影矩阵\r\n"); nRows = P2.rows; nCols = P2.cols; for (i = 0; i < nRows; ++i) { p = P2.ptr<double>(i); for (j = 0; j < nCols; j += 1)// { string ss = DoubleToString(p[j]); strText += ss.c_str(); strText += _T("\r\t"); } strText += _T("\r\n"); } GetDlgItem(showSomething)->SetWindowText(strText); } string DoubleToString(double d) { //Need #include <sstream> string str; stringstream ss; ss << d; ss >> str; return str; }
[ "419560069@qq.com" ]
419560069@qq.com
f10426cf82660e07ba94c448b3e257559e58986f
62408a02b44f2fd20c6d54e1f5def0184e69194c
/Kattis/parking2/12729296_AC_0ms_0kB.cpp
5d89710b6114972ef9a31c919cca971a83d8d686
[]
no_license
benedicka/Competitive-Programming
24eb90b8150aead5c13287b62d9dc860c4b9232e
a94ccfc2d726e239981d598e98d1aa538691fa47
refs/heads/main
2023-03-22T10:14:34.889913
2021-03-16T05:33:43
2021-03-16T05:33:43
348,212,250
0
0
null
null
null
null
UTF-8
C++
false
false
324
cpp
#include<stdio.h> #include<algorithm> using namespace std; int main() { int t,b; int n,a[20]; scanf("%d",&t); while (t--) { scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d",&a[i]); } sort(a,a+n); b=0; for(int i=n-1;i>0;i--) { b=b+a[i]-a[i-1]; } printf("%d\n",2*b); } return 0; }
[ "43498540+benedicka@users.noreply.github.com" ]
43498540+benedicka@users.noreply.github.com
eb98467e348230dc9ea88af34a1b8fba7f143d74
1d59d3947408c825666281e19941e18ecdc4c9cf
/c++/학교 수업 과제/Sources_7장16장제외/chap10/time.cpp
6b5f9d864b94166ae4162ff5eaf9df60473287b0
[]
no_license
dbwls89876/Ru
ac23a0f6a3e146211ec1590078d9b37450b1aafa
2594998049a8c1a9f471387c688bc3f0f429fba4
refs/heads/master
2023-01-12T07:09:44.478949
2023-01-12T01:05:46
2023-01-12T01:05:46
220,790,128
0
0
null
null
null
null
UHC
C++
false
false
544
cpp
#include <iostream> using namespace std; class Time { int hour, min, sec; public: Time(int h=0, int m=0, int s=0) : hour(h), min(m), sec(s) { } bool operator== (Time &t2) { return (hour == t2.hour && min == t2.min && sec == t2.sec); } bool operator!= (Time &t2) { return !(*this == t2); } }; int main() { Time t1(1, 2, 3), t2(1, 2, 3); // 참과 거짓을 1, 0이 아니라 true, false로 출력하도록 설정한다. cout.setf(cout.boolalpha); cout << (t1 == t2) << endl; cout << (t1 != t2) << endl; return 0; }
[ "dbwls89876@naver.com" ]
dbwls89876@naver.com
54bf3c4236d99c9d370a349a00d98fd49e5afa37
2296205a0029db45bef627df83f91d667cef83e9
/High Score.h
5e98627ecbdbea2528062f8688f27a0869cce0f6
[]
no_license
kwmoore81/Classes
fc8d4e4bf04c6842a8e55aa70361e238afca3449
2876c355c6da1ff1603bcae716b5dd7e784e7c01
refs/heads/master
2021-01-10T08:01:46.590261
2015-09-30T00:47:37
2015-09-30T00:47:37
43,335,652
0
0
null
null
null
null
UTF-8
C++
false
false
292
h
#pragma once class HighScores { private: int highScores[3]{ 0 , 0 , 0 }; public: void setHighScore1(int highScore[1]); int getHighScore1(); void setHighScore2(int highScore[2]); int getHighScore2(); void setHighScore3(int highScore[3]); int getHighScore3(); int highScoreAvg(); };
[ "kwmoore81@gmail.com" ]
kwmoore81@gmail.com
6927a53df0f4ceac0afe7dd65addf04d7729b3ad
55c1a0ce1973b681b525f9181a1cb1bf8eac0c39
/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
b1b3fe76b9b6a546e7ece55a2c1a4821f0d771bb
[ "NCSA" ]
permissive
FISC-Project/FISC-LLVM
e8fea8e55c4a1c7fdc5ffc3d09ddae448e9ffd6b
a2a1c8326084c025b3d1d2d245e47f9ce5ec27ff
refs/heads/master
2022-02-24T16:01:53.877327
2019-08-22T21:40:15
2019-08-22T21:40:15
88,315,134
1
2
null
null
null
null
UTF-8
C++
false
false
468,008
cpp
//===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the PPCISelLowering class. // //===----------------------------------------------------------------------===// #include "PPCISelLowering.h" #include "MCTargetDesc/PPCPredicates.h" #include "PPCCallingConv.h" #include "PPCMachineFunctionInfo.h" #include "PPCPerfectShuffle.h" #include "PPCTargetMachine.h" #include "PPCTargetObjectFile.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/Triple.h" #include "llvm/CodeGen/CallingConvLower.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineLoopInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/SelectionDAG.h" #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" #include "llvm/IR/CallingConv.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/Intrinsics.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc", cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden); static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref", cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden); static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned", cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden); // FIXME: Remove this once the bug has been fixed! extern cl::opt<bool> ANDIGlueBug; PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM, const PPCSubtarget &STI) : TargetLowering(TM), Subtarget(STI) { // Use _setjmp/_longjmp instead of setjmp/longjmp. setUseUnderscoreSetJmp(true); setUseUnderscoreLongJmp(true); // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all // arguments are at least 4/8 bytes aligned. bool isPPC64 = Subtarget.isPPC64(); setMinStackArgumentAlignment(isPPC64 ? 8:4); // Set up the register classes. addRegisterClass(MVT::i32, &PPC::GPRCRegClass); if (!Subtarget.useSoftFloat()) { addRegisterClass(MVT::f32, &PPC::F4RCRegClass); addRegisterClass(MVT::f64, &PPC::F8RCRegClass); } // PowerPC has an i16 but no i8 (or i1) SEXTLOAD for (MVT VT : MVT::integer_valuetypes()) { setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand); } setTruncStoreAction(MVT::f64, MVT::f32, Expand); // PowerPC has pre-inc load and store's. setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal); setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal); setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal); setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal); setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal); setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal); setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal); setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal); setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal); setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal); setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal); setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal); setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal); setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal); if (Subtarget.useCRBits()) { setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); if (isPPC64 || Subtarget.hasFPCVT()) { setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote); AddPromotedToType (ISD::SINT_TO_FP, MVT::i1, isPPC64 ? MVT::i64 : MVT::i32); setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote); AddPromotedToType(ISD::UINT_TO_FP, MVT::i1, isPPC64 ? MVT::i64 : MVT::i32); } else { setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom); setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom); } // PowerPC does not support direct load / store of condition registers setOperationAction(ISD::LOAD, MVT::i1, Custom); setOperationAction(ISD::STORE, MVT::i1, Custom); // FIXME: Remove this once the ANDI glue bug is fixed: if (ANDIGlueBug) setOperationAction(ISD::TRUNCATE, MVT::i1, Custom); for (MVT VT : MVT::integer_valuetypes()) { setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote); setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote); setTruncStoreAction(VT, MVT::i1, Expand); } addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass); } // This is used in the ppcf128->int sequence. Note it has different semantics // from FP_ROUND: that rounds to nearest, this rounds to zero. setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom); // We do not currently implement these libm ops for PowerPC. setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand); setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand); setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand); setOperationAction(ISD::FRINT, MVT::ppcf128, Expand); setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand); setOperationAction(ISD::FREM, MVT::ppcf128, Expand); // PowerPC has no SREM/UREM instructions setOperationAction(ISD::SREM, MVT::i32, Expand); setOperationAction(ISD::UREM, MVT::i32, Expand); setOperationAction(ISD::SREM, MVT::i64, Expand); setOperationAction(ISD::UREM, MVT::i64, Expand); // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM. setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand); setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand); setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); setOperationAction(ISD::UDIVREM, MVT::i32, Expand); setOperationAction(ISD::SDIVREM, MVT::i32, Expand); setOperationAction(ISD::UDIVREM, MVT::i64, Expand); setOperationAction(ISD::SDIVREM, MVT::i64, Expand); // We don't support sin/cos/sqrt/fmod/pow setOperationAction(ISD::FSIN , MVT::f64, Expand); setOperationAction(ISD::FCOS , MVT::f64, Expand); setOperationAction(ISD::FSINCOS, MVT::f64, Expand); setOperationAction(ISD::FREM , MVT::f64, Expand); setOperationAction(ISD::FPOW , MVT::f64, Expand); setOperationAction(ISD::FMA , MVT::f64, Legal); setOperationAction(ISD::FSIN , MVT::f32, Expand); setOperationAction(ISD::FCOS , MVT::f32, Expand); setOperationAction(ISD::FSINCOS, MVT::f32, Expand); setOperationAction(ISD::FREM , MVT::f32, Expand); setOperationAction(ISD::FPOW , MVT::f32, Expand); setOperationAction(ISD::FMA , MVT::f32, Legal); setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); // If we're enabling GP optimizations, use hardware square root if (!Subtarget.hasFSQRT() && !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() && Subtarget.hasFRE())) setOperationAction(ISD::FSQRT, MVT::f64, Expand); if (!Subtarget.hasFSQRT() && !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() && Subtarget.hasFRES())) setOperationAction(ISD::FSQRT, MVT::f32, Expand); if (Subtarget.hasFCPSGN()) { setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal); setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal); } else { setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); } if (Subtarget.hasFPRND()) { setOperationAction(ISD::FFLOOR, MVT::f64, Legal); setOperationAction(ISD::FCEIL, MVT::f64, Legal); setOperationAction(ISD::FTRUNC, MVT::f64, Legal); setOperationAction(ISD::FROUND, MVT::f64, Legal); setOperationAction(ISD::FFLOOR, MVT::f32, Legal); setOperationAction(ISD::FCEIL, MVT::f32, Legal); setOperationAction(ISD::FTRUNC, MVT::f32, Legal); setOperationAction(ISD::FROUND, MVT::f32, Legal); } // PowerPC does not have BSWAP, CTPOP or CTTZ setOperationAction(ISD::BSWAP, MVT::i32 , Expand); setOperationAction(ISD::CTTZ , MVT::i32 , Expand); setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand); setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand); setOperationAction(ISD::BSWAP, MVT::i64 , Expand); setOperationAction(ISD::CTTZ , MVT::i64 , Expand); setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand); setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand); if (Subtarget.hasPOPCNTD()) { setOperationAction(ISD::CTPOP, MVT::i32 , Legal); setOperationAction(ISD::CTPOP, MVT::i64 , Legal); } else { setOperationAction(ISD::CTPOP, MVT::i32 , Expand); setOperationAction(ISD::CTPOP, MVT::i64 , Expand); } // PowerPC does not have ROTR setOperationAction(ISD::ROTR, MVT::i32 , Expand); setOperationAction(ISD::ROTR, MVT::i64 , Expand); if (!Subtarget.useCRBits()) { // PowerPC does not have Select setOperationAction(ISD::SELECT, MVT::i32, Expand); setOperationAction(ISD::SELECT, MVT::i64, Expand); setOperationAction(ISD::SELECT, MVT::f32, Expand); setOperationAction(ISD::SELECT, MVT::f64, Expand); } // PowerPC wants to turn select_cc of FP into fsel when possible. setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); // PowerPC wants to optimize integer setcc a bit if (!Subtarget.useCRBits()) setOperationAction(ISD::SETCC, MVT::i32, Custom); // PowerPC does not have BRCOND which requires SetCC if (!Subtarget.useCRBits()) setOperationAction(ISD::BRCOND, MVT::Other, Expand); setOperationAction(ISD::BR_JT, MVT::Other, Expand); // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores. setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); // PowerPC does not have [U|S]INT_TO_FP setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand); setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand); if (Subtarget.hasDirectMove()) { setOperationAction(ISD::BITCAST, MVT::f32, Legal); setOperationAction(ISD::BITCAST, MVT::i32, Legal); setOperationAction(ISD::BITCAST, MVT::i64, Legal); setOperationAction(ISD::BITCAST, MVT::f64, Legal); } else { setOperationAction(ISD::BITCAST, MVT::f32, Expand); setOperationAction(ISD::BITCAST, MVT::i32, Expand); setOperationAction(ISD::BITCAST, MVT::i64, Expand); setOperationAction(ISD::BITCAST, MVT::f64, Expand); } // We cannot sextinreg(i1). Expand to shifts. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support // SjLj exception handling but a light-weight setjmp/longjmp replacement to // support continuation, user-level threading, and etc.. As a result, no // other SjLj exception interfaces are implemented and please don't build // your own exception handling based on them. // LLVM/Clang supports zero-cost DWARF exception handling. setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom); setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom); // We want to legalize GlobalAddress and ConstantPool nodes into the // appropriate instructions to materialize the address. setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom); setOperationAction(ISD::BlockAddress, MVT::i32, Custom); setOperationAction(ISD::ConstantPool, MVT::i32, Custom); setOperationAction(ISD::JumpTable, MVT::i32, Custom); setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); setOperationAction(ISD::BlockAddress, MVT::i64, Custom); setOperationAction(ISD::ConstantPool, MVT::i64, Custom); setOperationAction(ISD::JumpTable, MVT::i64, Custom); // TRAP is legal. setOperationAction(ISD::TRAP, MVT::Other, Legal); // TRAMPOLINE is custom lowered. setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom); setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom); // VASTART needs to be custom lowered to use the VarArgsFrameIndex setOperationAction(ISD::VASTART , MVT::Other, Custom); if (Subtarget.isSVR4ABI()) { if (isPPC64) { // VAARG always uses double-word chunks, so promote anything smaller. setOperationAction(ISD::VAARG, MVT::i1, Promote); AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64); setOperationAction(ISD::VAARG, MVT::i8, Promote); AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64); setOperationAction(ISD::VAARG, MVT::i16, Promote); AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64); setOperationAction(ISD::VAARG, MVT::i32, Promote); AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64); setOperationAction(ISD::VAARG, MVT::Other, Expand); } else { // VAARG is custom lowered with the 32-bit SVR4 ABI. setOperationAction(ISD::VAARG, MVT::Other, Custom); setOperationAction(ISD::VAARG, MVT::i64, Custom); } } else setOperationAction(ISD::VAARG, MVT::Other, Expand); if (Subtarget.isSVR4ABI() && !isPPC64) // VACOPY is custom lowered with the 32-bit SVR4 ABI. setOperationAction(ISD::VACOPY , MVT::Other, Custom); else setOperationAction(ISD::VACOPY , MVT::Other, Expand); // Use the default implementation. setOperationAction(ISD::VAEND , MVT::Other, Expand); setOperationAction(ISD::STACKSAVE , MVT::Other, Expand); setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom); setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom); setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom); setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom); setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom); // We want to custom lower some of our intrinsics. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); // To handle counter-based loop conditions. setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom); // Comparisons that require checking two conditions. setCondCodeAction(ISD::SETULT, MVT::f32, Expand); setCondCodeAction(ISD::SETULT, MVT::f64, Expand); setCondCodeAction(ISD::SETUGT, MVT::f32, Expand); setCondCodeAction(ISD::SETUGT, MVT::f64, Expand); setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand); setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand); setCondCodeAction(ISD::SETOGE, MVT::f32, Expand); setCondCodeAction(ISD::SETOGE, MVT::f64, Expand); setCondCodeAction(ISD::SETOLE, MVT::f32, Expand); setCondCodeAction(ISD::SETOLE, MVT::f64, Expand); setCondCodeAction(ISD::SETONE, MVT::f32, Expand); setCondCodeAction(ISD::SETONE, MVT::f64, Expand); if (Subtarget.has64BitSupport()) { // They also have instructions for converting between i64 and fp. setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand); setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand); // This is just the low 32 bits of a (signed) fp->i64 conversion. // We cannot do this with Promote because i64 is not a legal type. setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); if (Subtarget.hasLFIWAX() || Subtarget.isPPC64()) setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); } else { // PowerPC does not have FP_TO_UINT on 32-bit implementations. setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand); } // With the instructions enabled under FPCVT, we can do everything. if (Subtarget.hasFPCVT()) { if (Subtarget.has64BitSupport()) { setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); } setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); } if (Subtarget.use64BitRegs()) { // 64-bit PowerPC implementations can support i64 types directly addRegisterClass(MVT::i64, &PPC::G8RCRegClass); // BUILD_PAIR can't be handled natively, and should be expanded to shl/or setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); // 64-bit PowerPC wants to expand i128 shifts itself. setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); } else { // 32-bit PowerPC wants to expand i64 shifts itself. setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom); setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom); setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom); } if (Subtarget.hasAltivec()) { // First set operation action for all vector types to expand. Then we // will selectively turn on ones that can be effectively codegen'd. for (MVT VT : MVT::vector_valuetypes()) { // add/sub are legal for all supported vector VT's. setOperationAction(ISD::ADD, VT, Legal); setOperationAction(ISD::SUB, VT, Legal); // Vector instructions introduced in P8 if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) { setOperationAction(ISD::CTPOP, VT, Legal); setOperationAction(ISD::CTLZ, VT, Legal); } else { setOperationAction(ISD::CTPOP, VT, Expand); setOperationAction(ISD::CTLZ, VT, Expand); } // We promote all shuffles to v16i8. setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote); AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8); // We promote all non-typed operations to v4i32. setOperationAction(ISD::AND , VT, Promote); AddPromotedToType (ISD::AND , VT, MVT::v4i32); setOperationAction(ISD::OR , VT, Promote); AddPromotedToType (ISD::OR , VT, MVT::v4i32); setOperationAction(ISD::XOR , VT, Promote); AddPromotedToType (ISD::XOR , VT, MVT::v4i32); setOperationAction(ISD::LOAD , VT, Promote); AddPromotedToType (ISD::LOAD , VT, MVT::v4i32); setOperationAction(ISD::SELECT, VT, Promote); AddPromotedToType (ISD::SELECT, VT, MVT::v4i32); setOperationAction(ISD::SELECT_CC, VT, Promote); AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32); setOperationAction(ISD::STORE, VT, Promote); AddPromotedToType (ISD::STORE, VT, MVT::v4i32); // No other operations are legal. setOperationAction(ISD::MUL , VT, Expand); setOperationAction(ISD::SDIV, VT, Expand); setOperationAction(ISD::SREM, VT, Expand); setOperationAction(ISD::UDIV, VT, Expand); setOperationAction(ISD::UREM, VT, Expand); setOperationAction(ISD::FDIV, VT, Expand); setOperationAction(ISD::FREM, VT, Expand); setOperationAction(ISD::FNEG, VT, Expand); setOperationAction(ISD::FSQRT, VT, Expand); setOperationAction(ISD::FLOG, VT, Expand); setOperationAction(ISD::FLOG10, VT, Expand); setOperationAction(ISD::FLOG2, VT, Expand); setOperationAction(ISD::FEXP, VT, Expand); setOperationAction(ISD::FEXP2, VT, Expand); setOperationAction(ISD::FSIN, VT, Expand); setOperationAction(ISD::FCOS, VT, Expand); setOperationAction(ISD::FABS, VT, Expand); setOperationAction(ISD::FPOWI, VT, Expand); setOperationAction(ISD::FFLOOR, VT, Expand); setOperationAction(ISD::FCEIL, VT, Expand); setOperationAction(ISD::FTRUNC, VT, Expand); setOperationAction(ISD::FRINT, VT, Expand); setOperationAction(ISD::FNEARBYINT, VT, Expand); setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand); setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand); setOperationAction(ISD::BUILD_VECTOR, VT, Expand); setOperationAction(ISD::MULHU, VT, Expand); setOperationAction(ISD::MULHS, VT, Expand); setOperationAction(ISD::UMUL_LOHI, VT, Expand); setOperationAction(ISD::SMUL_LOHI, VT, Expand); setOperationAction(ISD::UDIVREM, VT, Expand); setOperationAction(ISD::SDIVREM, VT, Expand); setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand); setOperationAction(ISD::FPOW, VT, Expand); setOperationAction(ISD::BSWAP, VT, Expand); setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand); setOperationAction(ISD::CTTZ, VT, Expand); setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand); setOperationAction(ISD::VSELECT, VT, Expand); setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); setOperationAction(ISD::ROTL, VT, Expand); setOperationAction(ISD::ROTR, VT, Expand); for (MVT InnerVT : MVT::vector_valuetypes()) { setTruncStoreAction(VT, InnerVT, Expand); setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); } } // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle // with merges, splats, etc. setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom); setOperationAction(ISD::AND , MVT::v4i32, Legal); setOperationAction(ISD::OR , MVT::v4i32, Legal); setOperationAction(ISD::XOR , MVT::v4i32, Legal); setOperationAction(ISD::LOAD , MVT::v4i32, Legal); setOperationAction(ISD::SELECT, MVT::v4i32, Subtarget.useCRBits() ? Legal : Expand); setOperationAction(ISD::STORE , MVT::v4i32, Legal); setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal); setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal); setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal); setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal); setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal); addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass); addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass); addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass); addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass); setOperationAction(ISD::MUL, MVT::v4f32, Legal); setOperationAction(ISD::FMA, MVT::v4f32, Legal); if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) { setOperationAction(ISD::FDIV, MVT::v4f32, Legal); setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); } if (Subtarget.hasP8Altivec()) setOperationAction(ISD::MUL, MVT::v4i32, Legal); else setOperationAction(ISD::MUL, MVT::v4i32, Custom); setOperationAction(ISD::MUL, MVT::v8i16, Custom); setOperationAction(ISD::MUL, MVT::v16i8, Custom); setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom); setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom); setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom); setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom); setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom); setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); // Altivec does not contain unordered floating-point compare instructions setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand); setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand); setCondCodeAction(ISD::SETO, MVT::v4f32, Expand); setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand); if (Subtarget.hasVSX()) { setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal); setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); if (Subtarget.hasP8Vector()) { setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal); } if (Subtarget.hasDirectMove()) { setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal); setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal); setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal); setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal); setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal); setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal); setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal); setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal); } setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal); setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal); setOperationAction(ISD::FCEIL, MVT::v2f64, Legal); setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal); setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal); setOperationAction(ISD::FROUND, MVT::v2f64, Legal); setOperationAction(ISD::FROUND, MVT::v4f32, Legal); setOperationAction(ISD::MUL, MVT::v2f64, Legal); setOperationAction(ISD::FMA, MVT::v2f64, Legal); setOperationAction(ISD::FDIV, MVT::v2f64, Legal); setOperationAction(ISD::FSQRT, MVT::v2f64, Legal); setOperationAction(ISD::VSELECT, MVT::v16i8, Legal); setOperationAction(ISD::VSELECT, MVT::v8i16, Legal); setOperationAction(ISD::VSELECT, MVT::v4i32, Legal); setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); setOperationAction(ISD::VSELECT, MVT::v2f64, Legal); // Share the Altivec comparison restrictions. setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand); setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand); setCondCodeAction(ISD::SETO, MVT::v2f64, Expand); setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand); setOperationAction(ISD::LOAD, MVT::v2f64, Legal); setOperationAction(ISD::STORE, MVT::v2f64, Legal); setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal); if (Subtarget.hasP8Vector()) addRegisterClass(MVT::f32, &PPC::VSSRCRegClass); addRegisterClass(MVT::f64, &PPC::VSFRCRegClass); addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass); addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass); addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass); if (Subtarget.hasP8Altivec()) { setOperationAction(ISD::SHL, MVT::v2i64, Legal); setOperationAction(ISD::SRA, MVT::v2i64, Legal); setOperationAction(ISD::SRL, MVT::v2i64, Legal); setOperationAction(ISD::SETCC, MVT::v2i64, Legal); } else { setOperationAction(ISD::SHL, MVT::v2i64, Expand); setOperationAction(ISD::SRA, MVT::v2i64, Expand); setOperationAction(ISD::SRL, MVT::v2i64, Expand); setOperationAction(ISD::SETCC, MVT::v2i64, Custom); // VSX v2i64 only supports non-arithmetic operations. setOperationAction(ISD::ADD, MVT::v2i64, Expand); setOperationAction(ISD::SUB, MVT::v2i64, Expand); } setOperationAction(ISD::LOAD, MVT::v2i64, Promote); AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64); setOperationAction(ISD::STORE, MVT::v2i64, Promote); AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64); setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal); setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal); setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal); setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal); setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal); // Vector operation legalization checks the result type of // SIGN_EXTEND_INREG, overall legalization checks the inner type. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal); setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal); setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass); } if (Subtarget.hasP8Altivec()) { addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass); addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass); } } if (Subtarget.hasQPX()) { setOperationAction(ISD::FADD, MVT::v4f64, Legal); setOperationAction(ISD::FSUB, MVT::v4f64, Legal); setOperationAction(ISD::FMUL, MVT::v4f64, Legal); setOperationAction(ISD::FREM, MVT::v4f64, Expand); setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal); setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand); setOperationAction(ISD::LOAD , MVT::v4f64, Custom); setOperationAction(ISD::STORE , MVT::v4f64, Custom); setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom); setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom); if (!Subtarget.useCRBits()) setOperationAction(ISD::SELECT, MVT::v4f64, Expand); setOperationAction(ISD::VSELECT, MVT::v4f64, Legal); setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal); setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand); setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand); setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand); setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom); setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal); setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom); setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal); setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand); setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal); setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand); setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal); setOperationAction(ISD::FNEG , MVT::v4f64, Legal); setOperationAction(ISD::FABS , MVT::v4f64, Legal); setOperationAction(ISD::FSIN , MVT::v4f64, Expand); setOperationAction(ISD::FCOS , MVT::v4f64, Expand); setOperationAction(ISD::FPOWI , MVT::v4f64, Expand); setOperationAction(ISD::FPOW , MVT::v4f64, Expand); setOperationAction(ISD::FLOG , MVT::v4f64, Expand); setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand); setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand); setOperationAction(ISD::FEXP , MVT::v4f64, Expand); setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand); setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal); setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal); setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal); setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal); addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass); setOperationAction(ISD::FADD, MVT::v4f32, Legal); setOperationAction(ISD::FSUB, MVT::v4f32, Legal); setOperationAction(ISD::FMUL, MVT::v4f32, Legal); setOperationAction(ISD::FREM, MVT::v4f32, Expand); setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal); setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand); setOperationAction(ISD::LOAD , MVT::v4f32, Custom); setOperationAction(ISD::STORE , MVT::v4f32, Custom); if (!Subtarget.useCRBits()) setOperationAction(ISD::SELECT, MVT::v4f32, Expand); setOperationAction(ISD::VSELECT, MVT::v4f32, Legal); setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal); setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand); setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand); setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand); setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom); setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal); setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom); setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal); setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand); setOperationAction(ISD::FNEG , MVT::v4f32, Legal); setOperationAction(ISD::FABS , MVT::v4f32, Legal); setOperationAction(ISD::FSIN , MVT::v4f32, Expand); setOperationAction(ISD::FCOS , MVT::v4f32, Expand); setOperationAction(ISD::FPOWI , MVT::v4f32, Expand); setOperationAction(ISD::FPOW , MVT::v4f32, Expand); setOperationAction(ISD::FLOG , MVT::v4f32, Expand); setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand); setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand); setOperationAction(ISD::FEXP , MVT::v4f32, Expand); setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand); setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal); setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal); setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal); setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal); addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass); setOperationAction(ISD::AND , MVT::v4i1, Legal); setOperationAction(ISD::OR , MVT::v4i1, Legal); setOperationAction(ISD::XOR , MVT::v4i1, Legal); if (!Subtarget.useCRBits()) setOperationAction(ISD::SELECT, MVT::v4i1, Expand); setOperationAction(ISD::VSELECT, MVT::v4i1, Legal); setOperationAction(ISD::LOAD , MVT::v4i1, Custom); setOperationAction(ISD::STORE , MVT::v4i1, Custom); setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom); setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand); setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand); setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand); setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom); setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand); setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom); setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom); setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom); addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass); setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal); setOperationAction(ISD::FCEIL, MVT::v4f64, Legal); setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal); setOperationAction(ISD::FROUND, MVT::v4f64, Legal); setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal); setOperationAction(ISD::FCEIL, MVT::v4f32, Legal); setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal); setOperationAction(ISD::FROUND, MVT::v4f32, Legal); setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand); setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand); // These need to set FE_INEXACT, and so cannot be vectorized here. setOperationAction(ISD::FRINT, MVT::v4f64, Expand); setOperationAction(ISD::FRINT, MVT::v4f32, Expand); if (TM.Options.UnsafeFPMath) { setOperationAction(ISD::FDIV, MVT::v4f64, Legal); setOperationAction(ISD::FSQRT, MVT::v4f64, Legal); setOperationAction(ISD::FDIV, MVT::v4f32, Legal); setOperationAction(ISD::FSQRT, MVT::v4f32, Legal); } else { setOperationAction(ISD::FDIV, MVT::v4f64, Expand); setOperationAction(ISD::FSQRT, MVT::v4f64, Expand); setOperationAction(ISD::FDIV, MVT::v4f32, Expand); setOperationAction(ISD::FSQRT, MVT::v4f32, Expand); } } if (Subtarget.has64BitSupport()) setOperationAction(ISD::PREFETCH, MVT::Other, Legal); setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom); if (!isPPC64) { setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand); setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand); } setBooleanContents(ZeroOrOneBooleanContent); if (Subtarget.hasAltivec()) { // Altivec instructions set fields to all zeros or all ones. setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); } if (!isPPC64) { // These libcalls are not available in 32-bit. setLibcallName(RTLIB::SHL_I128, nullptr); setLibcallName(RTLIB::SRL_I128, nullptr); setLibcallName(RTLIB::SRA_I128, nullptr); } setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1); // We have target-specific dag combine patterns for the following nodes: setTargetDAGCombine(ISD::SINT_TO_FP); if (Subtarget.hasFPCVT()) setTargetDAGCombine(ISD::UINT_TO_FP); setTargetDAGCombine(ISD::LOAD); setTargetDAGCombine(ISD::STORE); setTargetDAGCombine(ISD::BR_CC); if (Subtarget.useCRBits()) setTargetDAGCombine(ISD::BRCOND); setTargetDAGCombine(ISD::BSWAP); setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); setTargetDAGCombine(ISD::INTRINSIC_VOID); setTargetDAGCombine(ISD::SIGN_EXTEND); setTargetDAGCombine(ISD::ZERO_EXTEND); setTargetDAGCombine(ISD::ANY_EXTEND); if (Subtarget.useCRBits()) { setTargetDAGCombine(ISD::TRUNCATE); setTargetDAGCombine(ISD::SETCC); setTargetDAGCombine(ISD::SELECT_CC); } // Use reciprocal estimates. if (TM.Options.UnsafeFPMath) { setTargetDAGCombine(ISD::FDIV); setTargetDAGCombine(ISD::FSQRT); } // Darwin long double math library functions have $LDBL128 appended. if (Subtarget.isDarwin()) { setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128"); setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128"); setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128"); setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128"); setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128"); setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128"); setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128"); setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128"); setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128"); setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128"); } // With 32 condition bits, we don't need to sink (and duplicate) compares // aggressively in CodeGenPrep. if (Subtarget.useCRBits()) { setHasMultipleConditionRegisters(); setJumpIsExpensive(); } setMinFunctionAlignment(2); if (Subtarget.isDarwin()) setPrefFunctionAlignment(4); switch (Subtarget.getDarwinDirective()) { default: break; case PPC::DIR_970: case PPC::DIR_A2: case PPC::DIR_E500mc: case PPC::DIR_E5500: case PPC::DIR_PWR4: case PPC::DIR_PWR5: case PPC::DIR_PWR5X: case PPC::DIR_PWR6: case PPC::DIR_PWR6X: case PPC::DIR_PWR7: case PPC::DIR_PWR8: setPrefFunctionAlignment(4); setPrefLoopAlignment(4); break; } setInsertFencesForAtomic(true); if (Subtarget.enableMachineScheduler()) setSchedulingPreference(Sched::Source); else setSchedulingPreference(Sched::Hybrid); computeRegisterProperties(STI.getRegisterInfo()); // The Freescale cores do better with aggressive inlining of memcpy and // friends. GCC uses same threshold of 128 bytes (= 32 word stores). if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc || Subtarget.getDarwinDirective() == PPC::DIR_E5500) { MaxStoresPerMemset = 32; MaxStoresPerMemsetOptSize = 16; MaxStoresPerMemcpy = 32; MaxStoresPerMemcpyOptSize = 8; MaxStoresPerMemmove = 32; MaxStoresPerMemmoveOptSize = 8; } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) { // The A2 also benefits from (very) aggressive inlining of memcpy and // friends. The overhead of a the function call, even when warm, can be // over one hundred cycles. MaxStoresPerMemset = 128; MaxStoresPerMemcpy = 128; MaxStoresPerMemmove = 128; } } /// getMaxByValAlign - Helper for getByValTypeAlignment to determine /// the desired ByVal argument alignment. static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign, unsigned MaxMaxAlign) { if (MaxAlign == MaxMaxAlign) return; if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256) MaxAlign = 32; else if (VTy->getBitWidth() >= 128 && MaxAlign < 16) MaxAlign = 16; } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { unsigned EltAlign = 0; getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign); if (EltAlign > MaxAlign) MaxAlign = EltAlign; } else if (StructType *STy = dyn_cast<StructType>(Ty)) { for (auto *EltTy : STy->elements()) { unsigned EltAlign = 0; getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign); if (EltAlign > MaxAlign) MaxAlign = EltAlign; if (MaxAlign == MaxMaxAlign) break; } } } /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate /// function arguments in the caller parameter area. unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty, const DataLayout &DL) const { // Darwin passes everything on 4 byte boundary. if (Subtarget.isDarwin()) return 4; // 16byte and wider vectors are passed on 16byte boundary. // The rest is 8 on PPC64 and 4 on PPC32 boundary. unsigned Align = Subtarget.isPPC64() ? 8 : 4; if (Subtarget.hasAltivec() || Subtarget.hasQPX()) getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16); return Align; } bool PPCTargetLowering::useSoftFloat() const { return Subtarget.useSoftFloat(); } const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const { switch ((PPCISD::NodeType)Opcode) { case PPCISD::FIRST_NUMBER: break; case PPCISD::FSEL: return "PPCISD::FSEL"; case PPCISD::FCFID: return "PPCISD::FCFID"; case PPCISD::FCFIDU: return "PPCISD::FCFIDU"; case PPCISD::FCFIDS: return "PPCISD::FCFIDS"; case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS"; case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ"; case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ"; case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ"; case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ"; case PPCISD::FRE: return "PPCISD::FRE"; case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE"; case PPCISD::STFIWX: return "PPCISD::STFIWX"; case PPCISD::VMADDFP: return "PPCISD::VMADDFP"; case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP"; case PPCISD::VPERM: return "PPCISD::VPERM"; case PPCISD::CMPB: return "PPCISD::CMPB"; case PPCISD::Hi: return "PPCISD::Hi"; case PPCISD::Lo: return "PPCISD::Lo"; case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY"; case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC"; case PPCISD::DYNAREAOFFSET: return "PPCISD::DYNAREAOFFSET"; case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg"; case PPCISD::SRL: return "PPCISD::SRL"; case PPCISD::SRA: return "PPCISD::SRA"; case PPCISD::SHL: return "PPCISD::SHL"; case PPCISD::SRA_ADDZE: return "PPCISD::SRA_ADDZE"; case PPCISD::CALL: return "PPCISD::CALL"; case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP"; case PPCISD::MTCTR: return "PPCISD::MTCTR"; case PPCISD::BCTRL: return "PPCISD::BCTRL"; case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC"; case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG"; case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE"; case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP"; case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP"; case PPCISD::MFOCRF: return "PPCISD::MFOCRF"; case PPCISD::MFVSR: return "PPCISD::MFVSR"; case PPCISD::MTVSRA: return "PPCISD::MTVSRA"; case PPCISD::MTVSRZ: return "PPCISD::MTVSRZ"; case PPCISD::ANDIo_1_EQ_BIT: return "PPCISD::ANDIo_1_EQ_BIT"; case PPCISD::ANDIo_1_GT_BIT: return "PPCISD::ANDIo_1_GT_BIT"; case PPCISD::VCMP: return "PPCISD::VCMP"; case PPCISD::VCMPo: return "PPCISD::VCMPo"; case PPCISD::LBRX: return "PPCISD::LBRX"; case PPCISD::STBRX: return "PPCISD::STBRX"; case PPCISD::LFIWAX: return "PPCISD::LFIWAX"; case PPCISD::LFIWZX: return "PPCISD::LFIWZX"; case PPCISD::LXVD2X: return "PPCISD::LXVD2X"; case PPCISD::STXVD2X: return "PPCISD::STXVD2X"; case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH"; case PPCISD::BDNZ: return "PPCISD::BDNZ"; case PPCISD::BDZ: return "PPCISD::BDZ"; case PPCISD::MFFS: return "PPCISD::MFFS"; case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ"; case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN"; case PPCISD::CR6SET: return "PPCISD::CR6SET"; case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET"; case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT"; case PPCISD::PPC32_PICGOT: return "PPCISD::PPC32_PICGOT"; case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA"; case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L"; case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS"; case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA"; case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L"; case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR"; case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR"; case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA"; case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L"; case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR"; case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR"; case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA"; case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L"; case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT"; case PPCISD::SC: return "PPCISD::SC"; case PPCISD::CLRBHRB: return "PPCISD::CLRBHRB"; case PPCISD::MFBHRBE: return "PPCISD::MFBHRBE"; case PPCISD::RFEBB: return "PPCISD::RFEBB"; case PPCISD::XXSWAPD: return "PPCISD::XXSWAPD"; case PPCISD::QVFPERM: return "PPCISD::QVFPERM"; case PPCISD::QVGPCI: return "PPCISD::QVGPCI"; case PPCISD::QVALIGNI: return "PPCISD::QVALIGNI"; case PPCISD::QVESPLATI: return "PPCISD::QVESPLATI"; case PPCISD::QBFLT: return "PPCISD::QBFLT"; case PPCISD::QVLFSb: return "PPCISD::QVLFSb"; } return nullptr; } EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C, EVT VT) const { if (!VT.isVector()) return Subtarget.useCRBits() ? MVT::i1 : MVT::i32; if (Subtarget.hasQPX()) return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements()); return VT.changeVectorElementTypeToInteger(); } bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const { assert(VT.isFloatingPoint() && "Non-floating-point FMA?"); return true; } //===----------------------------------------------------------------------===// // Node matching predicates, for use by the tblgen matching code. //===----------------------------------------------------------------------===// /// isFloatingPointZero - Return true if this is 0.0 or -0.0. static bool isFloatingPointZero(SDValue Op) { if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) return CFP->getValueAPF().isZero(); else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) { // Maybe this has already been legalized into the constant pool? if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1))) if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal())) return CFP->getValueAPF().isZero(); } return false; } /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return /// true if Op is undef or if it matches the specified value. static bool isConstantOrUndef(int Op, int Val) { return Op < 0 || Op == Val; } /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a /// VPKUHUM instruction. /// The ShuffleKind distinguishes between big-endian operations with /// two different inputs (0), either-endian operations with two identical /// inputs (1), and little-endian operations with two different inputs (2). /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, SelectionDAG &DAG) { bool IsLE = DAG.getDataLayout().isLittleEndian(); if (ShuffleKind == 0) { if (IsLE) return false; for (unsigned i = 0; i != 16; ++i) if (!isConstantOrUndef(N->getMaskElt(i), i*2+1)) return false; } else if (ShuffleKind == 2) { if (!IsLE) return false; for (unsigned i = 0; i != 16; ++i) if (!isConstantOrUndef(N->getMaskElt(i), i*2)) return false; } else if (ShuffleKind == 1) { unsigned j = IsLE ? 0 : 1; for (unsigned i = 0; i != 8; ++i) if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) || !isConstantOrUndef(N->getMaskElt(i+8), i*2+j)) return false; } return true; } /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a /// VPKUWUM instruction. /// The ShuffleKind distinguishes between big-endian operations with /// two different inputs (0), either-endian operations with two identical /// inputs (1), and little-endian operations with two different inputs (2). /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, SelectionDAG &DAG) { bool IsLE = DAG.getDataLayout().isLittleEndian(); if (ShuffleKind == 0) { if (IsLE) return false; for (unsigned i = 0; i != 16; i += 2) if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) || !isConstantOrUndef(N->getMaskElt(i+1), i*2+3)) return false; } else if (ShuffleKind == 2) { if (!IsLE) return false; for (unsigned i = 0; i != 16; i += 2) if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || !isConstantOrUndef(N->getMaskElt(i+1), i*2+1)) return false; } else if (ShuffleKind == 1) { unsigned j = IsLE ? 0 : 2; for (unsigned i = 0; i != 8; i += 2) if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1)) return false; } return true; } /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the /// current subtarget. /// /// The ShuffleKind distinguishes between big-endian operations with /// two different inputs (0), either-endian operations with two identical /// inputs (1), and little-endian operations with two different inputs (2). /// For the latter, the input operands are swapped (see PPCInstrAltivec.td). bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind, SelectionDAG &DAG) { const PPCSubtarget& Subtarget = static_cast<const PPCSubtarget&>(DAG.getSubtarget()); if (!Subtarget.hasP8Vector()) return false; bool IsLE = DAG.getDataLayout().isLittleEndian(); if (ShuffleKind == 0) { if (IsLE) return false; for (unsigned i = 0; i != 16; i += 4) if (!isConstantOrUndef(N->getMaskElt(i ), i*2+4) || !isConstantOrUndef(N->getMaskElt(i+1), i*2+5) || !isConstantOrUndef(N->getMaskElt(i+2), i*2+6) || !isConstantOrUndef(N->getMaskElt(i+3), i*2+7)) return false; } else if (ShuffleKind == 2) { if (!IsLE) return false; for (unsigned i = 0; i != 16; i += 4) if (!isConstantOrUndef(N->getMaskElt(i ), i*2) || !isConstantOrUndef(N->getMaskElt(i+1), i*2+1) || !isConstantOrUndef(N->getMaskElt(i+2), i*2+2) || !isConstantOrUndef(N->getMaskElt(i+3), i*2+3)) return false; } else if (ShuffleKind == 1) { unsigned j = IsLE ? 0 : 4; for (unsigned i = 0; i != 8; i += 4) if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) || !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) || !isConstantOrUndef(N->getMaskElt(i+2), i*2+j+2) || !isConstantOrUndef(N->getMaskElt(i+3), i*2+j+3) || !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) || !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1) || !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) || !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3)) return false; } return true; } /// isVMerge - Common function, used to match vmrg* shuffles. /// static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize, unsigned LHSStart, unsigned RHSStart) { if (N->getValueType(0) != MVT::v16i8) return false; assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) && "Unsupported merge size!"); for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j), LHSStart+j+i*UnitSize) || !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j), RHSStart+j+i*UnitSize)) return false; } return true; } /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes). /// The ShuffleKind distinguishes between big-endian merges with two /// different inputs (0), either-endian merges with two identical inputs (1), /// and little-endian merges with two different inputs (2). For the latter, /// the input operands are swapped (see PPCInstrAltivec.td). bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, unsigned ShuffleKind, SelectionDAG &DAG) { if (DAG.getDataLayout().isLittleEndian()) { if (ShuffleKind == 1) // unary return isVMerge(N, UnitSize, 0, 0); else if (ShuffleKind == 2) // swapped return isVMerge(N, UnitSize, 0, 16); else return false; } else { if (ShuffleKind == 1) // unary return isVMerge(N, UnitSize, 8, 8); else if (ShuffleKind == 0) // normal return isVMerge(N, UnitSize, 8, 24); else return false; } } /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes). /// The ShuffleKind distinguishes between big-endian merges with two /// different inputs (0), either-endian merges with two identical inputs (1), /// and little-endian merges with two different inputs (2). For the latter, /// the input operands are swapped (see PPCInstrAltivec.td). bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize, unsigned ShuffleKind, SelectionDAG &DAG) { if (DAG.getDataLayout().isLittleEndian()) { if (ShuffleKind == 1) // unary return isVMerge(N, UnitSize, 8, 8); else if (ShuffleKind == 2) // swapped return isVMerge(N, UnitSize, 8, 24); else return false; } else { if (ShuffleKind == 1) // unary return isVMerge(N, UnitSize, 0, 0); else if (ShuffleKind == 0) // normal return isVMerge(N, UnitSize, 0, 16); else return false; } } /** * \brief Common function used to match vmrgew and vmrgow shuffles * * The indexOffset determines whether to look for even or odd words in * the shuffle mask. This is based on the of the endianness of the target * machine. * - Little Endian: * - Use offset of 0 to check for odd elements * - Use offset of 4 to check for even elements * - Big Endian: * - Use offset of 0 to check for even elements * - Use offset of 4 to check for odd elements * A detailed description of the vector element ordering for little endian and * big endian can be found at * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html * Targeting your applications - what little endian and big endian IBM XL C/C++ * compiler differences mean to you * * The mask to the shuffle vector instruction specifies the indices of the * elements from the two input vectors to place in the result. The elements are * numbered in array-access order, starting with the first vector. These vectors * are always of type v16i8, thus each vector will contain 16 elements of size * 8. More info on the shuffle vector can be found in the * http://llvm.org/docs/LangRef.html#shufflevector-instruction * Language Reference. * * The RHSStartValue indicates whether the same input vectors are used (unary) * or two different input vectors are used, based on the following: * - If the instruction uses the same vector for both inputs, the range of the * indices will be 0 to 15. In this case, the RHSStart value passed should * be 0. * - If the instruction has two different vectors then the range of the * indices will be 0 to 31. In this case, the RHSStart value passed should * be 16 (indices 0-15 specify elements in the first vector while indices 16 * to 31 specify elements in the second vector). * * \param[in] N The shuffle vector SD Node to analyze * \param[in] IndexOffset Specifies whether to look for even or odd elements * \param[in] RHSStartValue Specifies the starting index for the righthand input * vector to the shuffle_vector instruction * \return true iff this shuffle vector represents an even or odd word merge */ static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset, unsigned RHSStartValue) { if (N->getValueType(0) != MVT::v16i8) return false; for (unsigned i = 0; i < 2; ++i) for (unsigned j = 0; j < 4; ++j) if (!isConstantOrUndef(N->getMaskElt(i*4+j), i*RHSStartValue+j+IndexOffset) || !isConstantOrUndef(N->getMaskElt(i*4+j+8), i*RHSStartValue+j+IndexOffset+8)) return false; return true; } /** * \brief Determine if the specified shuffle mask is suitable for the vmrgew or * vmrgow instructions. * * \param[in] N The shuffle vector SD Node to analyze * \param[in] CheckEven Check for an even merge (true) or an odd merge (false) * \param[in] ShuffleKind Identify the type of merge: * - 0 = big-endian merge with two different inputs; * - 1 = either-endian merge with two identical inputs; * - 2 = little-endian merge with two different inputs (inputs are swapped for * little-endian merges). * \param[in] DAG The current SelectionDAG * \return true iff this shuffle mask */ bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven, unsigned ShuffleKind, SelectionDAG &DAG) { if (DAG.getDataLayout().isLittleEndian()) { unsigned indexOffset = CheckEven ? 4 : 0; if (ShuffleKind == 1) // Unary return isVMerge(N, indexOffset, 0); else if (ShuffleKind == 2) // swapped return isVMerge(N, indexOffset, 16); else return false; } else { unsigned indexOffset = CheckEven ? 0 : 4; if (ShuffleKind == 1) // Unary return isVMerge(N, indexOffset, 0); else if (ShuffleKind == 0) // Normal return isVMerge(N, indexOffset, 16); else return false; } return false; } /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift /// amount, otherwise return -1. /// The ShuffleKind distinguishes between big-endian operations with two /// different inputs (0), either-endian operations with two identical inputs /// (1), and little-endian operations with two different inputs (2). For the /// latter, the input operands are swapped (see PPCInstrAltivec.td). int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind, SelectionDAG &DAG) { if (N->getValueType(0) != MVT::v16i8) return -1; ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); // Find the first non-undef value in the shuffle mask. unsigned i; for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i) /*search*/; if (i == 16) return -1; // all undef. // Otherwise, check to see if the rest of the elements are consecutively // numbered from this value. unsigned ShiftAmt = SVOp->getMaskElt(i); if (ShiftAmt < i) return -1; ShiftAmt -= i; bool isLE = DAG.getDataLayout().isLittleEndian(); if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) { // Check the rest of the elements to see if they are consecutive. for (++i; i != 16; ++i) if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) return -1; } else if (ShuffleKind == 1) { // Check the rest of the elements to see if they are consecutive. for (++i; i != 16; ++i) if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15)) return -1; } else return -1; if (isLE) ShiftAmt = 16 - ShiftAmt; return ShiftAmt; } /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand /// specifies a splat of a single element that is suitable for input to /// VSPLTB/VSPLTH/VSPLTW. bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) { assert(N->getValueType(0) == MVT::v16i8 && (EltSize == 1 || EltSize == 2 || EltSize == 4)); // The consecutive indices need to specify an element, not part of two // different elements. So abandon ship early if this isn't the case. if (N->getMaskElt(0) % EltSize != 0) return false; // This is a splat operation if each element of the permute is the same, and // if the value doesn't reference the second vector. unsigned ElementBase = N->getMaskElt(0); // FIXME: Handle UNDEF elements too! if (ElementBase >= 16) return false; // Check that the indices are consecutive, in the case of a multi-byte element // splatted with a v16i8 mask. for (unsigned i = 1; i != EltSize; ++i) if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase)) return false; for (unsigned i = EltSize, e = 16; i != e; i += EltSize) { if (N->getMaskElt(i) < 0) continue; for (unsigned j = 0; j != EltSize; ++j) if (N->getMaskElt(i+j) != N->getMaskElt(j)) return false; } return true; } /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the /// specified isSplatShuffleMask VECTOR_SHUFFLE mask. unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize, SelectionDAG &DAG) { ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); assert(isSplatShuffleMask(SVOp, EltSize)); if (DAG.getDataLayout().isLittleEndian()) return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize); else return SVOp->getMaskElt(0) / EltSize; } /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed /// by using a vspltis[bhw] instruction of the specified element size, return /// the constant being splatted. The ByteSize field indicates the number of /// bytes of each element [124] -> [bhw]. SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) { SDValue OpVal(nullptr, 0); // If ByteSize of the splat is bigger than the element size of the // build_vector, then we have a case where we are checking for a splat where // multiple elements of the buildvector are folded together into a single // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8). unsigned EltSize = 16/N->getNumOperands(); if (EltSize < ByteSize) { unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval. SDValue UniquedVals[4]; assert(Multiple > 1 && Multiple <= 4 && "How can this happen?"); // See if all of the elements in the buildvector agree across. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; // If the element isn't a constant, bail fully out. if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue(); if (!UniquedVals[i&(Multiple-1)].getNode()) UniquedVals[i&(Multiple-1)] = N->getOperand(i); else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i)) return SDValue(); // no match. } // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains // either constant or undef values that are identical for each chunk. See // if these chunks can form into a larger vspltis*. // Check to see if all of the leading entries are either 0 or -1. If // neither, then this won't fit into the immediate field. bool LeadingZero = true; bool LeadingOnes = true; for (unsigned i = 0; i != Multiple-1; ++i) { if (!UniquedVals[i].getNode()) continue; // Must have been undefs. LeadingZero &= isNullConstant(UniquedVals[i]); LeadingOnes &= isAllOnesConstant(UniquedVals[i]); } // Finally, check the least significant entry. if (LeadingZero) { if (!UniquedVals[Multiple-1].getNode()) return DAG.getTargetConstant(0, SDLoc(N), MVT::i32); // 0,0,0,undef int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue(); if (Val < 16) // 0,0,0,4 -> vspltisw(4) return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); } if (LeadingOnes) { if (!UniquedVals[Multiple-1].getNode()) return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue(); if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2) return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32); } return SDValue(); } // Check to see if this buildvec has a single non-undef value in its elements. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue; if (!OpVal.getNode()) OpVal = N->getOperand(i); else if (OpVal != N->getOperand(i)) return SDValue(); } if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def. unsigned ValSizeInBytes = EltSize; uint64_t Value = 0; if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) { Value = CN->getZExtValue(); } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) { assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!"); Value = FloatToBits(CN->getValueAPF().convertToFloat()); } // If the splat value is larger than the element value, then we can never do // this splat. The only case that we could fit the replicated bits into our // immediate field for would be zero, and we prefer to use vxor for it. if (ValSizeInBytes < ByteSize) return SDValue(); // If the element value is larger than the splat value, check if it consists // of a repeated bit pattern of size ByteSize. if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8)) return SDValue(); // Properly sign extend the value. int MaskVal = SignExtend32(Value, ByteSize * 8); // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros. if (MaskVal == 0) return SDValue(); // Finally, if this value fits in a 5 bit sext field, return it if (SignExtend32<5>(MaskVal) == MaskVal) return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32); return SDValue(); } /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift /// amount, otherwise return -1. int PPC::isQVALIGNIShuffleMask(SDNode *N) { EVT VT = N->getValueType(0); if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1) return -1; ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N); // Find the first non-undef value in the shuffle mask. unsigned i; for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i) /*search*/; if (i == 4) return -1; // all undef. // Otherwise, check to see if the rest of the elements are consecutively // numbered from this value. unsigned ShiftAmt = SVOp->getMaskElt(i); if (ShiftAmt < i) return -1; ShiftAmt -= i; // Check the rest of the elements to see if they are consecutive. for (++i; i != 4; ++i) if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i)) return -1; return ShiftAmt; } //===----------------------------------------------------------------------===// // Addressing Mode Selection //===----------------------------------------------------------------------===// /// isIntS16Immediate - This method tests to see if the node is either a 32-bit /// or 64-bit immediate, and if the value can be accurately represented as a /// sign extension from a 16-bit value. If so, this returns true and the /// immediate. static bool isIntS16Immediate(SDNode *N, short &Imm) { if (!isa<ConstantSDNode>(N)) return false; Imm = (short)cast<ConstantSDNode>(N)->getZExtValue(); if (N->getValueType(0) == MVT::i32) return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); else return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); } static bool isIntS16Immediate(SDValue Op, short &Imm) { return isIntS16Immediate(Op.getNode(), Imm); } /// SelectAddressRegReg - Given the specified addressed, check to see if it /// can be represented as an indexed [r+r] operation. Returns false if it /// can be more efficiently represented with [r+imm]. bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG) const { short imm = 0; if (N.getOpcode() == ISD::ADD) { if (isIntS16Immediate(N.getOperand(1), imm)) return false; // r+i if (N.getOperand(1).getOpcode() == PPCISD::Lo) return false; // r+i Base = N.getOperand(0); Index = N.getOperand(1); return true; } else if (N.getOpcode() == ISD::OR) { if (isIntS16Immediate(N.getOperand(1), imm)) return false; // r+i can fold it if we can. // If this is an or of disjoint bitfields, we can codegen this as an add // (for better address arithmetic) if the LHS and RHS of the OR are provably // disjoint. APInt LHSKnownZero, LHSKnownOne; APInt RHSKnownZero, RHSKnownOne; DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne); if (LHSKnownZero.getBoolValue()) { DAG.computeKnownBits(N.getOperand(1), RHSKnownZero, RHSKnownOne); // If all of the bits are known zero on the LHS or RHS, the add won't // carry. if (~(LHSKnownZero | RHSKnownZero) == 0) { Base = N.getOperand(0); Index = N.getOperand(1); return true; } } } return false; } // If we happen to be doing an i64 load or store into a stack slot that has // less than a 4-byte alignment, then the frame-index elimination may need to // use an indexed load or store instruction (because the offset may not be a // multiple of 4). The extra register needed to hold the offset comes from the // register scavenger, and it is possible that the scavenger will need to use // an emergency spill slot. As a result, we need to make sure that a spill slot // is allocated when doing an i64 load/store into a less-than-4-byte-aligned // stack slot. static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) { // FIXME: This does not handle the LWA case. if (VT != MVT::i64) return; // NOTE: We'll exclude negative FIs here, which come from argument // lowering, because there are no known test cases triggering this problem // using packed structures (or similar). We can remove this exclusion if // we find such a test case. The reason why this is so test-case driven is // because this entire 'fixup' is only to prevent crashes (from the // register scavenger) on not-really-valid inputs. For example, if we have: // %a = alloca i1 // %b = bitcast i1* %a to i64* // store i64* a, i64 b // then the store should really be marked as 'align 1', but is not. If it // were marked as 'align 1' then the indexed form would have been // instruction-selected initially, and the problem this 'fixup' is preventing // won't happen regardless. if (FrameIdx < 0) return; MachineFunction &MF = DAG.getMachineFunction(); MachineFrameInfo *MFI = MF.getFrameInfo(); unsigned Align = MFI->getObjectAlignment(FrameIdx); if (Align >= 4) return; PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); FuncInfo->setHasNonRISpills(); } /// Returns true if the address N can be represented by a base register plus /// a signed 16-bit displacement [r+imm], and if it is not better /// represented as reg+reg. If Aligned is true, only accept displacements /// suitable for STD and friends, i.e. multiples of 4. bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG, bool Aligned) const { // FIXME dl should come from parent load or store, not from address SDLoc dl(N); // If this can be more profitably realized as r+r, fail. if (SelectAddressRegReg(N, Disp, Base, DAG)) return false; if (N.getOpcode() == ISD::ADD) { short imm = 0; if (isIntS16Immediate(N.getOperand(1), imm) && (!Aligned || (imm & 3) == 0)) { Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); } else { Base = N.getOperand(0); } return true; // [r+i] } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) { // Match LOAD (ADD (X, Lo(G))). assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue() && "Cannot handle constant offsets yet!"); Disp = N.getOperand(1).getOperand(0); // The global address. assert(Disp.getOpcode() == ISD::TargetGlobalAddress || Disp.getOpcode() == ISD::TargetGlobalTLSAddress || Disp.getOpcode() == ISD::TargetConstantPool || Disp.getOpcode() == ISD::TargetJumpTable); Base = N.getOperand(0); return true; // [&g+r] } } else if (N.getOpcode() == ISD::OR) { short imm = 0; if (isIntS16Immediate(N.getOperand(1), imm) && (!Aligned || (imm & 3) == 0)) { // If this is an or of disjoint bitfields, we can codegen this as an add // (for better address arithmetic) if the LHS and RHS of the OR are // provably disjoint. APInt LHSKnownZero, LHSKnownOne; DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne); if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) { // If all of the bits are known zero on the LHS or RHS, the add won't // carry. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) { Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); } else { Base = N.getOperand(0); } Disp = DAG.getTargetConstant(imm, dl, N.getValueType()); return true; } } } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) { // Loading from a constant address. // If this address fits entirely in a 16-bit sext immediate field, codegen // this as "d, 0" short Imm; if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) { Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0)); Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, CN->getValueType(0)); return true; } // Handle 32-bit sext immediates with LIS + addr mode. if ((CN->getValueType(0) == MVT::i32 || (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) && (!Aligned || (CN->getZExtValue() & 3) == 0)) { int Addr = (int)CN->getZExtValue(); // Otherwise, break this down into an LIS + disp. Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32); Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl, MVT::i32); unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8; Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0); return true; } } Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout())); if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) { Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType()); fixupFuncForFI(DAG, FI->getIndex(), N.getValueType()); } else Base = N; return true; // [r+0] } /// SelectAddressRegRegOnly - Given the specified addressed, force it to be /// represented as an indexed [r+r] operation. bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG) const { // Check to see if we can easily represent this as an [r+r] address. This // will fail if it thinks that the address is more profitably represented as // reg+imm, e.g. where imm = 0. if (SelectAddressRegReg(N, Base, Index, DAG)) return true; // If the operand is an addition, always emit this as [r+r], since this is // better (for code size, and execution, as the memop does the add for free) // than emitting an explicit add. if (N.getOpcode() == ISD::ADD) { Base = N.getOperand(0); Index = N.getOperand(1); return true; } // Otherwise, do it the hard way, using R0 as the base register. Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO, N.getValueType()); Index = N; return true; } /// getPreIndexedAddressParts - returns true by value, base pointer and /// offset pointer and addressing mode by reference if the node's address /// can be legally represented as pre-indexed load / store address. bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, SDValue &Offset, ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { if (DisablePPCPreinc) return false; bool isLoad = true; SDValue Ptr; EVT VT; unsigned Alignment; if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { Ptr = LD->getBasePtr(); VT = LD->getMemoryVT(); Alignment = LD->getAlignment(); } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { Ptr = ST->getBasePtr(); VT = ST->getMemoryVT(); Alignment = ST->getAlignment(); isLoad = false; } else return false; // PowerPC doesn't have preinc load/store instructions for vectors (except // for QPX, which does have preinc r+r forms). if (VT.isVector()) { if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) { return false; } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) { AM = ISD::PRE_INC; return true; } } if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) { // Common code will reject creating a pre-inc form if the base pointer // is a frame index, or if N is a store and the base pointer is either // the same as or a predecessor of the value being stored. Check for // those situations here, and try with swapped Base/Offset instead. bool Swap = false; if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base)) Swap = true; else if (!isLoad) { SDValue Val = cast<StoreSDNode>(N)->getValue(); if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode())) Swap = true; } if (Swap) std::swap(Base, Offset); AM = ISD::PRE_INC; return true; } // LDU/STU can only handle immediates that are a multiple of 4. if (VT != MVT::i64) { if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false)) return false; } else { // LDU/STU need an address with at least 4-byte alignment. if (Alignment < 4) return false; if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true)) return false; } if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of // sext i32 to i64 when addr mode is r+i. if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 && LD->getExtensionType() == ISD::SEXTLOAD && isa<ConstantSDNode>(Offset)) return false; } AM = ISD::PRE_INC; return true; } //===----------------------------------------------------------------------===// // LowerOperation implementation //===----------------------------------------------------------------------===// /// GetLabelAccessInfo - Return true if we should reference labels using a /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags. static bool GetLabelAccessInfo(const TargetMachine &TM, const PPCSubtarget &Subtarget, unsigned &HiOpFlags, unsigned &LoOpFlags, const GlobalValue *GV = nullptr) { HiOpFlags = PPCII::MO_HA; LoOpFlags = PPCII::MO_LO; // Don't use the pic base if not in PIC relocation model. bool isPIC = TM.getRelocationModel() == Reloc::PIC_; if (isPIC) { HiOpFlags |= PPCII::MO_PIC_FLAG; LoOpFlags |= PPCII::MO_PIC_FLAG; } // If this is a reference to a global value that requires a non-lazy-ptr, make // sure that instruction lowering adds it. if (GV && Subtarget.hasLazyResolverStub(GV)) { HiOpFlags |= PPCII::MO_NLP_FLAG; LoOpFlags |= PPCII::MO_NLP_FLAG; if (GV->hasHiddenVisibility()) { HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG; } } return isPIC; } static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC, SelectionDAG &DAG) { SDLoc DL(HiPart); EVT PtrVT = HiPart.getValueType(); SDValue Zero = DAG.getConstant(0, DL, PtrVT); SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero); SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero); // With PIC, the first instruction is actually "GR+hi(&G)". if (isPIC) Hi = DAG.getNode(ISD::ADD, DL, PtrVT, DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi); // Generate non-pic code that has direct accesses to the constant pool. // The address of the global is just (hi(&g)+lo(&g)). return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo); } static void setUsesTOCBasePtr(MachineFunction &MF) { PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); FuncInfo->setUsesTOCBasePtr(); } static void setUsesTOCBasePtr(SelectionDAG &DAG) { setUsesTOCBasePtr(DAG.getMachineFunction()); } static SDValue getTOCEntry(SelectionDAG &DAG, SDLoc dl, bool Is64Bit, SDValue GA) { EVT VT = Is64Bit ? MVT::i64 : MVT::i32; SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT); SDValue Ops[] = { GA, Reg }; return DAG.getMemIntrinsicNode( PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT, MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true, false, 0); } SDValue PPCTargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const { EVT PtrVT = Op.getValueType(); ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); const Constant *C = CP->getConstVal(); // 64-bit SVR4 ABI code is always position-independent. // The actual address of the GlobalValue is stored in the TOC. if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { setUsesTOCBasePtr(DAG); SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0); return getTOCEntry(DAG, SDLoc(CP), true, GA); } unsigned MOHiFlag, MOLoFlag; bool isPIC = GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag); if (isPIC && Subtarget.isSVR4ABI()) { SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), PPCII::MO_PIC_FLAG); return getTOCEntry(DAG, SDLoc(CP), false, GA); } SDValue CPIHi = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag); SDValue CPILo = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag); return LowerLabelRef(CPIHi, CPILo, isPIC, DAG); } SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const { EVT PtrVT = Op.getValueType(); JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); // 64-bit SVR4 ABI code is always position-independent. // The actual address of the GlobalValue is stored in the TOC. if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { setUsesTOCBasePtr(DAG); SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT); return getTOCEntry(DAG, SDLoc(JT), true, GA); } unsigned MOHiFlag, MOLoFlag; bool isPIC = GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag); if (isPIC && Subtarget.isSVR4ABI()) { SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, PPCII::MO_PIC_FLAG); return getTOCEntry(DAG, SDLoc(GA), false, GA); } SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag); SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag); return LowerLabelRef(JTIHi, JTILo, isPIC, DAG); } SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const { EVT PtrVT = Op.getValueType(); BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op); const BlockAddress *BA = BASDN->getBlockAddress(); // 64-bit SVR4 ABI code is always position-independent. // The actual BlockAddress is stored in the TOC. if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { setUsesTOCBasePtr(DAG); SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()); return getTOCEntry(DAG, SDLoc(BASDN), true, GA); } unsigned MOHiFlag, MOLoFlag; bool isPIC = GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag); SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag); SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag); return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG); } SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const { // FIXME: TLS addresses currently use medium model code sequences, // which is the most useful form. Eventually support for small and // large models could be added if users need it, at the cost of // additional complexity. GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); if (DAG.getTarget().Options.EmulatedTLS) return LowerToTLSEmulatedModel(GA, DAG); SDLoc dl(GA); const GlobalValue *GV = GA->getGlobal(); EVT PtrVT = getPointerTy(DAG.getDataLayout()); bool is64bit = Subtarget.isPPC64(); const Module *M = DAG.getMachineFunction().getFunction()->getParent(); PICLevel::Level picLevel = M->getPICLevel(); TLSModel::Model Model = getTargetMachine().getTLSModel(GV); if (Model == TLSModel::LocalExec) { SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TPREL_HA); SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TPREL_LO); SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2, is64bit ? MVT::i64 : MVT::i32); SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg); return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi); } if (Model == TLSModel::InitialExec) { SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, PPCII::MO_TLS); SDValue GOTPtr; if (is64bit) { setUsesTOCBasePtr(DAG); SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl, PtrVT, GOTReg, TGA); } else GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT); SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl, PtrVT, TGA, GOTPtr); return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS); } if (Model == TLSModel::GeneralDynamic) { SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); SDValue GOTPtr; if (is64bit) { setUsesTOCBasePtr(DAG); SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT, GOTReg, TGA); } else { if (picLevel == PICLevel::Small) GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); else GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); } return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT, GOTPtr, TGA, TGA); } if (Model == TLSModel::LocalDynamic) { SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0); SDValue GOTPtr; if (is64bit) { setUsesTOCBasePtr(DAG); SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64); GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT, GOTReg, TGA); } else { if (picLevel == PICLevel::Small) GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT); else GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT); } SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl, PtrVT, GOTPtr, TGA, TGA); SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT, TLSAddr, TGA); return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA); } llvm_unreachable("Unknown TLS model!"); } SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const { EVT PtrVT = Op.getValueType(); GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op); SDLoc DL(GSDN); const GlobalValue *GV = GSDN->getGlobal(); // 64-bit SVR4 ABI code is always position-independent. // The actual address of the GlobalValue is stored in the TOC. if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) { setUsesTOCBasePtr(DAG); SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset()); return getTOCEntry(DAG, DL, true, GA); } unsigned MOHiFlag, MOLoFlag; bool isPIC = GetLabelAccessInfo(DAG.getTarget(), Subtarget, MOHiFlag, MOLoFlag, GV); if (isPIC && Subtarget.isSVR4ABI()) { SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), PPCII::MO_PIC_FLAG); return getTOCEntry(DAG, DL, false, GA); } SDValue GAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag); SDValue GALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag); SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG); // If the global reference is actually to a non-lazy-pointer, we have to do an // extra load to get the address of the global. if (MOHiFlag & PPCII::MO_NLP_FLAG) Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(), false, false, false, 0); return Ptr; } SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); SDLoc dl(Op); if (Op.getValueType() == MVT::v2i64) { // When the operands themselves are v2i64 values, we need to do something // special because VSX has no underlying comparison operations for these. if (Op.getOperand(0).getValueType() == MVT::v2i64) { // Equality can be handled by casting to the legal type for Altivec // comparisons, everything else needs to be expanded. if (CC == ISD::SETEQ || CC == ISD::SETNE) { return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, DAG.getSetCC(dl, MVT::v4i32, DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)), DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)), CC)); } return SDValue(); } // We handle most of these in the usual way. return Op; } // If we're comparing for equality to zero, expose the fact that this is // implented as a ctlz/srl pair on ppc, so that the dag combiner can // fold the new nodes. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { if (C->isNullValue() && CC == ISD::SETEQ) { EVT VT = Op.getOperand(0).getValueType(); SDValue Zext = Op.getOperand(0); if (VT.bitsLT(MVT::i32)) { VT = MVT::i32; Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0)); } unsigned Log2b = Log2_32(VT.getSizeInBits()); SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext); SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz, DAG.getConstant(Log2b, dl, MVT::i32)); return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc); } // Leave comparisons against 0 and -1 alone for now, since they're usually // optimized. FIXME: revisit this when we can custom lower all setcc // optimizations. if (C->isAllOnesValue() || C->isNullValue()) return SDValue(); } // If we have an integer seteq/setne, turn it into a compare against zero // by xor'ing the rhs with the lhs, which is faster than setting a // condition register, reading it back out, and masking the correct bit. The // normal approach here uses sub to do this instead of xor. Using xor exposes // the result to other bit-twiddling opportunities. EVT LHSVT = Op.getOperand(0).getValueType(); if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) { EVT VT = Op.getValueType(); SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0), Op.getOperand(1)); return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC); } return SDValue(); } SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget) const { SDNode *Node = Op.getNode(); EVT VT = Node->getValueType(0); EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); SDValue InChain = Node->getOperand(0); SDValue VAListPtr = Node->getOperand(1); const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue(); SDLoc dl(Node); assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only"); // gpr_index SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, VAListPtr, MachinePointerInfo(SV), MVT::i8, false, false, false, 0); InChain = GprIndex.getValue(1); if (VT == MVT::i64) { // Check if GprIndex is even SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex, DAG.getConstant(1, dl, MVT::i32)); SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd, DAG.getConstant(0, dl, MVT::i32), ISD::SETNE); SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex, DAG.getConstant(1, dl, MVT::i32)); // Align GprIndex to be even if it isn't GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne, GprIndex); } // fpr index is 1 byte after gpr SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, DAG.getConstant(1, dl, MVT::i32)); // fpr SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain, FprPtr, MachinePointerInfo(SV), MVT::i8, false, false, false, 0); InChain = FprIndex.getValue(1); SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, DAG.getConstant(8, dl, MVT::i32)); SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr, DAG.getConstant(4, dl, MVT::i32)); // areas SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo(), false, false, false, 0); InChain = OverflowArea.getValue(1); SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo(), false, false, false, 0); InChain = RegSaveArea.getValue(1); // select overflow_area if index > 8 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, DAG.getConstant(8, dl, MVT::i32), ISD::SETLT); // adjustment constant gpr_index * 4/8 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, DAG.getConstant(VT.isInteger() ? 4 : 8, dl, MVT::i32)); // OurReg = RegSaveArea + RegConstant SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea, RegConstant); // Floating types are 32 bytes into RegSaveArea if (VT.isFloatingPoint()) OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg, DAG.getConstant(32, dl, MVT::i32)); // increase {f,g}pr_index by 1 (or 2 if VT is i64) SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex, DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl, MVT::i32)); InChain = DAG.getTruncStore(InChain, dl, IndexPlus1, VT.isInteger() ? VAListPtr : FprPtr, MachinePointerInfo(SV), MVT::i8, false, false, 0); // determine if we should load from reg_save_area or overflow_area SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea); // increase overflow_area by 4/8 if gpr/fpr > 8 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea, DAG.getConstant(VT.isInteger() ? 4 : 8, dl, MVT::i32)); OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea, OverflowAreaPlusN); InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr, MachinePointerInfo(), MVT::i32, false, false, 0); return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(), false, false, false, 0); } SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget) const { assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only"); // We have to copy the entire va_list struct: // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2), DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true, false, MachinePointerInfo(), MachinePointerInfo()); } SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const { return Op.getOperand(0); } SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) const { SDValue Chain = Op.getOperand(0); SDValue Trmp = Op.getOperand(1); // trampoline SDValue FPtr = Op.getOperand(2); // nested function SDValue Nest = Op.getOperand(3); // 'nest' parameter value SDLoc dl(Op); EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); bool isPPC64 = (PtrVT == MVT::i64); Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext()); TargetLowering::ArgListTy Args; TargetLowering::ArgListEntry Entry; Entry.Ty = IntPtrTy; Entry.Node = Trmp; Args.push_back(Entry); // TrampSize == (isPPC64 ? 48 : 40); Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl, isPPC64 ? MVT::i64 : MVT::i32); Args.push_back(Entry); Entry.Node = FPtr; Args.push_back(Entry); Entry.Node = Nest; Args.push_back(Entry); // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg) TargetLowering::CallLoweringInfo CLI(DAG); CLI.setDebugLoc(dl).setChain(Chain) .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args), 0); std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); return CallResult.second; } SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget) const { MachineFunction &MF = DAG.getMachineFunction(); PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); SDLoc dl(Op); if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) { // vastart just stores the address of the VarArgsFrameIndex slot into the // memory location argument. EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout()); SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), MachinePointerInfo(SV), false, false, 0); } // For the 32-bit SVR4 ABI we follow the layout of the va_list struct. // We suppose the given va_list is already allocated. // // typedef struct { // char gpr; /* index into the array of 8 GPRs // * stored in the register save area // * gpr=0 corresponds to r3, // * gpr=1 to r4, etc. // */ // char fpr; /* index into the array of 8 FPRs // * stored in the register save area // * fpr=0 corresponds to f1, // * fpr=1 to f2, etc. // */ // char *overflow_arg_area; // /* location on stack that holds // * the next overflow argument // */ // char *reg_save_area; // /* where r3:r10 and f1:f8 (if saved) // * are stored // */ // } va_list[1]; SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32); SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32); EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout()); SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(), PtrVT); SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); uint64_t FrameOffset = PtrVT.getSizeInBits()/8; SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT); uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1; SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT); uint64_t FPROffset = 1; SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT); const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); // Store first byte : number of int regs SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1), MachinePointerInfo(SV), MVT::i8, false, false, 0); uint64_t nextOffset = FPROffset; SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1), ConstFPROffset); // Store second byte : number of float regs SDValue secondStore = DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr, MachinePointerInfo(SV, nextOffset), MVT::i8, false, false, 0); nextOffset += StackOffset; nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset); // Store second word : arguments given on stack SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr, MachinePointerInfo(SV, nextOffset), false, false, 0); nextOffset += FrameOffset; nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset); // Store third word : arguments given in registers return DAG.getStore(thirdStore, dl, FR, nextPtr, MachinePointerInfo(SV, nextOffset), false, false, 0); } #include "PPCGenCallingConv.inc" // Function whose sole purpose is to kill compiler warnings // stemming from unused functions included from PPCGenCallingConv.inc. CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const { return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS; } bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT, CCValAssign::LocInfo &LocInfo, ISD::ArgFlagsTy &ArgFlags, CCState &State) { return true; } bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT, MVT &LocVT, CCValAssign::LocInfo &LocInfo, ISD::ArgFlagsTy &ArgFlags, CCState &State) { static const MCPhysReg ArgRegs[] = { PPC::R3, PPC::R4, PPC::R5, PPC::R6, PPC::R7, PPC::R8, PPC::R9, PPC::R10, }; const unsigned NumArgRegs = array_lengthof(ArgRegs); unsigned RegNum = State.getFirstUnallocated(ArgRegs); // Skip one register if the first unallocated register has an even register // number and there are still argument registers available which have not been // allocated yet. RegNum is actually an index into ArgRegs, which means we // need to skip a register if RegNum is odd. if (RegNum != NumArgRegs && RegNum % 2 == 1) { State.AllocateReg(ArgRegs[RegNum]); } // Always return false here, as this function only makes sure that the first // unallocated register has an odd register number and does not actually // allocate a register for the current argument. return false; } bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT, MVT &LocVT, CCValAssign::LocInfo &LocInfo, ISD::ArgFlagsTy &ArgFlags, CCState &State) { static const MCPhysReg ArgRegs[] = { PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, PPC::F8 }; const unsigned NumArgRegs = array_lengthof(ArgRegs); unsigned RegNum = State.getFirstUnallocated(ArgRegs); // If there is only one Floating-point register left we need to put both f64 // values of a split ppc_fp128 value on the stack. if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) { State.AllocateReg(ArgRegs[RegNum]); } // Always return false here, as this function only makes sure that the two f64 // values a ppc_fp128 value is split into are both passed in registers or both // passed on the stack and does not actually allocate a register for the // current argument. return false; } /// FPR - The set of FP registers that should be allocated for arguments, /// on Darwin. static const MCPhysReg FPR[] = {PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13}; /// QFPR - The set of QPX registers that should be allocated for arguments. static const MCPhysReg QFPR[] = { PPC::QF1, PPC::QF2, PPC::QF3, PPC::QF4, PPC::QF5, PPC::QF6, PPC::QF7, PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13}; /// CalculateStackSlotSize - Calculates the size reserved for this argument on /// the stack. static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags, unsigned PtrByteSize) { unsigned ArgSize = ArgVT.getStoreSize(); if (Flags.isByVal()) ArgSize = Flags.getByValSize(); // Round up to multiples of the pointer size, except for array members, // which are always packed. if (!Flags.isInConsecutiveRegs()) ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; return ArgSize; } /// CalculateStackSlotAlignment - Calculates the alignment of this argument /// on the stack. static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, unsigned PtrByteSize) { unsigned Align = PtrByteSize; // Altivec parameters are padded to a 16 byte boundary. if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || ArgVT == MVT::v1i128) Align = 16; // QPX vector types stored in double-precision are padded to a 32 byte // boundary. else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1) Align = 32; // ByVal parameters are aligned as requested. if (Flags.isByVal()) { unsigned BVAlign = Flags.getByValAlign(); if (BVAlign > PtrByteSize) { if (BVAlign % PtrByteSize != 0) llvm_unreachable( "ByVal alignment is not a multiple of the pointer size"); Align = BVAlign; } } // Array members are always packed to their original alignment. if (Flags.isInConsecutiveRegs()) { // If the array member was split into multiple registers, the first // needs to be aligned to the size of the full type. (Except for // ppcf128, which is only aligned as its f64 components.) if (Flags.isSplit() && OrigVT != MVT::ppcf128) Align = OrigVT.getStoreSize(); else Align = ArgVT.getStoreSize(); } return Align; } /// CalculateStackSlotUsed - Return whether this argument will use its /// stack slot (instead of being passed in registers). ArgOffset, /// AvailableFPRs, and AvailableVRs must hold the current argument /// position, and will be updated to account for this argument. static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags, unsigned PtrByteSize, unsigned LinkageSize, unsigned ParamAreaSize, unsigned &ArgOffset, unsigned &AvailableFPRs, unsigned &AvailableVRs, bool HasQPX) { bool UseMemory = false; // Respect alignment of argument on the stack. unsigned Align = CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; // If there's no space left in the argument save area, we must // use memory (this check also catches zero-sized arguments). if (ArgOffset >= LinkageSize + ParamAreaSize) UseMemory = true; // Allocate argument on the stack. ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); if (Flags.isInConsecutiveRegsLast()) ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; // If we overran the argument save area, we must use memory // (this check catches arguments passed partially in memory) if (ArgOffset > LinkageSize + ParamAreaSize) UseMemory = true; // However, if the argument is actually passed in an FPR or a VR, // we don't use memory after all. if (!Flags.isByVal()) { if (ArgVT == MVT::f32 || ArgVT == MVT::f64 || // QPX registers overlap with the scalar FP registers. (HasQPX && (ArgVT == MVT::v4f32 || ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1))) if (AvailableFPRs > 0) { --AvailableFPRs; return false; } if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 || ArgVT == MVT::v1i128) if (AvailableVRs > 0) { --AvailableVRs; return false; } } return UseMemory; } /// EnsureStackAlignment - Round stack frame size up from NumBytes to /// ensure minimum alignment required for target. static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering, unsigned NumBytes) { unsigned TargetAlign = Lowering->getStackAlignment(); unsigned AlignMask = TargetAlign - 1; NumBytes = (NumBytes + AlignMask) & ~AlignMask; return NumBytes; } SDValue PPCTargetLowering::LowerFormalArguments(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { if (Subtarget.isSVR4ABI()) { if (Subtarget.isPPC64()) return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals); else return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals); } else { return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG, InVals); } } SDValue PPCTargetLowering::LowerFormalArguments_32SVR4( SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { // 32-bit SVR4 ABI Stack Frame Layout: // +-----------------------------------+ // +--> | Back chain | // | +-----------------------------------+ // | | Floating-point register save area | // | +-----------------------------------+ // | | General register save area | // | +-----------------------------------+ // | | CR save word | // | +-----------------------------------+ // | | VRSAVE save word | // | +-----------------------------------+ // | | Alignment padding | // | +-----------------------------------+ // | | Vector register save area | // | +-----------------------------------+ // | | Local variable space | // | +-----------------------------------+ // | | Parameter list area | // | +-----------------------------------+ // | | LR save word | // | +-----------------------------------+ // SP--> +--- | Back chain | // +-----------------------------------+ // // Specifications: // System V Application Binary Interface PowerPC Processor Supplement // AltiVec Technology Programming Interface Manual MachineFunction &MF = DAG.getMachineFunction(); MachineFrameInfo *MFI = MF.getFrameInfo(); PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout()); // Potential tail calls could cause overwriting of argument stack slots. bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && (CallConv == CallingConv::Fast)); unsigned PtrByteSize = 4; // Assign locations to all of the incoming arguments. SmallVector<CCValAssign, 16> ArgLocs; CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext()); // Reserve space for the linkage area on the stack. unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); CCInfo.AllocateStack(LinkageSize, PtrByteSize); CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4); for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { CCValAssign &VA = ArgLocs[i]; // Arguments stored in registers. if (VA.isRegLoc()) { const TargetRegisterClass *RC; EVT ValVT = VA.getValVT(); switch (ValVT.getSimpleVT().SimpleTy) { default: llvm_unreachable("ValVT not supported by formal arguments Lowering"); case MVT::i1: case MVT::i32: RC = &PPC::GPRCRegClass; break; case MVT::f32: if (Subtarget.hasP8Vector()) RC = &PPC::VSSRCRegClass; else RC = &PPC::F4RCRegClass; break; case MVT::f64: if (Subtarget.hasVSX()) RC = &PPC::VSFRCRegClass; else RC = &PPC::F8RCRegClass; break; case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: RC = &PPC::VRRCRegClass; break; case MVT::v4f32: RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass; break; case MVT::v2f64: case MVT::v2i64: RC = &PPC::VSHRCRegClass; break; case MVT::v4f64: RC = &PPC::QFRCRegClass; break; case MVT::v4i1: RC = &PPC::QBRCRegClass; break; } // Transform the arguments stored in physical registers into virtual ones. unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, ValVT == MVT::i1 ? MVT::i32 : ValVT); if (ValVT == MVT::i1) ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue); InVals.push_back(ArgValue); } else { // Argument stored in memory. assert(VA.isMemLoc()); unsigned ArgSize = VA.getLocVT().getStoreSize(); int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(), isImmutable); // Create load nodes to retrieve arguments from the stack. SDValue FIN = DAG.getFrameIndex(FI, PtrVT); InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo(), false, false, false, 0)); } } // Assign locations to all of the incoming aggregate by value arguments. // Aggregates passed by value are stored in the local variable space of the // caller's stack frame, right above the parameter list area. SmallVector<CCValAssign, 16> ByValArgLocs; CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), ByValArgLocs, *DAG.getContext()); // Reserve stack space for the allocations in CCInfo. CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal); // Area that is at least reserved in the caller of this function. unsigned MinReservedArea = CCByValInfo.getNextStackOffset(); MinReservedArea = std::max(MinReservedArea, LinkageSize); // Set the size that is at least reserved in caller of this function. Tail // call optimized function's reserved stack space needs to be aligned so that // taking the difference between two stack areas will result in an aligned // stack. MinReservedArea = EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); FuncInfo->setMinReservedArea(MinReservedArea); SmallVector<SDValue, 8> MemOps; // If the function takes variable number of arguments, make a frame index for // the start of the first vararg value... for expansion of llvm.va_start. if (isVarArg) { static const MCPhysReg GPArgRegs[] = { PPC::R3, PPC::R4, PPC::R5, PPC::R6, PPC::R7, PPC::R8, PPC::R9, PPC::R10, }; const unsigned NumGPArgRegs = array_lengthof(GPArgRegs); static const MCPhysReg FPArgRegs[] = { PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7, PPC::F8 }; unsigned NumFPArgRegs = array_lengthof(FPArgRegs); if (Subtarget.useSoftFloat()) NumFPArgRegs = 0; FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs)); FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs)); // Make room for NumGPArgRegs and NumFPArgRegs. int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 + NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8; FuncInfo->setVarArgsStackOffset( MFI->CreateFixedObject(PtrVT.getSizeInBits()/8, CCInfo.getNextStackOffset(), true)); FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false)); SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); // The fixed integer arguments of a variadic function are stored to the // VarArgsFrameIndex on the stack so that they may be loaded by deferencing // the result of va_next. for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) { // Get an existing live-in vreg, or add a new one. unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]); if (!VReg) VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass); SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo(), false, false, 0); MemOps.push_back(Store); // Increment the address by four for the next argument to store SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); } // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6 // is set. // The double arguments are stored to the VarArgsFrameIndex // on the stack. for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) { // Get an existing live-in vreg, or add a new one. unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]); if (!VReg) VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass); SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64); SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo(), false, false, 0); MemOps.push_back(Store); // Increment the address by eight for the next argument to store SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl, PtrVT); FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); } } if (!MemOps.empty()) Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); return Chain; } // PPC64 passes i8, i16, and i32 values in i64 registers. Promote // value to MVT::i64 and then truncate to the correct register size. SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT, SelectionDAG &DAG, SDValue ArgVal, SDLoc dl) const { if (Flags.isSExt()) ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal, DAG.getValueType(ObjectVT)); else if (Flags.isZExt()) ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal, DAG.getValueType(ObjectVT)); return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal); } SDValue PPCTargetLowering::LowerFormalArguments_64SVR4( SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { // TODO: add description of PPC stack frame format, or at least some docs. // bool isELFv2ABI = Subtarget.isELFv2ABI(); bool isLittleEndian = Subtarget.isLittleEndian(); MachineFunction &MF = DAG.getMachineFunction(); MachineFrameInfo *MFI = MF.getFrameInfo(); PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); assert(!(CallConv == CallingConv::Fast && isVarArg) && "fastcc not supported on varargs functions"); EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout()); // Potential tail calls could cause overwriting of argument stack slots. bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && (CallConv == CallingConv::Fast)); unsigned PtrByteSize = 8; unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); static const MCPhysReg GPR[] = { PPC::X3, PPC::X4, PPC::X5, PPC::X6, PPC::X7, PPC::X8, PPC::X9, PPC::X10, }; static const MCPhysReg VR[] = { PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 }; static const MCPhysReg VSRH[] = { PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8, PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13 }; const unsigned Num_GPR_Regs = array_lengthof(GPR); const unsigned Num_FPR_Regs = 13; const unsigned Num_VR_Regs = array_lengthof(VR); const unsigned Num_QFPR_Regs = Num_FPR_Regs; // Do a first pass over the arguments to determine whether the ABI // guarantees that our caller has allocated the parameter save area // on its stack frame. In the ELFv1 ABI, this is always the case; // in the ELFv2 ABI, it is true if this is a vararg function or if // any parameter is located in a stack slot. bool HasParameterArea = !isELFv2ABI || isVarArg; unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize; unsigned NumBytes = LinkageSize; unsigned AvailableFPRs = Num_FPR_Regs; unsigned AvailableVRs = Num_VR_Regs; for (unsigned i = 0, e = Ins.size(); i != e; ++i) { if (Ins[i].Flags.isNest()) continue; if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags, PtrByteSize, LinkageSize, ParamAreaSize, NumBytes, AvailableFPRs, AvailableVRs, Subtarget.hasQPX())) HasParameterArea = true; } // Add DAG nodes to load the arguments or copy them out of registers. On // entry to a function on PPC, the arguments start after the linkage area, // although the first ones are often in registers. unsigned ArgOffset = LinkageSize; unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; unsigned &QFPR_idx = FPR_idx; SmallVector<SDValue, 8> MemOps; Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); unsigned CurArgIdx = 0; for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { SDValue ArgVal; bool needsLoad = false; EVT ObjectVT = Ins[ArgNo].VT; EVT OrigVT = Ins[ArgNo].ArgVT; unsigned ObjSize = ObjectVT.getStoreSize(); unsigned ArgSize = ObjSize; ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; if (Ins[ArgNo].isOrigArg()) { std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); CurArgIdx = Ins[ArgNo].getOrigArgIndex(); } // We re-align the argument offset for each argument, except when using the // fast calling convention, when we need to make sure we do that only when // we'll actually use a stack slot. unsigned CurArgOffset, Align; auto ComputeArgOffset = [&]() { /* Respect alignment of argument on the stack. */ Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize); ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; CurArgOffset = ArgOffset; }; if (CallConv != CallingConv::Fast) { ComputeArgOffset(); /* Compute GPR index associated with argument offset. */ GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; GPR_idx = std::min(GPR_idx, Num_GPR_Regs); } // FIXME the codegen can be much improved in some cases. // We do not have to keep everything in memory. if (Flags.isByVal()) { assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); if (CallConv == CallingConv::Fast) ComputeArgOffset(); // ObjSize is the true size, ArgSize rounded up to multiple of registers. ObjSize = Flags.getByValSize(); ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; // Empty aggregate parameters do not take up registers. Examples: // struct { } a; // union { } b; // int c[0]; // etc. However, we have to provide a place-holder in InVals, so // pretend we have an 8-byte item at the current address for that // purpose. if (!ObjSize) { int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true); SDValue FIN = DAG.getFrameIndex(FI, PtrVT); InVals.push_back(FIN); continue; } // Create a stack object covering all stack doublewords occupied // by the argument. If the argument is (fully or partially) on // the stack, or if the argument is fully in registers but the // caller has allocated the parameter save anyway, we can refer // directly to the caller's stack frame. Otherwise, create a // local copy in our own frame. int FI; if (HasParameterArea || ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize) FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true); else FI = MFI->CreateStackObject(ArgSize, Align, false); SDValue FIN = DAG.getFrameIndex(FI, PtrVT); // Handle aggregates smaller than 8 bytes. if (ObjSize < PtrByteSize) { // The value of the object is its address, which differs from the // address of the enclosing doubleword on big-endian systems. SDValue Arg = FIN; if (!isLittleEndian) { SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT); Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff); } InVals.push_back(Arg); if (GPR_idx != Num_GPR_Regs) { unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); SDValue Store; if (ObjSize==1 || ObjSize==2 || ObjSize==4) { EVT ObjType = (ObjSize == 1 ? MVT::i8 : (ObjSize == 2 ? MVT::i16 : MVT::i32)); Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg, MachinePointerInfo(&*FuncArg), ObjType, false, false, 0); } else { // For sizes that don't fit a truncating store (3, 5, 6, 7), // store the whole register as-is to the parameter save area // slot. Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo(&*FuncArg), false, false, 0); } MemOps.push_back(Store); } // Whether we copied from a register or not, advance the offset // into the parameter save area by a full doubleword. ArgOffset += PtrByteSize; continue; } // The value of the object is its address, which is the address of // its first stack doubleword. InVals.push_back(FIN); // Store whatever pieces of the object are in registers to memory. for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { if (GPR_idx == Num_GPR_Regs) break; unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); SDValue Addr = FIN; if (j) { SDValue Off = DAG.getConstant(j, dl, PtrVT); Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off); } SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr, MachinePointerInfo(&*FuncArg, j), false, false, 0); MemOps.push_back(Store); ++GPR_idx; } ArgOffset += ArgSize; continue; } switch (ObjectVT.getSimpleVT().SimpleTy) { default: llvm_unreachable("Unhandled argument type!"); case MVT::i1: case MVT::i32: case MVT::i64: if (Flags.isNest()) { // The 'nest' parameter, if any, is passed in R11. unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass); ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); break; } // These can be scalar arguments or elements of an integer array type // passed directly. Clang may use those instead of "byval" aggregate // types to avoid forcing arguments to memory unnecessarily. if (GPR_idx != Num_GPR_Regs) { unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) // PPC64 passes i8, i16, and i32 values in i64 registers. Promote // value to MVT::i64 and then truncate to the correct register size. ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); } else { if (CallConv == CallingConv::Fast) ComputeArgOffset(); needsLoad = true; ArgSize = PtrByteSize; } if (CallConv != CallingConv::Fast || needsLoad) ArgOffset += 8; break; case MVT::f32: case MVT::f64: // These can be scalar arguments or elements of a float array type // passed directly. The latter are used to implement ELFv2 homogenous // float aggregates. if (FPR_idx != Num_FPR_Regs) { unsigned VReg; if (ObjectVT == MVT::f32) VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasP8Vector() ? &PPC::VSSRCRegClass : &PPC::F4RCRegClass); else VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ? &PPC::VSFRCRegClass : &PPC::F8RCRegClass); ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); ++FPR_idx; } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) { // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 // once we support fp <-> gpr moves. // This can only ever happen in the presence of f32 array types, // since otherwise we never run out of FPRs before running out // of GPRs. unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass); ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); if (ObjectVT == MVT::f32) { if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0)) ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal, DAG.getConstant(32, dl, MVT::i32)); ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal); } ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal); } else { if (CallConv == CallingConv::Fast) ComputeArgOffset(); needsLoad = true; } // When passing an array of floats, the array occupies consecutive // space in the argument area; only round up to the next doubleword // at the end of the array. Otherwise, each float takes 8 bytes. if (CallConv != CallingConv::Fast || needsLoad) { ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize; ArgOffset += ArgSize; if (Flags.isInConsecutiveRegsLast()) ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; } break; case MVT::v4f32: case MVT::v4i32: case MVT::v8i16: case MVT::v16i8: case MVT::v2f64: case MVT::v2i64: case MVT::v1i128: if (!Subtarget.hasQPX()) { // These can be scalar arguments or elements of a vector array type // passed directly. The latter are used to implement ELFv2 homogenous // vector aggregates. if (VR_idx != Num_VR_Regs) { unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ? MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) : MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); ++VR_idx; } else { if (CallConv == CallingConv::Fast) ComputeArgOffset(); needsLoad = true; } if (CallConv != CallingConv::Fast || needsLoad) ArgOffset += 16; break; } // not QPX assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 && "Invalid QPX parameter type"); /* fall through */ case MVT::v4f64: case MVT::v4i1: // QPX vectors are treated like their scalar floating-point subregisters // (except that they're larger). unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32; if (QFPR_idx != Num_QFPR_Regs) { const TargetRegisterClass *RC; switch (ObjectVT.getSimpleVT().SimpleTy) { case MVT::v4f64: RC = &PPC::QFRCRegClass; break; case MVT::v4f32: RC = &PPC::QSRCRegClass; break; default: RC = &PPC::QBRCRegClass; break; } unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC); ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); ++QFPR_idx; } else { if (CallConv == CallingConv::Fast) ComputeArgOffset(); needsLoad = true; } if (CallConv != CallingConv::Fast || needsLoad) ArgOffset += Sz; break; } // We need to load the argument to a virtual register if we determined // above that we ran out of physical registers of the appropriate type. if (needsLoad) { if (ObjSize < ArgSize && !isLittleEndian) CurArgOffset += ArgSize - ObjSize; int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable); SDValue FIN = DAG.getFrameIndex(FI, PtrVT); ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(), false, false, false, 0); } InVals.push_back(ArgVal); } // Area that is at least reserved in the caller of this function. unsigned MinReservedArea; if (HasParameterArea) MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize); else MinReservedArea = LinkageSize; // Set the size that is at least reserved in caller of this function. Tail // call optimized functions' reserved stack space needs to be aligned so that // taking the difference between two stack areas will result in an aligned // stack. MinReservedArea = EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); FuncInfo->setMinReservedArea(MinReservedArea); // If the function takes variable number of arguments, make a frame index for // the start of the first vararg value... for expansion of llvm.va_start. if (isVarArg) { int Depth = ArgOffset; FuncInfo->setVarArgsFrameIndex( MFI->CreateFixedObject(PtrByteSize, Depth, true)); SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); // If this function is vararg, store any remaining integer argument regs // to their spots on the stack so that they may be loaded by deferencing the // result of va_next. for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; GPR_idx < Num_GPR_Regs; ++GPR_idx) { unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo(), false, false, 0); MemOps.push_back(Store); // Increment the address by four for the next argument to store SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT); FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); } } if (!MemOps.empty()) Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); return Chain; } SDValue PPCTargetLowering::LowerFormalArguments_Darwin( SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { // TODO: add description of PPC stack frame format, or at least some docs. // MachineFunction &MF = DAG.getMachineFunction(); MachineFrameInfo *MFI = MF.getFrameInfo(); PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout()); bool isPPC64 = PtrVT == MVT::i64; // Potential tail calls could cause overwriting of argument stack slots. bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt && (CallConv == CallingConv::Fast)); unsigned PtrByteSize = isPPC64 ? 8 : 4; unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); unsigned ArgOffset = LinkageSize; // Area that is at least reserved in caller of this function. unsigned MinReservedArea = ArgOffset; static const MCPhysReg GPR_32[] = { // 32-bit registers. PPC::R3, PPC::R4, PPC::R5, PPC::R6, PPC::R7, PPC::R8, PPC::R9, PPC::R10, }; static const MCPhysReg GPR_64[] = { // 64-bit registers. PPC::X3, PPC::X4, PPC::X5, PPC::X6, PPC::X7, PPC::X8, PPC::X9, PPC::X10, }; static const MCPhysReg VR[] = { PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 }; const unsigned Num_GPR_Regs = array_lengthof(GPR_32); const unsigned Num_FPR_Regs = 13; const unsigned Num_VR_Regs = array_lengthof( VR); unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; // In 32-bit non-varargs functions, the stack space for vectors is after the // stack space for non-vectors. We do not use this space unless we have // too many vectors to fit in registers, something that only occurs in // constructed examples:), but we have to walk the arglist to figure // that out...for the pathological case, compute VecArgOffset as the // start of the vector parameter area. Computing VecArgOffset is the // entire point of the following loop. unsigned VecArgOffset = ArgOffset; if (!isVarArg && !isPPC64) { for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { EVT ObjectVT = Ins[ArgNo].VT; ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; if (Flags.isByVal()) { // ObjSize is the true size, ArgSize rounded up to multiple of regs. unsigned ObjSize = Flags.getByValSize(); unsigned ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; VecArgOffset += ArgSize; continue; } switch(ObjectVT.getSimpleVT().SimpleTy) { default: llvm_unreachable("Unhandled argument type!"); case MVT::i1: case MVT::i32: case MVT::f32: VecArgOffset += 4; break; case MVT::i64: // PPC64 case MVT::f64: // FIXME: We are guaranteed to be !isPPC64 at this point. // Does MVT::i64 apply? VecArgOffset += 8; break; case MVT::v4f32: case MVT::v4i32: case MVT::v8i16: case MVT::v16i8: // Nothing to do, we're only looking at Nonvector args here. break; } } } // We've found where the vector parameter area in memory is. Skip the // first 12 parameters; these don't use that memory. VecArgOffset = ((VecArgOffset+15)/16)*16; VecArgOffset += 12*16; // Add DAG nodes to load the arguments or copy them out of registers. On // entry to a function on PPC, the arguments start after the linkage area, // although the first ones are often in registers. SmallVector<SDValue, 8> MemOps; unsigned nAltivecParamsAtEnd = 0; Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin(); unsigned CurArgIdx = 0; for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) { SDValue ArgVal; bool needsLoad = false; EVT ObjectVT = Ins[ArgNo].VT; unsigned ObjSize = ObjectVT.getSizeInBits()/8; unsigned ArgSize = ObjSize; ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags; if (Ins[ArgNo].isOrigArg()) { std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx); CurArgIdx = Ins[ArgNo].getOrigArgIndex(); } unsigned CurArgOffset = ArgOffset; // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary. if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 || ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) { if (isVarArg || isPPC64) { MinReservedArea = ((MinReservedArea+15)/16)*16; MinReservedArea += CalculateStackSlotSize(ObjectVT, Flags, PtrByteSize); } else nAltivecParamsAtEnd++; } else // Calculate min reserved area. MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT, Flags, PtrByteSize); // FIXME the codegen can be much improved in some cases. // We do not have to keep everything in memory. if (Flags.isByVal()) { assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit"); // ObjSize is the true size, ArgSize rounded up to multiple of registers. ObjSize = Flags.getByValSize(); ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; // Objects of size 1 and 2 are right justified, everything else is // left justified. This means the memory address is adjusted forwards. if (ObjSize==1 || ObjSize==2) { CurArgOffset = CurArgOffset + (4 - ObjSize); } // The value of the object is its address. int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true); SDValue FIN = DAG.getFrameIndex(FI, PtrVT); InVals.push_back(FIN); if (ObjSize==1 || ObjSize==2) { if (GPR_idx != Num_GPR_Regs) { unsigned VReg; if (isPPC64) VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); else VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16; SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo(&*FuncArg), ObjType, false, false, 0); MemOps.push_back(Store); ++GPR_idx; } ArgOffset += PtrByteSize; continue; } for (unsigned j = 0; j < ArgSize; j += PtrByteSize) { // Store whatever pieces of the object are in registers // to memory. ArgOffset will be the address of the beginning // of the object. if (GPR_idx != Num_GPR_Regs) { unsigned VReg; if (isPPC64) VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); else VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true); SDValue FIN = DAG.getFrameIndex(FI, PtrVT); SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo(&*FuncArg, j), false, false, 0); MemOps.push_back(Store); ++GPR_idx; ArgOffset += PtrByteSize; } else { ArgOffset += ArgSize - (ArgOffset-CurArgOffset); break; } } continue; } switch (ObjectVT.getSimpleVT().SimpleTy) { default: llvm_unreachable("Unhandled argument type!"); case MVT::i1: case MVT::i32: if (!isPPC64) { if (GPR_idx != Num_GPR_Regs) { unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32); if (ObjectVT == MVT::i1) ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal); ++GPR_idx; } else { needsLoad = true; ArgSize = PtrByteSize; } // All int arguments reserve stack space in the Darwin ABI. ArgOffset += PtrByteSize; break; } // FALLTHROUGH case MVT::i64: // PPC64 if (GPR_idx != Num_GPR_Regs) { unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64); if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1) // PPC64 passes i8, i16, and i32 values in i64 registers. Promote // value to MVT::i64 and then truncate to the correct register size. ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl); ++GPR_idx; } else { needsLoad = true; ArgSize = PtrByteSize; } // All int arguments reserve stack space in the Darwin ABI. ArgOffset += 8; break; case MVT::f32: case MVT::f64: // Every 4 bytes of argument space consumes one of the GPRs available for // argument passing. if (GPR_idx != Num_GPR_Regs) { ++GPR_idx; if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64) ++GPR_idx; } if (FPR_idx != Num_FPR_Regs) { unsigned VReg; if (ObjectVT == MVT::f32) VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass); else VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass); ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); ++FPR_idx; } else { needsLoad = true; } // All FP arguments reserve stack space in the Darwin ABI. ArgOffset += isPPC64 ? 8 : ObjSize; break; case MVT::v4f32: case MVT::v4i32: case MVT::v8i16: case MVT::v16i8: // Note that vector arguments in registers don't reserve stack space, // except in varargs functions. if (VR_idx != Num_VR_Regs) { unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass); ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT); if (isVarArg) { while ((ArgOffset % 16) != 0) { ArgOffset += PtrByteSize; if (GPR_idx != Num_GPR_Regs) GPR_idx++; } ArgOffset += 16; GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64? } ++VR_idx; } else { if (!isVarArg && !isPPC64) { // Vectors go after all the nonvectors. CurArgOffset = VecArgOffset; VecArgOffset += 16; } else { // Vectors are aligned. ArgOffset = ((ArgOffset+15)/16)*16; CurArgOffset = ArgOffset; ArgOffset += 16; } needsLoad = true; } break; } // We need to load the argument to a virtual register if we determined above // that we ran out of physical registers of the appropriate type. if (needsLoad) { int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset + (ArgSize - ObjSize), isImmutable); SDValue FIN = DAG.getFrameIndex(FI, PtrVT); ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(), false, false, false, 0); } InVals.push_back(ArgVal); } // Allow for Altivec parameters at the end, if needed. if (nAltivecParamsAtEnd) { MinReservedArea = ((MinReservedArea+15)/16)*16; MinReservedArea += 16*nAltivecParamsAtEnd; } // Area that is at least reserved in the caller of this function. MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize); // Set the size that is at least reserved in caller of this function. Tail // call optimized functions' reserved stack space needs to be aligned so that // taking the difference between two stack areas will result in an aligned // stack. MinReservedArea = EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea); FuncInfo->setMinReservedArea(MinReservedArea); // If the function takes variable number of arguments, make a frame index for // the start of the first vararg value... for expansion of llvm.va_start. if (isVarArg) { int Depth = ArgOffset; FuncInfo->setVarArgsFrameIndex( MFI->CreateFixedObject(PtrVT.getSizeInBits()/8, Depth, true)); SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT); // If this function is vararg, store any remaining integer argument regs // to their spots on the stack so that they may be loaded by deferencing the // result of va_next. for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) { unsigned VReg; if (isPPC64) VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass); else VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass); SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT); SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo(), false, false, 0); MemOps.push_back(Store); // Increment the address by four for the next argument to store SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT); FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff); } } if (!MemOps.empty()) Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps); return Chain; } /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be /// adjusted to accommodate the arguments for the tailcall. static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall, unsigned ParamSize) { if (!isTailCall) return 0; PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>(); unsigned CallerMinReservedArea = FI->getMinReservedArea(); int SPDiff = (int)CallerMinReservedArea - (int)ParamSize; // Remember only if the new adjustement is bigger. if (SPDiff < FI->getTailCallSPDelta()) FI->setTailCallSPDelta(SPDiff); return SPDiff; } /// IsEligibleForTailCallOptimization - Check whether the call is eligible /// for tail call optimization. Targets which want to do tail call /// optimization should implement this function. bool PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG& DAG) const { if (!getTargetMachine().Options.GuaranteedTailCallOpt) return false; // Variable argument functions are not supported. if (isVarArg) return false; MachineFunction &MF = DAG.getMachineFunction(); CallingConv::ID CallerCC = MF.getFunction()->getCallingConv(); if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) { // Functions containing by val parameters are not supported. for (unsigned i = 0; i != Ins.size(); i++) { ISD::ArgFlagsTy Flags = Ins[i].Flags; if (Flags.isByVal()) return false; } // Non-PIC/GOT tail calls are supported. if (getTargetMachine().getRelocationModel() != Reloc::PIC_) return true; // At the moment we can only do local tail calls (in same module, hidden // or protected) if we are generating PIC. if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) return G->getGlobal()->hasHiddenVisibility() || G->getGlobal()->hasProtectedVisibility(); } return false; } /// isCallCompatibleAddress - Return the immediate to use if the specified /// 32-bit value is representable in the immediate field of a BxA instruction. static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) { ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); if (!C) return nullptr; int Addr = C->getZExtValue(); if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero. SignExtend32<26>(Addr) != Addr) return nullptr; // Top 6 bits have to be sext of immediate. return DAG.getConstant((int)C->getZExtValue() >> 2, SDLoc(Op), DAG.getTargetLoweringInfo().getPointerTy( DAG.getDataLayout())).getNode(); } namespace { struct TailCallArgumentInfo { SDValue Arg; SDValue FrameIdxOp; int FrameIdx; TailCallArgumentInfo() : FrameIdx(0) {} }; } /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot. static void StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG, SDValue Chain, const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs, SmallVectorImpl<SDValue> &MemOpChains, SDLoc dl) { for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) { SDValue Arg = TailCallArgs[i].Arg; SDValue FIN = TailCallArgs[i].FrameIdxOp; int FI = TailCallArgs[i].FrameIdx; // Store relative to framepointer. MemOpChains.push_back(DAG.getStore( Chain, dl, Arg, FIN, MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), false, false, 0)); } } /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to /// the appropriate stack slot for the tail call optimized function call. static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue OldRetAddr, SDValue OldFP, int SPDiff, bool isPPC64, bool isDarwinABI, SDLoc dl) { if (SPDiff) { // Calculate the new stack slot for the return address. int SlotSize = isPPC64 ? 8 : 4; const PPCFrameLowering *FL = MF.getSubtarget<PPCSubtarget>().getFrameLowering(); int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset(); int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewRetAddrLoc, true); EVT VT = isPPC64 ? MVT::i64 : MVT::i32; SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT); Chain = DAG.getStore( Chain, dl, OldRetAddr, NewRetAddrFrIdx, MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), NewRetAddr), false, false, 0); // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack // slot as the FP is never overwritten. if (isDarwinABI) { int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset(); int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc, true); SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT); Chain = DAG.getStore( Chain, dl, OldFP, NewFramePtrIdx, MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), NewFPIdx), false, false, 0); } } return Chain; } /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate /// the position of the argument. static void CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64, SDValue Arg, int SPDiff, unsigned ArgOffset, SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) { int Offset = ArgOffset + SPDiff; uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8; int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true); EVT VT = isPPC64 ? MVT::i64 : MVT::i32; SDValue FIN = DAG.getFrameIndex(FI, VT); TailCallArgumentInfo Info; Info.Arg = Arg; Info.FrameIdxOp = FIN; Info.FrameIdx = FI; TailCallArguments.push_back(Info); } /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address /// stack slot. Returns the chain as result and the loaded frame pointers in /// LROpOut/FPOpout. Used when tail calling. SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG, int SPDiff, SDValue Chain, SDValue &LROpOut, SDValue &FPOpOut, bool isDarwinABI, SDLoc dl) const { if (SPDiff) { // Load the LR and FP stack slot for later adjusting. EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32; LROpOut = getReturnAddrFrameIndex(DAG); LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(), false, false, false, 0); Chain = SDValue(LROpOut.getNode(), 1); // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack // slot as the FP is never overwritten. if (isDarwinABI) { FPOpOut = getFramePointerFrameIndex(DAG); FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(), false, false, false, 0); Chain = SDValue(FPOpOut.getNode(), 1); } } return Chain; } /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified /// by "Src" to address "Dst" of size "Size". Alignment information is /// specified by the specific parameter attribute. The copy will be passed as /// a byval function parameter. /// Sometimes what we are copying is the end of a larger object, the part that /// does not fit in registers. static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain, ISD::ArgFlagsTy Flags, SelectionDAG &DAG, SDLoc dl) { SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32); return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(), false, false, false, MachinePointerInfo(), MachinePointerInfo()); } /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of /// tail calls. static void LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg, SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64, bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains, SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, SDLoc dl) { EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); if (!isTailCall) { if (isVector) { SDValue StackPtr; if (isPPC64) StackPtr = DAG.getRegister(PPC::X1, MVT::i64); else StackPtr = DAG.getRegister(PPC::R1, MVT::i32); PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, DAG.getConstant(ArgOffset, dl, PtrVT)); } MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo(), false, false, 0)); // Calculate and remember argument location. } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset, TailCallArguments); } static void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain, SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes, SDValue LROp, SDValue FPOp, bool isDarwinABI, SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) { MachineFunction &MF = DAG.getMachineFunction(); // Emit a sequence of copyto/copyfrom virtual registers for arguments that // might overwrite each other in case of tail call optimization. SmallVector<SDValue, 8> MemOpChains2; // Do not flag preceding copytoreg stuff together with the following stuff. InFlag = SDValue(); StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments, MemOpChains2, dl); if (!MemOpChains2.empty()) Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2); // Store the return address to the appropriate stack slot. Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff, isPPC64, isDarwinABI, dl); // Emit callseq_end just before tailcall node. Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), DAG.getIntPtrConstant(0, dl, true), InFlag, dl); InFlag = Chain.getValue(1); } // Is this global address that of a function that can be called by name? (as // opposed to something that must hold a descriptor for an indirect call). static bool isFunctionGlobalAddress(SDValue Callee) { if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { if (Callee.getOpcode() == ISD::GlobalTLSAddress || Callee.getOpcode() == ISD::TargetGlobalTLSAddress) return false; return G->getGlobal()->getType()->getElementType()->isFunctionTy(); } return false; } static unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain, SDValue CallSeqStart, SDLoc dl, int SPDiff, bool isTailCall, bool IsPatchPoint, bool hasNest, SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass, SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys, ImmutableCallSite *CS, const PPCSubtarget &Subtarget) { bool isPPC64 = Subtarget.isPPC64(); bool isSVR4ABI = Subtarget.isSVR4ABI(); bool isELFv2ABI = Subtarget.isELFv2ABI(); EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); NodeTys.push_back(MVT::Other); // Returns a chain NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use. unsigned CallOpc = PPCISD::CALL; bool needIndirectCall = true; if (!isSVR4ABI || !isPPC64) if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) { // If this is an absolute destination address, use the munged value. Callee = SDValue(Dest, 0); needIndirectCall = false; } if (isFunctionGlobalAddress(Callee)) { GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee); // A call to a TLS address is actually an indirect call to a // thread-specific pointer. unsigned OpFlags = 0; if ((DAG.getTarget().getRelocationModel() != Reloc::Static && (Subtarget.getTargetTriple().isMacOSX() && Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) && !G->getGlobal()->isStrongDefinitionForLinker()) || (Subtarget.isTargetELF() && !isPPC64 && !G->getGlobal()->hasLocalLinkage() && DAG.getTarget().getRelocationModel() == Reloc::PIC_)) { // PC-relative references to external symbols should go through $stub, // unless we're building with the leopard linker or later, which // automatically synthesizes these stubs. OpFlags = PPCII::MO_PLT_OR_STUB; } // If the callee is a GlobalAddress/ExternalSymbol node (quite common, // every direct call is) turn it into a TargetGlobalAddress / // TargetExternalSymbol node so that legalize doesn't hack it. Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, Callee.getValueType(), 0, OpFlags); needIndirectCall = false; } if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { unsigned char OpFlags = 0; if ((DAG.getTarget().getRelocationModel() != Reloc::Static && (Subtarget.getTargetTriple().isMacOSX() && Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) || (Subtarget.isTargetELF() && !isPPC64 && DAG.getTarget().getRelocationModel() == Reloc::PIC_)) { // PC-relative references to external symbols should go through $stub, // unless we're building with the leopard linker or later, which // automatically synthesizes these stubs. OpFlags = PPCII::MO_PLT_OR_STUB; } Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(), OpFlags); needIndirectCall = false; } if (IsPatchPoint) { // We'll form an invalid direct call when lowering a patchpoint; the full // sequence for an indirect call is complicated, and many of the // instructions introduced might have side effects (and, thus, can't be // removed later). The call itself will be removed as soon as the // argument/return lowering is complete, so the fact that it has the wrong // kind of operands should not really matter. needIndirectCall = false; } if (needIndirectCall) { // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair // to do the call, we can't use PPCISD::CALL. SDValue MTCTROps[] = {Chain, Callee, InFlag}; if (isSVR4ABI && isPPC64 && !isELFv2ABI) { // Function pointers in the 64-bit SVR4 ABI do not point to the function // entry point, but to the function descriptor (the function entry point // address is part of the function descriptor though). // The function descriptor is a three doubleword structure with the // following fields: function entry point, TOC base address and // environment pointer. // Thus for a call through a function pointer, the following actions need // to be performed: // 1. Save the TOC of the caller in the TOC save area of its stack // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()). // 2. Load the address of the function entry point from the function // descriptor. // 3. Load the TOC of the callee from the function descriptor into r2. // 4. Load the environment pointer from the function descriptor into // r11. // 5. Branch to the function entry point address. // 6. On return of the callee, the TOC of the caller needs to be // restored (this is done in FinishCall()). // // The loads are scheduled at the beginning of the call sequence, and the // register copies are flagged together to ensure that no other // operations can be scheduled in between. E.g. without flagging the // copies together, a TOC access in the caller could be scheduled between // the assignment of the callee TOC and the branch to the callee, which // results in the TOC access going through the TOC of the callee instead // of going through the TOC of the caller, which leads to incorrect code. // Load the address of the function entry point from the function // descriptor. SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1); if (LDChain.getValueType() == MVT::Glue) LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2); bool LoadsInv = Subtarget.hasInvariantFunctionDescriptors(); MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr); SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI, false, false, LoadsInv, 8); // Load environment pointer into r11. SDValue PtrOff = DAG.getIntPtrConstant(16, dl); SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff); SDValue LoadEnvPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16), false, false, LoadsInv, 8); SDValue TOCOff = DAG.getIntPtrConstant(8, dl); SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff); SDValue TOCPtr = DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8), false, false, LoadsInv, 8); setUsesTOCBasePtr(DAG); SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, InFlag); Chain = TOCVal.getValue(0); InFlag = TOCVal.getValue(1); // If the function call has an explicit 'nest' parameter, it takes the // place of the environment pointer. if (!hasNest) { SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, InFlag); Chain = EnvVal.getValue(0); InFlag = EnvVal.getValue(1); } MTCTROps[0] = Chain; MTCTROps[1] = LoadFuncPtr; MTCTROps[2] = InFlag; } Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2)); InFlag = Chain.getValue(1); NodeTys.clear(); NodeTys.push_back(MVT::Other); NodeTys.push_back(MVT::Glue); Ops.push_back(Chain); CallOpc = PPCISD::BCTRL; Callee.setNode(nullptr); // Add use of X11 (holding environment pointer) if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest) Ops.push_back(DAG.getRegister(PPC::X11, PtrVT)); // Add CTR register as callee so a bctr can be emitted later. if (isTailCall) Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT)); } // If this is a direct call, pass the chain and the callee. if (Callee.getNode()) { Ops.push_back(Chain); Ops.push_back(Callee); } // If this is a tail call add stack pointer delta. if (isTailCall) Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32)); // Add argument registers to the end of the list so that they are known live // into the call. for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) Ops.push_back(DAG.getRegister(RegsToPass[i].first, RegsToPass[i].second.getValueType())); // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live // into the call. if (isSVR4ABI && isPPC64 && !IsPatchPoint) { setUsesTOCBasePtr(DAG); Ops.push_back(DAG.getRegister(PPC::X2, PtrVT)); } return CallOpc; } static bool isLocalCall(const SDValue &Callee) { if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) return G->getGlobal()->isStrongDefinitionForLinker(); return false; } SDValue PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { SmallVector<CCValAssign, 16> RVLocs; CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, *DAG.getContext()); CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC); // Copy all of the result registers out of their specified physreg. for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) { CCValAssign &VA = RVLocs[i]; assert(VA.isRegLoc() && "Can only return in registers!"); SDValue Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(), InFlag); Chain = Val.getValue(1); InFlag = Val.getValue(2); switch (VA.getLocInfo()) { default: llvm_unreachable("Unknown loc info!"); case CCValAssign::Full: break; case CCValAssign::AExt: Val = DAG.getNode(ISD::TRUNCATE, 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; } InVals.push_back(Val); } return Chain; } SDValue PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl, bool isTailCall, bool isVarArg, bool IsPatchPoint, bool hasNest, SelectionDAG &DAG, SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag, SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff, unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins, SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const { std::vector<EVT> NodeTys; SmallVector<SDValue, 8> Ops; unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl, SPDiff, isTailCall, IsPatchPoint, hasNest, RegsToPass, Ops, NodeTys, CS, Subtarget); // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64()) Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32)); // When performing tail call optimization the callee pops its arguments off // the stack. Account for this here so these bytes can be pushed back on in // PPCFrameLowering::eliminateCallFramePseudoInstr. int BytesCalleePops = (CallConv == CallingConv::Fast && getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0; // Add a register mask operand representing the call-preserved registers. const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); const uint32_t *Mask = TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv); assert(Mask && "Missing call preserved mask for calling convention"); Ops.push_back(DAG.getRegisterMask(Mask)); if (InFlag.getNode()) Ops.push_back(InFlag); // Emit tail call. if (isTailCall) { assert(((Callee.getOpcode() == ISD::Register && cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) || Callee.getOpcode() == ISD::TargetExternalSymbol || Callee.getOpcode() == ISD::TargetGlobalAddress || isa<ConstantSDNode>(Callee)) && "Expecting an global address, external symbol, absolute value or register"); DAG.getMachineFunction().getFrameInfo()->setHasTailCall(); return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops); } // Add a NOP immediately after the branch instruction when using the 64-bit // SVR4 ABI. At link time, if caller and callee are in a different module and // thus have a different TOC, the call will be replaced with a call to a stub // function which saves the current TOC, loads the TOC of the callee and // branches to the callee. The NOP will be replaced with a load instruction // which restores the TOC of the caller from the TOC save slot of the current // stack frame. If caller and callee belong to the same module (and have the // same TOC), the NOP will remain unchanged. if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() && !IsPatchPoint) { if (CallOpc == PPCISD::BCTRL) { // This is a call through a function pointer. // Restore the caller TOC from the save area into R2. // See PrepareCall() for more information about calls through function // pointers in the 64-bit SVR4 ABI. // We are using a target-specific load with r2 hard coded, because the // result of a target-independent load would never go directly into r2, // since r2 is a reserved register (which prevents the register allocator // from allocating it), resulting in an additional register being // allocated and an unnecessary move instruction being generated. CallOpc = PPCISD::BCTRL_LOAD_TOC; EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT); unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff); // The address needs to go after the chain input but before the flag (or // any other variadic arguments). Ops.insert(std::next(Ops.begin()), AddTOC); } else if ((CallOpc == PPCISD::CALL) && (!isLocalCall(Callee) || DAG.getTarget().getRelocationModel() == Reloc::PIC_)) // Otherwise insert NOP for non-local calls. CallOpc = PPCISD::CALL_NOP; } Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops); InFlag = Chain.getValue(1); Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), DAG.getIntPtrConstant(BytesCalleePops, dl, true), InFlag, dl); if (!Ins.empty()) InFlag = Chain.getValue(1); return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG, InVals); } SDValue PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI, SmallVectorImpl<SDValue> &InVals) const { SelectionDAG &DAG = CLI.DAG; SDLoc &dl = CLI.DL; SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; SmallVectorImpl<ISD::InputArg> &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 IsPatchPoint = CLI.IsPatchPoint; ImmutableCallSite *CS = CLI.CS; if (isTailCall) isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, Ins, DAG); if (!isTailCall && CS && CS->isMustTailCall()) report_fatal_error("failed to perform tail call elimination on a call " "site marked musttail"); if (Subtarget.isSVR4ABI()) { if (Subtarget.isPPC64()) return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg, isTailCall, IsPatchPoint, Outs, OutVals, Ins, dl, DAG, InVals, CS); else return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg, isTailCall, IsPatchPoint, Outs, OutVals, Ins, dl, DAG, InVals, CS); } return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg, isTailCall, IsPatchPoint, Outs, OutVals, Ins, dl, DAG, InVals, CS); } SDValue PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, bool isTailCall, bool IsPatchPoint, const SmallVectorImpl<ISD::OutputArg> &Outs, const SmallVectorImpl<SDValue> &OutVals, const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const { // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description // of the 32-bit SVR4 ABI stack frame layout. assert((CallConv == CallingConv::C || CallConv == CallingConv::Fast) && "Unknown calling convention!"); unsigned PtrByteSize = 4; MachineFunction &MF = DAG.getMachineFunction(); // Mark this function as potentially containing a function that contains a // tail call. As a consequence the frame pointer will be used for dynamicalloc // and restoring the callers stack pointer in this functions epilog. This is // done because by tail calling the called function might overwrite the value // in this function's (MF) stack pointer stack slot 0(SP). if (getTargetMachine().Options.GuaranteedTailCallOpt && CallConv == CallingConv::Fast) MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); // Count how many bytes are to be pushed on the stack, including the linkage // area, parameter list area and the part of the local variable space which // contains copies of aggregates which are passed by value. // Assign locations to all of the outgoing arguments. SmallVector<CCValAssign, 16> ArgLocs; CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext()); // Reserve space for the linkage area on the stack. CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(), PtrByteSize); if (isVarArg) { // Handle fixed and variable vector arguments differently. // Fixed vector arguments go into registers as long as registers are // available. Variable vector arguments always go into memory. unsigned NumArgs = Outs.size(); for (unsigned i = 0; i != NumArgs; ++i) { MVT ArgVT = Outs[i].VT; ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; bool Result; if (Outs[i].IsFixed) { Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); } else { Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); } if (Result) { #ifndef NDEBUG errs() << "Call operand #" << i << " has unhandled type " << EVT(ArgVT).getEVTString() << "\n"; #endif llvm_unreachable(nullptr); } } } else { // All arguments are treated the same. CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4); } // Assign locations to all of the outgoing aggregate by value arguments. SmallVector<CCValAssign, 16> ByValArgLocs; CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(), ByValArgLocs, *DAG.getContext()); // Reserve stack space for the allocations in CCInfo. CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize); CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal); // Size of the linkage area, parameter list area and the part of the local // space variable where copies of aggregates which are passed by value are // stored. unsigned NumBytes = CCByValInfo.getNextStackOffset(); // Calculate by how many bytes the stack has to be adjusted in case of tail // call optimization. int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); // Adjust the stack pointer for the new arguments... // These operations are automatically eliminated by the prolog/epilog pass Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), dl); SDValue CallSeqStart = Chain; // Load the return address and frame pointer so it can be moved somewhere else // later. SDValue LROp, FPOp; Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false, dl); // Set up a copy of the stack pointer for use loading and storing any // arguments that may not fit in the registers available for argument // passing. SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32); SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; SmallVector<TailCallArgumentInfo, 8> TailCallArguments; SmallVector<SDValue, 8> MemOpChains; bool seenFloatArg = false; // Walk the register/memloc assignments, inserting copies/loads. for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { CCValAssign &VA = ArgLocs[i]; SDValue Arg = OutVals[i]; ISD::ArgFlagsTy Flags = Outs[i].Flags; if (Flags.isByVal()) { // Argument is an aggregate which is passed by value, thus we need to // create a copy of it in the local variable space of the current stack // frame (which is the stack frame of the caller) and pass the address of // this copy to the callee. assert((j < ByValArgLocs.size()) && "Index out of bounds!"); CCValAssign &ByValVA = ByValArgLocs[j++]; assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!"); // Memory reserved in the local variable space of the callers stack frame. unsigned LocMemOffset = ByValVA.getLocMemOffset(); SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), StackPtr, PtrOff); // Create a copy of the argument in the local area of the current // stack frame. SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, CallSeqStart.getNode()->getOperand(0), Flags, DAG, dl); // This must go outside the CALLSEQ_START..END. SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, CallSeqStart.getNode()->getOperand(1), SDLoc(MemcpyCall)); DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), NewCallSeqStart.getNode()); Chain = CallSeqStart = NewCallSeqStart; // Pass the address of the aggregate copy on the stack either in a // physical register or in the parameter list area of the current stack // frame to the callee. Arg = PtrOff; } if (VA.isRegLoc()) { if (Arg.getValueType() == MVT::i1) Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg); seenFloatArg |= VA.getLocVT().isFloatingPoint(); // Put argument in a physical register. RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); } else { // Put argument in the parameter list area of the current stack frame. assert(VA.isMemLoc()); unsigned LocMemOffset = VA.getLocMemOffset(); if (!isTailCall) { SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl); PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()), StackPtr, PtrOff); MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo(), false, false, 0)); } else { // Calculate and remember argument location. CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset, TailCallArguments); } } } 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 (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, RegsToPass[i].second, InFlag); InFlag = Chain.getValue(1); } // Set CR bit 6 to true if this is a vararg call with floating args passed in // registers. if (isVarArg) { SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue); SDValue Ops[] = { Chain, InFlag }; Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET, dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1)); InFlag = Chain.getValue(1); } if (isTailCall) PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp, false, TailCallArguments); return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, /* unused except on PPC64 ELFv1 */ false, DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, NumBytes, Ins, InVals, CS); } // Copy an argument into memory, being careful to do this outside the // call sequence for the call to which the argument belongs. SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags, SelectionDAG &DAG, SDLoc dl) const { SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff, CallSeqStart.getNode()->getOperand(0), Flags, DAG, dl); // The MEMCPY must go outside the CALLSEQ_START..END. SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, CallSeqStart.getNode()->getOperand(1), SDLoc(MemcpyCall)); DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), NewCallSeqStart.getNode()); return NewCallSeqStart; } SDValue PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, bool isTailCall, bool IsPatchPoint, const SmallVectorImpl<ISD::OutputArg> &Outs, const SmallVectorImpl<SDValue> &OutVals, const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const { bool isELFv2ABI = Subtarget.isELFv2ABI(); bool isLittleEndian = Subtarget.isLittleEndian(); unsigned NumOps = Outs.size(); bool hasNest = false; EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); unsigned PtrByteSize = 8; MachineFunction &MF = DAG.getMachineFunction(); // Mark this function as potentially containing a function that contains a // tail call. As a consequence the frame pointer will be used for dynamicalloc // and restoring the callers stack pointer in this functions epilog. This is // done because by tail calling the called function might overwrite the value // in this function's (MF) stack pointer stack slot 0(SP). if (getTargetMachine().Options.GuaranteedTailCallOpt && CallConv == CallingConv::Fast) MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); assert(!(CallConv == CallingConv::Fast && isVarArg) && "fastcc not supported on varargs functions"); // Count how many bytes are to be pushed on the stack, including the linkage // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage // area is 32 bytes reserved space for [SP][CR][LR][TOC]. unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); unsigned NumBytes = LinkageSize; unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; unsigned &QFPR_idx = FPR_idx; static const MCPhysReg GPR[] = { PPC::X3, PPC::X4, PPC::X5, PPC::X6, PPC::X7, PPC::X8, PPC::X9, PPC::X10, }; static const MCPhysReg VR[] = { PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 }; static const MCPhysReg VSRH[] = { PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8, PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13 }; const unsigned NumGPRs = array_lengthof(GPR); const unsigned NumFPRs = 13; const unsigned NumVRs = array_lengthof(VR); const unsigned NumQFPRs = NumFPRs; // When using the fast calling convention, we don't provide backing for // arguments that will be in registers. unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0; // Add up all the space actually used. for (unsigned i = 0; i != NumOps; ++i) { ISD::ArgFlagsTy Flags = Outs[i].Flags; EVT ArgVT = Outs[i].VT; EVT OrigVT = Outs[i].ArgVT; if (Flags.isNest()) continue; if (CallConv == CallingConv::Fast) { if (Flags.isByVal()) NumGPRsUsed += (Flags.getByValSize()+7)/8; else switch (ArgVT.getSimpleVT().SimpleTy) { default: llvm_unreachable("Unexpected ValueType for argument!"); case MVT::i1: case MVT::i32: case MVT::i64: if (++NumGPRsUsed <= NumGPRs) continue; break; case MVT::v4i32: case MVT::v8i16: case MVT::v16i8: case MVT::v2f64: case MVT::v2i64: case MVT::v1i128: if (++NumVRsUsed <= NumVRs) continue; break; case MVT::v4f32: // When using QPX, this is handled like a FP register, otherwise, it // is an Altivec register. if (Subtarget.hasQPX()) { if (++NumFPRsUsed <= NumFPRs) continue; } else { if (++NumVRsUsed <= NumVRs) continue; } break; case MVT::f32: case MVT::f64: case MVT::v4f64: // QPX case MVT::v4i1: // QPX if (++NumFPRsUsed <= NumFPRs) continue; break; } } /* Respect alignment of argument on the stack. */ unsigned Align = CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); NumBytes = ((NumBytes + Align - 1) / Align) * Align; NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); if (Flags.isInConsecutiveRegsLast()) NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; } unsigned NumBytesActuallyUsed = NumBytes; // The prolog code of the callee may store up to 8 GPR argument registers to // the stack, allowing va_start to index over them in memory if its varargs. // Because we cannot tell if this is needed on the caller side, we have to // conservatively assume that it is needed. As such, make sure we have at // least enough stack space for the caller to store the 8 GPRs. // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area. NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); // Tail call needs the stack to be aligned. if (getTargetMachine().Options.GuaranteedTailCallOpt && CallConv == CallingConv::Fast) NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); // Calculate by how many bytes the stack has to be adjusted in case of tail // call optimization. int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); // To protect arguments on the stack from being clobbered in a tail call, // force all the loads to happen before doing any other lowering. if (isTailCall) Chain = DAG.getStackArgumentTokenFactor(Chain); // Adjust the stack pointer for the new arguments... // These operations are automatically eliminated by the prolog/epilog pass Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), dl); SDValue CallSeqStart = Chain; // Load the return address and frame pointer so it can be move somewhere else // later. SDValue LROp, FPOp; Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true, dl); // Set up a copy of the stack pointer for use loading and storing any // arguments that may not fit in the registers available for argument // passing. SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64); // Figure out which arguments are going to go in registers, and which in // memory. Also, if this is a vararg function, floating point operations // must be stored to our stack, and loaded into integer regs as well, if // any integer regs are available for argument passing. unsigned ArgOffset = LinkageSize; SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; SmallVector<TailCallArgumentInfo, 8> TailCallArguments; SmallVector<SDValue, 8> MemOpChains; for (unsigned i = 0; i != NumOps; ++i) { SDValue Arg = OutVals[i]; ISD::ArgFlagsTy Flags = Outs[i].Flags; EVT ArgVT = Outs[i].VT; EVT OrigVT = Outs[i].ArgVT; // PtrOff will be used to store the current argument to the stack if a // register cannot be found for it. SDValue PtrOff; // We re-align the argument offset for each argument, except when using the // fast calling convention, when we need to make sure we do that only when // we'll actually use a stack slot. auto ComputePtrOff = [&]() { /* Respect alignment of argument on the stack. */ unsigned Align = CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize); ArgOffset = ((ArgOffset + Align - 1) / Align) * Align; PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); }; if (CallConv != CallingConv::Fast) { ComputePtrOff(); /* Compute GPR index associated with argument offset. */ GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize; GPR_idx = std::min(GPR_idx, NumGPRs); } // Promote integers to 64-bit values. if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) { // FIXME: Should this use ANY_EXTEND if neither sext nor zext? unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); } // FIXME memcpy is used way more than necessary. Correctness first. // Note: "by value" is code for passing a structure by value, not // basic types. if (Flags.isByVal()) { // Note: Size includes alignment padding, so // struct x { short a; char b; } // will have Size = 4. With #pragma pack(1), it will have Size = 3. // These are the proper values we need for right-justifying the // aggregate in a parameter register. unsigned Size = Flags.getByValSize(); // An empty aggregate parameter takes up no storage and no // registers. if (Size == 0) continue; if (CallConv == CallingConv::Fast) ComputePtrOff(); // All aggregates smaller than 8 bytes must be passed right-justified. if (Size==1 || Size==2 || Size==4) { EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32); if (GPR_idx != NumGPRs) { SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, MachinePointerInfo(), VT, false, false, false, 0); MemOpChains.push_back(Load.getValue(1)); RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); ArgOffset += PtrByteSize; continue; } } if (GPR_idx == NumGPRs && Size < 8) { SDValue AddPtr = PtrOff; if (!isLittleEndian) { SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, PtrOff.getValueType()); AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); } Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, CallSeqStart, Flags, DAG, dl); ArgOffset += PtrByteSize; continue; } // Copy entire object into memory. There are cases where gcc-generated // code assumes it is there, even if it could be put entirely into // registers. (This is not what the doc says.) // FIXME: The above statement is likely due to a misunderstanding of the // documents. All arguments must be copied into the parameter area BY // THE CALLEE in the event that the callee takes the address of any // formal argument. That has not yet been implemented. However, it is // reasonable to use the stack area as a staging area for the register // load. // Skip this for small aggregates, as we will use the same slot for a // right-justified copy, below. if (Size >= 8) Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, CallSeqStart, Flags, DAG, dl); // When a register is available, pass a small aggregate right-justified. if (Size < 8 && GPR_idx != NumGPRs) { // The easiest way to get this right-justified in a register // is to copy the structure into the rightmost portion of a // local variable slot, then load the whole slot into the // register. // FIXME: The memcpy seems to produce pretty awful code for // small aggregates, particularly for packed ones. // FIXME: It would be preferable to use the slot in the // parameter save area instead of a new local variable. SDValue AddPtr = PtrOff; if (!isLittleEndian) { SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType()); AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); } Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, CallSeqStart, Flags, DAG, dl); // Load the slot into the register. SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo(), false, false, false, 0); MemOpChains.push_back(Load.getValue(1)); RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); // Done with this argument. ArgOffset += PtrByteSize; continue; } // For aggregates larger than PtrByteSize, copy the pieces of the // object that fit into registers from the parameter save area. for (unsigned j=0; j<Size; j+=PtrByteSize) { SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); if (GPR_idx != NumGPRs) { SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(), false, false, false, 0); MemOpChains.push_back(Load.getValue(1)); RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); ArgOffset += PtrByteSize; } else { ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; break; } } continue; } switch (Arg.getSimpleValueType().SimpleTy) { default: llvm_unreachable("Unexpected ValueType for argument!"); case MVT::i1: case MVT::i32: case MVT::i64: if (Flags.isNest()) { // The 'nest' parameter, if any, is passed in R11. RegsToPass.push_back(std::make_pair(PPC::X11, Arg)); hasNest = true; break; } // These can be scalar arguments or elements of an integer array type // passed directly. Clang may use those instead of "byval" aggregate // types to avoid forcing arguments to memory unnecessarily. if (GPR_idx != NumGPRs) { RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); } else { if (CallConv == CallingConv::Fast) ComputePtrOff(); LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, true, isTailCall, false, MemOpChains, TailCallArguments, dl); if (CallConv == CallingConv::Fast) ArgOffset += PtrByteSize; } if (CallConv != CallingConv::Fast) ArgOffset += PtrByteSize; break; case MVT::f32: case MVT::f64: { // These can be scalar arguments or elements of a float array type // passed directly. The latter are used to implement ELFv2 homogenous // float aggregates. // Named arguments go into FPRs first, and once they overflow, the // remaining arguments go into GPRs and then the parameter save area. // Unnamed arguments for vararg functions always go to GPRs and // then the parameter save area. For now, put all arguments to vararg // routines always in both locations (FPR *and* GPR or stack slot). bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs; bool NeededLoad = false; // First load the argument into the next available FPR. if (FPR_idx != NumFPRs) RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); // Next, load the argument into GPR or stack slot if needed. if (!NeedGPROrStack) ; else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) { // FIXME: We may want to re-enable this for CallingConv::Fast on the P8 // once we support fp <-> gpr moves. // In the non-vararg case, this can only ever happen in the // presence of f32 array types, since otherwise we never run // out of FPRs before running out of GPRs. SDValue ArgVal; // Double values are always passed in a single GPR. if (Arg.getValueType() != MVT::f32) { ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg); // Non-array float values are extended and passed in a GPR. } else if (!Flags.isInConsecutiveRegs()) { ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); // If we have an array of floats, we collect every odd element // together with its predecessor into one GPR. } else if (ArgOffset % PtrByteSize != 0) { SDValue Lo, Hi; Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]); Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); if (!isLittleEndian) std::swap(Lo, Hi); ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi); // The final element, if even, goes into the first half of a GPR. } else if (Flags.isInConsecutiveRegsLast()) { ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg); ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal); if (!isLittleEndian) ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal, DAG.getConstant(32, dl, MVT::i32)); // Non-final even elements are skipped; they will be handled // together the with subsequent argument on the next go-around. } else ArgVal = SDValue(); if (ArgVal.getNode()) RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal)); } else { if (CallConv == CallingConv::Fast) ComputePtrOff(); // Single-precision floating-point values are mapped to the // second (rightmost) word of the stack doubleword. if (Arg.getValueType() == MVT::f32 && !isLittleEndian && !Flags.isInConsecutiveRegs()) { SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); } LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, true, isTailCall, false, MemOpChains, TailCallArguments, dl); NeededLoad = true; } // When passing an array of floats, the array occupies consecutive // space in the argument area; only round up to the next doubleword // at the end of the array. Otherwise, each float takes 8 bytes. if (CallConv != CallingConv::Fast || NeededLoad) { ArgOffset += (Arg.getValueType() == MVT::f32 && Flags.isInConsecutiveRegs()) ? 4 : 8; if (Flags.isInConsecutiveRegsLast()) ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize; } break; } case MVT::v4f32: case MVT::v4i32: case MVT::v8i16: case MVT::v16i8: case MVT::v2f64: case MVT::v2i64: case MVT::v1i128: if (!Subtarget.hasQPX()) { // These can be scalar arguments or elements of a vector array type // passed directly. The latter are used to implement ELFv2 homogenous // vector aggregates. // For a varargs call, named arguments go into VRs or on the stack as // usual; unnamed arguments always go to the stack or the corresponding // GPRs when within range. For now, we always put the value in both // locations (or even all three). if (isVarArg) { // We could elide this store in the case where the object fits // entirely in R registers. Maybe later. SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo(), false, false, 0); MemOpChains.push_back(Store); if (VR_idx != NumVRs) { SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo(), false, false, false, 0); MemOpChains.push_back(Load.getValue(1)); unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 || Arg.getSimpleValueType() == MVT::v2i64) ? VSRH[VR_idx] : VR[VR_idx]; ++VR_idx; RegsToPass.push_back(std::make_pair(VReg, Load)); } ArgOffset += 16; for (unsigned i=0; i<16; i+=PtrByteSize) { if (GPR_idx == NumGPRs) break; SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, DAG.getConstant(i, dl, PtrVT)); SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(), false, false, false, 0); MemOpChains.push_back(Load.getValue(1)); RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); } break; } // Non-varargs Altivec params go into VRs or on the stack. if (VR_idx != NumVRs) { unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 || Arg.getSimpleValueType() == MVT::v2i64) ? VSRH[VR_idx] : VR[VR_idx]; ++VR_idx; RegsToPass.push_back(std::make_pair(VReg, Arg)); } else { if (CallConv == CallingConv::Fast) ComputePtrOff(); LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, true, isTailCall, true, MemOpChains, TailCallArguments, dl); if (CallConv == CallingConv::Fast) ArgOffset += 16; } if (CallConv != CallingConv::Fast) ArgOffset += 16; break; } // not QPX assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 && "Invalid QPX parameter type"); /* fall through */ case MVT::v4f64: case MVT::v4i1: { bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32; if (isVarArg) { // We could elide this store in the case where the object fits // entirely in R registers. Maybe later. SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo(), false, false, 0); MemOpChains.push_back(Store); if (QFPR_idx != NumQFPRs) { SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store, PtrOff, MachinePointerInfo(), false, false, false, 0); MemOpChains.push_back(Load.getValue(1)); RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load)); } ArgOffset += (IsF32 ? 16 : 32); for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) { if (GPR_idx == NumGPRs) break; SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, DAG.getConstant(i, dl, PtrVT)); SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(), false, false, false, 0); MemOpChains.push_back(Load.getValue(1)); RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); } break; } // Non-varargs QPX params go into registers or on the stack. if (QFPR_idx != NumQFPRs) { RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg)); } else { if (CallConv == CallingConv::Fast) ComputePtrOff(); LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, true, isTailCall, true, MemOpChains, TailCallArguments, dl); if (CallConv == CallingConv::Fast) ArgOffset += (IsF32 ? 16 : 32); } if (CallConv != CallingConv::Fast) ArgOffset += (IsF32 ? 16 : 32); break; } } } assert(NumBytesActuallyUsed == ArgOffset); (void)NumBytesActuallyUsed; if (!MemOpChains.empty()) Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); // Check if this is an indirect call (MTCTR/BCTRL). // See PrepareCall() for more information about calls through function // pointers in the 64-bit SVR4 ABI. if (!isTailCall && !IsPatchPoint && !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) { // Load r2 into a virtual register and store it to the TOC save area. setUsesTOCBasePtr(DAG); SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64); // TOC save area offset. unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl); SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); Chain = DAG.getStore( Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset), false, false, 0); // In the ELFv2 ABI, R12 must contain the address of an indirect callee. // This does not mean the MTCTR instruction must use R12; it's easier // to model this as an extra parameter, so do that. if (isELFv2ABI && !IsPatchPoint) RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee)); } // 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 (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, RegsToPass[i].second, InFlag); InFlag = Chain.getValue(1); } if (isTailCall) PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp, FPOp, true, TailCallArguments); return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, hasNest, DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, NumBytes, Ins, InVals, CS); } SDValue PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg, bool isTailCall, bool IsPatchPoint, const SmallVectorImpl<ISD::OutputArg> &Outs, const SmallVectorImpl<SDValue> &OutVals, const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc dl, SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const { unsigned NumOps = Outs.size(); EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); bool isPPC64 = PtrVT == MVT::i64; unsigned PtrByteSize = isPPC64 ? 8 : 4; MachineFunction &MF = DAG.getMachineFunction(); // Mark this function as potentially containing a function that contains a // tail call. As a consequence the frame pointer will be used for dynamicalloc // and restoring the callers stack pointer in this functions epilog. This is // done because by tail calling the called function might overwrite the value // in this function's (MF) stack pointer stack slot 0(SP). if (getTargetMachine().Options.GuaranteedTailCallOpt && CallConv == CallingConv::Fast) MF.getInfo<PPCFunctionInfo>()->setHasFastCall(); // Count how many bytes are to be pushed on the stack, including the linkage // area, and parameter passing area. We start with 24/48 bytes, which is // prereserved space for [SP][CR][LR][3 x unused]. unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize(); unsigned NumBytes = LinkageSize; // Add up all the space actually used. // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually // they all go in registers, but we must reserve stack space for them for // possible use by the caller. In varargs or 64-bit calls, parameters are // assigned stack space in order, with padding so Altivec parameters are // 16-byte aligned. unsigned nAltivecParamsAtEnd = 0; for (unsigned i = 0; i != NumOps; ++i) { ISD::ArgFlagsTy Flags = Outs[i].Flags; EVT ArgVT = Outs[i].VT; // Varargs Altivec parameters are padded to a 16 byte boundary. if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 || ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 || ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) { if (!isVarArg && !isPPC64) { // Non-varargs Altivec parameters go after all the non-Altivec // parameters; handle those later so we know how much padding we need. nAltivecParamsAtEnd++; continue; } // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary. NumBytes = ((NumBytes+15)/16)*16; } NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize); } // Allow for Altivec parameters at the end, if needed. if (nAltivecParamsAtEnd) { NumBytes = ((NumBytes+15)/16)*16; NumBytes += 16*nAltivecParamsAtEnd; } // The prolog code of the callee may store up to 8 GPR argument registers to // the stack, allowing va_start to index over them in memory if its varargs. // Because we cannot tell if this is needed on the caller side, we have to // conservatively assume that it is needed. As such, make sure we have at // least enough stack space for the caller to store the 8 GPRs. NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize); // Tail call needs the stack to be aligned. if (getTargetMachine().Options.GuaranteedTailCallOpt && CallConv == CallingConv::Fast) NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes); // Calculate by how many bytes the stack has to be adjusted in case of tail // call optimization. int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes); // To protect arguments on the stack from being clobbered in a tail call, // force all the loads to happen before doing any other lowering. if (isTailCall) Chain = DAG.getStackArgumentTokenFactor(Chain); // Adjust the stack pointer for the new arguments... // These operations are automatically eliminated by the prolog/epilog pass Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, dl, true), dl); SDValue CallSeqStart = Chain; // Load the return address and frame pointer so it can be move somewhere else // later. SDValue LROp, FPOp; Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true, dl); // Set up a copy of the stack pointer for use loading and storing any // arguments that may not fit in the registers available for argument // passing. SDValue StackPtr; if (isPPC64) StackPtr = DAG.getRegister(PPC::X1, MVT::i64); else StackPtr = DAG.getRegister(PPC::R1, MVT::i32); // Figure out which arguments are going to go in registers, and which in // memory. Also, if this is a vararg function, floating point operations // must be stored to our stack, and loaded into integer regs as well, if // any integer regs are available for argument passing. unsigned ArgOffset = LinkageSize; unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0; static const MCPhysReg GPR_32[] = { // 32-bit registers. PPC::R3, PPC::R4, PPC::R5, PPC::R6, PPC::R7, PPC::R8, PPC::R9, PPC::R10, }; static const MCPhysReg GPR_64[] = { // 64-bit registers. PPC::X3, PPC::X4, PPC::X5, PPC::X6, PPC::X7, PPC::X8, PPC::X9, PPC::X10, }; static const MCPhysReg VR[] = { PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8, PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13 }; const unsigned NumGPRs = array_lengthof(GPR_32); const unsigned NumFPRs = 13; const unsigned NumVRs = array_lengthof(VR); const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32; SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; SmallVector<TailCallArgumentInfo, 8> TailCallArguments; SmallVector<SDValue, 8> MemOpChains; for (unsigned i = 0; i != NumOps; ++i) { SDValue Arg = OutVals[i]; ISD::ArgFlagsTy Flags = Outs[i].Flags; // PtrOff will be used to store the current argument to the stack if a // register cannot be found for it. SDValue PtrOff; PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType()); PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff); // On PPC64, promote integers to 64-bit values. if (isPPC64 && Arg.getValueType() == MVT::i32) { // FIXME: Should this use ANY_EXTEND if neither sext nor zext? unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg); } // FIXME memcpy is used way more than necessary. Correctness first. // Note: "by value" is code for passing a structure by value, not // basic types. if (Flags.isByVal()) { unsigned Size = Flags.getByValSize(); // Very small objects are passed right-justified. Everything else is // passed left-justified. if (Size==1 || Size==2) { EVT VT = (Size==1) ? MVT::i8 : MVT::i16; if (GPR_idx != NumGPRs) { SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg, MachinePointerInfo(), VT, false, false, false, 0); MemOpChains.push_back(Load.getValue(1)); RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); ArgOffset += PtrByteSize; } else { SDValue Const = DAG.getConstant(PtrByteSize - Size, dl, PtrOff.getValueType()); SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const); Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr, CallSeqStart, Flags, DAG, dl); ArgOffset += PtrByteSize; } continue; } // Copy entire object into memory. There are cases where gcc-generated // code assumes it is there, even if it could be put entirely into // registers. (This is not what the doc says.) Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff, CallSeqStart, Flags, DAG, dl); // For small aggregates (Darwin only) and aggregates >= PtrByteSize, // copy the pieces of the object that fit into registers from the // parameter save area. for (unsigned j=0; j<Size; j+=PtrByteSize) { SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType()); SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const); if (GPR_idx != NumGPRs) { SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(), false, false, false, 0); MemOpChains.push_back(Load.getValue(1)); RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); ArgOffset += PtrByteSize; } else { ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize; break; } } continue; } switch (Arg.getSimpleValueType().SimpleTy) { default: llvm_unreachable("Unexpected ValueType for argument!"); case MVT::i1: case MVT::i32: case MVT::i64: if (GPR_idx != NumGPRs) { if (Arg.getValueType() == MVT::i1) Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg); RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg)); } else { LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, isPPC64, isTailCall, false, MemOpChains, TailCallArguments, dl); } ArgOffset += PtrByteSize; break; case MVT::f32: case MVT::f64: if (FPR_idx != NumFPRs) { RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg)); if (isVarArg) { SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo(), false, false, 0); MemOpChains.push_back(Store); // Float varargs are always shadowed in available integer registers if (GPR_idx != NumGPRs) { SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo(), false, false, false, 0); MemOpChains.push_back(Load.getValue(1)); RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); } if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){ SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType()); PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour); SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo(), false, false, false, 0); MemOpChains.push_back(Load.getValue(1)); RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); } } else { // If we have any FPRs remaining, we may also have GPRs remaining. // Args passed in FPRs consume either 1 (f32) or 2 (f64) available // GPRs. if (GPR_idx != NumGPRs) ++GPR_idx; if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64) // PPC64 has 64-bit GPR's obviously :) ++GPR_idx; } } else LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, isPPC64, isTailCall, false, MemOpChains, TailCallArguments, dl); if (isPPC64) ArgOffset += 8; else ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8; break; case MVT::v4f32: case MVT::v4i32: case MVT::v8i16: case MVT::v16i8: if (isVarArg) { // These go aligned on the stack, or in the corresponding R registers // when within range. The Darwin PPC ABI doc claims they also go in // V registers; in fact gcc does this only for arguments that are // prototyped, not for those that match the ... We do it for all // arguments, seems to work. while (ArgOffset % 16 !=0) { ArgOffset += PtrByteSize; if (GPR_idx != NumGPRs) GPR_idx++; } // We could elide this store in the case where the object fits // entirely in R registers. Maybe later. PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, DAG.getConstant(ArgOffset, dl, PtrVT)); SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo(), false, false, 0); MemOpChains.push_back(Store); if (VR_idx != NumVRs) { SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo(), false, false, false, 0); MemOpChains.push_back(Load.getValue(1)); RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load)); } ArgOffset += 16; for (unsigned i=0; i<16; i+=PtrByteSize) { if (GPR_idx == NumGPRs) break; SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, DAG.getConstant(i, dl, PtrVT)); SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(), false, false, false, 0); MemOpChains.push_back(Load.getValue(1)); RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load)); } break; } // Non-varargs Altivec params generally go in registers, but have // stack space allocated at the end. if (VR_idx != NumVRs) { // Doesn't have GPR space allocated. RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg)); } else if (nAltivecParamsAtEnd==0) { // We are emitting Altivec params in order. LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, isPPC64, isTailCall, true, MemOpChains, TailCallArguments, dl); ArgOffset += 16; } break; } } // If all Altivec parameters fit in registers, as they usually do, // they get stack space following the non-Altivec parameters. We // don't track this here because nobody below needs it. // If there are more Altivec parameters than fit in registers emit // the stores here. if (!isVarArg && nAltivecParamsAtEnd > NumVRs) { unsigned j = 0; // Offset is aligned; skip 1st 12 params which go in V registers. ArgOffset = ((ArgOffset+15)/16)*16; ArgOffset += 12*16; for (unsigned i = 0; i != NumOps; ++i) { SDValue Arg = OutVals[i]; EVT ArgType = Outs[i].VT; if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 || ArgType==MVT::v8i16 || ArgType==MVT::v16i8) { if (++j > NumVRs) { SDValue PtrOff; // We are emitting Altivec params in order. LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset, isPPC64, isTailCall, true, MemOpChains, TailCallArguments, dl); ArgOffset += 16; } } } } if (!MemOpChains.empty()) Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains); // On Darwin, R12 must contain the address of an indirect callee. This does // not mean the MTCTR instruction must use R12; it's easier to model this as // an extra parameter, so do that. if (!isTailCall && !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee) && !isBLACompatibleAddress(Callee, DAG)) RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 : PPC::R12), Callee)); // 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 (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) { Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first, RegsToPass[i].second, InFlag); InFlag = Chain.getValue(1); } if (isTailCall) PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp, FPOp, true, TailCallArguments); return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, /* unused except on PPC64 ELFv1 */ false, DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff, NumBytes, Ins, InVals, CS); } bool PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { SmallVector<CCValAssign, 16> RVLocs; CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); return CCInfo.CheckReturn(Outs, RetCC_PPC); } SDValue PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, bool isVarArg, const SmallVectorImpl<ISD::OutputArg> &Outs, const SmallVectorImpl<SDValue> &OutVals, SDLoc dl, SelectionDAG &DAG) const { SmallVector<CCValAssign, 16> RVLocs; CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, *DAG.getContext()); CCInfo.AnalyzeReturn(Outs, RetCC_PPC); SDValue Flag; SmallVector<SDValue, 4> RetOps(1, Chain); // Copy the result values into the output registers. for (unsigned i = 0; i != RVLocs.size(); ++i) { CCValAssign &VA = RVLocs[i]; assert(VA.isRegLoc() && "Can only return in registers!"); SDValue Arg = OutVals[i]; switch (VA.getLocInfo()) { default: llvm_unreachable("Unknown loc info!"); case CCValAssign::Full: break; case CCValAssign::AExt: Arg = DAG.getNode(ISD::ANY_EXTEND, 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; } Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag); Flag = Chain.getValue(1); RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); } RetOps[0] = Chain; // Update chain. // Add the flag if we have it. if (Flag.getNode()) RetOps.push_back(Flag); return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps); } SDValue PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET( SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget) const { SDLoc dl(Op); // Get the corect type for integers. EVT IntVT = Op.getValueType(); // Get the inputs. SDValue Chain = Op.getOperand(0); SDValue FPSIdx = getFramePointerFrameIndex(DAG); // Build a DYNAREAOFFSET node. SDValue Ops[2] = {Chain, FPSIdx}; SDVTList VTs = DAG.getVTList(IntVT); return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops); } SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget) const { // When we pop the dynamic allocation we need to restore the SP link. SDLoc dl(Op); // Get the corect type for pointers. EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); // Construct the stack pointer operand. bool isPPC64 = Subtarget.isPPC64(); unsigned SP = isPPC64 ? PPC::X1 : PPC::R1; SDValue StackPtr = DAG.getRegister(SP, PtrVT); // Get the operands for the STACKRESTORE. SDValue Chain = Op.getOperand(0); SDValue SaveSP = Op.getOperand(1); // Load the old link SP. SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo(), false, false, false, 0); // Restore the stack pointer. Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP); // Store the old link SP. return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(), false, false, 0); } SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const { MachineFunction &MF = DAG.getMachineFunction(); bool isPPC64 = Subtarget.isPPC64(); EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout()); // Get current frame pointer save index. The users of this index will be // primarily DYNALLOC instructions. PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); int RASI = FI->getReturnAddrSaveIndex(); // If the frame pointer save index hasn't been defined yet. if (!RASI) { // Find out what the fix offset of the frame pointer save area. int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset(); // Allocate the frame index for frame pointer save area. RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false); // Save the result. FI->setReturnAddrSaveIndex(RASI); } return DAG.getFrameIndex(RASI, PtrVT); } SDValue PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const { MachineFunction &MF = DAG.getMachineFunction(); bool isPPC64 = Subtarget.isPPC64(); EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout()); // Get current frame pointer save index. The users of this index will be // primarily DYNALLOC instructions. PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>(); int FPSI = FI->getFramePointerSaveIndex(); // If the frame pointer save index hasn't been defined yet. if (!FPSI) { // Find out what the fix offset of the frame pointer save area. int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset(); // Allocate the frame index for frame pointer save area. FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true); // Save the result. FI->setFramePointerSaveIndex(FPSI); } return DAG.getFrameIndex(FPSI, PtrVT); } SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG, const PPCSubtarget &Subtarget) const { // Get the inputs. SDValue Chain = Op.getOperand(0); SDValue Size = Op.getOperand(1); SDLoc dl(Op); // Get the corect type for pointers. EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); // Negate the size. SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT, DAG.getConstant(0, dl, PtrVT), Size); // Construct a node for the frame pointer save index. SDValue FPSIdx = getFramePointerFrameIndex(DAG); // Build a DYNALLOC node. SDValue Ops[3] = { Chain, NegSize, FPSIdx }; SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other); return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops); } SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const { SDLoc DL(Op); return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL, DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0), Op.getOperand(1)); } SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const { SDLoc DL(Op); return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other, Op.getOperand(0), Op.getOperand(1)); } SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { if (Op.getValueType().isVector()) return LowerVectorLoad(Op, DAG); assert(Op.getValueType() == MVT::i1 && "Custom lowering only for i1 loads"); // First, load 8 bits into 32 bits, then truncate to 1 bit. SDLoc dl(Op); LoadSDNode *LD = cast<LoadSDNode>(Op); SDValue Chain = LD->getChain(); SDValue BasePtr = LD->getBasePtr(); MachineMemOperand *MMO = LD->getMemOperand(); SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain, BasePtr, MVT::i8, MMO); SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD); SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) }; return DAG.getMergeValues(Ops, dl); } SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { if (Op.getOperand(1).getValueType().isVector()) return LowerVectorStore(Op, DAG); assert(Op.getOperand(1).getValueType() == MVT::i1 && "Custom lowering only for i1 stores"); // First, zero extend to 32 bits, then use a truncating store to 8 bits. SDLoc dl(Op); StoreSDNode *ST = cast<StoreSDNode>(Op); SDValue Chain = ST->getChain(); SDValue BasePtr = ST->getBasePtr(); SDValue Value = ST->getValue(); MachineMemOperand *MMO = ST->getMemOperand(); Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()), Value); return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO); } // FIXME: Remove this once the ANDI glue bug is fixed: SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const { assert(Op.getValueType() == MVT::i1 && "Custom lowering only for i1 results"); SDLoc DL(Op); return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1, Op.getOperand(0)); } /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when /// possible. SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const { // Not FP? Not a fsel. if (!Op.getOperand(0).getValueType().isFloatingPoint() || !Op.getOperand(2).getValueType().isFloatingPoint()) return Op; // We might be able to do better than this under some circumstances, but in // general, fsel-based lowering of select is a finite-math-only optimization. // For more information, see section F.3 of the 2.06 ISA specification. if (!DAG.getTarget().Options.NoInfsFPMath || !DAG.getTarget().Options.NoNaNsFPMath) return Op; // TODO: Propagate flags from the select rather than global settings. SDNodeFlags Flags; Flags.setNoInfs(true); Flags.setNoNaNs(true); ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); EVT ResVT = Op.getValueType(); EVT CmpVT = Op.getOperand(0).getValueType(); SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); SDValue TV = Op.getOperand(2), FV = Op.getOperand(3); SDLoc dl(Op); // If the RHS of the comparison is a 0.0, we don't need to do the // subtraction at all. SDValue Sel1; if (isFloatingPointZero(RHS)) switch (CC) { default: break; // SETUO etc aren't handled by fsel. case ISD::SETNE: std::swap(TV, FV); case ISD::SETEQ: if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); return DAG.getNode(PPCISD::FSEL, dl, ResVT, DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV); case ISD::SETULT: case ISD::SETLT: std::swap(TV, FV); // fsel is natively setge, swap operands for setlt case ISD::SETOGE: case ISD::SETGE: if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV); case ISD::SETUGT: case ISD::SETGT: std::swap(TV, FV); // fsel is natively setge, swap operands for setlt case ISD::SETOLE: case ISD::SETLE: if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS); return DAG.getNode(PPCISD::FSEL, dl, ResVT, DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV); } SDValue Cmp; switch (CC) { default: break; // SETUO etc aren't handled by fsel. case ISD::SETNE: std::swap(TV, FV); case ISD::SETEQ: Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags); if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1); return DAG.getNode(PPCISD::FSEL, dl, ResVT, DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV); case ISD::SETULT: case ISD::SETLT: Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags); if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); case ISD::SETOGE: case ISD::SETGE: Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, &Flags); if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); case ISD::SETUGT: case ISD::SETGT: Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags); if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV); case ISD::SETOLE: case ISD::SETLE: Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, &Flags); if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp); return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV); } return Op; } void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI, SelectionDAG &DAG, SDLoc dl) const { assert(Op.getOperand(0).getValueType().isFloatingPoint()); SDValue Src = Op.getOperand(0); if (Src.getValueType() == MVT::f32) Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); SDValue Tmp; switch (Op.getSimpleValueType().SimpleTy) { default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); case MVT::i32: Tmp = DAG.getNode( Op.getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIWZ : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), dl, MVT::f64, Src); break; case MVT::i64: assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && "i64 FP_TO_UINT is supported only with FPCVT"); Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ, dl, MVT::f64, Src); break; } // Convert the FP value to an int value through memory. bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() && (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()); SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64); int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex(); MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); // Emit a store to the stack slot. SDValue Chain; if (i32Stack) { MachineFunction &MF = DAG.getMachineFunction(); MachineMemOperand *MMO = MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4); SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr }; Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO); } else Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, false, false, 0); // Result is a load from the stack slot. If loading 4 bytes, make sure to // add in a bias. if (Op.getValueType() == MVT::i32 && !i32Stack) { FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, DAG.getConstant(4, dl, FIPtr.getValueType())); MPI = MPI.getWithOffset(4); } RLI.Chain = Chain; RLI.Ptr = FIPtr; RLI.MPI = MPI; } /// \brief Custom lowers floating point to integer conversions to use /// the direct move instructions available in ISA 2.07 to avoid the /// need for load/store combinations. SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op, SelectionDAG &DAG, SDLoc dl) const { assert(Op.getOperand(0).getValueType().isFloatingPoint()); SDValue Src = Op.getOperand(0); if (Src.getValueType() == MVT::f32) Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); SDValue Tmp; switch (Op.getSimpleValueType().SimpleTy) { default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!"); case MVT::i32: Tmp = DAG.getNode( Op.getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIWZ : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ), dl, MVT::f64, Src); Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp); break; case MVT::i64: assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) && "i64 FP_TO_UINT is supported only with FPCVT"); Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ, dl, MVT::f64, Src); Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp); break; } return Tmp; } SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG, SDLoc dl) const { if (Subtarget.hasDirectMove() && Subtarget.isPPC64()) return LowerFP_TO_INTDirectMove(Op, DAG, dl); ReuseLoadInfo RLI; LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false, false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo, RLI.Ranges); } // We're trying to insert a regular store, S, and then a load, L. If the // incoming value, O, is a load, we might just be able to have our load use the // address used by O. However, we don't know if anything else will store to // that address before we can load from it. To prevent this situation, we need // to insert our load, L, into the chain as a peer of O. To do this, we give L // the same chain operand as O, we create a token factor from the chain results // of O and L, and we replace all uses of O's chain result with that token // factor (see spliceIntoChain below for this last part). bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT, ReuseLoadInfo &RLI, SelectionDAG &DAG, ISD::LoadExtType ET) const { SDLoc dl(Op); if (ET == ISD::NON_EXTLOAD && (Op.getOpcode() == ISD::FP_TO_UINT || Op.getOpcode() == ISD::FP_TO_SINT) && isOperationLegalOrCustom(Op.getOpcode(), Op.getOperand(0).getValueType())) { LowerFP_TO_INTForReuse(Op, RLI, DAG, dl); return true; } LoadSDNode *LD = dyn_cast<LoadSDNode>(Op); if (!LD || LD->getExtensionType() != ET || LD->isVolatile() || LD->isNonTemporal()) return false; if (LD->getMemoryVT() != MemVT) return false; RLI.Ptr = LD->getBasePtr(); if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) { assert(LD->getAddressingMode() == ISD::PRE_INC && "Non-pre-inc AM on PPC?"); RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr, LD->getOffset()); } RLI.Chain = LD->getChain(); RLI.MPI = LD->getPointerInfo(); RLI.IsInvariant = LD->isInvariant(); RLI.Alignment = LD->getAlignment(); RLI.AAInfo = LD->getAAInfo(); RLI.Ranges = LD->getRanges(); RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1); return true; } // Given the head of the old chain, ResChain, insert a token factor containing // it and NewResChain, and make users of ResChain now be users of that token // factor. void PPCTargetLowering::spliceIntoChain(SDValue ResChain, SDValue NewResChain, SelectionDAG &DAG) const { if (!ResChain) return; SDLoc dl(NewResChain); SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, NewResChain, DAG.getUNDEF(MVT::Other)); assert(TF.getNode() != NewResChain.getNode() && "A new TF really is required here"); DAG.ReplaceAllUsesOfValueWith(ResChain, TF); DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain); } /// \brief Custom lowers integer to floating point conversions to use /// the direct move instructions available in ISA 2.07 to avoid the /// need for load/store combinations. SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op, SelectionDAG &DAG, SDLoc dl) const { assert((Op.getValueType() == MVT::f32 || Op.getValueType() == MVT::f64) && "Invalid floating point type as target of conversion"); assert(Subtarget.hasFPCVT() && "Int to FP conversions with direct moves require FPCVT"); SDValue FP; SDValue Src = Op.getOperand(0); bool SinglePrec = Op.getValueType() == MVT::f32; bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32; bool Signed = Op.getOpcode() == ISD::SINT_TO_FP; unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) : (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU); if (WordInt) { FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ, dl, MVT::f64, Src); FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); } else { FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src); FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP); } return FP; } SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const { SDLoc dl(Op); if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) { if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64) return SDValue(); SDValue Value = Op.getOperand(0); // The values are now known to be -1 (false) or 1 (true). To convert this // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64); FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64, FPHalfs, FPHalfs, FPHalfs, FPHalfs); Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); if (Op.getValueType() != MVT::v4f64) Value = DAG.getNode(ISD::FP_ROUND, dl, Op.getValueType(), Value, DAG.getIntPtrConstant(1, dl)); return Value; } // Don't handle ppc_fp128 here; let it be lowered to a libcall. if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) return SDValue(); if (Op.getOperand(0).getValueType() == MVT::i1) return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0), DAG.getConstantFP(1.0, dl, Op.getValueType()), DAG.getConstantFP(0.0, dl, Op.getValueType())); // If we have direct moves, we can do all the conversion, skip the store/load // however, without FPCVT we can't do most conversions. if (Subtarget.hasDirectMove() && Subtarget.isPPC64() && Subtarget.hasFPCVT()) return LowerINT_TO_FPDirectMove(Op, DAG, dl); assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && "UINT_TO_FP is supported only with FPCVT"); // If we have FCFIDS, then use it when converting to single-precision. // Otherwise, convert to double-precision and then round. unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS : PPCISD::FCFIDS) : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU : PPCISD::FCFID); MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ? MVT::f32 : MVT::f64; if (Op.getOperand(0).getValueType() == MVT::i64) { SDValue SINT = Op.getOperand(0); // When converting to single-precision, we actually need to convert // to double-precision first and then round to single-precision. // To avoid double-rounding effects during that operation, we have // to prepare the input operand. Bits that might be truncated when // converting to double-precision are replaced by a bit that won't // be lost at this stage, but is below the single-precision rounding // position. // // However, if -enable-unsafe-fp-math is in effect, accept double // rounding to avoid the extra overhead. if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT() && !DAG.getTarget().Options.UnsafeFPMath) { // Twiddle input to make sure the low 11 bits are zero. (If this // is the case, we are guaranteed the value will fit into the 53 bit // mantissa of an IEEE double-precision value without rounding.) // If any of those low 11 bits were not zero originally, make sure // bit 12 (value 2048) is set instead, so that the final rounding // to single-precision gets the correct result. SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64, SINT, DAG.getConstant(2047, dl, MVT::i64)); Round = DAG.getNode(ISD::ADD, dl, MVT::i64, Round, DAG.getConstant(2047, dl, MVT::i64)); Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT); Round = DAG.getNode(ISD::AND, dl, MVT::i64, Round, DAG.getConstant(-2048, dl, MVT::i64)); // However, we cannot use that value unconditionally: if the magnitude // of the input value is small, the bit-twiddling we did above might // end up visibly changing the output. Fortunately, in that case, we // don't need to twiddle bits since the original input will convert // exactly to double-precision floating-point already. Therefore, // construct a conditional to use the original value if the top 11 // bits are all sign-bit copies, and use the rounded value computed // above otherwise. SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64, SINT, DAG.getConstant(53, dl, MVT::i32)); Cond = DAG.getNode(ISD::ADD, dl, MVT::i64, Cond, DAG.getConstant(1, dl, MVT::i64)); Cond = DAG.getSetCC(dl, MVT::i32, Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT); SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT); } ReuseLoadInfo RLI; SDValue Bits; MachineFunction &MF = DAG.getMachineFunction(); if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) { Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false, false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo, RLI.Ranges); spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); } else if (Subtarget.hasLFIWAX() && canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) { MachineMemOperand *MMO = MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, RLI.Alignment, RLI.AAInfo, RLI.Ranges); SDValue Ops[] = { RLI.Chain, RLI.Ptr }; Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl, DAG.getVTList(MVT::f64, MVT::Other), Ops, MVT::i32, MMO); spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); } else if (Subtarget.hasFPCVT() && canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) { MachineMemOperand *MMO = MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, RLI.Alignment, RLI.AAInfo, RLI.Ranges); SDValue Ops[] = { RLI.Chain, RLI.Ptr }; Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl, DAG.getVTList(MVT::f64, MVT::Other), Ops, MVT::i32, MMO); spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG); } else if (((Subtarget.hasLFIWAX() && SINT.getOpcode() == ISD::SIGN_EXTEND) || (Subtarget.hasFPCVT() && SINT.getOpcode() == ISD::ZERO_EXTEND)) && SINT.getOperand(0).getValueType() == MVT::i32) { MachineFrameInfo *FrameInfo = MF.getFrameInfo(); EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()); int FrameIdx = FrameInfo->CreateStackObject(4, 4, false); SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); SDValue Store = DAG.getStore( DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx, MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx), false, false, 0); assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && "Expected an i32 store"); RLI.Ptr = FIdx; RLI.Chain = Store; RLI.MPI = MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); RLI.Alignment = 4; MachineMemOperand *MMO = MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, RLI.Alignment, RLI.AAInfo, RLI.Ranges); SDValue Ops[] = { RLI.Chain, RLI.Ptr }; Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ? PPCISD::LFIWZX : PPCISD::LFIWAX, dl, DAG.getVTList(MVT::f64, MVT::Other), Ops, MVT::i32, MMO); } else Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT); SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits); if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); return FP; } assert(Op.getOperand(0).getValueType() == MVT::i32 && "Unhandled INT_TO_FP type in custom expander!"); // Since we only generate this in 64-bit mode, we can take advantage of // 64-bit registers. In particular, sign extend the input value into the // 64-bit register with extsw, store the WHOLE 64-bit value into the stack // then lfd it and fcfid it. MachineFunction &MF = DAG.getMachineFunction(); MachineFrameInfo *FrameInfo = MF.getFrameInfo(); EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout()); SDValue Ld; if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) { ReuseLoadInfo RLI; bool ReusingLoad; if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI, DAG))) { int FrameIdx = FrameInfo->CreateStackObject(4, 4, false); SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); SDValue Store = DAG.getStore( DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx), false, false, 0); assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 && "Expected an i32 store"); RLI.Ptr = FIdx; RLI.Chain = Store; RLI.MPI = MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); RLI.Alignment = 4; } MachineMemOperand *MMO = MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4, RLI.Alignment, RLI.AAInfo, RLI.Ranges); SDValue Ops[] = { RLI.Chain, RLI.Ptr }; Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::LFIWZX : PPCISD::LFIWAX, dl, DAG.getVTList(MVT::f64, MVT::Other), Ops, MVT::i32, MMO); if (ReusingLoad) spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG); } else { assert(Subtarget.isPPC64() && "i32->FP without LFIWAX supported only on PPC64"); int FrameIdx = FrameInfo->CreateStackObject(8, 8, false); SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Op.getOperand(0)); // STD the extended value into the stack slot. SDValue Store = DAG.getStore( DAG.getEntryNode(), dl, Ext64, FIdx, MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx), false, false, 0); // Load the value as a double. Ld = DAG.getLoad( MVT::f64, dl, Store, FIdx, MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx), false, false, false, 0); } // FCFID it and return it. SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld); if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); return FP; } SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) const { SDLoc dl(Op); /* The rounding mode is in bits 30:31 of FPSR, and has the following settings: 00 Round to nearest 01 Round to 0 10 Round to +inf 11 Round to -inf FLT_ROUNDS, on the other hand, expects the following: -1 Undefined 0 Round to 0 1 Round to nearest 2 Round to +inf 3 Round to -inf To perform the conversion, we do: ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1)) */ MachineFunction &MF = DAG.getMachineFunction(); EVT VT = Op.getValueType(); EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout()); // Save FP Control Word to register EVT NodeTys[] = { MVT::f64, // return register MVT::Glue // unused in this context }; SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None); // Save FP register to stack slot int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false); SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT); SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot, MachinePointerInfo(), false, false,0); // Load FP Control Word from low 32 bits of stack slot. SDValue Four = DAG.getConstant(4, dl, PtrVT); SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four); SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(), false, false, false, 0); // Transform as necessary SDValue CWD1 = DAG.getNode(ISD::AND, dl, MVT::i32, CWD, DAG.getConstant(3, dl, MVT::i32)); SDValue CWD2 = DAG.getNode(ISD::SRL, dl, MVT::i32, DAG.getNode(ISD::AND, dl, MVT::i32, DAG.getNode(ISD::XOR, dl, MVT::i32, CWD, DAG.getConstant(3, dl, MVT::i32)), DAG.getConstant(3, dl, MVT::i32)), DAG.getConstant(1, dl, MVT::i32)); SDValue RetVal = DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2); return DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal); } SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const { EVT VT = Op.getValueType(); unsigned BitWidth = VT.getSizeInBits(); SDLoc dl(Op); assert(Op.getNumOperands() == 3 && VT == Op.getOperand(1).getValueType() && "Unexpected SHL!"); // Expand into a bunch of logical ops. Note that these ops // depend on the PPC behavior for oversized shift amounts. SDValue Lo = Op.getOperand(0); SDValue Hi = Op.getOperand(1); SDValue Amt = Op.getOperand(2); EVT AmtVT = Amt.getValueType(); SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Amt); SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt); SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1); SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3); SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, DAG.getConstant(-BitWidth, dl, AmtVT)); SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5); SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt); SDValue OutOps[] = { OutLo, OutHi }; return DAG.getMergeValues(OutOps, dl); } SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const { EVT VT = Op.getValueType(); SDLoc dl(Op); unsigned BitWidth = VT.getSizeInBits(); assert(Op.getNumOperands() == 3 && VT == Op.getOperand(1).getValueType() && "Unexpected SRL!"); // Expand into a bunch of logical ops. Note that these ops // depend on the PPC behavior for oversized shift amounts. SDValue Lo = Op.getOperand(0); SDValue Hi = Op.getOperand(1); SDValue Amt = Op.getOperand(2); EVT AmtVT = Amt.getValueType(); SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Amt); SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, DAG.getConstant(-BitWidth, dl, AmtVT)); SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5); SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6); SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt); SDValue OutOps[] = { OutLo, OutHi }; return DAG.getMergeValues(OutOps, dl); } SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const { SDLoc dl(Op); EVT VT = Op.getValueType(); unsigned BitWidth = VT.getSizeInBits(); assert(Op.getNumOperands() == 3 && VT == Op.getOperand(1).getValueType() && "Unexpected SRA!"); // Expand into a bunch of logical ops, followed by a select_cc. SDValue Lo = Op.getOperand(0); SDValue Hi = Op.getOperand(1); SDValue Amt = Op.getOperand(2); EVT AmtVT = Amt.getValueType(); SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Amt); SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt); SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1); SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3); SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt, DAG.getConstant(-BitWidth, dl, AmtVT)); SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5); SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt); SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT), Tmp4, Tmp6, ISD::SETLE); SDValue OutOps[] = { OutLo, OutHi }; return DAG.getMergeValues(OutOps, dl); } //===----------------------------------------------------------------------===// // Vector related lowering. // /// BuildSplatI - Build a canonical splati of Val with an element size of /// SplatSize. Cast the result to VT. static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT, SelectionDAG &DAG, SDLoc dl) { assert(Val >= -16 && Val <= 15 && "vsplti is out of range!"); static const MVT VTys[] = { // canonical VT to use for each size. MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32 }; EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1]; // Force vspltis[hw] -1 to vspltisb -1 to canonicalize. if (Val == -1) SplatSize = 1; EVT CanonicalVT = VTys[SplatSize-1]; // Build a canonical splat for this value. SDValue Elt = DAG.getConstant(Val, dl, MVT::i32); SmallVector<SDValue, 8> Ops; Ops.assign(CanonicalVT.getVectorNumElements(), Elt); SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops); return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res); } /// BuildIntrinsicOp - Return a unary operator intrinsic node with the /// specified intrinsic ID. static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG, SDLoc dl, EVT DestVT = MVT::Other) { if (DestVT == MVT::Other) DestVT = Op.getValueType(); return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, DAG.getConstant(IID, dl, MVT::i32), Op); } /// BuildIntrinsicOp - Return a binary operator intrinsic node with the /// specified intrinsic ID. static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS, SelectionDAG &DAG, SDLoc dl, EVT DestVT = MVT::Other) { if (DestVT == MVT::Other) DestVT = LHS.getValueType(); return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, DAG.getConstant(IID, dl, MVT::i32), LHS, RHS); } /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the /// specified intrinsic ID. static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1, SDValue Op2, SelectionDAG &DAG, SDLoc dl, EVT DestVT = MVT::Other) { if (DestVT == MVT::Other) DestVT = Op0.getValueType(); return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT, DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2); } /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified /// amount. The result has the specified value type. static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT, SelectionDAG &DAG, SDLoc dl) { // Force LHS/RHS to be the right type. LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS); RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS); int Ops[16]; for (unsigned i = 0; i != 16; ++i) Ops[i] = i + Amt; SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops); return DAG.getNode(ISD::BITCAST, dl, VT, T); } // If this is a case we can't handle, return null and let the default // expansion code take care of it. If we CAN select this case, and if it // selects to a single instruction, return Op. Otherwise, if we can codegen // this case more efficiently than a constant pool load, lower it to the // sequence of ops that should be used. SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const { SDLoc dl(Op); BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR"); if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) { // We first build an i32 vector, load it into a QPX register, // then convert it to a floating-point vector and compare it // to a zero vector to get the boolean result. MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); int FrameIdx = FrameInfo->CreateStackObject(16, 16, false); MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); EVT PtrVT = getPointerTy(DAG.getDataLayout()); SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); assert(BVN->getNumOperands() == 4 && "BUILD_VECTOR for v4i1 does not have 4 operands"); bool IsConst = true; for (unsigned i = 0; i < 4; ++i) { if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue; if (!isa<ConstantSDNode>(BVN->getOperand(i))) { IsConst = false; break; } } if (IsConst) { Constant *One = ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0); Constant *NegOne = ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0); SmallVector<Constant*, 4> CV(4, NegOne); for (unsigned i = 0; i < 4; ++i) { if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext())); else if (isNullConstant(BVN->getOperand(i))) continue; else CV[i] = One; } Constant *CP = ConstantVector::get(CV); SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()), 16 /* alignment */); SmallVector<SDValue, 2> Ops; Ops.push_back(DAG.getEntryNode()); Ops.push_back(CPIdx); SmallVector<EVT, 2> ValueVTs; ValueVTs.push_back(MVT::v4i1); ValueVTs.push_back(MVT::Other); // chain SDVTList VTs = DAG.getVTList(ValueVTs); return DAG.getMemIntrinsicNode( PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32, MachinePointerInfo::getConstantPool(DAG.getMachineFunction())); } SmallVector<SDValue, 4> Stores; for (unsigned i = 0; i < 4; ++i) { if (BVN->getOperand(i).getOpcode() == ISD::UNDEF) continue; unsigned Offset = 4*i; SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize(); if (StoreSize > 4) { Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx, PtrInfo.getWithOffset(Offset), MVT::i32, false, false, 0)); } else { SDValue StoreValue = BVN->getOperand(i); if (StoreSize < 4) StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue); Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx, PtrInfo.getWithOffset(Offset), false, false, 0)); } } SDValue StoreChain; if (!Stores.empty()) StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); else StoreChain = DAG.getEntryNode(); // Now load from v4i32 into the QPX register; this will extend it to // v4i64 but not yet convert it to a floating point. Nevertheless, this // is typed as v4f64 because the QPX register integer states are not // explicitly represented. SmallVector<SDValue, 2> Ops; Ops.push_back(StoreChain); Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32)); Ops.push_back(FIdx); SmallVector<EVT, 2> ValueVTs; ValueVTs.push_back(MVT::v4f64); ValueVTs.push_back(MVT::Other); // chain SDVTList VTs = DAG.getVTList(ValueVTs); SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, VTs, Ops, MVT::v4i32, PtrInfo); LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32), LoadedVect); SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::f64); FPZeros = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64, FPZeros, FPZeros, FPZeros, FPZeros); return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ); } // All other QPX vectors are handled by generic code. if (Subtarget.hasQPX()) return SDValue(); // Check if this is a splat of a constant value. APInt APSplatBits, APSplatUndef; unsigned SplatBitSize; bool HasAnyUndefs; if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize, HasAnyUndefs, 0, !Subtarget.isLittleEndian()) || SplatBitSize > 32) return SDValue(); unsigned SplatBits = APSplatBits.getZExtValue(); unsigned SplatUndef = APSplatUndef.getZExtValue(); unsigned SplatSize = SplatBitSize / 8; // First, handle single instruction cases. // All zeros? if (SplatBits == 0) { // Canonicalize all zero vectors to be v4i32. if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) { SDValue Z = DAG.getConstant(0, dl, MVT::i32); Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z); Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z); } return Op; } // If the sign extended value is in the range [-16,15], use VSPLTI[bhw]. int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >> (32-SplatBitSize)); if (SextVal >= -16 && SextVal <= 15) return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl); // Two instruction sequences. // If this value is in the range [-32,30] and is even, use: // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2) // If this value is in the range [17,31] and is odd, use: // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16) // If this value is in the range [-31,-17] and is odd, use: // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16) // Note the last two are three-instruction sequences. if (SextVal >= -32 && SextVal <= 31) { // To avoid having these optimizations undone by constant folding, // we convert to a pseudo that will be expanded later into one of // the above forms. SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32); EVT VT = (SplatSize == 1 ? MVT::v16i8 : (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32)); SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32); SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize); if (VT == Op.getValueType()) return RetVal; else return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal); } // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important // for fneg/fabs. if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) { // Make -1 and vspltisw -1: SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl); // Make the VSLW intrinsic, computing 0x8000_0000. SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV, OnesV, DAG, dl); // xor by OnesV to invert it. Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV); return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); } // Check to see if this is a wide variety of vsplti*, binop self cases. static const signed char SplatCsts[] = { -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7, -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16 }; for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) { // Indirect through the SplatCsts array so that we favor 'vsplti -1' for // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1' int i = SplatCsts[idx]; // Figure out what shift amount will be used by altivec if shifted by i in // this splat size. unsigned TypeShiftAmt = i & (SplatBitSize-1); // vsplti + shl self. if (SextVal == (int)((unsigned)i << TypeShiftAmt)) { SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); static const unsigned IIDs[] = { // Intrinsic to use for each size. Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0, Intrinsic::ppc_altivec_vslw }; Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); } // vsplti + srl self. if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); static const unsigned IIDs[] = { // Intrinsic to use for each size. Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0, Intrinsic::ppc_altivec_vsrw }; Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); } // vsplti + sra self. if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) { SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); static const unsigned IIDs[] = { // Intrinsic to use for each size. Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0, Intrinsic::ppc_altivec_vsraw }; Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); } // vsplti + rol self. if (SextVal == (int)(((unsigned)i << TypeShiftAmt) | ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) { SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl); static const unsigned IIDs[] = { // Intrinsic to use for each size. Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0, Intrinsic::ppc_altivec_vrlw }; Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl); return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res); } // t = vsplti c, result = vsldoi t, t, 1 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) { SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1; return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); } // t = vsplti c, result = vsldoi t, t, 2 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) { SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2; return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); } // t = vsplti c, result = vsldoi t, t, 3 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) { SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl); unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3; return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl); } } return SDValue(); } /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit /// the specified operations to build the shuffle. static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, SDValue RHS, SelectionDAG &DAG, SDLoc dl) { unsigned OpNum = (PFEntry >> 26) & 0x0F; unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1); unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1); enum { OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> OP_VMRGHW, OP_VMRGLW, OP_VSPLTISW0, OP_VSPLTISW1, OP_VSPLTISW2, OP_VSPLTISW3, OP_VSLDOI4, OP_VSLDOI8, OP_VSLDOI12 }; if (OpNum == OP_COPY) { if (LHSID == (1*9+2)*9+3) return LHS; assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!"); return RHS; } SDValue OpLHS, OpRHS; OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); int ShufIdxs[16]; switch (OpNum) { default: llvm_unreachable("Unknown i32 permute!"); case OP_VMRGHW: ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3; ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19; ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7; ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23; break; case OP_VMRGLW: ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11; ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27; ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15; ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31; break; case OP_VSPLTISW0: for (unsigned i = 0; i != 16; ++i) ShufIdxs[i] = (i&3)+0; break; case OP_VSPLTISW1: for (unsigned i = 0; i != 16; ++i) ShufIdxs[i] = (i&3)+4; break; case OP_VSPLTISW2: for (unsigned i = 0; i != 16; ++i) ShufIdxs[i] = (i&3)+8; break; case OP_VSPLTISW3: for (unsigned i = 0; i != 16; ++i) ShufIdxs[i] = (i&3)+12; break; case OP_VSLDOI4: return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl); case OP_VSLDOI8: return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl); case OP_VSLDOI12: return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl); } EVT VT = OpLHS.getValueType(); OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS); OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS); SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs); return DAG.getNode(ISD::BITCAST, dl, VT, T); } /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this /// is a shuffle we can handle in a single instruction, return it. Otherwise, /// return the code it can be lowered into. Worst case, it can always be /// lowered into a vperm. SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const { SDLoc dl(Op); SDValue V1 = Op.getOperand(0); SDValue V2 = Op.getOperand(1); ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op); EVT VT = Op.getValueType(); bool isLittleEndian = Subtarget.isLittleEndian(); if (Subtarget.hasQPX()) { if (VT.getVectorNumElements() != 4) return SDValue(); if (V2.getOpcode() == ISD::UNDEF) V2 = V1; int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp); if (AlignIdx != -1) { return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2, DAG.getConstant(AlignIdx, dl, MVT::i32)); } else if (SVOp->isSplat()) { int SplatIdx = SVOp->getSplatIndex(); if (SplatIdx >= 4) { std::swap(V1, V2); SplatIdx -= 4; } // FIXME: If SplatIdx == 0 and the input came from a load, then there is // nothing to do. return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1, DAG.getConstant(SplatIdx, dl, MVT::i32)); } // Lower this into a qvgpci/qvfperm pair. // Compute the qvgpci literal unsigned idx = 0; for (unsigned i = 0; i < 4; ++i) { int m = SVOp->getMaskElt(i); unsigned mm = m >= 0 ? (unsigned) m : i; idx |= mm << (3-i)*3; } SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64, DAG.getConstant(idx, dl, MVT::i32)); return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3); } // Cases that are handled by instructions that take permute immediates // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be // selected by the instruction selector. if (V2.getOpcode() == ISD::UNDEF) { if (PPC::isSplatShuffleMask(SVOp, 1) || PPC::isSplatShuffleMask(SVOp, 2) || PPC::isSplatShuffleMask(SVOp, 4) || PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) || PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) || PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 || PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) || PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) || PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) || PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) || PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) || PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) || (Subtarget.hasP8Altivec() && ( PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) || PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) || PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) { return Op; } } // Altivec has a variety of "shuffle immediates" that take two vector inputs // and produce a fixed permutation. If any of these match, do not lower to // VPERM. unsigned int ShuffleKind = isLittleEndian ? 2 : 0; if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) || PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) || PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 || PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) || PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) || PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) || PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) || PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) || PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) || (Subtarget.hasP8Altivec() && ( PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) || PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) || PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG)))) return Op; // Check to see if this is a shuffle of 4-byte values. If so, we can use our // perfect shuffle table to emit an optimal matching sequence. ArrayRef<int> PermMask = SVOp->getMask(); unsigned PFIndexes[4]; bool isFourElementShuffle = true; for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number unsigned EltNo = 8; // Start out undef. for (unsigned j = 0; j != 4; ++j) { // Intra-element byte. if (PermMask[i*4+j] < 0) continue; // Undef, ignore it. unsigned ByteSource = PermMask[i*4+j]; if ((ByteSource & 3) != j) { isFourElementShuffle = false; break; } if (EltNo == 8) { EltNo = ByteSource/4; } else if (EltNo != ByteSource/4) { isFourElementShuffle = false; break; } } PFIndexes[i] = EltNo; } // If this shuffle can be expressed as a shuffle of 4-byte elements, use the // perfect shuffle vector to determine if it is cost effective to do this as // discrete instructions, or whether we should use a vperm. // For now, we skip this for little endian until such time as we have a // little-endian perfect shuffle table. if (isFourElementShuffle && !isLittleEndian) { // Compute the index in the perfect shuffle table. unsigned PFTableIndex = PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3]; unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; unsigned Cost = (PFEntry >> 30); // Determining when to avoid vperm is tricky. Many things affect the cost // of vperm, particularly how many times the perm mask needs to be computed. // For example, if the perm mask can be hoisted out of a loop or is already // used (perhaps because there are multiple permutes with the same shuffle // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of // the loop requires an extra register. // // As a compromise, we only emit discrete instructions if the shuffle can be // generated in 3 or fewer operations. When we have loop information // available, if this block is within a loop, we should avoid using vperm // for 3-operation perms and use a constant pool load instead. if (Cost < 3) return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); } // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant // vector that will get spilled to the constant pool. if (V2.getOpcode() == ISD::UNDEF) V2 = V1; // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except // that it is in input element units, not in bytes. Convert now. // For little endian, the order of the input vectors is reversed, and // the permutation mask is complemented with respect to 31. This is // necessary to produce proper semantics with the big-endian-biased vperm // instruction. EVT EltVT = V1.getValueType().getVectorElementType(); unsigned BytesPerElement = EltVT.getSizeInBits()/8; SmallVector<SDValue, 16> ResultMask; for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) { unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i]; for (unsigned j = 0; j != BytesPerElement; ++j) if (isLittleEndian) ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j), dl, MVT::i32)); else ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl, MVT::i32)); } SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8, ResultMask); if (isLittleEndian) return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V2, V1, VPermMask); else return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask); } /// getVectorCompareInfo - Given an intrinsic, return false if it is not a /// vector comparison. If it is, return true and fill in Opc/isDot with /// information about the intrinsic. static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc, bool &isDot, const PPCSubtarget &Subtarget) { unsigned IntrinsicID = cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue(); CompareOpc = -1; isDot = false; switch (IntrinsicID) { default: return false; // Comparison predicates. case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break; case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break; case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break; case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break; case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break; case Intrinsic::ppc_altivec_vcmpequd_p: if (Subtarget.hasP8Altivec()) { CompareOpc = 199; isDot = 1; } else return false; break; case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break; case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break; case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break; case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break; case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break; case Intrinsic::ppc_altivec_vcmpgtsd_p: if (Subtarget.hasP8Altivec()) { CompareOpc = 967; isDot = 1; } else return false; break; case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break; case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break; case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break; case Intrinsic::ppc_altivec_vcmpgtud_p: if (Subtarget.hasP8Altivec()) { CompareOpc = 711; isDot = 1; } else return false; break; // VSX predicate comparisons use the same infrastructure case Intrinsic::ppc_vsx_xvcmpeqdp_p: case Intrinsic::ppc_vsx_xvcmpgedp_p: case Intrinsic::ppc_vsx_xvcmpgtdp_p: case Intrinsic::ppc_vsx_xvcmpeqsp_p: case Intrinsic::ppc_vsx_xvcmpgesp_p: case Intrinsic::ppc_vsx_xvcmpgtsp_p: if (Subtarget.hasVSX()) { switch (IntrinsicID) { case Intrinsic::ppc_vsx_xvcmpeqdp_p: CompareOpc = 99; break; case Intrinsic::ppc_vsx_xvcmpgedp_p: CompareOpc = 115; break; case Intrinsic::ppc_vsx_xvcmpgtdp_p: CompareOpc = 107; break; case Intrinsic::ppc_vsx_xvcmpeqsp_p: CompareOpc = 67; break; case Intrinsic::ppc_vsx_xvcmpgesp_p: CompareOpc = 83; break; case Intrinsic::ppc_vsx_xvcmpgtsp_p: CompareOpc = 75; break; } isDot = 1; } else return false; break; // Normal Comparisons. case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break; case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break; case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break; case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break; case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break; case Intrinsic::ppc_altivec_vcmpequd: if (Subtarget.hasP8Altivec()) { CompareOpc = 199; isDot = 0; } else return false; break; case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break; case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break; case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break; case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break; case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break; case Intrinsic::ppc_altivec_vcmpgtsd: if (Subtarget.hasP8Altivec()) { CompareOpc = 967; isDot = 0; } else return false; break; case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break; case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break; case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break; case Intrinsic::ppc_altivec_vcmpgtud: if (Subtarget.hasP8Altivec()) { CompareOpc = 711; isDot = 0; } else return false; break; } return true; } /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom /// lower, do it, otherwise return null. SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const { // If this is a lowered altivec predicate compare, CompareOpc is set to the // opcode number of the comparison. SDLoc dl(Op); int CompareOpc; bool isDot; if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget)) return SDValue(); // Don't custom lower most intrinsics. // If this is a non-dot comparison, make the VCMP node and we are done. if (!isDot) { SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(), Op.getOperand(1), Op.getOperand(2), DAG.getConstant(CompareOpc, dl, MVT::i32)); return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp); } // Create the PPCISD altivec 'dot' comparison node. SDValue Ops[] = { Op.getOperand(2), // LHS Op.getOperand(3), // RHS DAG.getConstant(CompareOpc, dl, MVT::i32) }; EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue }; SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); // Now that we have the comparison, emit a copy from the CR to a GPR. // This is flagged to the above dot comparison. SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32, DAG.getRegister(PPC::CR6, MVT::i32), CompNode.getValue(1)); // Unpack the result based on how the target uses it. unsigned BitNo; // Bit # of CR6. bool InvertBit; // Invert result? switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) { default: // Can't happen, don't crash on invalid number though. case 0: // Return the value of the EQ bit of CR6. BitNo = 0; InvertBit = false; break; case 1: // Return the inverted value of the EQ bit of CR6. BitNo = 0; InvertBit = true; break; case 2: // Return the value of the LT bit of CR6. BitNo = 2; InvertBit = false; break; case 3: // Return the inverted value of the LT bit of CR6. BitNo = 2; InvertBit = true; break; } // Shift the bit into the low position. Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags, DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32)); // Isolate the bit. Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags, DAG.getConstant(1, dl, MVT::i32)); // If we are supposed to, toggle the bit. if (InvertBit) Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags, DAG.getConstant(1, dl, MVT::i32)); return Flags; } SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const { SDLoc dl(Op); // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int // instructions), but for smaller types, we need to first extend up to v2i32 // before doing going farther. if (Op.getValueType() == MVT::v2i64) { EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); if (ExtVT != MVT::v2i32) { Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)); Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op, DAG.getValueType(EVT::getVectorVT(*DAG.getContext(), ExtVT.getVectorElementType(), 4))); Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op); Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op, DAG.getValueType(MVT::v2i32)); } return Op; } return SDValue(); } SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const { SDLoc dl(Op); // Create a stack slot that is 16-byte aligned. MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); int FrameIdx = FrameInfo->CreateStackObject(16, 16, false); EVT PtrVT = getPointerTy(DAG.getDataLayout()); SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); // Store the input value into Value#0 of the stack slot. SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx, MachinePointerInfo(), false, false, 0); // Load it out. return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(), false, false, false, 0); } SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const { SDLoc dl(Op); SDNode *N = Op.getNode(); assert(N->getOperand(0).getValueType() == MVT::v4i1 && "Unknown extract_vector_elt type"); SDValue Value = N->getOperand(0); // The first part of this is like the store lowering except that we don't // need to track the chain. // The values are now known to be -1 (false) or 1 (true). To convert this // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to // understand how to form the extending load. SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64); FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64, FPHalfs, FPHalfs, FPHalfs, FPHalfs); Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); // Now convert to an integer and store. Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), Value); MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); int FrameIdx = FrameInfo->CreateStackObject(16, 16, false); MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); EVT PtrVT = getPointerTy(DAG.getDataLayout()); SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); SDValue StoreChain = DAG.getEntryNode(); SmallVector<SDValue, 2> Ops; Ops.push_back(StoreChain); Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32)); Ops.push_back(Value); Ops.push_back(FIdx); SmallVector<EVT, 2> ValueVTs; ValueVTs.push_back(MVT::Other); // chain SDVTList VTs = DAG.getVTList(ValueVTs); StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, VTs, Ops, MVT::v4i32, PtrInfo); // Extract the value requested. unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); SDValue IntVal = DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset), false, false, false, 0); if (!Subtarget.useCRBits()) return IntVal; return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal); } /// Lowering for QPX v4i1 loads SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op, SelectionDAG &DAG) const { SDLoc dl(Op); LoadSDNode *LN = cast<LoadSDNode>(Op.getNode()); SDValue LoadChain = LN->getChain(); SDValue BasePtr = LN->getBasePtr(); if (Op.getValueType() == MVT::v4f64 || Op.getValueType() == MVT::v4f32) { EVT MemVT = LN->getMemoryVT(); unsigned Alignment = LN->getAlignment(); // If this load is properly aligned, then it is legal. if (Alignment >= MemVT.getStoreSize()) return Op; EVT ScalarVT = Op.getValueType().getScalarType(), ScalarMemVT = MemVT.getScalarType(); unsigned Stride = ScalarMemVT.getStoreSize(); SmallVector<SDValue, 8> Vals, LoadChains; for (unsigned Idx = 0; Idx < 4; ++Idx) { SDValue Load; if (ScalarVT != ScalarMemVT) Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain, BasePtr, LN->getPointerInfo().getWithOffset(Idx*Stride), ScalarMemVT, LN->isVolatile(), LN->isNonTemporal(), LN->isInvariant(), MinAlign(Alignment, Idx*Stride), LN->getAAInfo()); else Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr, LN->getPointerInfo().getWithOffset(Idx*Stride), LN->isVolatile(), LN->isNonTemporal(), LN->isInvariant(), MinAlign(Alignment, Idx*Stride), LN->getAAInfo()); if (Idx == 0 && LN->isIndexed()) { assert(LN->getAddressingMode() == ISD::PRE_INC && "Unknown addressing mode on vector load"); Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(), LN->getAddressingMode()); } Vals.push_back(Load); LoadChains.push_back(Load.getValue(1)); BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, DAG.getConstant(Stride, dl, BasePtr.getValueType())); } SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, Op.getValueType(), Vals); if (LN->isIndexed()) { SDValue RetOps[] = { Value, Vals[0].getValue(1), TF }; return DAG.getMergeValues(RetOps, dl); } SDValue RetOps[] = { Value, TF }; return DAG.getMergeValues(RetOps, dl); } assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower"); assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported"); // To lower v4i1 from a byte array, we load the byte elements of the // vector and then reuse the BUILD_VECTOR logic. SmallVector<SDValue, 4> VectElmts, VectElmtChains; for (unsigned i = 0; i < 4; ++i) { SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); VectElmts.push_back(DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx, LN->getPointerInfo().getWithOffset(i), MVT::i8 /* memory type */, LN->isVolatile(), LN->isNonTemporal(), LN->isInvariant(), 1 /* alignment */, LN->getAAInfo())); VectElmtChains.push_back(VectElmts[i].getValue(1)); } LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains); SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i1, VectElmts); SDValue RVals[] = { Value, LoadChain }; return DAG.getMergeValues(RVals, dl); } /// Lowering for QPX v4i1 stores SDValue PPCTargetLowering::LowerVectorStore(SDValue Op, SelectionDAG &DAG) const { SDLoc dl(Op); StoreSDNode *SN = cast<StoreSDNode>(Op.getNode()); SDValue StoreChain = SN->getChain(); SDValue BasePtr = SN->getBasePtr(); SDValue Value = SN->getValue(); if (Value.getValueType() == MVT::v4f64 || Value.getValueType() == MVT::v4f32) { EVT MemVT = SN->getMemoryVT(); unsigned Alignment = SN->getAlignment(); // If this store is properly aligned, then it is legal. if (Alignment >= MemVT.getStoreSize()) return Op; EVT ScalarVT = Value.getValueType().getScalarType(), ScalarMemVT = MemVT.getScalarType(); unsigned Stride = ScalarMemVT.getStoreSize(); SmallVector<SDValue, 8> Stores; for (unsigned Idx = 0; Idx < 4; ++Idx) { SDValue Ex = DAG.getNode( ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value, DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout()))); SDValue Store; if (ScalarVT != ScalarMemVT) Store = DAG.getTruncStore(StoreChain, dl, Ex, BasePtr, SN->getPointerInfo().getWithOffset(Idx*Stride), ScalarMemVT, SN->isVolatile(), SN->isNonTemporal(), MinAlign(Alignment, Idx*Stride), SN->getAAInfo()); else Store = DAG.getStore(StoreChain, dl, Ex, BasePtr, SN->getPointerInfo().getWithOffset(Idx*Stride), SN->isVolatile(), SN->isNonTemporal(), MinAlign(Alignment, Idx*Stride), SN->getAAInfo()); if (Idx == 0 && SN->isIndexed()) { assert(SN->getAddressingMode() == ISD::PRE_INC && "Unknown addressing mode on vector store"); Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(), SN->getAddressingMode()); } BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, DAG.getConstant(Stride, dl, BasePtr.getValueType())); Stores.push_back(Store); } SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); if (SN->isIndexed()) { SDValue RetOps[] = { TF, Stores[0].getValue(1) }; return DAG.getMergeValues(RetOps, dl); } return TF; } assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported"); assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower"); // The values are now known to be -1 (false) or 1 (true). To convert this // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5). // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5 Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value); // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to // understand how to form the extending load. SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::f64); FPHalfs = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f64, FPHalfs, FPHalfs, FPHalfs, FPHalfs); Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs); // Now convert to an integer and store. Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64, DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32), Value); MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo(); int FrameIdx = FrameInfo->CreateStackObject(16, 16, false); MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx); EVT PtrVT = getPointerTy(DAG.getDataLayout()); SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT); SmallVector<SDValue, 2> Ops; Ops.push_back(StoreChain); Ops.push_back(DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32)); Ops.push_back(Value); Ops.push_back(FIdx); SmallVector<EVT, 2> ValueVTs; ValueVTs.push_back(MVT::Other); // chain SDVTList VTs = DAG.getVTList(ValueVTs); StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, dl, VTs, Ops, MVT::v4i32, PtrInfo); // Move data into the byte array. SmallVector<SDValue, 4> Loads, LoadChains; for (unsigned i = 0; i < 4; ++i) { unsigned Offset = 4*i; SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType()); Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx); Loads.push_back(DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset), false, false, false, 0)); LoadChains.push_back(Loads[i].getValue(1)); } StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains); SmallVector<SDValue, 4> Stores; for (unsigned i = 0; i < 4; ++i) { SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType()); Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx); Stores.push_back(DAG.getTruncStore( StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i), MVT::i8 /* memory type */, SN->isNonTemporal(), SN->isVolatile(), 1 /* alignment */, SN->getAAInfo())); } StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores); return StoreChain; } SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const { SDLoc dl(Op); if (Op.getValueType() == MVT::v4i32) { SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl); SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt. SDValue RHSSwap = // = vrlw RHS, 16 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl); // Shrinkify inputs to v8i16. LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS); RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS); RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap); // Low parts multiplied together, generating 32-bit results (we ignore the // top parts). SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh, LHS, RHS, DAG, dl, MVT::v4i32); SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm, LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32); // Shift the high parts up 16 bits. HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd, Neg16, DAG, dl); return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd); } else if (Op.getValueType() == MVT::v8i16) { SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl); return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm, LHS, RHS, Zero, DAG, dl); } else if (Op.getValueType() == MVT::v16i8) { SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1); bool isLittleEndian = Subtarget.isLittleEndian(); // Multiply the even 8-bit parts, producing 16-bit sums. SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub, LHS, RHS, DAG, dl, MVT::v8i16); EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts); // Multiply the odd 8-bit parts, producing 16-bit sums. SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub, LHS, RHS, DAG, dl, MVT::v8i16); OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts); // Merge the results together. Because vmuleub and vmuloub are // instructions with a big-endian bias, we must reverse the // element numbering and reverse the meaning of "odd" and "even" // when generating little endian code. int Ops[16]; for (unsigned i = 0; i != 8; ++i) { if (isLittleEndian) { Ops[i*2 ] = 2*i; Ops[i*2+1] = 2*i+16; } else { Ops[i*2 ] = 2*i+1; Ops[i*2+1] = 2*i+1+16; } } if (isLittleEndian) return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops); else return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops); } else { llvm_unreachable("Unknown mul to lower!"); } } /// LowerOperation - Provide custom lowering hooks for some operations. /// SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { switch (Op.getOpcode()) { default: llvm_unreachable("Wasn't expecting to be able to lower this!"); case ISD::ConstantPool: return LowerConstantPool(Op, DAG); case ISD::BlockAddress: return LowerBlockAddress(Op, DAG); case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG); case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG); case ISD::JumpTable: return LowerJumpTable(Op, DAG); case ISD::SETCC: return LowerSETCC(Op, DAG); case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG); case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG); case ISD::VASTART: return LowerVASTART(Op, DAG, Subtarget); case ISD::VAARG: return LowerVAARG(Op, DAG, Subtarget); case ISD::VACOPY: return LowerVACOPY(Op, DAG, Subtarget); case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget); case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget); case ISD::GET_DYNAMIC_AREA_OFFSET: return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG, Subtarget); case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG); case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG); case ISD::LOAD: return LowerLOAD(Op, DAG); case ISD::STORE: return LowerSTORE(Op, DAG); case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG); case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG); case ISD::FP_TO_UINT: case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG, SDLoc(Op)); case ISD::UINT_TO_FP: case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG); case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG); // Lower 64-bit shifts. case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG); case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG); case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG); // Vector-related lowering. case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG); case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG); case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG); case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG); case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG); case ISD::MUL: return LowerMUL(Op, DAG); // For counter-based loop handling. case ISD::INTRINSIC_W_CHAIN: return SDValue(); // Frame & Return address. case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG); } } void PPCTargetLowering::ReplaceNodeResults(SDNode *N, SmallVectorImpl<SDValue>&Results, SelectionDAG &DAG) const { SDLoc dl(N); switch (N->getOpcode()) { default: llvm_unreachable("Do not know how to custom type legalize this operation!"); case ISD::READCYCLECOUNTER: { SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0)); Results.push_back(RTB); Results.push_back(RTB.getValue(1)); Results.push_back(RTB.getValue(2)); break; } case ISD::INTRINSIC_W_CHAIN: { if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != Intrinsic::ppc_is_decremented_ctr_nonzero) break; assert(N->getValueType(0) == MVT::i1 && "Unexpected result type for CTR decrement intrinsic"); EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), N->getValueType(0)); SDVTList VTs = DAG.getVTList(SVT, MVT::Other); SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0), N->getOperand(1)); Results.push_back(NewInt); Results.push_back(NewInt.getValue(1)); break; } case ISD::VAARG: { if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64()) return; EVT VT = N->getValueType(0); if (VT == MVT::i64) { SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget); Results.push_back(NewNode); Results.push_back(NewNode.getValue(1)); } return; } case ISD::FP_ROUND_INREG: { assert(N->getValueType(0) == MVT::ppcf128); assert(N->getOperand(0).getValueType() == MVT::ppcf128); SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, N->getOperand(0), DAG.getIntPtrConstant(0, dl)); SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, N->getOperand(0), DAG.getIntPtrConstant(1, dl)); // Add the two halves of the long double in round-to-zero mode. SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi); // We know the low half is about to be thrown away, so just use something // convenient. Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128, FPreg, FPreg)); return; } case ISD::FP_TO_SINT: case ISD::FP_TO_UINT: // LowerFP_TO_INT() can only handle f32 and f64. if (N->getOperand(0).getValueType() == MVT::ppcf128) return; Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl)); return; } } //===----------------------------------------------------------------------===// // Other Lowering Code //===----------------------------------------------------------------------===// static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) { Module *M = Builder.GetInsertBlock()->getParent()->getParent(); Function *Func = Intrinsic::getDeclaration(M, Id); return Builder.CreateCall(Func, {}); } // The mappings for emitLeading/TrailingFence is taken from // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder, AtomicOrdering Ord, bool IsStore, bool IsLoad) const { if (Ord == SequentiallyConsistent) return callIntrinsic(Builder, Intrinsic::ppc_sync); if (isAtLeastRelease(Ord)) return callIntrinsic(Builder, Intrinsic::ppc_lwsync); return nullptr; } Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder, AtomicOrdering Ord, bool IsStore, bool IsLoad) const { if (IsLoad && isAtLeastAcquire(Ord)) return callIntrinsic(Builder, Intrinsic::ppc_lwsync); // FIXME: this is too conservative, a dependent branch + isync is enough. // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification. return nullptr; } MachineBasicBlock * PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB, unsigned AtomicSize, unsigned BinOpcode) const { // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. const TargetInstrInfo *TII = Subtarget.getInstrInfo(); auto LoadMnemonic = PPC::LDARX; auto StoreMnemonic = PPC::STDCX; switch (AtomicSize) { default: llvm_unreachable("Unexpected size of atomic entity"); case 1: LoadMnemonic = PPC::LBARX; StoreMnemonic = PPC::STBCX; assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); break; case 2: LoadMnemonic = PPC::LHARX; StoreMnemonic = PPC::STHCX; assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4"); break; case 4: LoadMnemonic = PPC::LWARX; StoreMnemonic = PPC::STWCX; break; case 8: LoadMnemonic = PPC::LDARX; StoreMnemonic = PPC::STDCX; break; } const BasicBlock *LLVM_BB = BB->getBasicBlock(); MachineFunction *F = BB->getParent(); MachineFunction::iterator It = ++BB->getIterator(); unsigned dest = MI->getOperand(0).getReg(); unsigned ptrA = MI->getOperand(1).getReg(); unsigned ptrB = MI->getOperand(2).getReg(); unsigned incr = MI->getOperand(3).getReg(); DebugLoc dl = MI->getDebugLoc(); MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); F->insert(It, loopMBB); F->insert(It, exitMBB); exitMBB->splice(exitMBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)), BB->end()); exitMBB->transferSuccessorsAndUpdatePHIs(BB); MachineRegisterInfo &RegInfo = F->getRegInfo(); unsigned TmpReg = (!BinOpcode) ? incr : RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass); // thisMBB: // ... // fallthrough --> loopMBB BB->addSuccessor(loopMBB); // loopMBB: // l[wd]arx dest, ptr // add r0, dest, incr // st[wd]cx. r0, ptr // bne- loopMBB // fallthrough --> exitMBB BB = loopMBB; BuildMI(BB, dl, TII->get(LoadMnemonic), dest) .addReg(ptrA).addReg(ptrB); if (BinOpcode) BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest); BuildMI(BB, dl, TII->get(StoreMnemonic)) .addReg(TmpReg).addReg(ptrA).addReg(ptrB); BuildMI(BB, dl, TII->get(PPC::BCC)) .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); BB->addSuccessor(loopMBB); BB->addSuccessor(exitMBB); // exitMBB: // ... BB = exitMBB; return BB; } MachineBasicBlock * PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB, bool is8bit, // operation unsigned BinOpcode) const { // If we support part-word atomic mnemonics, just use them if (Subtarget.hasPartwordAtomics()) return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode); // This also handles ATOMIC_SWAP, indicated by BinOpcode==0. const TargetInstrInfo *TII = Subtarget.getInstrInfo(); // In 64 bit mode we have to use 64 bits for addresses, even though the // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address // registers without caring whether they're 32 or 64, but here we're // doing actual arithmetic on the addresses. bool is64bit = Subtarget.isPPC64(); unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; const BasicBlock *LLVM_BB = BB->getBasicBlock(); MachineFunction *F = BB->getParent(); MachineFunction::iterator It = ++BB->getIterator(); unsigned dest = MI->getOperand(0).getReg(); unsigned ptrA = MI->getOperand(1).getReg(); unsigned ptrB = MI->getOperand(2).getReg(); unsigned incr = MI->getOperand(3).getReg(); DebugLoc dl = MI->getDebugLoc(); MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB); MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); F->insert(It, loopMBB); F->insert(It, exitMBB); exitMBB->splice(exitMBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)), BB->end()); exitMBB->transferSuccessorsAndUpdatePHIs(BB); MachineRegisterInfo &RegInfo = F->getRegInfo(); const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; unsigned PtrReg = RegInfo.createVirtualRegister(RC); unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); unsigned ShiftReg = RegInfo.createVirtualRegister(RC); unsigned Incr2Reg = RegInfo.createVirtualRegister(RC); unsigned MaskReg = RegInfo.createVirtualRegister(RC); unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC); unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); unsigned Ptr1Reg; unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC); // thisMBB: // ... // fallthrough --> loopMBB BB->addSuccessor(loopMBB); // The 4-byte load must be aligned, while a char or short may be // anywhere in the word. Hence all this nasty bookkeeping code. // add ptr1, ptrA, ptrB [copy if ptrA==0] // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] // xori shift, shift1, 24 [16] // rlwinm ptr, ptr1, 0, 0, 29 // slw incr2, incr, shift // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] // slw mask, mask2, shift // loopMBB: // lwarx tmpDest, ptr // add tmp, tmpDest, incr2 // andc tmp2, tmpDest, mask // and tmp3, tmp, mask // or tmp4, tmp3, tmp2 // stwcx. tmp4, ptr // bne- loopMBB // fallthrough --> exitMBB // srw dest, tmpDest, shift if (ptrA != ZeroReg) { Ptr1Reg = RegInfo.createVirtualRegister(RC); BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) .addReg(ptrA).addReg(ptrB); } else { Ptr1Reg = ptrB; } BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); if (is64bit) BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) .addReg(Ptr1Reg).addImm(0).addImm(61); else BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg) .addReg(incr).addReg(ShiftReg); if (is8bit) BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); else { BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535); } BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) .addReg(Mask2Reg).addReg(ShiftReg); BB = loopMBB; BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) .addReg(ZeroReg).addReg(PtrReg); if (BinOpcode) BuildMI(BB, dl, TII->get(BinOpcode), TmpReg) .addReg(Incr2Reg).addReg(TmpDestReg); BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg) .addReg(TmpDestReg).addReg(MaskReg); BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg) .addReg(TmpReg).addReg(MaskReg); BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg) .addReg(Tmp3Reg).addReg(Tmp2Reg); BuildMI(BB, dl, TII->get(PPC::STWCX)) .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg); BuildMI(BB, dl, TII->get(PPC::BCC)) .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB); BB->addSuccessor(loopMBB); BB->addSuccessor(exitMBB); // exitMBB: // ... BB = exitMBB; BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg) .addReg(ShiftReg); return BB; } llvm::MachineBasicBlock* PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI, MachineBasicBlock *MBB) const { DebugLoc DL = MI->getDebugLoc(); const TargetInstrInfo *TII = Subtarget.getInstrInfo(); MachineFunction *MF = MBB->getParent(); MachineRegisterInfo &MRI = MF->getRegInfo(); const BasicBlock *BB = MBB->getBasicBlock(); MachineFunction::iterator I = ++MBB->getIterator(); // Memory Reference MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); unsigned DstReg = MI->getOperand(0).getReg(); const TargetRegisterClass *RC = MRI.getRegClass(DstReg); assert(RC->hasType(MVT::i32) && "Invalid destination!"); unsigned mainDstReg = MRI.createVirtualRegister(RC); unsigned restoreDstReg = MRI.createVirtualRegister(RC); MVT PVT = getPointerTy(MF->getDataLayout()); assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!"); // For v = setjmp(buf), we generate // // thisMBB: // SjLjSetup mainMBB // bl mainMBB // v_restore = 1 // b sinkMBB // // mainMBB: // buf[LabelOffset] = LR // v_main = 0 // // sinkMBB: // v = phi(main, restore) // MachineBasicBlock *thisMBB = MBB; MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB); MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB); MF->insert(I, mainMBB); MF->insert(I, sinkMBB); MachineInstrBuilder MIB; // Transfer the remainder of BB and its successor edges to sinkMBB. sinkMBB->splice(sinkMBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)), MBB->end()); sinkMBB->transferSuccessorsAndUpdatePHIs(MBB); // Note that the structure of the jmp_buf used here is not compatible // with that used by libc, and is not designed to be. Specifically, it // stores only those 'reserved' registers that LLVM does not otherwise // understand how to spill. Also, by convention, by the time this // intrinsic is called, Clang has already stored the frame address in the // first slot of the buffer and stack address in the third. Following the // X86 target code, we'll store the jump address in the second slot. We also // need to save the TOC pointer (R2) to handle jumps between shared // libraries, and that will be stored in the fourth slot. The thread // identifier (R13) is not affected. // thisMBB: const int64_t LabelOffset = 1 * PVT.getStoreSize(); const int64_t TOCOffset = 3 * PVT.getStoreSize(); const int64_t BPOffset = 4 * PVT.getStoreSize(); // Prepare IP either in reg. const TargetRegisterClass *PtrRC = getRegClassFor(PVT); unsigned LabelReg = MRI.createVirtualRegister(PtrRC); unsigned BufReg = MI->getOperand(1).getReg(); if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) { setUsesTOCBasePtr(*MBB->getParent()); MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD)) .addReg(PPC::X2) .addImm(TOCOffset) .addReg(BufReg); MIB.setMemRefs(MMOBegin, MMOEnd); } // Naked functions never have a base pointer, and so we use r1. For all // other functions, this decision must be delayed until during PEI. unsigned BaseReg; if (MF->getFunction()->hasFnAttribute(Attribute::Naked)) BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1; else BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP; MIB = BuildMI(*thisMBB, MI, DL, TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW)) .addReg(BaseReg) .addImm(BPOffset) .addReg(BufReg); MIB.setMemRefs(MMOBegin, MMOEnd); // Setup MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB); const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo(); MIB.addRegMask(TRI->getNoPreservedMask()); BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1); MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup)) .addMBB(mainMBB); MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB); thisMBB->addSuccessor(mainMBB, BranchProbability::getZero()); thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne()); // mainMBB: // mainDstReg = 0 MIB = BuildMI(mainMBB, DL, TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg); // Store IP if (Subtarget.isPPC64()) { MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD)) .addReg(LabelReg) .addImm(LabelOffset) .addReg(BufReg); } else { MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW)) .addReg(LabelReg) .addImm(LabelOffset) .addReg(BufReg); } MIB.setMemRefs(MMOBegin, MMOEnd); BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0); mainMBB->addSuccessor(sinkMBB); // sinkMBB: BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(PPC::PHI), DstReg) .addReg(mainDstReg).addMBB(mainMBB) .addReg(restoreDstReg).addMBB(thisMBB); MI->eraseFromParent(); return sinkMBB; } MachineBasicBlock * PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI, MachineBasicBlock *MBB) const { DebugLoc DL = MI->getDebugLoc(); const TargetInstrInfo *TII = Subtarget.getInstrInfo(); MachineFunction *MF = MBB->getParent(); MachineRegisterInfo &MRI = MF->getRegInfo(); // Memory Reference MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin(); MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end(); MVT PVT = getPointerTy(MF->getDataLayout()); assert((PVT == MVT::i64 || PVT == MVT::i32) && "Invalid Pointer Size!"); const TargetRegisterClass *RC = (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; unsigned Tmp = MRI.createVirtualRegister(RC); // Since FP is only updated here but NOT referenced, it's treated as GPR. unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31; unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1; unsigned BP = (PVT == MVT::i64) ? PPC::X30 : (Subtarget.isSVR4ABI() && MF->getTarget().getRelocationModel() == Reloc::PIC_ ? PPC::R29 : PPC::R30); MachineInstrBuilder MIB; const int64_t LabelOffset = 1 * PVT.getStoreSize(); const int64_t SPOffset = 2 * PVT.getStoreSize(); const int64_t TOCOffset = 3 * PVT.getStoreSize(); const int64_t BPOffset = 4 * PVT.getStoreSize(); unsigned BufReg = MI->getOperand(0).getReg(); // Reload FP (the jumped-to function may not have had a // frame pointer, and if so, then its r31 will be restored // as necessary). if (PVT == MVT::i64) { MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP) .addImm(0) .addReg(BufReg); } else { MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP) .addImm(0) .addReg(BufReg); } MIB.setMemRefs(MMOBegin, MMOEnd); // Reload IP if (PVT == MVT::i64) { MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp) .addImm(LabelOffset) .addReg(BufReg); } else { MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp) .addImm(LabelOffset) .addReg(BufReg); } MIB.setMemRefs(MMOBegin, MMOEnd); // Reload SP if (PVT == MVT::i64) { MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP) .addImm(SPOffset) .addReg(BufReg); } else { MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP) .addImm(SPOffset) .addReg(BufReg); } MIB.setMemRefs(MMOBegin, MMOEnd); // Reload BP if (PVT == MVT::i64) { MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP) .addImm(BPOffset) .addReg(BufReg); } else { MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP) .addImm(BPOffset) .addReg(BufReg); } MIB.setMemRefs(MMOBegin, MMOEnd); // Reload TOC if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) { setUsesTOCBasePtr(*MBB->getParent()); MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2) .addImm(TOCOffset) .addReg(BufReg); MIB.setMemRefs(MMOBegin, MMOEnd); } // Jump BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp); BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR)); MI->eraseFromParent(); return MBB; } MachineBasicBlock * PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI, MachineBasicBlock *BB) const { if (MI->getOpcode() == TargetOpcode::STACKMAP || MI->getOpcode() == TargetOpcode::PATCHPOINT) { if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() && MI->getOpcode() == TargetOpcode::PATCHPOINT) { // Call lowering should have added an r2 operand to indicate a dependence // on the TOC base pointer value. It can't however, because there is no // way to mark the dependence as implicit there, and so the stackmap code // will confuse it with a regular operand. Instead, add the dependence // here. setUsesTOCBasePtr(*BB->getParent()); MI->addOperand(MachineOperand::CreateReg(PPC::X2, false, true)); } return emitPatchPoint(MI, BB); } if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 || MI->getOpcode() == PPC::EH_SjLj_SetJmp64) { return emitEHSjLjSetJmp(MI, BB); } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 || MI->getOpcode() == PPC::EH_SjLj_LongJmp64) { return emitEHSjLjLongJmp(MI, BB); } const TargetInstrInfo *TII = Subtarget.getInstrInfo(); // To "insert" these instructions we actually have to insert their // control-flow patterns. const BasicBlock *LLVM_BB = BB->getBasicBlock(); MachineFunction::iterator It = ++BB->getIterator(); MachineFunction *F = BB->getParent(); if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 || MI->getOpcode() == PPC::SELECT_CC_I8 || MI->getOpcode() == PPC::SELECT_I4 || MI->getOpcode() == PPC::SELECT_I8)) { SmallVector<MachineOperand, 2> Cond; if (MI->getOpcode() == PPC::SELECT_CC_I4 || MI->getOpcode() == PPC::SELECT_CC_I8) Cond.push_back(MI->getOperand(4)); else Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); Cond.push_back(MI->getOperand(1)); DebugLoc dl = MI->getDebugLoc(); TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(), Cond, MI->getOperand(2).getReg(), MI->getOperand(3).getReg()); } else if (MI->getOpcode() == PPC::SELECT_CC_I4 || MI->getOpcode() == PPC::SELECT_CC_I8 || MI->getOpcode() == PPC::SELECT_CC_F4 || MI->getOpcode() == PPC::SELECT_CC_F8 || MI->getOpcode() == PPC::SELECT_CC_QFRC || MI->getOpcode() == PPC::SELECT_CC_QSRC || MI->getOpcode() == PPC::SELECT_CC_QBRC || MI->getOpcode() == PPC::SELECT_CC_VRRC || MI->getOpcode() == PPC::SELECT_CC_VSFRC || MI->getOpcode() == PPC::SELECT_CC_VSSRC || MI->getOpcode() == PPC::SELECT_CC_VSRC || MI->getOpcode() == PPC::SELECT_I4 || MI->getOpcode() == PPC::SELECT_I8 || MI->getOpcode() == PPC::SELECT_F4 || MI->getOpcode() == PPC::SELECT_F8 || MI->getOpcode() == PPC::SELECT_QFRC || MI->getOpcode() == PPC::SELECT_QSRC || MI->getOpcode() == PPC::SELECT_QBRC || MI->getOpcode() == PPC::SELECT_VRRC || MI->getOpcode() == PPC::SELECT_VSFRC || MI->getOpcode() == PPC::SELECT_VSSRC || MI->getOpcode() == PPC::SELECT_VSRC) { // The incoming instruction knows the destination vreg to set, the // condition code register to branch on, the true/false values to // select between, and a branch opcode to use. // thisMBB: // ... // TrueVal = ... // cmpTY ccX, r1, r2 // bCC copy1MBB // fallthrough --> copy0MBB MachineBasicBlock *thisMBB = BB; MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB); MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); DebugLoc dl = MI->getDebugLoc(); F->insert(It, copy0MBB); F->insert(It, sinkMBB); // Transfer the remainder of BB and its successor edges to sinkMBB. sinkMBB->splice(sinkMBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)), BB->end()); sinkMBB->transferSuccessorsAndUpdatePHIs(BB); // Next, add the true and fallthrough blocks as its successors. BB->addSuccessor(copy0MBB); BB->addSuccessor(sinkMBB); if (MI->getOpcode() == PPC::SELECT_I4 || MI->getOpcode() == PPC::SELECT_I8 || MI->getOpcode() == PPC::SELECT_F4 || MI->getOpcode() == PPC::SELECT_F8 || MI->getOpcode() == PPC::SELECT_QFRC || MI->getOpcode() == PPC::SELECT_QSRC || MI->getOpcode() == PPC::SELECT_QBRC || MI->getOpcode() == PPC::SELECT_VRRC || MI->getOpcode() == PPC::SELECT_VSFRC || MI->getOpcode() == PPC::SELECT_VSSRC || MI->getOpcode() == PPC::SELECT_VSRC) { BuildMI(BB, dl, TII->get(PPC::BC)) .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB); } else { unsigned SelectPred = MI->getOperand(4).getImm(); BuildMI(BB, dl, TII->get(PPC::BCC)) .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB); } // copy0MBB: // %FalseValue = ... // # fallthrough to sinkMBB BB = copy0MBB; // Update machine-CFG edges BB->addSuccessor(sinkMBB); // sinkMBB: // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ] // ... BB = sinkMBB; BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI->getOperand(0).getReg()) .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB) .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB); } else if (MI->getOpcode() == PPC::ReadTB) { // To read the 64-bit time-base register on a 32-bit target, we read the // two halves. Should the counter have wrapped while it was being read, we // need to try again. // ... // readLoop: // mfspr Rx,TBU # load from TBU // mfspr Ry,TB # load from TB // mfspr Rz,TBU # load from TBU // cmpw crX,Rx,Rz # check if 'old'='new' // bne readLoop # branch if they're not equal // ... MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB); MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB); DebugLoc dl = MI->getDebugLoc(); F->insert(It, readMBB); F->insert(It, sinkMBB); // Transfer the remainder of BB and its successor edges to sinkMBB. sinkMBB->splice(sinkMBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)), BB->end()); sinkMBB->transferSuccessorsAndUpdatePHIs(BB); BB->addSuccessor(readMBB); BB = readMBB; MachineRegisterInfo &RegInfo = F->getRegInfo(); unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass); unsigned LoReg = MI->getOperand(0).getReg(); unsigned HiReg = MI->getOperand(1).getReg(); BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269); BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268); BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269); unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg) .addReg(HiReg).addReg(ReadAgainReg); BuildMI(BB, dl, TII->get(PPC::BCC)) .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB); BB->addSuccessor(readMBB); BB->addSuccessor(sinkMBB); } else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8) BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16) BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32) BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64) BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8) BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16) BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32) BB = EmitAtomicBinary(MI, BB, 4, PPC::AND); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64) BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8) BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16) BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32) BB = EmitAtomicBinary(MI, BB, 4, PPC::OR); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64) BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8) BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16) BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32) BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64) BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8) BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16) BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32) BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64) BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8) BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16) BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32) BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF); else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64) BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8); else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8) BB = EmitPartwordAtomicBinary(MI, BB, true, 0); else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16) BB = EmitPartwordAtomicBinary(MI, BB, false, 0); else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32) BB = EmitAtomicBinary(MI, BB, 4, 0); else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64) BB = EmitAtomicBinary(MI, BB, 8, 0); else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 || MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 || (Subtarget.hasPartwordAtomics() && MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) || (Subtarget.hasPartwordAtomics() && MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) { bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64; auto LoadMnemonic = PPC::LDARX; auto StoreMnemonic = PPC::STDCX; switch(MI->getOpcode()) { default: llvm_unreachable("Compare and swap of unknown size"); case PPC::ATOMIC_CMP_SWAP_I8: LoadMnemonic = PPC::LBARX; StoreMnemonic = PPC::STBCX; assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); break; case PPC::ATOMIC_CMP_SWAP_I16: LoadMnemonic = PPC::LHARX; StoreMnemonic = PPC::STHCX; assert(Subtarget.hasPartwordAtomics() && "No support partword atomics."); break; case PPC::ATOMIC_CMP_SWAP_I32: LoadMnemonic = PPC::LWARX; StoreMnemonic = PPC::STWCX; break; case PPC::ATOMIC_CMP_SWAP_I64: LoadMnemonic = PPC::LDARX; StoreMnemonic = PPC::STDCX; break; } unsigned dest = MI->getOperand(0).getReg(); unsigned ptrA = MI->getOperand(1).getReg(); unsigned ptrB = MI->getOperand(2).getReg(); unsigned oldval = MI->getOperand(3).getReg(); unsigned newval = MI->getOperand(4).getReg(); DebugLoc dl = MI->getDebugLoc(); MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); F->insert(It, loop1MBB); F->insert(It, loop2MBB); F->insert(It, midMBB); F->insert(It, exitMBB); exitMBB->splice(exitMBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)), BB->end()); exitMBB->transferSuccessorsAndUpdatePHIs(BB); // thisMBB: // ... // fallthrough --> loopMBB BB->addSuccessor(loop1MBB); // loop1MBB: // l[bhwd]arx dest, ptr // cmp[wd] dest, oldval // bne- midMBB // loop2MBB: // st[bhwd]cx. newval, ptr // bne- loopMBB // b exitBB // midMBB: // st[bhwd]cx. dest, ptr // exitBB: BB = loop1MBB; BuildMI(BB, dl, TII->get(LoadMnemonic), dest) .addReg(ptrA).addReg(ptrB); BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0) .addReg(oldval).addReg(dest); BuildMI(BB, dl, TII->get(PPC::BCC)) .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); BB->addSuccessor(loop2MBB); BB->addSuccessor(midMBB); BB = loop2MBB; BuildMI(BB, dl, TII->get(StoreMnemonic)) .addReg(newval).addReg(ptrA).addReg(ptrB); BuildMI(BB, dl, TII->get(PPC::BCC)) .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); BB->addSuccessor(loop1MBB); BB->addSuccessor(exitMBB); BB = midMBB; BuildMI(BB, dl, TII->get(StoreMnemonic)) .addReg(dest).addReg(ptrA).addReg(ptrB); BB->addSuccessor(exitMBB); // exitMBB: // ... BB = exitMBB; } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 || MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) { // We must use 64-bit registers for addresses when targeting 64-bit, // since we're actually doing arithmetic on them. Other registers // can be 32-bit. bool is64bit = Subtarget.isPPC64(); bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8; unsigned dest = MI->getOperand(0).getReg(); unsigned ptrA = MI->getOperand(1).getReg(); unsigned ptrB = MI->getOperand(2).getReg(); unsigned oldval = MI->getOperand(3).getReg(); unsigned newval = MI->getOperand(4).getReg(); DebugLoc dl = MI->getDebugLoc(); MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB); MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB); MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB); MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB); F->insert(It, loop1MBB); F->insert(It, loop2MBB); F->insert(It, midMBB); F->insert(It, exitMBB); exitMBB->splice(exitMBB->begin(), BB, std::next(MachineBasicBlock::iterator(MI)), BB->end()); exitMBB->transferSuccessorsAndUpdatePHIs(BB); MachineRegisterInfo &RegInfo = F->getRegInfo(); const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass; unsigned PtrReg = RegInfo.createVirtualRegister(RC); unsigned Shift1Reg = RegInfo.createVirtualRegister(RC); unsigned ShiftReg = RegInfo.createVirtualRegister(RC); unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC); unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC); unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC); unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC); unsigned MaskReg = RegInfo.createVirtualRegister(RC); unsigned Mask2Reg = RegInfo.createVirtualRegister(RC); unsigned Mask3Reg = RegInfo.createVirtualRegister(RC); unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC); unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC); unsigned TmpDestReg = RegInfo.createVirtualRegister(RC); unsigned Ptr1Reg; unsigned TmpReg = RegInfo.createVirtualRegister(RC); unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO; // thisMBB: // ... // fallthrough --> loopMBB BB->addSuccessor(loop1MBB); // The 4-byte load must be aligned, while a char or short may be // anywhere in the word. Hence all this nasty bookkeeping code. // add ptr1, ptrA, ptrB [copy if ptrA==0] // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27] // xori shift, shift1, 24 [16] // rlwinm ptr, ptr1, 0, 0, 29 // slw newval2, newval, shift // slw oldval2, oldval,shift // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535] // slw mask, mask2, shift // and newval3, newval2, mask // and oldval3, oldval2, mask // loop1MBB: // lwarx tmpDest, ptr // and tmp, tmpDest, mask // cmpw tmp, oldval3 // bne- midMBB // loop2MBB: // andc tmp2, tmpDest, mask // or tmp4, tmp2, newval3 // stwcx. tmp4, ptr // bne- loop1MBB // b exitBB // midMBB: // stwcx. tmpDest, ptr // exitBB: // srw dest, tmpDest, shift if (ptrA != ZeroReg) { Ptr1Reg = RegInfo.createVirtualRegister(RC); BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg) .addReg(ptrA).addReg(ptrB); } else { Ptr1Reg = ptrB; } BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg) .addImm(3).addImm(27).addImm(is8bit ? 28 : 27); BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg) .addReg(Shift1Reg).addImm(is8bit ? 24 : 16); if (is64bit) BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg) .addReg(Ptr1Reg).addImm(0).addImm(61); else BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg) .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29); BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg) .addReg(newval).addReg(ShiftReg); BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg) .addReg(oldval).addReg(ShiftReg); if (is8bit) BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255); else { BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0); BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg) .addReg(Mask3Reg).addImm(65535); } BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg) .addReg(Mask2Reg).addReg(ShiftReg); BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg) .addReg(NewVal2Reg).addReg(MaskReg); BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg) .addReg(OldVal2Reg).addReg(MaskReg); BB = loop1MBB; BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg) .addReg(ZeroReg).addReg(PtrReg); BuildMI(BB, dl, TII->get(PPC::AND),TmpReg) .addReg(TmpDestReg).addReg(MaskReg); BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0) .addReg(TmpReg).addReg(OldVal3Reg); BuildMI(BB, dl, TII->get(PPC::BCC)) .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB); BB->addSuccessor(loop2MBB); BB->addSuccessor(midMBB); BB = loop2MBB; BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg) .addReg(TmpDestReg).addReg(MaskReg); BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg) .addReg(Tmp2Reg).addReg(NewVal3Reg); BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg) .addReg(ZeroReg).addReg(PtrReg); BuildMI(BB, dl, TII->get(PPC::BCC)) .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB); BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB); BB->addSuccessor(loop1MBB); BB->addSuccessor(exitMBB); BB = midMBB; BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg) .addReg(ZeroReg).addReg(PtrReg); BB->addSuccessor(exitMBB); // exitMBB: // ... BB = exitMBB; BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg) .addReg(ShiftReg); } else if (MI->getOpcode() == PPC::FADDrtz) { // This pseudo performs an FADD with rounding mode temporarily forced // to round-to-zero. We emit this via custom inserter since the FPSCR // is not modeled at the SelectionDAG level. unsigned Dest = MI->getOperand(0).getReg(); unsigned Src1 = MI->getOperand(1).getReg(); unsigned Src2 = MI->getOperand(2).getReg(); DebugLoc dl = MI->getDebugLoc(); MachineRegisterInfo &RegInfo = F->getRegInfo(); unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass); // Save FPSCR value. BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg); // Set rounding mode to round-to-zero. BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31); BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30); // Perform addition. BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2); // Restore FPSCR value. BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg); } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT || MI->getOpcode() == PPC::ANDIo_1_GT_BIT || MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 || MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) { unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 || MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ? PPC::ANDIo8 : PPC::ANDIo; bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT || MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8); MachineRegisterInfo &RegInfo = F->getRegInfo(); unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass); DebugLoc dl = MI->getDebugLoc(); BuildMI(*BB, MI, dl, TII->get(Opcode), Dest) .addReg(MI->getOperand(1).getReg()).addImm(1); BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg()) .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT); } else if (MI->getOpcode() == PPC::TCHECK_RET) { DebugLoc Dl = MI->getDebugLoc(); MachineRegisterInfo &RegInfo = F->getRegInfo(); unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass); BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg); return BB; } else { llvm_unreachable("Unexpected instr type to insert"); } MI->eraseFromParent(); // The pseudo instruction is gone now. return BB; } //===----------------------------------------------------------------------===// // Target Optimization Hooks //===----------------------------------------------------------------------===// static std::string getRecipOp(const char *Base, EVT VT) { std::string RecipOp(Base); if (VT.getScalarType() == MVT::f64) RecipOp += "d"; else RecipOp += "f"; if (VT.isVector()) RecipOp = "vec-" + RecipOp; return RecipOp; } SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand, DAGCombinerInfo &DCI, unsigned &RefinementSteps, bool &UseOneConstNR) const { EVT VT = Operand.getValueType(); if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) || (VT == MVT::f64 && Subtarget.hasFRSQRTE()) || (VT == MVT::v4f32 && Subtarget.hasAltivec()) || (VT == MVT::v2f64 && Subtarget.hasVSX()) || (VT == MVT::v4f32 && Subtarget.hasQPX()) || (VT == MVT::v4f64 && Subtarget.hasQPX())) { TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals; std::string RecipOp = getRecipOp("sqrt", VT); if (!Recips.isEnabled(RecipOp)) return SDValue(); RefinementSteps = Recips.getRefinementSteps(RecipOp); UseOneConstNR = true; return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand); } return SDValue(); } SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, DAGCombinerInfo &DCI, unsigned &RefinementSteps) const { EVT VT = Operand.getValueType(); if ((VT == MVT::f32 && Subtarget.hasFRES()) || (VT == MVT::f64 && Subtarget.hasFRE()) || (VT == MVT::v4f32 && Subtarget.hasAltivec()) || (VT == MVT::v2f64 && Subtarget.hasVSX()) || (VT == MVT::v4f32 && Subtarget.hasQPX()) || (VT == MVT::v4f64 && Subtarget.hasQPX())) { TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals; std::string RecipOp = getRecipOp("div", VT); if (!Recips.isEnabled(RecipOp)) return SDValue(); RefinementSteps = Recips.getRefinementSteps(RecipOp); return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand); } return SDValue(); } unsigned PPCTargetLowering::combineRepeatedFPDivisors() const { // Note: This functionality is used only when unsafe-fp-math is enabled, and // on cores with reciprocal estimates (which are used when unsafe-fp-math is // enabled for division), this functionality is redundant with the default // combiner logic (once the division -> reciprocal/multiply transformation // has taken place). As a result, this matters more for older cores than for // newer ones. // Combine multiple FDIVs with the same divisor into multiple FMULs by the // reciprocal if there are two or more FDIVs (for embedded cores with only // one FP pipeline) for three or more FDIVs (for generic OOO cores). switch (Subtarget.getDarwinDirective()) { default: return 3; case PPC::DIR_440: case PPC::DIR_A2: case PPC::DIR_E500mc: case PPC::DIR_E5500: return 2; } } // isConsecutiveLSLoc needs to work even if all adds have not yet been // collapsed, and so we need to look through chains of them. static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base, int64_t& Offset, SelectionDAG &DAG) { if (DAG.isBaseWithConstantOffset(Loc)) { Base = Loc.getOperand(0); Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue(); // The base might itself be a base plus an offset, and if so, accumulate // that as well. getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG); } } static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base, unsigned Bytes, int Dist, SelectionDAG &DAG) { if (VT.getSizeInBits() / 8 != Bytes) return false; SDValue BaseLoc = Base->getBasePtr(); if (Loc.getOpcode() == ISD::FrameIndex) { if (BaseLoc.getOpcode() != ISD::FrameIndex) return false; const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo(); int FI = cast<FrameIndexSDNode>(Loc)->getIndex(); int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex(); int FS = MFI->getObjectSize(FI); int BFS = MFI->getObjectSize(BFI); if (FS != BFS || FS != (int)Bytes) return false; return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes); } SDValue Base1 = Loc, Base2 = BaseLoc; int64_t Offset1 = 0, Offset2 = 0; getBaseWithConstantOffset(Loc, Base1, Offset1, DAG); getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG); if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes)) return true; const TargetLowering &TLI = DAG.getTargetLoweringInfo(); const GlobalValue *GV1 = nullptr; const GlobalValue *GV2 = nullptr; Offset1 = 0; Offset2 = 0; bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1); bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2); if (isGA1 && isGA2 && GV1 == GV2) return Offset1 == (Offset2 + Dist*Bytes); return false; } // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does // not enforce equality of the chain operands. static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base, unsigned Bytes, int Dist, SelectionDAG &DAG) { if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) { EVT VT = LS->getMemoryVT(); SDValue Loc = LS->getBasePtr(); return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG); } if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) { EVT VT; switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { default: return false; case Intrinsic::ppc_qpx_qvlfd: case Intrinsic::ppc_qpx_qvlfda: VT = MVT::v4f64; break; case Intrinsic::ppc_qpx_qvlfs: case Intrinsic::ppc_qpx_qvlfsa: VT = MVT::v4f32; break; case Intrinsic::ppc_qpx_qvlfcd: case Intrinsic::ppc_qpx_qvlfcda: VT = MVT::v2f64; break; case Intrinsic::ppc_qpx_qvlfcs: case Intrinsic::ppc_qpx_qvlfcsa: VT = MVT::v2f32; break; case Intrinsic::ppc_qpx_qvlfiwa: case Intrinsic::ppc_qpx_qvlfiwz: case Intrinsic::ppc_altivec_lvx: case Intrinsic::ppc_altivec_lvxl: case Intrinsic::ppc_vsx_lxvw4x: VT = MVT::v4i32; break; case Intrinsic::ppc_vsx_lxvd2x: VT = MVT::v2f64; break; case Intrinsic::ppc_altivec_lvebx: VT = MVT::i8; break; case Intrinsic::ppc_altivec_lvehx: VT = MVT::i16; break; case Intrinsic::ppc_altivec_lvewx: VT = MVT::i32; break; } return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG); } if (N->getOpcode() == ISD::INTRINSIC_VOID) { EVT VT; switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { default: return false; case Intrinsic::ppc_qpx_qvstfd: case Intrinsic::ppc_qpx_qvstfda: VT = MVT::v4f64; break; case Intrinsic::ppc_qpx_qvstfs: case Intrinsic::ppc_qpx_qvstfsa: VT = MVT::v4f32; break; case Intrinsic::ppc_qpx_qvstfcd: case Intrinsic::ppc_qpx_qvstfcda: VT = MVT::v2f64; break; case Intrinsic::ppc_qpx_qvstfcs: case Intrinsic::ppc_qpx_qvstfcsa: VT = MVT::v2f32; break; case Intrinsic::ppc_qpx_qvstfiw: case Intrinsic::ppc_qpx_qvstfiwa: case Intrinsic::ppc_altivec_stvx: case Intrinsic::ppc_altivec_stvxl: case Intrinsic::ppc_vsx_stxvw4x: VT = MVT::v4i32; break; case Intrinsic::ppc_vsx_stxvd2x: VT = MVT::v2f64; break; case Intrinsic::ppc_altivec_stvebx: VT = MVT::i8; break; case Intrinsic::ppc_altivec_stvehx: VT = MVT::i16; break; case Intrinsic::ppc_altivec_stvewx: VT = MVT::i32; break; } return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG); } return false; } // Return true is there is a nearyby consecutive load to the one provided // (regardless of alignment). We search up and down the chain, looking though // token factors and other loads (but nothing else). As a result, a true result // indicates that it is safe to create a new consecutive load adjacent to the // load provided. static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) { SDValue Chain = LD->getChain(); EVT VT = LD->getMemoryVT(); SmallSet<SDNode *, 16> LoadRoots; SmallVector<SDNode *, 8> Queue(1, Chain.getNode()); SmallSet<SDNode *, 16> Visited; // First, search up the chain, branching to follow all token-factor operands. // If we find a consecutive load, then we're done, otherwise, record all // nodes just above the top-level loads and token factors. while (!Queue.empty()) { SDNode *ChainNext = Queue.pop_back_val(); if (!Visited.insert(ChainNext).second) continue; if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) { if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) return true; if (!Visited.count(ChainLD->getChain().getNode())) Queue.push_back(ChainLD->getChain().getNode()); } else if (ChainNext->getOpcode() == ISD::TokenFactor) { for (const SDUse &O : ChainNext->ops()) if (!Visited.count(O.getNode())) Queue.push_back(O.getNode()); } else LoadRoots.insert(ChainNext); } // Second, search down the chain, starting from the top-level nodes recorded // in the first phase. These top-level nodes are the nodes just above all // loads and token factors. Starting with their uses, recursively look though // all loads (just the chain uses) and token factors to find a consecutive // load. Visited.clear(); Queue.clear(); for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(), IE = LoadRoots.end(); I != IE; ++I) { Queue.push_back(*I); while (!Queue.empty()) { SDNode *LoadRoot = Queue.pop_back_val(); if (!Visited.insert(LoadRoot).second) continue; if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot)) if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG)) return true; for (SDNode::use_iterator UI = LoadRoot->use_begin(), UE = LoadRoot->use_end(); UI != UE; ++UI) if (((isa<MemSDNode>(*UI) && cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) || UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI)) Queue.push_back(*UI); } } return false; } SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N, DAGCombinerInfo &DCI) const { SelectionDAG &DAG = DCI.DAG; SDLoc dl(N); assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits"); // If we're tracking CR bits, we need to be careful that we don't have: // trunc(binary-ops(zext(x), zext(y))) // or // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...) // such that we're unnecessarily moving things into GPRs when it would be // better to keep them in CR bits. // Note that trunc here can be an actual i1 trunc, or can be the effective // truncation that comes from a setcc or select_cc. if (N->getOpcode() == ISD::TRUNCATE && N->getValueType(0) != MVT::i1) return SDValue(); if (N->getOperand(0).getValueType() != MVT::i32 && N->getOperand(0).getValueType() != MVT::i64) return SDValue(); if (N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) { // If we're looking at a comparison, then we need to make sure that the // high bits (all except for the first) don't matter the result. ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand( N->getOpcode() == ISD::SETCC ? 2 : 4))->get(); unsigned OpBits = N->getOperand(0).getValueSizeInBits(); if (ISD::isSignedIntSetCC(CC)) { if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits || DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits) return SDValue(); } else if (ISD::isUnsignedIntSetCC(CC)) { if (!DAG.MaskedValueIsZero(N->getOperand(0), APInt::getHighBitsSet(OpBits, OpBits-1)) || !DAG.MaskedValueIsZero(N->getOperand(1), APInt::getHighBitsSet(OpBits, OpBits-1))) return SDValue(); } else { // This is neither a signed nor an unsigned comparison, just make sure // that the high bits are equal. APInt Op1Zero, Op1One; APInt Op2Zero, Op2One; DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One); DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One); // We don't really care about what is known about the first bit (if // anything), so clear it in all masks prior to comparing them. Op1Zero.clearBit(0); Op1One.clearBit(0); Op2Zero.clearBit(0); Op2One.clearBit(0); if (Op1Zero != Op2Zero || Op1One != Op2One) return SDValue(); } } // We now know that the higher-order bits are irrelevant, we just need to // make sure that all of the intermediate operations are bit operations, and // all inputs are extensions. if (N->getOperand(0).getOpcode() != ISD::AND && N->getOperand(0).getOpcode() != ISD::OR && N->getOperand(0).getOpcode() != ISD::XOR && N->getOperand(0).getOpcode() != ISD::SELECT && N->getOperand(0).getOpcode() != ISD::SELECT_CC && N->getOperand(0).getOpcode() != ISD::TRUNCATE && N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND && N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND && N->getOperand(0).getOpcode() != ISD::ANY_EXTEND) return SDValue(); if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) && N->getOperand(1).getOpcode() != ISD::AND && N->getOperand(1).getOpcode() != ISD::OR && N->getOperand(1).getOpcode() != ISD::XOR && N->getOperand(1).getOpcode() != ISD::SELECT && N->getOperand(1).getOpcode() != ISD::SELECT_CC && N->getOperand(1).getOpcode() != ISD::TRUNCATE && N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND && N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND && N->getOperand(1).getOpcode() != ISD::ANY_EXTEND) return SDValue(); SmallVector<SDValue, 4> Inputs; SmallVector<SDValue, 8> BinOps, PromOps; SmallPtrSet<SDNode *, 16> Visited; for (unsigned i = 0; i < 2; ++i) { if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND || N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND || N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) && N->getOperand(i).getOperand(0).getValueType() == MVT::i1) || isa<ConstantSDNode>(N->getOperand(i))) Inputs.push_back(N->getOperand(i)); else BinOps.push_back(N->getOperand(i)); if (N->getOpcode() == ISD::TRUNCATE) break; } // Visit all inputs, collect all binary operations (and, or, xor and // select) that are all fed by extensions. while (!BinOps.empty()) { SDValue BinOp = BinOps.back(); BinOps.pop_back(); if (!Visited.insert(BinOp.getNode()).second) continue; PromOps.push_back(BinOp); for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { // The condition of the select is not promoted. if (BinOp.getOpcode() == ISD::SELECT && i == 0) continue; if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) continue; if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) && BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) || isa<ConstantSDNode>(BinOp.getOperand(i))) { Inputs.push_back(BinOp.getOperand(i)); } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || BinOp.getOperand(i).getOpcode() == ISD::OR || BinOp.getOperand(i).getOpcode() == ISD::XOR || BinOp.getOperand(i).getOpcode() == ISD::SELECT || BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC || BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND || BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND || BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) { BinOps.push_back(BinOp.getOperand(i)); } else { // We have an input that is not an extension or another binary // operation; we'll abort this transformation. return SDValue(); } } } // Make sure that this is a self-contained cluster of operations (which // is not quite the same thing as saying that everything has only one // use). for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { if (isa<ConstantSDNode>(Inputs[i])) continue; for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), UE = Inputs[i].getNode()->use_end(); UI != UE; ++UI) { SDNode *User = *UI; if (User != N && !Visited.count(User)) return SDValue(); // Make sure that we're not going to promote the non-output-value // operand(s) or SELECT or SELECT_CC. // FIXME: Although we could sometimes handle this, and it does occur in // practice that one of the condition inputs to the select is also one of // the outputs, we currently can't deal with this. if (User->getOpcode() == ISD::SELECT) { if (User->getOperand(0) == Inputs[i]) return SDValue(); } else if (User->getOpcode() == ISD::SELECT_CC) { if (User->getOperand(0) == Inputs[i] || User->getOperand(1) == Inputs[i]) return SDValue(); } } } for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), UE = PromOps[i].getNode()->use_end(); UI != UE; ++UI) { SDNode *User = *UI; if (User != N && !Visited.count(User)) return SDValue(); // Make sure that we're not going to promote the non-output-value // operand(s) or SELECT or SELECT_CC. // FIXME: Although we could sometimes handle this, and it does occur in // practice that one of the condition inputs to the select is also one of // the outputs, we currently can't deal with this. if (User->getOpcode() == ISD::SELECT) { if (User->getOperand(0) == PromOps[i]) return SDValue(); } else if (User->getOpcode() == ISD::SELECT_CC) { if (User->getOperand(0) == PromOps[i] || User->getOperand(1) == PromOps[i]) return SDValue(); } } } // Replace all inputs with the extension operand. for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { // Constants may have users outside the cluster of to-be-promoted nodes, // and so we need to replace those as we do the promotions. if (isa<ConstantSDNode>(Inputs[i])) continue; else DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); } // Replace all operations (these are all the same, but have a different // (i1) return type). DAG.getNode will validate that the types of // a binary operator match, so go through the list in reverse so that // we've likely promoted both operands first. Any intermediate truncations or // extensions disappear. while (!PromOps.empty()) { SDValue PromOp = PromOps.back(); PromOps.pop_back(); if (PromOp.getOpcode() == ISD::TRUNCATE || PromOp.getOpcode() == ISD::SIGN_EXTEND || PromOp.getOpcode() == ISD::ZERO_EXTEND || PromOp.getOpcode() == ISD::ANY_EXTEND) { if (!isa<ConstantSDNode>(PromOp.getOperand(0)) && PromOp.getOperand(0).getValueType() != MVT::i1) { // The operand is not yet ready (see comment below). PromOps.insert(PromOps.begin(), PromOp); continue; } SDValue RepValue = PromOp.getOperand(0); if (isa<ConstantSDNode>(RepValue)) RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue); DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue); continue; } unsigned C; switch (PromOp.getOpcode()) { default: C = 0; break; case ISD::SELECT: C = 1; break; case ISD::SELECT_CC: C = 2; break; } if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && PromOp.getOperand(C).getValueType() != MVT::i1) || (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && PromOp.getOperand(C+1).getValueType() != MVT::i1)) { // The to-be-promoted operands of this node have not yet been // promoted (this should be rare because we're going through the // list backward, but if one of the operands has several users in // this cluster of to-be-promoted nodes, it is possible). PromOps.insert(PromOps.begin(), PromOp); continue; } SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), PromOp.getNode()->op_end()); // If there are any constant inputs, make sure they're replaced now. for (unsigned i = 0; i < 2; ++i) if (isa<ConstantSDNode>(Ops[C+i])) Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]); DAG.ReplaceAllUsesOfValueWith(PromOp, DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops)); } // Now we're left with the initial truncation itself. if (N->getOpcode() == ISD::TRUNCATE) return N->getOperand(0); // Otherwise, this is a comparison. The operands to be compared have just // changed type (to i1), but everything else is the same. return SDValue(N, 0); } SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N, DAGCombinerInfo &DCI) const { SelectionDAG &DAG = DCI.DAG; SDLoc dl(N); // If we're tracking CR bits, we need to be careful that we don't have: // zext(binary-ops(trunc(x), trunc(y))) // or // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...) // such that we're unnecessarily moving things into CR bits that can more // efficiently stay in GPRs. Note that if we're not certain that the high // bits are set as required by the final extension, we still may need to do // some masking to get the proper behavior. // This same functionality is important on PPC64 when dealing with // 32-to-64-bit extensions; these occur often when 32-bit values are used as // the return values of functions. Because it is so similar, it is handled // here as well. if (N->getValueType(0) != MVT::i32 && N->getValueType(0) != MVT::i64) return SDValue(); if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) || (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64()))) return SDValue(); if (N->getOperand(0).getOpcode() != ISD::AND && N->getOperand(0).getOpcode() != ISD::OR && N->getOperand(0).getOpcode() != ISD::XOR && N->getOperand(0).getOpcode() != ISD::SELECT && N->getOperand(0).getOpcode() != ISD::SELECT_CC) return SDValue(); SmallVector<SDValue, 4> Inputs; SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps; SmallPtrSet<SDNode *, 16> Visited; // Visit all inputs, collect all binary operations (and, or, xor and // select) that are all fed by truncations. while (!BinOps.empty()) { SDValue BinOp = BinOps.back(); BinOps.pop_back(); if (!Visited.insert(BinOp.getNode()).second) continue; PromOps.push_back(BinOp); for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) { // The condition of the select is not promoted. if (BinOp.getOpcode() == ISD::SELECT && i == 0) continue; if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3) continue; if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE || isa<ConstantSDNode>(BinOp.getOperand(i))) { Inputs.push_back(BinOp.getOperand(i)); } else if (BinOp.getOperand(i).getOpcode() == ISD::AND || BinOp.getOperand(i).getOpcode() == ISD::OR || BinOp.getOperand(i).getOpcode() == ISD::XOR || BinOp.getOperand(i).getOpcode() == ISD::SELECT || BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) { BinOps.push_back(BinOp.getOperand(i)); } else { // We have an input that is not a truncation or another binary // operation; we'll abort this transformation. return SDValue(); } } } // The operands of a select that must be truncated when the select is // promoted because the operand is actually part of the to-be-promoted set. DenseMap<SDNode *, EVT> SelectTruncOp[2]; // Make sure that this is a self-contained cluster of operations (which // is not quite the same thing as saying that everything has only one // use). for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { if (isa<ConstantSDNode>(Inputs[i])) continue; for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(), UE = Inputs[i].getNode()->use_end(); UI != UE; ++UI) { SDNode *User = *UI; if (User != N && !Visited.count(User)) return SDValue(); // If we're going to promote the non-output-value operand(s) or SELECT or // SELECT_CC, record them for truncation. if (User->getOpcode() == ISD::SELECT) { if (User->getOperand(0) == Inputs[i]) SelectTruncOp[0].insert(std::make_pair(User, User->getOperand(0).getValueType())); } else if (User->getOpcode() == ISD::SELECT_CC) { if (User->getOperand(0) == Inputs[i]) SelectTruncOp[0].insert(std::make_pair(User, User->getOperand(0).getValueType())); if (User->getOperand(1) == Inputs[i]) SelectTruncOp[1].insert(std::make_pair(User, User->getOperand(1).getValueType())); } } } for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) { for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(), UE = PromOps[i].getNode()->use_end(); UI != UE; ++UI) { SDNode *User = *UI; if (User != N && !Visited.count(User)) return SDValue(); // If we're going to promote the non-output-value operand(s) or SELECT or // SELECT_CC, record them for truncation. if (User->getOpcode() == ISD::SELECT) { if (User->getOperand(0) == PromOps[i]) SelectTruncOp[0].insert(std::make_pair(User, User->getOperand(0).getValueType())); } else if (User->getOpcode() == ISD::SELECT_CC) { if (User->getOperand(0) == PromOps[i]) SelectTruncOp[0].insert(std::make_pair(User, User->getOperand(0).getValueType())); if (User->getOperand(1) == PromOps[i]) SelectTruncOp[1].insert(std::make_pair(User, User->getOperand(1).getValueType())); } } } unsigned PromBits = N->getOperand(0).getValueSizeInBits(); bool ReallyNeedsExt = false; if (N->getOpcode() != ISD::ANY_EXTEND) { // If all of the inputs are not already sign/zero extended, then // we'll still need to do that at the end. for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { if (isa<ConstantSDNode>(Inputs[i])) continue; unsigned OpBits = Inputs[i].getOperand(0).getValueSizeInBits(); assert(PromBits < OpBits && "Truncation not to a smaller bit count?"); if ((N->getOpcode() == ISD::ZERO_EXTEND && !DAG.MaskedValueIsZero(Inputs[i].getOperand(0), APInt::getHighBitsSet(OpBits, OpBits-PromBits))) || (N->getOpcode() == ISD::SIGN_EXTEND && DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) < (OpBits-(PromBits-1)))) { ReallyNeedsExt = true; break; } } } // Replace all inputs, either with the truncation operand, or a // truncation or extension to the final output type. for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) { // Constant inputs need to be replaced with the to-be-promoted nodes that // use them because they might have users outside of the cluster of // promoted nodes. if (isa<ConstantSDNode>(Inputs[i])) continue; SDValue InSrc = Inputs[i].getOperand(0); if (Inputs[i].getValueType() == N->getValueType(0)) DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc); else if (N->getOpcode() == ISD::SIGN_EXTEND) DAG.ReplaceAllUsesOfValueWith(Inputs[i], DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0))); else if (N->getOpcode() == ISD::ZERO_EXTEND) DAG.ReplaceAllUsesOfValueWith(Inputs[i], DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0))); else DAG.ReplaceAllUsesOfValueWith(Inputs[i], DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0))); } // Replace all operations (these are all the same, but have a different // (promoted) return type). DAG.getNode will validate that the types of // a binary operator match, so go through the list in reverse so that // we've likely promoted both operands first. while (!PromOps.empty()) { SDValue PromOp = PromOps.back(); PromOps.pop_back(); unsigned C; switch (PromOp.getOpcode()) { default: C = 0; break; case ISD::SELECT: C = 1; break; case ISD::SELECT_CC: C = 2; break; } if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) && PromOp.getOperand(C).getValueType() != N->getValueType(0)) || (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) && PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) { // The to-be-promoted operands of this node have not yet been // promoted (this should be rare because we're going through the // list backward, but if one of the operands has several users in // this cluster of to-be-promoted nodes, it is possible). PromOps.insert(PromOps.begin(), PromOp); continue; } // For SELECT and SELECT_CC nodes, we do a similar check for any // to-be-promoted comparison inputs. if (PromOp.getOpcode() == ISD::SELECT || PromOp.getOpcode() == ISD::SELECT_CC) { if ((SelectTruncOp[0].count(PromOp.getNode()) && PromOp.getOperand(0).getValueType() != N->getValueType(0)) || (SelectTruncOp[1].count(PromOp.getNode()) && PromOp.getOperand(1).getValueType() != N->getValueType(0))) { PromOps.insert(PromOps.begin(), PromOp); continue; } } SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(), PromOp.getNode()->op_end()); // If this node has constant inputs, then they'll need to be promoted here. for (unsigned i = 0; i < 2; ++i) { if (!isa<ConstantSDNode>(Ops[C+i])) continue; if (Ops[C+i].getValueType() == N->getValueType(0)) continue; if (N->getOpcode() == ISD::SIGN_EXTEND) Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); else if (N->getOpcode() == ISD::ZERO_EXTEND) Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); else Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0)); } // If we've promoted the comparison inputs of a SELECT or SELECT_CC, // truncate them again to the original value type. if (PromOp.getOpcode() == ISD::SELECT || PromOp.getOpcode() == ISD::SELECT_CC) { auto SI0 = SelectTruncOp[0].find(PromOp.getNode()); if (SI0 != SelectTruncOp[0].end()) Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]); auto SI1 = SelectTruncOp[1].find(PromOp.getNode()); if (SI1 != SelectTruncOp[1].end()) Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]); } DAG.ReplaceAllUsesOfValueWith(PromOp, DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops)); } // Now we're left with the initial extension itself. if (!ReallyNeedsExt) return N->getOperand(0); // To zero extend, just mask off everything except for the first bit (in the // i1 case). if (N->getOpcode() == ISD::ZERO_EXTEND) return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0), DAG.getConstant(APInt::getLowBitsSet( N->getValueSizeInBits(0), PromBits), dl, N->getValueType(0))); assert(N->getOpcode() == ISD::SIGN_EXTEND && "Invalid extension type"); EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout()); SDValue ShiftCst = DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy); return DAG.getNode( ISD::SRA, dl, N->getValueType(0), DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst), ShiftCst); } SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N, DAGCombinerInfo &DCI) const { assert((N->getOpcode() == ISD::SINT_TO_FP || N->getOpcode() == ISD::UINT_TO_FP) && "Need an int -> FP conversion node here"); if (!Subtarget.has64BitSupport()) return SDValue(); SelectionDAG &DAG = DCI.DAG; SDLoc dl(N); SDValue Op(N, 0); // Don't handle ppc_fp128 here or i1 conversions. if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64) return SDValue(); if (Op.getOperand(0).getValueType() == MVT::i1) return SDValue(); // For i32 intermediate values, unfortunately, the conversion functions // leave the upper 32 bits of the value are undefined. Within the set of // scalar instructions, we have no method for zero- or sign-extending the // value. Thus, we cannot handle i32 intermediate values here. if (Op.getOperand(0).getValueType() == MVT::i32) return SDValue(); assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) && "UINT_TO_FP is supported only with FPCVT"); // If we have FCFIDS, then use it when converting to single-precision. // Otherwise, convert to double-precision and then round. unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS : PPCISD::FCFIDS) : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU : PPCISD::FCFID); MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ? MVT::f32 : MVT::f64; // If we're converting from a float, to an int, and back to a float again, // then we don't need the store/load pair at all. if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT && Subtarget.hasFPCVT()) || (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) { SDValue Src = Op.getOperand(0).getOperand(0); if (Src.getValueType() == MVT::f32) { Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src); DCI.AddToWorklist(Src.getNode()); } else if (Src.getValueType() != MVT::f64) { // Make sure that we don't pick up a ppc_fp128 source value. return SDValue(); } unsigned FCTOp = Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ; SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src); SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp); if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) { FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0, dl)); DCI.AddToWorklist(FP.getNode()); } return FP; } return SDValue(); } // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for // builtins) into loads with swaps. SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N, DAGCombinerInfo &DCI) const { SelectionDAG &DAG = DCI.DAG; SDLoc dl(N); SDValue Chain; SDValue Base; MachineMemOperand *MMO; switch (N->getOpcode()) { default: llvm_unreachable("Unexpected opcode for little endian VSX load"); case ISD::LOAD: { LoadSDNode *LD = cast<LoadSDNode>(N); Chain = LD->getChain(); Base = LD->getBasePtr(); MMO = LD->getMemOperand(); // If the MMO suggests this isn't a load of a full vector, leave // things alone. For a built-in, we have to make the change for // correctness, so if there is a size problem that will be a bug. if (MMO->getSize() < 16) return SDValue(); break; } case ISD::INTRINSIC_W_CHAIN: { MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); Chain = Intrin->getChain(); // Similarly to the store case below, Intrin->getBasePtr() doesn't get // us what we want. Get operand 2 instead. Base = Intrin->getOperand(2); MMO = Intrin->getMemOperand(); break; } } MVT VecTy = N->getValueType(0).getSimpleVT(); SDValue LoadOps[] = { Chain, Base }; SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl, DAG.getVTList(MVT::v2f64, MVT::Other), LoadOps, MVT::v2f64, MMO); DCI.AddToWorklist(Load.getNode()); Chain = Load.getValue(1); SDValue Swap = DAG.getNode( PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load); DCI.AddToWorklist(Swap.getNode()); // Add a bitcast if the resulting load type doesn't match v2f64. if (VecTy != MVT::v2f64) { SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap); DCI.AddToWorklist(N.getNode()); // Package {bitcast value, swap's chain} to match Load's shape. return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other), N, Swap.getValue(1)); } return Swap; } // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for // builtins) into stores with swaps. SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N, DAGCombinerInfo &DCI) const { SelectionDAG &DAG = DCI.DAG; SDLoc dl(N); SDValue Chain; SDValue Base; unsigned SrcOpnd; MachineMemOperand *MMO; switch (N->getOpcode()) { default: llvm_unreachable("Unexpected opcode for little endian VSX store"); case ISD::STORE: { StoreSDNode *ST = cast<StoreSDNode>(N); Chain = ST->getChain(); Base = ST->getBasePtr(); MMO = ST->getMemOperand(); SrcOpnd = 1; // If the MMO suggests this isn't a store of a full vector, leave // things alone. For a built-in, we have to make the change for // correctness, so if there is a size problem that will be a bug. if (MMO->getSize() < 16) return SDValue(); break; } case ISD::INTRINSIC_VOID: { MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N); Chain = Intrin->getChain(); // Intrin->getBasePtr() oddly does not get what we want. Base = Intrin->getOperand(3); MMO = Intrin->getMemOperand(); SrcOpnd = 2; break; } } SDValue Src = N->getOperand(SrcOpnd); MVT VecTy = Src.getValueType().getSimpleVT(); // All stores are done as v2f64 and possible bit cast. if (VecTy != MVT::v2f64) { Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src); DCI.AddToWorklist(Src.getNode()); } SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src); DCI.AddToWorklist(Swap.getNode()); Chain = Swap.getValue(1); SDValue StoreOps[] = { Chain, Swap, Base }; SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl, DAG.getVTList(MVT::Other), StoreOps, VecTy, MMO); DCI.AddToWorklist(Store.getNode()); return Store; } SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI) const { SelectionDAG &DAG = DCI.DAG; SDLoc dl(N); switch (N->getOpcode()) { default: break; case PPCISD::SHL: if (isNullConstant(N->getOperand(0))) // 0 << V -> 0. return N->getOperand(0); break; case PPCISD::SRL: if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0. return N->getOperand(0); break; case PPCISD::SRA: if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) { if (C->isNullValue() || // 0 >>s V -> 0. C->isAllOnesValue()) // -1 >>s V -> -1. return N->getOperand(0); } break; case ISD::SIGN_EXTEND: case ISD::ZERO_EXTEND: case ISD::ANY_EXTEND: return DAGCombineExtBoolTrunc(N, DCI); case ISD::TRUNCATE: case ISD::SETCC: case ISD::SELECT_CC: return DAGCombineTruncBoolExt(N, DCI); case ISD::SINT_TO_FP: case ISD::UINT_TO_FP: return combineFPToIntToFP(N, DCI); case ISD::STORE: { // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)). if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() && N->getOperand(1).getOpcode() == ISD::FP_TO_SINT && N->getOperand(1).getValueType() == MVT::i32 && N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) { SDValue Val = N->getOperand(1).getOperand(0); if (Val.getValueType() == MVT::f32) { Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val); DCI.AddToWorklist(Val.getNode()); } Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val); DCI.AddToWorklist(Val.getNode()); SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2), DAG.getValueType(N->getOperand(1).getValueType()) }; Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl, DAG.getVTList(MVT::Other), Ops, cast<StoreSDNode>(N)->getMemoryVT(), cast<StoreSDNode>(N)->getMemOperand()); DCI.AddToWorklist(Val.getNode()); return Val; } // Turn STORE (BSWAP) -> sthbrx/stwbrx. if (cast<StoreSDNode>(N)->isUnindexed() && N->getOperand(1).getOpcode() == ISD::BSWAP && N->getOperand(1).getNode()->hasOneUse() && (N->getOperand(1).getValueType() == MVT::i32 || N->getOperand(1).getValueType() == MVT::i16 || (Subtarget.hasLDBRX() && Subtarget.isPPC64() && N->getOperand(1).getValueType() == MVT::i64))) { SDValue BSwapOp = N->getOperand(1).getOperand(0); // Do an any-extend to 32-bits if this is a half-word input. if (BSwapOp.getValueType() == MVT::i16) BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp); SDValue Ops[] = { N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(N->getOperand(1).getValueType()) }; return DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other), Ops, cast<StoreSDNode>(N)->getMemoryVT(), cast<StoreSDNode>(N)->getMemOperand()); } // For little endian, VSX stores require generating xxswapd/lxvd2x. EVT VT = N->getOperand(1).getValueType(); if (VT.isSimple()) { MVT StoreVT = VT.getSimpleVT(); if (Subtarget.hasVSX() && Subtarget.isLittleEndian() && (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 || StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32)) return expandVSXStoreForLE(N, DCI); } break; } case ISD::LOAD: { LoadSDNode *LD = cast<LoadSDNode>(N); EVT VT = LD->getValueType(0); // For little endian, VSX loads require generating lxvd2x/xxswapd. if (VT.isSimple()) { MVT LoadVT = VT.getSimpleVT(); if (Subtarget.hasVSX() && Subtarget.isLittleEndian() && (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 || LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32)) return expandVSXLoadForLE(N, DCI); } EVT MemVT = LD->getMemoryVT(); Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty); Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext()); unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy); if (LD->isUnindexed() && VT.isVector() && ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) && // P8 and later hardware should just use LOAD. !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v4f32)) || (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) && LD->getAlignment() >= ScalarABIAlignment)) && LD->getAlignment() < ABIAlignment) { // This is a type-legal unaligned Altivec or QPX load. SDValue Chain = LD->getChain(); SDValue Ptr = LD->getBasePtr(); bool isLittleEndian = Subtarget.isLittleEndian(); // This implements the loading of unaligned vectors as described in // the venerable Apple Velocity Engine overview. Specifically: // https://developer.apple.com/hardwaredrivers/ve/alignment.html // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html // // The general idea is to expand a sequence of one or more unaligned // loads into an alignment-based permutation-control instruction (lvsl // or lvsr), a series of regular vector loads (which always truncate // their input address to an aligned address), and a series of // permutations. The results of these permutations are the requested // loaded values. The trick is that the last "extra" load is not taken // from the address you might suspect (sizeof(vector) bytes after the // last requested load), but rather sizeof(vector) - 1 bytes after the // last requested vector. The point of this is to avoid a page fault if // the base address happened to be aligned. This works because if the // base address is aligned, then adding less than a full vector length // will cause the last vector in the sequence to be (re)loaded. // Otherwise, the next vector will be fetched as you might suspect was // necessary. // We might be able to reuse the permutation generation from // a different base address offset from this one by an aligned amount. // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this // optimization later. Intrinsic::ID Intr, IntrLD, IntrPerm; MVT PermCntlTy, PermTy, LDTy; if (Subtarget.hasAltivec()) { Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr : Intrinsic::ppc_altivec_lvsl; IntrLD = Intrinsic::ppc_altivec_lvx; IntrPerm = Intrinsic::ppc_altivec_vperm; PermCntlTy = MVT::v16i8; PermTy = MVT::v4i32; LDTy = MVT::v4i32; } else { Intr = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld : Intrinsic::ppc_qpx_qvlpcls; IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd : Intrinsic::ppc_qpx_qvlfs; IntrPerm = Intrinsic::ppc_qpx_qvfperm; PermCntlTy = MVT::v4f64; PermTy = MVT::v4f64; LDTy = MemVT.getSimpleVT(); } SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy); // Create the new MMO for the new base load. It is like the original MMO, // but represents an area in memory almost twice the vector size centered // on the original address. If the address is unaligned, we might start // reading up to (sizeof(vector)-1) bytes below the address of the // original unaligned load. MachineFunction &MF = DAG.getMachineFunction(); MachineMemOperand *BaseMMO = MF.getMachineMemOperand(LD->getMemOperand(), -(long)MemVT.getStoreSize()+1, 2*MemVT.getStoreSize()-1); // Create the new base load. SDValue LDXIntID = DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout())); SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr }; SDValue BaseLoad = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, DAG.getVTList(PermTy, MVT::Other), BaseLoadOps, LDTy, BaseMMO); // Note that the value of IncOffset (which is provided to the next // load's pointer info offset value, and thus used to calculate the // alignment), and the value of IncValue (which is actually used to // increment the pointer value) are different! This is because we // require the next load to appear to be aligned, even though it // is actually offset from the base pointer by a lesser amount. int IncOffset = VT.getSizeInBits() / 8; int IncValue = IncOffset; // Walk (both up and down) the chain looking for another load at the real // (aligned) offset (the alignment of the other load does not matter in // this case). If found, then do not use the offset reduction trick, as // that will prevent the loads from being later combined (as they would // otherwise be duplicates). if (!findConsecutiveLoad(LD, DAG)) --IncValue; SDValue Increment = DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout())); Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment); MachineMemOperand *ExtraMMO = MF.getMachineMemOperand(LD->getMemOperand(), 1, 2*MemVT.getStoreSize()-1); SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr }; SDValue ExtraLoad = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl, DAG.getVTList(PermTy, MVT::Other), ExtraLoadOps, LDTy, ExtraMMO); SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, BaseLoad.getValue(1), ExtraLoad.getValue(1)); // Because vperm has a big-endian bias, we must reverse the order // of the input vectors and complement the permute control vector // when generating little endian code. We have already handled the // latter by using lvsr instead of lvsl, so just reverse BaseLoad // and ExtraLoad here. SDValue Perm; if (isLittleEndian) Perm = BuildIntrinsicOp(IntrPerm, ExtraLoad, BaseLoad, PermCntl, DAG, dl); else Perm = BuildIntrinsicOp(IntrPerm, BaseLoad, ExtraLoad, PermCntl, DAG, dl); if (VT != PermTy) Perm = Subtarget.hasAltivec() ? DAG.getNode(ISD::BITCAST, dl, VT, Perm) : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX DAG.getTargetConstant(1, dl, MVT::i64)); // second argument is 1 because this rounding // is always exact. // The output of the permutation is our loaded result, the TokenFactor is // our new chain. DCI.CombineTo(N, Perm, TF); return SDValue(N, 0); } } break; case ISD::INTRINSIC_WO_CHAIN: { bool isLittleEndian = Subtarget.isLittleEndian(); unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr : Intrinsic::ppc_altivec_lvsl); if ((IID == Intr || IID == Intrinsic::ppc_qpx_qvlpcld || IID == Intrinsic::ppc_qpx_qvlpcls) && N->getOperand(1)->getOpcode() == ISD::ADD) { SDValue Add = N->getOperand(1); int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ? 5 /* 32 byte alignment */ : 4 /* 16 byte alignment */; if (DAG.MaskedValueIsZero( Add->getOperand(1), APInt::getAllOnesValue(Bits /* alignment */) .zext( Add.getValueType().getScalarType().getSizeInBits()))) { SDNode *BasePtr = Add->getOperand(0).getNode(); for (SDNode::use_iterator UI = BasePtr->use_begin(), UE = BasePtr->use_end(); UI != UE; ++UI) { if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) { // We've found another LVSL/LVSR, and this address is an aligned // multiple of that one. The results will be the same, so use the // one we've just found instead. return SDValue(*UI, 0); } } } if (isa<ConstantSDNode>(Add->getOperand(1))) { SDNode *BasePtr = Add->getOperand(0).getNode(); for (SDNode::use_iterator UI = BasePtr->use_begin(), UE = BasePtr->use_end(); UI != UE; ++UI) { if (UI->getOpcode() == ISD::ADD && isa<ConstantSDNode>(UI->getOperand(1)) && (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() - cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) % (1ULL << Bits) == 0) { SDNode *OtherAdd = *UI; for (SDNode::use_iterator VI = OtherAdd->use_begin(), VE = OtherAdd->use_end(); VI != VE; ++VI) { if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN && cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) { return SDValue(*VI, 0); } } } } } } } break; case ISD::INTRINSIC_W_CHAIN: { // For little endian, VSX loads require generating lxvd2x/xxswapd. if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) { switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { default: break; case Intrinsic::ppc_vsx_lxvw4x: case Intrinsic::ppc_vsx_lxvd2x: return expandVSXLoadForLE(N, DCI); } } break; } case ISD::INTRINSIC_VOID: { // For little endian, VSX stores require generating xxswapd/stxvd2x. if (Subtarget.hasVSX() && Subtarget.isLittleEndian()) { switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { default: break; case Intrinsic::ppc_vsx_stxvw4x: case Intrinsic::ppc_vsx_stxvd2x: return expandVSXStoreForLE(N, DCI); } } break; } case ISD::BSWAP: // Turn BSWAP (LOAD) -> lhbrx/lwbrx. if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) && N->getOperand(0).hasOneUse() && (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 || (Subtarget.hasLDBRX() && Subtarget.isPPC64() && N->getValueType(0) == MVT::i64))) { SDValue Load = N->getOperand(0); LoadSDNode *LD = cast<LoadSDNode>(Load); // Create the byte-swapping load. SDValue Ops[] = { LD->getChain(), // Chain LD->getBasePtr(), // Ptr DAG.getValueType(N->getValueType(0)) // VT }; SDValue BSLoad = DAG.getMemIntrinsicNode(PPCISD::LBRX, dl, DAG.getVTList(N->getValueType(0) == MVT::i64 ? MVT::i64 : MVT::i32, MVT::Other), Ops, LD->getMemoryVT(), LD->getMemOperand()); // If this is an i16 load, insert the truncate. SDValue ResVal = BSLoad; if (N->getValueType(0) == MVT::i16) ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad); // First, combine the bswap away. This makes the value produced by the // load dead. DCI.CombineTo(N, ResVal); // Next, combine the load away, we give it a bogus result value but a real // chain result. The result value is dead because the bswap is dead. DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1)); // Return N so it doesn't get rechecked! return SDValue(N, 0); } break; case PPCISD::VCMP: { // If a VCMPo node already exists with exactly the same operands as this // node, use its result instead of this node (VCMPo computes both a CR6 and // a normal output). // if (!N->getOperand(0).hasOneUse() && !N->getOperand(1).hasOneUse() && !N->getOperand(2).hasOneUse()) { // Scan all of the users of the LHS, looking for VCMPo's that match. SDNode *VCMPoNode = nullptr; SDNode *LHSN = N->getOperand(0).getNode(); for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end(); UI != E; ++UI) if (UI->getOpcode() == PPCISD::VCMPo && UI->getOperand(1) == N->getOperand(1) && UI->getOperand(2) == N->getOperand(2) && UI->getOperand(0) == N->getOperand(0)) { VCMPoNode = *UI; break; } // If there is no VCMPo node, or if the flag value has a single use, don't // transform this. if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1)) break; // Look at the (necessarily single) use of the flag value. If it has a // chain, this transformation is more complex. Note that multiple things // could use the value result, which we should ignore. SDNode *FlagUser = nullptr; for (SDNode::use_iterator UI = VCMPoNode->use_begin(); FlagUser == nullptr; ++UI) { assert(UI != VCMPoNode->use_end() && "Didn't find user!"); SDNode *User = *UI; for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) { if (User->getOperand(i) == SDValue(VCMPoNode, 1)) { FlagUser = User; break; } } } // If the user is a MFOCRF instruction, we know this is safe. // Otherwise we give up for right now. if (FlagUser->getOpcode() == PPCISD::MFOCRF) return SDValue(VCMPoNode, 0); } break; } case ISD::BRCOND: { SDValue Cond = N->getOperand(1); SDValue Target = N->getOperand(2); if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN && cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() == Intrinsic::ppc_is_decremented_ctr_nonzero) { // We now need to make the intrinsic dead (it cannot be instruction // selected). DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0)); assert(Cond.getNode()->hasOneUse() && "Counter decrement has more than one use"); return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other, N->getOperand(0), Target); } } break; case ISD::BR_CC: { // If this is a branch on an altivec predicate comparison, lower this so // that we don't have to do a MFOCRF: instead, branch directly on CR6. This // lowering is done pre-legalize, because the legalizer lowers the predicate // compare down to code that is difficult to reassemble. ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); SDValue LHS = N->getOperand(2), RHS = N->getOperand(3); // Sometimes the promoted value of the intrinsic is ANDed by some non-zero // value. If so, pass-through the AND to get to the intrinsic. if (LHS.getOpcode() == ISD::AND && LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN && cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() == Intrinsic::ppc_is_decremented_ctr_nonzero && isa<ConstantSDNode>(LHS.getOperand(1)) && !isNullConstant(LHS.getOperand(1))) LHS = LHS.getOperand(0); if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN && cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() == Intrinsic::ppc_is_decremented_ctr_nonzero && isa<ConstantSDNode>(RHS)) { assert((CC == ISD::SETEQ || CC == ISD::SETNE) && "Counter decrement comparison is not EQ or NE"); unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); bool isBDNZ = (CC == ISD::SETEQ && Val) || (CC == ISD::SETNE && !Val); // We now need to make the intrinsic dead (it cannot be instruction // selected). DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0)); assert(LHS.getNode()->hasOneUse() && "Counter decrement has more than one use"); return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other, N->getOperand(0), N->getOperand(4)); } int CompareOpc; bool isDot; if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN && isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) && getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) { assert(isDot && "Can't compare against a vector result!"); // If this is a comparison against something other than 0/1, then we know // that the condition is never/always true. unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue(); if (Val != 0 && Val != 1) { if (CC == ISD::SETEQ) // Cond never true, remove branch. return N->getOperand(0); // Always !=, turn it into an unconditional branch. return DAG.getNode(ISD::BR, dl, MVT::Other, N->getOperand(0), N->getOperand(4)); } bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0); // Create the PPCISD altivec 'dot' comparison node. SDValue Ops[] = { LHS.getOperand(2), // LHS of compare LHS.getOperand(3), // RHS of compare DAG.getConstant(CompareOpc, dl, MVT::i32) }; EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue }; SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops); // Unpack the result based on how the target uses it. PPC::Predicate CompOpc; switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) { default: // Can't happen, don't crash on invalid number though. case 0: // Branch on the value of the EQ bit of CR6. CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE; break; case 1: // Branch on the inverted value of the EQ bit of CR6. CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ; break; case 2: // Branch on the value of the LT bit of CR6. CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE; break; case 3: // Branch on the inverted value of the LT bit of CR6. CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT; break; } return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0), DAG.getConstant(CompOpc, dl, MVT::i32), DAG.getRegister(PPC::CR6, MVT::i32), N->getOperand(4), CompNode.getValue(1)); } break; } } return SDValue(); } SDValue PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, SelectionDAG &DAG, std::vector<SDNode *> *Created) const { // fold (sdiv X, pow2) EVT VT = N->getValueType(0); if (VT == MVT::i64 && !Subtarget.isPPC64()) return SDValue(); if ((VT != MVT::i32 && VT != MVT::i64) || !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) return SDValue(); SDLoc DL(N); SDValue N0 = N->getOperand(0); bool IsNegPow2 = (-Divisor).isPowerOf2(); unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros(); SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT); SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt); if (Created) Created->push_back(Op.getNode()); if (IsNegPow2) { Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op); if (Created) Created->push_back(Op.getNode()); } return Op; } //===----------------------------------------------------------------------===// // Inline Assembly Support //===----------------------------------------------------------------------===// void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, APInt &KnownZero, APInt &KnownOne, const SelectionDAG &DAG, unsigned Depth) const { KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0); switch (Op.getOpcode()) { default: break; case PPCISD::LBRX: { // lhbrx is known to have the top bits cleared out. if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16) KnownZero = 0xFFFF0000; break; } case ISD::INTRINSIC_WO_CHAIN: { switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) { default: break; case Intrinsic::ppc_altivec_vcmpbfp_p: case Intrinsic::ppc_altivec_vcmpeqfp_p: case Intrinsic::ppc_altivec_vcmpequb_p: case Intrinsic::ppc_altivec_vcmpequh_p: case Intrinsic::ppc_altivec_vcmpequw_p: case Intrinsic::ppc_altivec_vcmpequd_p: case Intrinsic::ppc_altivec_vcmpgefp_p: case Intrinsic::ppc_altivec_vcmpgtfp_p: case Intrinsic::ppc_altivec_vcmpgtsb_p: case Intrinsic::ppc_altivec_vcmpgtsh_p: case Intrinsic::ppc_altivec_vcmpgtsw_p: case Intrinsic::ppc_altivec_vcmpgtsd_p: case Intrinsic::ppc_altivec_vcmpgtub_p: case Intrinsic::ppc_altivec_vcmpgtuh_p: case Intrinsic::ppc_altivec_vcmpgtuw_p: case Intrinsic::ppc_altivec_vcmpgtud_p: KnownZero = ~1U; // All bits but the low one are known to be zero. break; } } } } unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { switch (Subtarget.getDarwinDirective()) { default: break; case PPC::DIR_970: case PPC::DIR_PWR4: case PPC::DIR_PWR5: case PPC::DIR_PWR5X: case PPC::DIR_PWR6: case PPC::DIR_PWR6X: case PPC::DIR_PWR7: case PPC::DIR_PWR8: { if (!ML) break; const PPCInstrInfo *TII = Subtarget.getInstrInfo(); // For small loops (between 5 and 8 instructions), align to a 32-byte // boundary so that the entire loop fits in one instruction-cache line. uint64_t LoopSize = 0; for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I) for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) { LoopSize += TII->GetInstSizeInBytes(J); if (LoopSize > 32) break; } if (LoopSize > 16 && LoopSize <= 32) return 5; break; } } return TargetLowering::getPrefLoopAlignment(ML); } /// getConstraintType - Given a constraint, return the type of /// constraint it is for this target. PPCTargetLowering::ConstraintType PPCTargetLowering::getConstraintType(StringRef Constraint) const { if (Constraint.size() == 1) { switch (Constraint[0]) { default: break; case 'b': case 'r': case 'f': case 'v': case 'y': return C_RegisterClass; case 'Z': // FIXME: While Z does indicate a memory constraint, it specifically // indicates an r+r address (used in conjunction with the 'y' modifier // in the replacement string). Currently, we're forcing the base // register to be r0 in the asm printer (which is interpreted as zero) // and forming the complete address in the second register. This is // suboptimal. return C_Memory; } } else if (Constraint == "wc") { // individual CR bits. return C_RegisterClass; } else if (Constraint == "wa" || Constraint == "wd" || Constraint == "wf" || Constraint == "ws") { return C_RegisterClass; // VSX registers. } return TargetLowering::getConstraintType(Constraint); } /// Examine constraint type and operand type and determine a weight value. /// This object must already have been set up with the operand type /// and the current alternative constraint selected. TargetLowering::ConstraintWeight PPCTargetLowering::getSingleConstraintMatchWeight( AsmOperandInfo &info, const char *constraint) const { ConstraintWeight weight = CW_Invalid; Value *CallOperandVal = info.CallOperandVal; // If we don't have a value, we can't do a match, // but allow it at the lowest weight. if (!CallOperandVal) return CW_Default; Type *type = CallOperandVal->getType(); // Look at the constraint type. if (StringRef(constraint) == "wc" && type->isIntegerTy(1)) return CW_Register; // an individual CR bit. else if ((StringRef(constraint) == "wa" || StringRef(constraint) == "wd" || StringRef(constraint) == "wf") && type->isVectorTy()) return CW_Register; else if (StringRef(constraint) == "ws" && type->isDoubleTy()) return CW_Register; switch (*constraint) { default: weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); break; case 'b': if (type->isIntegerTy()) weight = CW_Register; break; case 'f': if (type->isFloatTy()) weight = CW_Register; break; case 'd': if (type->isDoubleTy()) weight = CW_Register; break; case 'v': if (type->isVectorTy()) weight = CW_Register; break; case 'y': weight = CW_Register; break; case 'Z': weight = CW_Memory; break; } return weight; } std::pair<unsigned, const TargetRegisterClass *> PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { if (Constraint.size() == 1) { // GCC RS6000 Constraint Letters switch (Constraint[0]) { case 'b': // R1-R31 if (VT == MVT::i64 && Subtarget.isPPC64()) return std::make_pair(0U, &PPC::G8RC_NOX0RegClass); return std::make_pair(0U, &PPC::GPRC_NOR0RegClass); case 'r': // R0-R31 if (VT == MVT::i64 && Subtarget.isPPC64()) return std::make_pair(0U, &PPC::G8RCRegClass); return std::make_pair(0U, &PPC::GPRCRegClass); case 'f': if (VT == MVT::f32 || VT == MVT::i32) return std::make_pair(0U, &PPC::F4RCRegClass); if (VT == MVT::f64 || VT == MVT::i64) return std::make_pair(0U, &PPC::F8RCRegClass); if (VT == MVT::v4f64 && Subtarget.hasQPX()) return std::make_pair(0U, &PPC::QFRCRegClass); if (VT == MVT::v4f32 && Subtarget.hasQPX()) return std::make_pair(0U, &PPC::QSRCRegClass); break; case 'v': if (VT == MVT::v4f64 && Subtarget.hasQPX()) return std::make_pair(0U, &PPC::QFRCRegClass); if (VT == MVT::v4f32 && Subtarget.hasQPX()) return std::make_pair(0U, &PPC::QSRCRegClass); if (Subtarget.hasAltivec()) return std::make_pair(0U, &PPC::VRRCRegClass); case 'y': // crrc return std::make_pair(0U, &PPC::CRRCRegClass); } } else if (Constraint == "wc" && Subtarget.useCRBits()) { // An individual CR bit. return std::make_pair(0U, &PPC::CRBITRCRegClass); } else if ((Constraint == "wa" || Constraint == "wd" || Constraint == "wf") && Subtarget.hasVSX()) { return std::make_pair(0U, &PPC::VSRCRegClass); } else if (Constraint == "ws" && Subtarget.hasVSX()) { if (VT == MVT::f32 && Subtarget.hasP8Vector()) return std::make_pair(0U, &PPC::VSSRCRegClass); else return std::make_pair(0U, &PPC::VSFRCRegClass); } std::pair<unsigned, const TargetRegisterClass *> R = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers // (which we call X[0-9]+). If a 64-bit value has been requested, and a // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent // register. // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use // the AsmName field from *RegisterInfo.td, then this would not be necessary. if (R.first && VT == MVT::i64 && Subtarget.isPPC64() && PPC::GPRCRegClass.contains(R.first)) return std::make_pair(TRI->getMatchingSuperReg(R.first, PPC::sub_32, &PPC::G8RCRegClass), &PPC::G8RCRegClass); // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same. if (!R.second && StringRef("{cc}").equals_lower(Constraint)) { R.first = PPC::CR0; R.second = &PPC::CRRCRegClass; } return R; } /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops /// vector. If it is invalid, don't add anything to Ops. void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op, std::string &Constraint, std::vector<SDValue>&Ops, SelectionDAG &DAG) const { SDValue Result; // Only support length 1 constraints. if (Constraint.length() > 1) return; char Letter = Constraint[0]; switch (Letter) { default: break; case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': { ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op); if (!CST) return; // Must be an immediate to match. SDLoc dl(Op); int64_t Value = CST->getSExtValue(); EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative // numbers are printed as such. switch (Letter) { default: llvm_unreachable("Unknown constraint letter!"); case 'I': // "I" is a signed 16-bit constant. if (isInt<16>(Value)) Result = DAG.getTargetConstant(Value, dl, TCVT); break; case 'J': // "J" is a constant with only the high-order 16 bits nonzero. if (isShiftedUInt<16, 16>(Value)) Result = DAG.getTargetConstant(Value, dl, TCVT); break; case 'L': // "L" is a signed 16-bit constant shifted left 16 bits. if (isShiftedInt<16, 16>(Value)) Result = DAG.getTargetConstant(Value, dl, TCVT); break; case 'K': // "K" is a constant with only the low-order 16 bits nonzero. if (isUInt<16>(Value)) Result = DAG.getTargetConstant(Value, dl, TCVT); break; case 'M': // "M" is a constant that is greater than 31. if (Value > 31) Result = DAG.getTargetConstant(Value, dl, TCVT); break; case 'N': // "N" is a positive constant that is an exact power of two. if (Value > 0 && isPowerOf2_64(Value)) Result = DAG.getTargetConstant(Value, dl, TCVT); break; case 'O': // "O" is the constant zero. if (Value == 0) Result = DAG.getTargetConstant(Value, dl, TCVT); break; case 'P': // "P" is a constant whose negation is a signed 16-bit constant. if (isInt<16>(-Value)) Result = DAG.getTargetConstant(Value, dl, TCVT); break; } break; } } if (Result.getNode()) { Ops.push_back(Result); return; } // Handle standard constraint letters. TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); } // isLegalAddressingMode - Return true if the addressing mode represented // by AM is legal for this target, for a load/store of the specified type. bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS) const { // PPC does not allow r+i addressing modes for vectors! if (Ty->isVectorTy() && AM.BaseOffs != 0) return false; // PPC allows a sign-extended 16-bit immediate field. if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1) return false; // No global is ever allowed as a base. if (AM.BaseGV) return false; // PPC only support r+r, switch (AM.Scale) { case 0: // "r+i" or just "i", depending on HasBaseReg. break; case 1: if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed. return false; // Otherwise we have r+r or r+i. break; case 2: if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed. return false; // Allow 2*r as r+r. break; default: // No other scales are supported. return false; } return true; } SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const { MachineFunction &MF = DAG.getMachineFunction(); MachineFrameInfo *MFI = MF.getFrameInfo(); MFI->setReturnAddressIsTaken(true); if (verifyReturnAddressArgumentIsConstant(Op, DAG)) return SDValue(); SDLoc dl(Op); unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); // Make sure the function does not optimize away the store of the RA to // the stack. PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); FuncInfo->setLRStoreRequired(); bool isPPC64 = Subtarget.isPPC64(); auto PtrVT = getPointerTy(MF.getDataLayout()); if (Depth > 0) { SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); SDValue Offset = DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl, isPPC64 ? MVT::i64 : MVT::i32); return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset), MachinePointerInfo(), false, false, false, 0); } // Just load the return address off the stack. SDValue RetAddrFI = getReturnAddrFrameIndex(DAG); return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI, MachinePointerInfo(), false, false, false, 0); } SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const { SDLoc dl(Op); unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); MachineFunction &MF = DAG.getMachineFunction(); MachineFrameInfo *MFI = MF.getFrameInfo(); MFI->setFrameAddressIsTaken(true); EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(MF.getDataLayout()); bool isPPC64 = PtrVT == MVT::i64; // Naked functions never have a frame pointer, and so we use r1. For all // other functions, this decision must be delayed until during PEI. unsigned FrameReg; if (MF.getFunction()->hasFnAttribute(Attribute::Naked)) FrameReg = isPPC64 ? PPC::X1 : PPC::R1; else FrameReg = isPPC64 ? PPC::FP8 : PPC::FP; SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT); while (Depth--) FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(), FrameAddr, MachinePointerInfo(), false, false, false, 0); return FrameAddr; } // FIXME? Maybe this could be a TableGen attribute on some registers and // this table could be generated automatically from RegInfo. unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT, SelectionDAG &DAG) const { bool isPPC64 = Subtarget.isPPC64(); bool isDarwinABI = Subtarget.isDarwinABI(); if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) || (!isPPC64 && VT != MVT::i32)) report_fatal_error("Invalid register global variable type"); bool is64Bit = isPPC64 && VT == MVT::i64; unsigned Reg = StringSwitch<unsigned>(RegName) .Case("r1", is64Bit ? PPC::X1 : PPC::R1) .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2) .Case("r13", (!isPPC64 && isDarwinABI) ? 0 : (is64Bit ? PPC::X13 : PPC::R13)) .Default(0); if (Reg) return Reg; report_fatal_error("Invalid register name global variable"); } bool PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { // The PowerPC target isn't yet aware of offsets. return false; } bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, const CallInst &I, unsigned Intrinsic) const { switch (Intrinsic) { case Intrinsic::ppc_qpx_qvlfd: case Intrinsic::ppc_qpx_qvlfs: case Intrinsic::ppc_qpx_qvlfcd: case Intrinsic::ppc_qpx_qvlfcs: case Intrinsic::ppc_qpx_qvlfiwa: case Intrinsic::ppc_qpx_qvlfiwz: case Intrinsic::ppc_altivec_lvx: case Intrinsic::ppc_altivec_lvxl: case Intrinsic::ppc_altivec_lvebx: case Intrinsic::ppc_altivec_lvehx: case Intrinsic::ppc_altivec_lvewx: case Intrinsic::ppc_vsx_lxvd2x: case Intrinsic::ppc_vsx_lxvw4x: { EVT VT; switch (Intrinsic) { case Intrinsic::ppc_altivec_lvebx: VT = MVT::i8; break; case Intrinsic::ppc_altivec_lvehx: VT = MVT::i16; break; case Intrinsic::ppc_altivec_lvewx: VT = MVT::i32; break; case Intrinsic::ppc_vsx_lxvd2x: VT = MVT::v2f64; break; case Intrinsic::ppc_qpx_qvlfd: VT = MVT::v4f64; break; case Intrinsic::ppc_qpx_qvlfs: VT = MVT::v4f32; break; case Intrinsic::ppc_qpx_qvlfcd: VT = MVT::v2f64; break; case Intrinsic::ppc_qpx_qvlfcs: VT = MVT::v2f32; break; default: VT = MVT::v4i32; break; } Info.opc = ISD::INTRINSIC_W_CHAIN; Info.memVT = VT; Info.ptrVal = I.getArgOperand(0); Info.offset = -VT.getStoreSize()+1; Info.size = 2*VT.getStoreSize()-1; Info.align = 1; Info.vol = false; Info.readMem = true; Info.writeMem = false; return true; } case Intrinsic::ppc_qpx_qvlfda: case Intrinsic::ppc_qpx_qvlfsa: case Intrinsic::ppc_qpx_qvlfcda: case Intrinsic::ppc_qpx_qvlfcsa: case Intrinsic::ppc_qpx_qvlfiwaa: case Intrinsic::ppc_qpx_qvlfiwza: { EVT VT; switch (Intrinsic) { case Intrinsic::ppc_qpx_qvlfda: VT = MVT::v4f64; break; case Intrinsic::ppc_qpx_qvlfsa: VT = MVT::v4f32; break; case Intrinsic::ppc_qpx_qvlfcda: VT = MVT::v2f64; break; case Intrinsic::ppc_qpx_qvlfcsa: VT = MVT::v2f32; break; default: VT = MVT::v4i32; break; } Info.opc = ISD::INTRINSIC_W_CHAIN; Info.memVT = VT; Info.ptrVal = I.getArgOperand(0); Info.offset = 0; Info.size = VT.getStoreSize(); Info.align = 1; Info.vol = false; Info.readMem = true; Info.writeMem = false; return true; } case Intrinsic::ppc_qpx_qvstfd: case Intrinsic::ppc_qpx_qvstfs: case Intrinsic::ppc_qpx_qvstfcd: case Intrinsic::ppc_qpx_qvstfcs: case Intrinsic::ppc_qpx_qvstfiw: case Intrinsic::ppc_altivec_stvx: case Intrinsic::ppc_altivec_stvxl: case Intrinsic::ppc_altivec_stvebx: case Intrinsic::ppc_altivec_stvehx: case Intrinsic::ppc_altivec_stvewx: case Intrinsic::ppc_vsx_stxvd2x: case Intrinsic::ppc_vsx_stxvw4x: { EVT VT; switch (Intrinsic) { case Intrinsic::ppc_altivec_stvebx: VT = MVT::i8; break; case Intrinsic::ppc_altivec_stvehx: VT = MVT::i16; break; case Intrinsic::ppc_altivec_stvewx: VT = MVT::i32; break; case Intrinsic::ppc_vsx_stxvd2x: VT = MVT::v2f64; break; case Intrinsic::ppc_qpx_qvstfd: VT = MVT::v4f64; break; case Intrinsic::ppc_qpx_qvstfs: VT = MVT::v4f32; break; case Intrinsic::ppc_qpx_qvstfcd: VT = MVT::v2f64; break; case Intrinsic::ppc_qpx_qvstfcs: VT = MVT::v2f32; break; default: VT = MVT::v4i32; break; } Info.opc = ISD::INTRINSIC_VOID; Info.memVT = VT; Info.ptrVal = I.getArgOperand(1); Info.offset = -VT.getStoreSize()+1; Info.size = 2*VT.getStoreSize()-1; Info.align = 1; Info.vol = false; Info.readMem = false; Info.writeMem = true; return true; } case Intrinsic::ppc_qpx_qvstfda: case Intrinsic::ppc_qpx_qvstfsa: case Intrinsic::ppc_qpx_qvstfcda: case Intrinsic::ppc_qpx_qvstfcsa: case Intrinsic::ppc_qpx_qvstfiwa: { EVT VT; switch (Intrinsic) { case Intrinsic::ppc_qpx_qvstfda: VT = MVT::v4f64; break; case Intrinsic::ppc_qpx_qvstfsa: VT = MVT::v4f32; break; case Intrinsic::ppc_qpx_qvstfcda: VT = MVT::v2f64; break; case Intrinsic::ppc_qpx_qvstfcsa: VT = MVT::v2f32; break; default: VT = MVT::v4i32; break; } Info.opc = ISD::INTRINSIC_VOID; Info.memVT = VT; Info.ptrVal = I.getArgOperand(1); Info.offset = 0; Info.size = VT.getStoreSize(); Info.align = 1; Info.vol = false; Info.readMem = false; Info.writeMem = true; return true; } default: break; } return false; } /// getOptimalMemOpType - Returns the target specific optimal type for load /// and store operations as a result of memset, memcpy, and memmove /// lowering. If DstAlign is zero that means it's safe to destination /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it /// means there isn't a need to check it against alignment requirement, /// probably because the source does not need to be loaded. If 'IsMemset' is /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy /// source is constant so it does not need to be loaded. /// It returns EVT::Other if the type should be determined using generic /// target-independent logic. EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, bool ZeroMemset, bool MemcpyStrSrc, MachineFunction &MF) const { if (getTargetMachine().getOptLevel() != CodeGenOpt::None) { const Function *F = MF.getFunction(); // When expanding a memset, require at least two QPX instructions to cover // the cost of loading the value to be stored from the constant pool. if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) && (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) && !F->hasFnAttribute(Attribute::NoImplicitFloat)) { return MVT::v4f64; } // We should use Altivec/VSX loads and stores when available. For unaligned // addresses, unaligned VSX loads are only fast starting with the P8. if (Subtarget.hasAltivec() && Size >= 16 && (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) || ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector()))) return MVT::v4i32; } if (Subtarget.isPPC64()) { return MVT::i64; } return MVT::i32; } /// \brief Returns true if it is beneficial to convert a load of a constant /// to just the constant itself. bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, Type *Ty) const { assert(Ty->isIntegerTy()); unsigned BitSize = Ty->getPrimitiveSizeInBits(); return !(BitSize == 0 || BitSize > 64); } bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) return false; unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); return NumBits1 == 64 && NumBits2 == 32; } bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { if (!VT1.isInteger() || !VT2.isInteger()) return false; unsigned NumBits1 = VT1.getSizeInBits(); unsigned NumBits2 = VT2.getSizeInBits(); return NumBits1 == 64 && NumBits2 == 32; } bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { // Generally speaking, zexts are not free, but they are free when they can be // folded with other operations. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) { EVT MemVT = LD->getMemoryVT(); if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 || (Subtarget.isPPC64() && MemVT == MVT::i32)) && (LD->getExtensionType() == ISD::NON_EXTLOAD || LD->getExtensionType() == ISD::ZEXTLOAD)) return true; } // FIXME: Add other cases... // - 32-bit shifts with a zext to i64 // - zext after ctlz, bswap, etc. // - zext after and by a constant mask return TargetLowering::isZExtFree(Val, VT2); } bool PPCTargetLowering::isFPExtFree(EVT VT) const { assert(VT.isFloatingPoint()); return true; } bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const { return isInt<16>(Imm) || isUInt<16>(Imm); } bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const { return isInt<16>(Imm) || isUInt<16>(Imm); } bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned, unsigned, bool *Fast) const { if (DisablePPCUnaligned) return false; // PowerPC supports unaligned memory access for simple non-vector types. // Although accessing unaligned addresses is not as efficient as accessing // aligned addresses, it is generally more efficient than manual expansion, // and generally only traps for software emulation when crossing page // boundaries. if (!VT.isSimple()) return false; if (VT.getSimpleVT().isVector()) { if (Subtarget.hasVSX()) { if (VT != MVT::v2f64 && VT != MVT::v2i64 && VT != MVT::v4f32 && VT != MVT::v4i32) return false; } else { return false; } } if (VT == MVT::ppcf128) return false; if (Fast) *Fast = true; return true; } bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { VT = VT.getScalarType(); if (!VT.isSimple()) return false; switch (VT.getSimpleVT().SimpleTy) { case MVT::f32: case MVT::f64: return true; default: break; } return false; } const MCPhysReg * PPCTargetLowering::getScratchRegisters(CallingConv::ID) const { // LR is a callee-save register, but we must treat it as clobbered by any call // site. Hence we include LR in the scratch registers, which are in turn added // as implicit-defs for stackmaps and patchpoints. The same reasoning applies // to CTR, which is used by any indirect call. static const MCPhysReg ScratchRegs[] = { PPC::X12, PPC::LR8, PPC::CTR8, 0 }; return ScratchRegs; } unsigned PPCTargetLowering::getExceptionPointerRegister( const Constant *PersonalityFn) const { return Subtarget.isPPC64() ? PPC::X3 : PPC::R3; } unsigned PPCTargetLowering::getExceptionSelectorRegister( const Constant *PersonalityFn) const { return Subtarget.isPPC64() ? PPC::X4 : PPC::R4; } bool PPCTargetLowering::shouldExpandBuildVectorWithShuffles( EVT VT , unsigned DefinedValues) const { if (VT == MVT::v2i64) return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves if (Subtarget.hasQPX()) { if (VT == MVT::v4f32 || VT == MVT::v4f64 || VT == MVT::v4i1) return true; } return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues); } Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const { if (DisableILPPref || Subtarget.enableMachineScheduler()) return TargetLowering::getSchedulingPreference(N); return Sched::ILP; } // Create a fast isel object. FastISel * PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo, const TargetLibraryInfo *LibInfo) const { return PPC::createFastISel(FuncInfo, LibInfo); }
[ "santosmiguel25@gmail.com" ]
santosmiguel25@gmail.com
43696e02ac3fa38d038077dd161ee13ba94aed12
05cf250793d00cdd7fc7c03cd60a2a705865eab9
/afrodita-firefox/src/main/include-deps/gcc/nsIDOMDocumentFragment.h
bbbadd1105e7362b33205308eb03ca9009edde97
[]
no_license
SoffidIAM/esso
53dcfcbf22b02f0b2fdc1314eb55749c5d1ca158
8b3e04e596a549b9b8ecab186f16680298afd1dc
refs/heads/master
2022-07-25T06:59:29.348943
2022-07-07T13:10:37
2022-07-07T13:10:37
19,988,314
9
5
null
2020-10-12T23:51:27
2014-05-20T16:25:21
C++
UTF-8
C++
false
false
2,172
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM c:/dev/mozilla/mozilla/dom/public/idl/core/nsIDOMDocumentFragment.idl */ #ifndef __gen_nsIDOMDocumentFragment_h__ #define __gen_nsIDOMDocumentFragment_h__ #ifndef __gen_nsIDOMNode_h__ #include "nsIDOMNode.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIDOMDocumentFragment */ #define NS_IDOMDOCUMENTFRAGMENT_IID_STR "a6cf9076-15b3-11d2-932e-00805f8add32" #define NS_IDOMDOCUMENTFRAGMENT_IID \ {0xa6cf9076, 0x15b3, 0x11d2, \ { 0x93, 0x2e, 0x00, 0x80, 0x5f, 0x8a, 0xdd, 0x32 }} class NS_NO_VTABLE nsIDOMDocumentFragment : public nsIDOMNode { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMDOCUMENTFRAGMENT_IID) }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMDocumentFragment, NS_IDOMDOCUMENTFRAGMENT_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDOMDOCUMENTFRAGMENT \ /* no methods! */ /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDOMDOCUMENTFRAGMENT(_to) \ /* no methods! */ /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDOMDOCUMENTFRAGMENT(_to) \ /* no methods! */ #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDOMDocumentFragment : public nsIDOMDocumentFragment { public: NS_DECL_ISUPPORTS NS_DECL_NSIDOMDOCUMENTFRAGMENT nsDOMDocumentFragment(); private: ~nsDOMDocumentFragment(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsDOMDocumentFragment, nsIDOMDocumentFragment) nsDOMDocumentFragment::nsDOMDocumentFragment() { /* member initializers and constructor code */ } nsDOMDocumentFragment::~nsDOMDocumentFragment() { /* destructor code */ } /* End of implementation class template. */ #endif #endif /* __gen_nsIDOMDocumentFragment_h__ */
[ "open@forge.brujula.es" ]
open@forge.brujula.es
44e54fed7a800fe6833d2a25d0fd84e4993b4a55
e37d0e2adfceac661fbd844912d22c25d91f3cc0
/CPP-Primer-Plus/chapter05-loops/block.cpp
fbfcf1162b2bddf024c08a788d6e90411f9e1016
[]
no_license
mikechen66/CPP-Programming
7638927918f59302264f40bbca4ffbfe17398ec6
c49d6d197cad3735d60351434192938c95f8abe7
refs/heads/main
2023-07-11T20:27:12.236223
2021-08-26T08:50:37
2021-08-26T08:50:37
384,588,683
1
0
null
null
null
null
UTF-8
C++
false
false
791
cpp
// block.cpp -- use a block statement #include <iostream> int main() { using namespace std; cout << "The Amazing Accounto will sum and average "; cout << "five numbers for you.\n"; cout << "Please enter five values:\n"; double number; double sum = 0.0; for (int i = 1; i <= 5; i++) { // block starts here cout << "Value " << i << ": "; cin >> number; sum += number; } // block ends here cout << "Five exquisite choices indeed! "; cout << "They sum to " << sum << endl; cout << "and average to " << sum / 5 << ".\n"; cout << "The Amazing Accounto bids you adieu!\n"; // cin.get(); // cin.get(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
2b3c186ef827050264cf3d73ff9f910b133085ae
982651840c71afd066684d4a9211639a494312b8
/resize1/test1.cpp
7499c3a58754e30fa919c6bcdadfa034eccbe04f
[]
no_license
songyww/Imagedownsample
69ae5e99fcac6cad7fbc2125d530c645c02cb3aa
5fff60ca438efd42e30440be1be8e0ced0efe9bc
refs/heads/master
2020-12-30T12:36:50.576496
2017-05-16T02:14:49
2017-05-16T02:14:49
91,403,517
0
0
null
null
null
null
GB18030
C++
false
false
1,426
cpp
//#include "stdafx.h" #include <iostream> #include <cv.h> #include <cxcore.h> #include <highgui.h> #include <cmath> using namespace std; using namespace cv; int main() { vector<double> time_vect; // double t; double t1; time_vect.clear(); IplImage *scr=0; IplImage *dst=0; double scale=1.0/2.0; CvSize dst_cvsize; if (scr=cvLoadImage("E:\\0514\\10000\\1\\5.jpg",-1)) { dst_cvsize.width=(int)(scr->width*scale); dst_cvsize.height=(int)(scr->height*scale); dst=cvCreateImage(dst_cvsize,scr->depth,scr->nChannels); t =(double)cvGetTickCount();//开始计时 cvResize(scr,dst,CV_INTER_AREA);// // CV_INTER_NN - 最近邻插值, // CV_INTER_LINEAR - 双线性插值 (缺省使用) // CV_INTER_AREA - 使用象素关系重采样。当图像缩小时候,该方法可以避免波纹出现。 /*当图像放大时,类似于 CV_INTER_NN 方法..*/ // CV_INTER_CUBIC - 立方插值. t=(double)(cvGetTickCount()-t)/(cvGetTickFrequency()*1000*1000.); time_vect.push_back(t); cvSaveImage("E:\\0514\\10000\\1\\dd2.jpg",dst); /* cvNamedWindow("scr",CV_WINDOW_AUTOSIZE); cvNamedWindow("dst",CV_WINDOW_AUTOSIZE); cvShowImage("scr",scr); cvShowImage("dst",dst); cvWaitKey(); cvReleaseImage(&scr); cvReleaseImage(&dst); cvDestroyWindow("scr"); cvDestroyWindow("dst");*/ } // cvWaitKey(); return 0; time_vect.clear(); }
[ "1157572383@qq.com" ]
1157572383@qq.com
229dbeade36df33c0b7135fa7d57ce73986ed6dd
9ea624a093561c87e47b822008e35d40a136a953
/tst/OpcUaStackCore/StandardDataTypes/BuildInfo_t.cpp
250eb21793040bf504169b078831f0b85848bf44
[ "Apache-2.0" ]
permissive
ASNeG/OpcUaStack
399828371ed4c128360c710dcd831b41f192f27d
e7c365f006be878dcb588a83af9a0dde49bf2b5a
refs/heads/master
2023-08-30T16:12:24.823685
2022-06-27T21:35:44
2022-06-27T21:35:44
149,216,768
141
41
Apache-2.0
2023-08-22T09:10:17
2018-09-18T02:25:58
C++
UTF-8
C++
false
false
3,913
cpp
#include "unittest.h" #include "OpcUaStackCore/Core/Core.h" #include "OpcUaStackCore/BuildInTypes/OpcUaIdentifier.h" #include "OpcUaStackCore/BuildInTypes/OpcUaExtensionObject.h" #include "OpcUaStackCore/StandardDataTypes/BuildInfo.h" using namespace OpcUaStackCore; BOOST_AUTO_TEST_SUITE(BuildInfo_) BOOST_AUTO_TEST_CASE(BuildInfo_) { std::cout << "BuildInfo_t" << std::endl; } BOOST_AUTO_TEST_CASE(BuildInfo_encode_decode) { BuildInfo value1; BuildInfo value2; OpcUaDateTime now(boost::posix_time::microsec_clock::local_time()); value1.productUri() = "ProductUri"; value1.manufacturerName() = "ManufacturerName"; value1.productName() = "ProductName"; value1.softwareVersion() = "SoftwareVersion"; value1.buildNumber() = "BuildNumber"; value1.buildDate() = now; std::stringstream ss; value1.opcUaBinaryEncode(ss); value2.opcUaBinaryDecode(ss); BOOST_REQUIRE(value2.productUri().value() == "ProductUri"); BOOST_REQUIRE(value2.manufacturerName().value() == "ManufacturerName"); BOOST_REQUIRE(value2.productName().value() == "ProductName"); BOOST_REQUIRE(value2.softwareVersion().value() == "SoftwareVersion"); BOOST_REQUIRE(value2.buildNumber().value() == "BuildNumber"); BOOST_REQUIRE(value2.buildDate() == now); } BOOST_AUTO_TEST_CASE(BuildInfo_ExtensionObject) { Core core; core.init(); OpcUaExtensionObject value1; OpcUaExtensionObject value2; OpcUaDateTime now(boost::posix_time::microsec_clock::local_time()); OpcUaNodeId typeId; typeId.set(OpcUaId_BuildInfo_Encoding_DefaultBinary); value1.typeId(typeId); value1.parameter<BuildInfo>()->productUri() = "ProductUri"; value1.parameter<BuildInfo>()->manufacturerName() = "ManufacturerName"; value1.parameter<BuildInfo>()->productName() = "ProductName"; value1.parameter<BuildInfo>()->softwareVersion() = "SoftwareVersion"; value1.parameter<BuildInfo>()->buildNumber() = "BuildNumber"; value1.parameter<BuildInfo>()->buildDate() = now; std::stringstream ss; value1.opcUaBinaryEncode(ss); value2.opcUaBinaryDecode(ss); BOOST_REQUIRE(value2.parameter<BuildInfo>()->productUri().value() == "ProductUri"); BOOST_REQUIRE(value2.parameter<BuildInfo>()->manufacturerName().value() == "ManufacturerName"); BOOST_REQUIRE(value2.parameter<BuildInfo>()->productName().value() == "ProductName"); BOOST_REQUIRE(value2.parameter<BuildInfo>()->softwareVersion().value() == "SoftwareVersion"); BOOST_REQUIRE(value2.parameter<BuildInfo>()->buildNumber().value() == "BuildNumber"); BOOST_REQUIRE(value2.parameter<BuildInfo>()->buildDate() == now); } BOOST_AUTO_TEST_CASE(BuildInfo_ExtensionObject_copyTo) { Core core; core.init(); OpcUaExtensionObject value1; OpcUaExtensionObject value2; OpcUaDateTime now(boost::posix_time::microsec_clock::local_time()); OpcUaNodeId typeId; typeId.set(OpcUaId_BuildInfo_Encoding_DefaultBinary); value1.typeId(typeId); value1.parameter<BuildInfo>()->productUri() = "ProductUri"; value1.parameter<BuildInfo>()->manufacturerName() = "ManufacturerName"; value1.parameter<BuildInfo>()->productName() = "ProductName"; value1.parameter<BuildInfo>()->softwareVersion() = "SoftwareVersion"; value1.parameter<BuildInfo>()->buildNumber() = "BuildNumber"; value1.parameter<BuildInfo>()->buildDate() = now; value1.copyTo(value2); BOOST_REQUIRE(value2.parameter<BuildInfo>()->productUri().value() == "ProductUri"); BOOST_REQUIRE(value2.parameter<BuildInfo>()->manufacturerName().value() == "ManufacturerName"); BOOST_REQUIRE(value2.parameter<BuildInfo>()->productName().value() == "ProductName"); BOOST_REQUIRE(value2.parameter<BuildInfo>()->softwareVersion().value() == "SoftwareVersion"); BOOST_REQUIRE(value2.parameter<BuildInfo>()->buildNumber().value() == "BuildNumber"); BOOST_REQUIRE(value2.parameter<BuildInfo>()->buildDate() == now); } BOOST_AUTO_TEST_SUITE_END()
[ "kai@huebl-sgh.de" ]
kai@huebl-sgh.de
c868eae3736a99adc77cabc90763d7c3503cfddc
6dccb3185a93e45b0992dfdf5938b5e3ab9d46de
/src/ParaGraphTest/src/graph_test_utils.h
a3755e4e0eab57a3773cc2d1395452c1247cee68
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
appu226/ParaGraph
7a16f40424879a4aac5c8f1e264fc63dd9fa6c02
82604a286b50d414515f22521882115980f2ee80
refs/heads/master
2020-03-07T15:25:38.515538
2018-09-02T12:39:57
2018-09-02T12:39:57
127,554,552
1
0
Apache-2.0
2018-08-04T15:11:58
2018-03-31T17:22:32
C++
UTF-8
C++
false
false
1,191
h
/** * Copyright 2018 Parakram Majumdar * * 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. */ #ifndef PARA_GRAPH_GRAPH_TEST_UTILS_H_ #define PARA_GRAPH_GRAPH_TEST_UTILS_H_ #include <para/graph/math.h> #include <random> namespace para { namespace graph { void assert_tensors_are_close(const tensor& lhs, const tensor& rhs, double relative_tolerance, const std::string& message); tensor_cptr generate_random_tensor(const tensor::N_vector& dims, std::default_random_engine& dre, double max = 1.0); std::string print_tensor(const tensor& t, const std::string& name); } // end namespace graph } // end namespace para #endif /* end ifndef PARA_GRAPH_GRAPH_TEST_UTILS_H_ */
[ "appu226@yahoo.co.in" ]
appu226@yahoo.co.in
3ce7e02aac787c4f79993b051beead14e9461f5d
03c66ce2d72e276d7cdb4b7bb3dc03ba326ffb07
/SpaceEngine-master/Space/Bullet.cpp
57a89a8e82b52cee9097e81daf49b7a3567fa6d1
[]
no_license
Whatop/Games
f9dd6f8e517bd1cb6a21c85e66a7cb00e3fb1d08
e0de457fc6acbce9c1d3f37622f2e57f2b58344a
refs/heads/main
2023-08-17T21:33:11.618439
2021-10-24T15:04:28
2021-10-24T15:04:28
307,647,199
1
0
null
null
null
null
UTF-8
C++
false
false
839
cpp
#include "stdafx.h" #include "Bullet.h" Bullet::Bullet(std::wstring fileName, std::string Enemy,Vec2 pos, bool LastDireIsRight) { m_Bullet = Sprite::Create(fileName); m_Bullet->SetParent(this); timer = 0.f; m_Position = pos; if (LastDireIsRight) { m_Scale.x = 1; // -> } else if (!LastDireIsRight) { m_Scale.x = -1; } m_Bullet->A = 50; m_Name = Enemy; } Bullet::~Bullet() { } void Bullet::Update(float deltaTime, float Time) { ObjMgr->CollisionCheak(this, m_Name); timer += dt; if (timer >= 0.08f) SetDestroy(true); } void Bullet::Render() { m_Bullet->Render(); } void Bullet::OnCollision(Object* other) { if (other->m_Tag == "Enemy") { ObjMgr->RemoveObject(this); } if (other->m_Tag == "Player") { ObjMgr->RemoveObject(this); } if (other->m_Tag == "Shield") { ObjMgr->RemoveObject(this); } }
[ "73518664+Whatop@users.noreply.github.com" ]
73518664+Whatop@users.noreply.github.com
945f5d716c017101d407971746d0acf8ac467acc
e90f7cd01fba0aff87f90277cd2631f373b8b986
/MxGL/Sources/MxAnimation.h
5f8e36d74ad690ceaa0a3d94138bf7caf6f74b0b
[ "MIT" ]
permissive
Emmanuel-DUPUIS/heightmapterrain
db7645072694308907f3e84df4c0281e333a70f6
9c1f41afe8d314607c20ad6341648920debbebbf
refs/heads/master
2021-05-14T12:38:08.487559
2018-03-02T13:45:16
2018-03-02T13:45:16
116,415,832
0
0
null
null
null
null
UTF-8
C++
false
false
1,254
h
//======================================================================== // Height Map Terrain Model // MIT License // Copyright (c) 2017 Emmanuel DUPUIS, emmanuel.dupuis@undecentum.com //======================================================================== #pragma once #include <string> #include <memory> class MxScene; class MxAnimation { protected: bool _Enabled; bool _Completed; int _FrozenUntil; float _Step; float _DeltaStep; int _StartPause; int _EndPause; int _StartTime; int _LastTime; public: MxAnimation(int iStartPause, int iEndPause); virtual ~MxAnimation() {} void enable() { _Enabled = true; } void disable() { _Enabled = false; } void toggleAbility() { _Enabled = !_Enabled; } bool isEnable(int iTime) { return _Enabled; } bool isFrozen(int iTime); int frozenUntil() const { return _FrozenUntil; } void freezeUntil(int iTime) { if (iTime > _FrozenUntil) _FrozenUntil = iTime; } void upadeStage(int iTime, float iStep, float iDeltaStep); virtual void init(int iTime); virtual std::string getStage() const; virtual void execute(MxScene* iScene, int iTime, uint64_t iFrame) = 0; };
[ "noreply@github.com" ]
noreply@github.com
2cf298a379c604d16d23f5a72d1cc5649aaa198c
d939ea588d1b215261b92013e050993b21651f9a
/ie/src/v20200304/model/MediaJoiningInfo.cpp
91fb99c3d673c7c35862ed381d2b86a942355c0a
[ "Apache-2.0" ]
permissive
chenxx98/tencentcloud-sdk-cpp
374e6d1349f8992893ded7aa08f911dd281f1bda
a9e75d321d96504bc3437300d26e371f5f4580a0
refs/heads/master
2023-03-27T05:35:50.158432
2021-03-26T05:18:10
2021-03-26T05:18:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,339
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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. */ #include <tencentcloud/ie/v20200304/model/MediaJoiningInfo.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Ie::V20200304::Model; using namespace rapidjson; using namespace std; MediaJoiningInfo::MediaJoiningInfo() : m_targetInfoHasBeenSet(false) { } CoreInternalOutcome MediaJoiningInfo::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("TargetInfo") && !value["TargetInfo"].IsNull()) { if (!value["TargetInfo"].IsObject()) { return CoreInternalOutcome(Error("response `MediaJoiningInfo.TargetInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_targetInfo.Deserialize(value["TargetInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_targetInfoHasBeenSet = true; } return CoreInternalOutcome(true); } void MediaJoiningInfo::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_targetInfoHasBeenSet) { Value iKey(kStringType); string key = "TargetInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(kObjectType).Move(), allocator); m_targetInfo.ToJsonObject(value[key.c_str()], allocator); } } MediaTargetInfo MediaJoiningInfo::GetTargetInfo() const { return m_targetInfo; } void MediaJoiningInfo::SetTargetInfo(const MediaTargetInfo& _targetInfo) { m_targetInfo = _targetInfo; m_targetInfoHasBeenSet = true; } bool MediaJoiningInfo::TargetInfoHasBeenSet() const { return m_targetInfoHasBeenSet; }
[ "tencentcloudapi@tenent.com" ]
tencentcloudapi@tenent.com
810c33d34b86f02900a606c24422f3b2612abf83
d7d6678b2c73f46ffe657f37169f8e17e2899984
/controllers/ros/include/webots_ros/node_get_base_type_name.h
bffeb511ab8e037182fe57dca602dc7f32e2a4b9
[]
no_license
rggasoto/AdvRobotNav
ad8245618e1cc65aaf9a0d659c4bb1588f035f18
d562ba4fba896dc23ea917bc2ca2d3c9e839b037
refs/heads/master
2021-05-31T12:00:12.452249
2016-04-15T14:02:05
2016-04-15T14:02:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,353
h
#ifndef WEBOTS_ROS_MESSAGE_NODE_GET_BASE_TYPE_NAME_H #define WEBOTS_ROS_MESSAGE_NODE_GET_BASE_TYPE_NAME_H #include "ros/service_traits.h" #include "node_get_base_type_nameRequest.h" #include "node_get_base_type_nameResponse.h" namespace webots_ros { struct node_get_base_type_name { typedef node_get_base_type_nameRequest Request; typedef node_get_base_type_nameResponse Response; Request request; Response response; typedef Request RequestType; typedef Response ResponseType; }; } // namespace webots_ros namespace ros { namespace service_traits { template<> struct MD5Sum< ::webots_ros::node_get_base_type_name > { static const char* value() { return "51d3f5e9907c2b98d816acf3aad2e00e"; } static const char* value(const ::webots_ros::node_get_base_type_name&) { return value(); } }; template<> struct DataType< ::webots_ros::node_get_base_type_name > { static const char* value() { return "webots_ros/node_get_base_type_name"; } static const char* value(const ::webots_ros::node_get_base_type_name&) { return value(); } }; template<> struct MD5Sum< ::webots_ros::node_get_base_type_nameRequest> { static const char* value() { return MD5Sum< ::webots_ros::node_get_base_type_name >::value(); } static const char* value(const ::webots_ros::node_get_base_type_nameRequest&) { return value(); } }; template<> struct DataType< ::webots_ros::node_get_base_type_nameRequest> { static const char* value() { return DataType< ::webots_ros::node_get_base_type_name >::value(); } static const char* value(const ::webots_ros::node_get_base_type_nameRequest&) { return value(); } }; template<> struct MD5Sum< ::webots_ros::node_get_base_type_nameResponse> { static const char* value() { return MD5Sum< ::webots_ros::node_get_base_type_name >::value(); } static const char* value(const ::webots_ros::node_get_base_type_nameResponse&) { return value(); } }; template<> struct DataType< ::webots_ros::node_get_base_type_nameResponse> { static const char* value() { return DataType< ::webots_ros::node_get_base_type_name >::value(); } static const char* value(const ::webots_ros::node_get_base_type_nameResponse&) { return value(); } }; } // namespace service_traits } // namespace ros #endif // WEBOTS_ROS_MESSAGE_NODE_GET_BASE_TYPE_NAME_H
[ "rggasoto@wpi.edu" ]
rggasoto@wpi.edu
22cf7a86af19cdbb590898e545dfc18065da251e
15f05e055673242daf59d3f46d9b6c6908ebd85a
/LaserRobot.cc
1d0d3d089bd41c9effeb7286cb11cbd4e3a5cc5c
[]
no_license
erdincay/MyRobot
fd3900676ba41f64abfa5c6f605d177354c75a4a
fec17bdbc97d81c3dd01b2f805c41f30210fef8e
refs/heads/master
2021-01-14T13:47:57.177366
2014-03-17T06:01:56
2014-03-17T06:01:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,006
cc
#include "LaserRobot.h" const int defaultPosition2dProxyPort = 0; const int defaultLaserProxyPort = 0; using namespace std; LaserRobot::LaserRobot(boost::asio::io_service & io_service, string host, int player_port) :timerWalk_(io_service) { robot_ = new PlayerClient(host, player_port); pp_ = new Position2dProxy(robot_, defaultPosition2dProxyPort); lp_ = new LaserProxy(robot_, defaultLaserProxyPort); pp_->RequestGeom(); } LaserRobot::~LaserRobot() { cout<<"~LaserRobot()"<<endl; delete lp_; delete pp_; delete robot_; } double LaserRobot::GetXPos() { return pp_->GetXPos(); } double LaserRobot::GetYPos() { return pp_->GetYPos(); } double LaserRobot::GetYaw() { return pp_->GetYaw(); } double LaserRobot::GetXSpeed() { return pp_->GetXSpeed(); } double LaserRobot::GetYSpeed() { return pp_->GetYSpeed(); } double LaserRobot::GetYawSpeed() { return pp_->GetYawSpeed(); } void LaserRobot::SetSpeed(double xSpeed, double turnSpeed) { pp_->SetSpeed(xSpeed, turnSpeed); } void LaserRobot::SetSpeed(double xSpeed, double ySpeed, double turnSpeed) { pp_->SetSpeed(xSpeed, ySpeed, turnSpeed); } void LaserRobot::SetVelHead(double xSpeed, double yawHead) { pp_->SetVelHead(xSpeed,yawHead); } void LaserRobot::GoTo(double x_pos, double y_pos) { pp_->GoTo(x_pos,y_pos, 0); } void LaserRobot::GoTo(player_pose2d_t pos, player_pose2d_t speed) { pp_->GoTo(pos, speed); } void LaserRobot::Read() { robot_->Read(); } void LaserRobot::LaserAvoidance(double & newspeed, double & newturnrate) { //double newspeed = 0; //double newturnrate = 0; // this blocks until new data comes; 10Hz by default robot_->Read(); double minR = lp_->GetMinRight(); double minL = lp_->GetMinLeft(); // laser avoid (stolen from esben's java example) //std::cout << "minR: " << minR << "minL: " << minL << std::endl; double l = (1e5*minR)/500-100; double r = (1e5*minL)/500-100; if (l > 100) l = 100; if (r > 100) r = 100; newspeed = (r+l)/1e3; newturnrate = (r-l); newturnrate = limit(newturnrate, -40.0, 40.0); newturnrate = dtor(newturnrate); //std::cout << "speed: " << newspeed << " turn: " << newturnrate << std::endl; //std::cout<<GetXPos()<<", "<<GetYPos()<<std::endl; // write commands to robot //pp_->SetSpeed(newspeed, newturnrate); } void LaserRobot::handle_timerWalk(const boost::system::error_code& error) { if (!error) { Resume(); } } void LaserRobot::Resume() { double newspeed = 0.0; double newturnrate = 0.0; LaserAvoidance(newspeed, newturnrate); SetSpeed(newspeed, newturnrate); timerWalk_.expires_from_now(boost::posix_time::millisec(500)); timerWalk_.async_wait(boost::bind(&LaserRobot::handle_timerWalk, this, boost::asio::placeholders::error)); } void LaserRobot::Walk() { SetSpeed(0.5, 0.0); Resume(); } void LaserRobot::Stop() { timerWalk_.cancel(); SetSpeed(0.0, 0.0); } void LaserRobot::Run() { cout << "LaserRobot is running" << endl; Walk(); }
[ "kding@csupomona.edu" ]
kding@csupomona.edu
d5b3e554a975662ad10a0e9dff23a7fb693b1280
5cdbd4c2e128b310576bb93ea77d29a9d5331b11
/Diablo3/Dx3D/cParticleEmitter.cpp
479d3f77317e15898f2857dae5fa66796edafad8
[]
no_license
kimkinam/SGA_Diablo
b929cdef5f04c9331dbcc901ba87f2dd5436737f
7297290c5e57c0ff9ffac28f90522184d095f2c3
refs/heads/master
2020-07-01T08:16:32.236082
2016-12-19T09:21:17
2016-12-19T09:21:17
73,990,008
0
0
null
null
null
null
UHC
C++
false
false
16,475
cpp
#include "StdAfx.h" #include "cParticleEmitter.h" cParticleEmitter::cParticleEmitter(void) :m_matParent(NULL) , m_IsActvieAll(false) { } cParticleEmitter::~cParticleEmitter(void) { } void cParticleEmitter::Init( DWORD partcleNum, //총 파티클 량 float emission, //초당 발생량 float liveTimeMin, //파티클하나의 시간 float liveTimeMax, const D3DXVECTOR3& velocityMin, //파티클 시작 속도 const D3DXVECTOR3& velocityMax, const D3DXVECTOR3& accelMin, //파티클 가속 const D3DXVECTOR3& accelMax, const VEC_COLOR& colors, //파티클 컬러 벡터배열 const VEC_SCALE& scales, //파티클 스케일 컬러배열 float scaleMin, //파티클 스케일 float scaleMax, LPDIRECT3DTEXTURE9 pPaticleTexture, //파티클 Texture bool bLocal //이게 true 면 파티클의 움직임이 나의Transform Local 기준으로 움직인다. ) { //해당 파티클 랜더의 총 파티클 수 m_PaticleNum = partcleNum; //총파티클 수만큼 버텍스 배열을 만든다. m_ParticleVerticles = new PARTICLE_VERTEX[ m_PaticleNum ]; //파티클 객체 생성 m_pPaticles = new cParticle[ m_PaticleNum ]; //초당 생성량 m_fEmissionPerSec = emission; //초당 생성량 따른 발생 간격 m_fEmisionIntervalTime = 1.0f / m_fEmissionPerSec; //지난 시간도 0 m_fEmisionDeltaTime = 0.0f; //발생 여부 false m_bEmission = false; //컬러 대입 //m_Colors = colors; m_Colors.clear(); for( int i = 0 ; i < colors.size() ;i++ ) m_Colors.push_back( colors[i] ); //사이즈 대입 //m_Scales = scales; m_Scales.clear(); for( int i = 0 ; i < scales.size() ;i++ ) m_Scales.push_back( scales[i] ); //시작 라이브 타임 대입 m_fStartLiveTimeMin = liveTimeMin; m_fStartLiveTimeMax = liveTimeMax; //시작 속도 대입 m_StartVelocityMin = velocityMin; m_StartVelocityMax = velocityMax; //시작 가속 대입 m_StartAccelateMin = accelMin; m_StartAccelateMax = accelMax; //시작 스케일 대입 m_fStartScaleMin = scaleMin; m_fStartScaleMax = scaleMax; //시작순번 초기화 m_dwParticleCount = 0; //Texture 참조 m_pTex = pPaticleTexture; //m_bLocal = bLocal; EmissionType = PZERO; } void cParticleEmitter::Release() { SAFE_DELETE_ARRAY( m_pPaticles ); SAFE_DELETE_ARRAY( m_ParticleVerticles ); } //사방 팔방으로 입자 퍼트린다. void cParticleEmitter::Burst( int num, float minSpeed, float maxSpeed, float maxLife, float minLife ) { for( int i = 0 ; i < num ; i++ ) { D3DXVECTOR3 randVec( RandomFloatRange( -1.0f, 1.0f ), RandomFloatRange( -1.0f, 1.0f ), RandomFloatRange( -1.0f, 1.0f ) ); D3DXVec3Normalize( &randVec, &randVec ); randVec*= RandomFloatRange( minSpeed, maxSpeed ); StartOneParticle( randVec, RandomFloatRange(maxLife,minLife ) ); } } void cParticleEmitter::Fire(int num, D3DXVECTOR3 startPos, float minSpeed, float maxSpeed, float maxLife, float minLife) { m_fEmisionDeltaTime += g_pTimeManager->GetDeltaTime(); while (m_fEmisionDeltaTime >= 1.0f / num) { m_fEmisionDeltaTime -= 1.0f / num; //for (int i = 0; i < num; i++) //{ D3DXVECTOR3 randVec( RandomFloatRange(-0.05f, 0.05f), RandomFloatRange(0.08f, 1.0f), RandomFloatRange(-0.05f, 0.05f)); D3DXVec3Normalize(&randVec, &randVec); randVec *= RandomFloatRange(minSpeed, maxSpeed); D3DXVECTOR3 randVec2( RandomFloatRange(-0.01f, 0.01f), RandomFloatRange(0.1f, 1.0f), RandomFloatRange(-0.01f, 0.01f)); randVec2 *= RandomFloatRange(minSpeed, maxSpeed); StartOneParticle(randVec, startPos,randVec2, RandomFloatRange(maxLife, minLife)); } //} } void cParticleEmitter::FireTail(int num, D3DXVECTOR3 startPos, float minSpeed, float maxSpeed, float maxLife, float minLife) { m_fEmisionDeltaTime += g_pTimeManager->GetDeltaTime(); while (m_fEmisionDeltaTime >= 1.0f /num) { m_fEmisionDeltaTime -= 1.0f / num; //for (int i = 0; i < num; i++) //{ //D3DXVECTOR3 randVec( // RandomFloatRange(-0.05f, 0.05f), // RandomFloatRange(-0.01f, 0.01f), // RandomFloatRange(-0.05f, 0.05f)); D3DXVECTOR3 randVec( RandomFloatRange(0.0f, 0.0f), RandomFloatRange(0.0f, 0.0f), RandomFloatRange(0.0f, 0.0f)); D3DXVec3Normalize(&randVec, &randVec); randVec *= RandomFloatRange(minSpeed, maxSpeed); D3DXVECTOR3 randVec2( RandomFloatRange(-0.001f, 0.001f), RandomFloatRange(-0.001f, 0.001f), RandomFloatRange(-0.001f, 0.001f)); randVec2 *= RandomFloatRange(minSpeed, maxSpeed); StartOneParticle(randVec, startPos, randVec2, RandomFloatRange(maxLife, minLife)); } //} } void cParticleEmitter::LighteningBreath(int num, D3DXVECTOR3 startPos, D3DXVECTOR3 dir, float minSpeed, float maxSpeed, float minLife, float maxLife) { m_fEmisionDeltaTime += g_pTimeManager->GetDeltaTime() * 3; while (m_fEmisionDeltaTime >= 1.0f / num) { m_fEmisionDeltaTime -= 1.0f/num; D3DXVECTOR3 vNormDir, vNormUp, vNormRight; D3DXVec3Normalize(&vNormDir, &dir); D3DXVec3Cross(&vNormRight, &D3DXVECTOR3(0, 1, 0), &vNormDir); D3DXVec3Normalize(&vNormRight, &vNormRight); D3DXVec3Cross(&vNormUp, &vNormDir, &vNormRight); D3DXVec3Normalize(&vNormUp, &vNormUp); D3DXMATRIXA16 matWorld; D3DXMatrixIdentity(&matWorld); memcpy(&matWorld._11, &vNormRight, sizeof(D3DXVECTOR3)); memcpy(&matWorld._21, &vNormUp, sizeof(D3DXVECTOR3)); memcpy(&matWorld._31, &vNormDir, sizeof(D3DXVECTOR3)); //for (int i = 0; i < num; i++) //{ D3DXVECTOR3 velocity = dir*3.0f; D3DXVECTOR3 randVec2( RandomFloatRange(0, 0), RandomFloatRange(0.3f, -0.3f), RandomFloatRange(-0.1f, 5.0)); D3DXVec3TransformCoord(&randVec2, &randVec2, &matWorld); //life time = 2.3, 3.0f; StartOneParticle(dir, startPos, randVec2, RandomFloatRange(maxLife, minLife)); } //} } void cParticleEmitter::BaseObjectUpdate( float timeDelta ) { //모든 파티클 업데이트 m_IsActvieAll = false; for( int i = 0 ; i < m_PaticleNum ; i++ ){ if (m_pPaticles[i].isLive()) { if (!m_IsActvieAll) m_IsActvieAll = true; } m_pPaticles[i].Update( timeDelta ); } //너가 지금 발생 상태니? if( m_bEmission ){ //하나 발생하고 지난시간 m_fEmisionDeltaTime += timeDelta; while( m_fEmisionDeltaTime >= m_fEmisionIntervalTime){ m_fEmisionDeltaTime -= m_fEmisionIntervalTime; //파티클 하나 발사 StartOneParticle(); } } } void cParticleEmitter::BaseObjectRender() { //if (!m_bEmission)return; if (!m_IsActvieAll) return; //그릴 파티클 수 DWORD drawParticleNum = 0; for( int i = 0 ; i < m_PaticleNum ; i++ ){ //해당파티클이 활성화 중이니? if( m_pPaticles[i].isLive() ){ //해당 파티클의 정보를 얻는다. m_pPaticles[i].GetParticleVertex( m_ParticleVerticles + drawParticleNum, m_Colors, m_Scales ); drawParticleNum++; } } g_pD3DDevice->SetRenderState( D3DRS_LIGHTING, false ); //라이팅을 끈다. g_pD3DDevice->SetTexture(0, NULL); g_pD3DDevice->SetRenderState( D3DRS_POINTSPRITEENABLE, true ); //포인트 스플라이트 활성화 g_pD3DDevice->SetRenderState( D3DRS_POINTSCALEENABLE, true ); //포인트의 스케일값 먹이겠다. g_pD3DDevice->SetRenderState( D3DRS_POINTSIZE_MIN, FloatToDWORD( 0.0f ) ); //포인트의 최소 크기 ( 화면기준 ) g_pD3DDevice->SetRenderState( D3DRS_POINTSIZE_MAX, FloatToDWORD( 250.0f ) ); //포인트의 최대 크기 ( 화면기준 ) //g_pD3DDevice->SetRenderState( D3DRS_POINTSIZE, FloatToDWORD( 10.0f ) ); //포인트 기준 사이즈 ( 정점의 포인트 사이즈가 있으면 무시되는듯 ); g_pD3DDevice->SetRenderState( D3DRS_ZWRITEENABLE, false ); //z 버퍼의 쓰기를 막는다. //출력되는 POINT size //finalSize = viewportHeight * pointSize * sqrt( 1 / ( A + B(D) + C(D^2) ) ); //아래와 같이 하면 자연스러운 거리에 따른 스케일이 나타남 g_pD3DDevice->SetRenderState( D3DRS_POINTSCALE_A, FloatToDWORD( 0.0f ) ); g_pD3DDevice->SetRenderState( D3DRS_POINTSCALE_B, FloatToDWORD( 0.0f ) ); g_pD3DDevice->SetRenderState( D3DRS_POINTSCALE_C, FloatToDWORD( 1.0f ) ); //알파 블렌딩 셋팅 g_pD3DDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, true ); g_pD3DDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA ); g_pD3DDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_ONE); //Texture 의 값과 Diffuse 여기서는 정점컬러의 알파값 을 섞어 최종 출력을 한다. g_pD3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE ); g_pD3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE ); g_pD3DDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG2, D3DTA_TEXTURE ); D3DXMATRIXA16 matWorld; if( m_matParent ) matWorld = *m_matParent; else D3DXMatrixIdentity( &matWorld ); g_pD3DDevice->SetTransform( D3DTS_WORLD, &matWorld ); //파티클 Texture 셋팅 //g_pD3DDevice->SetTexture(0, NULL); g_pD3DDevice->SetTexture( 0, m_pTex ); //파티클 정점 출력 g_pD3DDevice->SetFVF( PARTICLE_VERTEX::FVF ); g_pD3DDevice->DrawPrimitiveUP( D3DPT_POINTLIST, drawParticleNum, m_ParticleVerticles, sizeof( PARTICLE_VERTEX ) ); //파티클 그리고 난후 후처리 g_pD3DDevice->SetRenderState( D3DRS_LIGHTING, true ); g_pD3DDevice->SetRenderState( D3DRS_POINTSPRITEENABLE, false ); g_pD3DDevice->SetRenderState( D3DRS_POINTSCALEENABLE, false ); g_pD3DDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, false ); g_pD3DDevice->SetRenderState( D3DRS_ZWRITEENABLE, true ); g_pD3DDevice->SetTexture( 0, NULL ); } //파티클 생성 시작 void cParticleEmitter::StartEmission() { m_bEmission = true; } //파티클 생성 중지 void cParticleEmitter::StopEmission() { m_bEmission = false; } /////////////////////////////////////////////////// //파티클 하나 생성 void cParticleEmitter::StartOneParticle() { if (m_dwParticleCount == this->m_PaticleNum) { return; } //라이브 타임 랜덤 float liveTime = RandomFloatRange( m_fStartLiveTimeMin, m_fStartLiveTimeMax ); // float liveTime = RandomFloatRange( // 1, 3); //파티클이 생성될 위치 D3DXVECTOR3 position; //로컬이 아닌경우 자신의 월드 위치에서 시작하고 if( m_matParent) position = D3DXVECTOR3(m_matParent->_41, m_matParent->_42,m_matParent->_43); //로컬인 경우 0 에서 시작한다. else position = D3DXVECTOR3( 0, 0, 0 ); //생성 범위에 따른 추가 위치.... if( EmissionType == PATICLE_EMISSION_TYPE::SPHERE ) { //랜덤벡터 D3DXVECTOR3 randDir( RandomFloatRange( -1.0f, 1.0f ), RandomFloatRange( -1.0f, 1.0f ), RandomFloatRange( -1.0f, 1.0f ) ); D3DXVec3Normalize( &randDir, &randDir ); //랜덤거리 float randDistance = RandomFloatRange( 0, SphereEmissionRange ); //추가위치 position += randDir * randDistance; } else if( EmissionType == PATICLE_EMISSION_TYPE::SPHERE_OUTLINE ) { //랜덤벡터 D3DXVECTOR3 randDir( RandomFloatRange( -1.0f, 1.0f ), RandomFloatRange( -1.0f, 1.0f ), RandomFloatRange( -1.0f, 1.0f ) ); //D3DXVECTOR3 randDir( // 0,0,-1); D3DXVec3Normalize( &randDir, &randDir ); //추가위치 position += randDir * SphereEmissionRange; } else if( EmissionType == PATICLE_EMISSION_TYPE::BOX ) { //랜덤벡터 D3DXVECTOR3 randDir( RandomFloatRange( MinEmissionRangeX, MaxEmissionRangeX ), RandomFloatRange( MinEmissionRangeY, MaxEmissionRangeY ), RandomFloatRange( MinEmissionRangeZ, MaxEmissionRangeZ ) ); //추가위치 position += randDir; } //벡터 랜덤 D3DXVECTOR3 velocity; // velocity.x =RandomFloatRange( 0, -0 ); // velocity.y =RandomFloatRange(0, -0); // velocity.z =RandomFloatRange(0, 0); velocity.x = RandomFloatRange(m_StartVelocityMin.x, m_StartVelocityMax.x); velocity.y = RandomFloatRange(m_StartVelocityMin.y, m_StartVelocityMax.y); velocity.z = RandomFloatRange(m_StartVelocityMin.z, m_StartVelocityMax.z); D3DXVECTOR3 accelation; accelation.x = RandomFloatRange(m_StartAccelateMin.x, m_StartAccelateMax.x); accelation.y = RandomFloatRange(m_StartAccelateMin.y, m_StartAccelateMax.y); accelation.z = RandomFloatRange(m_StartAccelateMin.z, m_StartAccelateMax.z); //accelation.x = RandomFloatRange(0.4f,-0.4f); //accelation.y = RandomFloatRange( 0.4f,-0.4f ); //accelation.z = RandomFloatRange( -1, 0 ); //자신의 월드 매트릭스를 가지고 온다. if(m_matParent !=NULL ) { //D3DXMATRIXA16 matWorld = this->pTransform->GetFinalMatrix(); D3DXVec3TransformNormal( &velocity, &velocity, m_matParent); D3DXVec3TransformNormal( &accelation, &accelation, m_matParent); } //position.x += *RandomFloatRange(0.3, -0.1); //position.y += *RandomFloatRange(0.3, -0.1f); //position.z += *RandomFloatRange(-0.3, 1); //스케일도 랜덤 float scale = RandomFloatRange( m_fStartScaleMin, m_fStartScaleMax ); //순번대로 발생시킨다 m_pPaticles[ m_dwParticleCount ].Start( liveTime, &position, &velocity, &accelation, scale ); //다음 파티클을 위한 순번 증가 m_dwParticleCount++; if( m_dwParticleCount == this->m_PaticleNum ) m_dwParticleCount = 0; } //파티클 하나 생성 ( 방향 넣어서 ) void cParticleEmitter::StartOneParticle( D3DXVECTOR3 dir, float life ) { float liveTime = life*0.1f; //파티클이 생성될 위치 D3DXVECTOR3 position; if( m_matParent ) position = D3DXVECTOR3( m_matParent->_41,m_matParent->_42,m_matParent->_43); else position = D3DXVECTOR3( 0, 0, 0 ); //벡터 랜덤 D3DXVECTOR3 velocity; velocity.x = dir.x; velocity.y = dir.y; velocity.z = dir.z; D3DXVECTOR3 accelation; accelation.x = RandomFloatRange( m_StartAccelateMin.x, m_StartAccelateMax.x ); accelation.y = RandomFloatRange( m_StartAccelateMin.y, m_StartAccelateMax.y ); accelation.z = RandomFloatRange( m_StartAccelateMin.z, m_StartAccelateMax.z ); //자신의 월드 매트릭스를 가지고 온다. if( m_matParent) { D3DXVec3TransformNormal( &velocity, &velocity, m_matParent); D3DXVec3TransformNormal( &accelation, &accelation, m_matParent); } //스케일도 랜덤 float scale = RandomFloatRange( m_fStartScaleMin, m_fStartScaleMax ); //발생시킨다 m_pPaticles[ m_dwParticleCount ].Start( liveTime, &position, &velocity, &accelation, scale ); m_dwParticleCount++; if( m_dwParticleCount == this->m_PaticleNum ) m_dwParticleCount = 0; } //파티클 하나 생성 ( 방향,속도 넣어서 ) void cParticleEmitter::StartOneParticle(D3DXVECTOR3 dir, D3DXVECTOR3 accelSpeed, float life) { float liveTime = life; //파티클이 생성될 위치 D3DXVECTOR3 position; if (m_matParent) position = D3DXVECTOR3(m_matParent->_41, m_matParent->_42, m_matParent->_43); else position = D3DXVECTOR3(0, 0, 0); //벡터 랜덤 D3DXVECTOR3 velocity; velocity.x = dir.x; velocity.y = dir.y; velocity.z = dir.z; D3DXVECTOR3 accelation; accelation.x = accelSpeed.x; accelation.y = accelSpeed.y; accelation.z = accelSpeed.z; //자신의 월드 매트릭스를 가지고 온다. if (m_matParent) { D3DXVec3TransformNormal(&velocity, &velocity, m_matParent); D3DXVec3TransformNormal(&accelation, &accelation, m_matParent); } //스케일도 랜덤 float scale = RandomFloatRange(m_fStartScaleMin, m_fStartScaleMax); //발생시킨다 m_pPaticles[m_dwParticleCount].Start( liveTime, &position, &velocity, &accelation, scale); m_dwParticleCount++; if (m_dwParticleCount == this->m_PaticleNum) m_dwParticleCount = 0; } void cParticleEmitter::StartOneParticle(D3DXVECTOR3 dir, D3DXVECTOR3 pos, D3DXVECTOR3 accelSpeed, float life) { float liveTime = life; //파티클이 생성될 위치 D3DXVECTOR3 position; position = pos; //벡터 랜덤 D3DXVECTOR3 velocity; velocity.x = dir.x; velocity.y = dir.y; velocity.z = dir.z; D3DXVECTOR3 accelation; accelation.x = accelSpeed.x; accelation.y = accelSpeed.y; accelation.z = accelSpeed.z; //자신의 월드 매트릭스를 가지고 온다. if (m_matParent) { D3DXVec3TransformNormal(&velocity, &velocity, m_matParent); D3DXVec3TransformNormal(&accelation, &accelation, m_matParent); } //스케일도 랜덤 float scale = RandomFloatRange(m_fStartScaleMin, m_fStartScaleMax); //발생시킨다 m_pPaticles[m_dwParticleCount].Start( liveTime, &position, &velocity, &accelation, scale); m_dwParticleCount++; if (m_dwParticleCount == this->m_PaticleNum) m_dwParticleCount = 0; }
[ "gksrlxo8776@gmail.com" ]
gksrlxo8776@gmail.com
4b91878fd6db4c0e21c9e28b04a70a04ab6b78d4
b40c3e4ac7fbe3efe7a481b5ee5d4a5721965b29
/GraphAlgorithms/Investigation.cpp
2c4a882f9428cd8ff8bdbf8a92648ffceac9d18a
[]
no_license
PoojaB01/CSES-Solutions
eae045c680330d6467f27e7c7da46b8e50302aa9
a9e8d7aabdcf1b3cc44762a2c2ce8a5ab26a7ce5
refs/heads/main
2023-08-17T07:45:03.654892
2021-02-06T17:02:51
2021-02-06T17:02:51
322,924,860
0
0
null
null
null
null
UTF-8
C++
false
false
2,299
cpp
// https://cses.fi/problemset/task/1202 #include <bits/stdc++.h> using namespace std; #define lli long long lli MAX = 1e17; lli MOD = 1e9 + 7; struct query { lli dist; lli n_routes; int max_edge; int min_edge; }; void solve() { int n, m, x, y, z; cin >> n >> m; vector<pair<int, lli>> edge[n + 1]; for (int i = 0; i < m; i++) { cin >> x >> y >> z; edge[x].push_back({y, z}); } vector<pair<lli, vector<int>>> d(n + 1, {MAX, {}}); set<pair<lli, int>> s; d[1] = {0, {}}; s.insert({0, 1}); while (!s.empty()) { pair<lli, int> p = *s.begin(); s.erase(s.begin()); for (auto i : edge[p.second]) { if (d[i.first].first == MAX) { s.insert({p.first + i.second, i.first}); d[i.first] = {p.first + i.second, {p.second}}; } else { if (d[i.first].first > p.first + i.second) { s.erase({d[i.first].first, i.first}); s.insert({p.first + i.second, i.first}); d[i.first] = {p.first + i.second, {p.second}}; } else if (d[i.first].first == p.first + i.second) { d[i.first].second.push_back(p.second); } } } } query dp[n + 1]; for (int i = 2; i < n + 1; i++) { s.insert({d[i].first, i}); dp[i].dist = d[i].first; dp[i].n_routes = 0; dp[i].max_edge = 0; dp[i].min_edge = m + 1; } dp[1].dist = 0; dp[1].n_routes = 1; dp[1].max_edge = 0; dp[1].min_edge = 0; for (auto itr = s.begin(); itr != s.end(); itr++) { x = itr->second; for (int i : d[x].second) { dp[x].n_routes = (dp[i].n_routes + dp[x].n_routes) % MOD; dp[x].max_edge = max(dp[x].max_edge, dp[i].max_edge + 1); dp[x].min_edge = min(dp[x].min_edge, dp[i].min_edge + 1); } } cout << dp[n].dist << ' ' << dp[n].n_routes << ' ' << dp[n].min_edge << ' ' << dp[n].max_edge; cout << endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); return 0; }
[ "pooja.bhagat2000@gmail.com" ]
pooja.bhagat2000@gmail.com
8be9ada74bb451a4f3f9b49635064eddd1e80b0a
90ae23d854eae3aa2d1a5186dc06158984737bed
/Source/UE/Monster.cpp
8f9f2e32028792a22a06aa5ff7ecf8ff6c74dbea
[]
no_license
RankerPG/UE
ae2a393fb02dd7a28357c6f3f99b322979ddad58
28ad1c893cf67b81ad090b3b0ab0f80d75d8e289
refs/heads/master
2023-01-08T09:56:01.943420
2020-10-28T10:29:30
2020-10-28T10:29:30
278,215,378
0
0
null
null
null
null
UTF-8
C++
false
false
7,875
cpp
#include "Monster.h" #include "MonsterAnimInstance.h" #include "SpawnPoint.h" #include "UEGameInstance.h" #include "MinionAIController.h" #include "DrawDebugHelpers.h" #include "DamageFontWidget.h" #include <components/WidgetComponent.h> #include "CharacterInfoHUDWidget.h" #include "SkillEffect.h" #include "EffectSound.h" #include "UEGameInstance.h" AMonster::AMonster() { PrimaryActorTick.bCanEverTick = true; GetCapsuleComponent()->SetCollisionProfileName(TEXT("Monster")); GetMesh()->SetCollisionEnabled(ECollisionEnabled::NoCollision); m_pAnim = nullptr; m_pMesh = Cast<USkeletalMeshComponent>(GetComponentByClass(USkeletalMeshComponent::StaticClass())); m_iPatrolNum = 0; m_isAttackEnable = true; static ConstructorHelpers::FClassFinder<UUserWidget> DamageWidgetFinder(TEXT("WidgetBlueprint'/Game/UI/BP_DamageFont.BP_DamageFont_C'")); if (DamageWidgetFinder.Succeeded()) { for (int i = 0; i < 20; ++i) { FString strName = FString::Printf(TEXT("DamageFont_%d"), i); UWidgetComponent* pDamageFontWidget = CreateDefaultSubobject<UWidgetComponent>(FName(*strName)); pDamageFontWidget->SetupAttachment(m_pMesh); pDamageFontWidget->SetWidgetSpace(EWidgetSpace::Screen); pDamageFontWidget->SetWidgetClass(DamageWidgetFinder.Class); m_arrFont.Add(pDamageFontWidget); } } m_pMonsterInfoHUDWidget = CreateDefaultSubobject<UWidgetComponent>(TEXT("InfoHUD")); m_pMonsterInfoHUDWidget->SetupAttachment(GetMesh()); m_pMonsterInfoHUDWidget->SetWidgetSpace(EWidgetSpace::Screen); static ConstructorHelpers::FClassFinder<UUserWidget> CharacterInfoHUDClass(TEXT("WidgetBlueprint'/Game/UI/BP_CharacterInfoHUDWidget.BP_CharacterInfoHUDWidget_C'")); if (CharacterInfoHUDClass.Succeeded()) { m_pMonsterInfoHUDWidget->SetWidgetClass(CharacterInfoHUDClass.Class); } m_iFontIndex = 0; } FString AMonster::Get_AnimType() { return m_pAnim->Get_AnimType(); } const FVector& AMonster::Get_NextPatrolPos() { m_iPatrolNum = (++m_iPatrolNum) % m_PatrolPosArray.Num(); return m_PatrolPosArray[m_iPatrolNum]; } ECharacterState AMonster::Get_State() { if (!IsValid(m_pAnim)) return ECharacterState::StateNone; return m_pAnim->Get_State(); } void AMonster::Set_AnimType(const FString& strAnim) { m_pAnim->Set_AnimType(strAnim); } void AMonster::Set_Frozen(float fFrozenTime) { m_pAnim->Set_Frozen(fFrozenTime); } void AMonster::Set_Stun(float fStunTime) { m_pAnim->Set_Stun(fStunTime); } void AMonster::Set_Knockback(float fKnockbackTime) { m_pAnim->Set_Knockback(fKnockbackTime); } void AMonster::BeginPlay() { Super::BeginPlay(); for (auto& font : m_arrFont) { Cast<UDamageFontWidget>(font->GetUserWidgetObject())->Set_Onwer(font); } Cast<UCharacterInfoHUDWidget>(m_pMonsterInfoHUDWidget->GetUserWidgetObject())->Set_Name(m_strMonsterName); } void AMonster::EndPlay(const EEndPlayReason::Type EndPlayReason) { Super::EndPlay(EndPlayReason); } void AMonster::Tick(float DeltaTime) { Super::Tick(DeltaTime); m_pMonsterInfoHUDWidget->SetVisibility(false); //FVector vLoc = Cast<UUEGameInstance>(GetGameInstance())->Get_Player()->GetActorLocation(); //if (2000.f < FVector::Distance(GetActorLocation(), vLoc)) //{ // m_pMonsterInfoHUDWidget->SetVisibility(false); //} //else //{ // m_pMonsterInfoHUDWidget->SetVisibility(true); //} } void AMonster::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); } void AMonster::PossessedBy(AController* NewController) { Super::PossessedBy(NewController); FMonsterInfo* info = Cast<UUEGameInstance>(GetGameInstance())->FindMonsterInfo(*m_strMonsterName); if (nullptr != info) { m_fTraceRange = info->TraceRange; m_fAttackRange = info->AttackRange; m_fAttackDelay = info->AttackDelay; m_fAttackPoint = info->AttackPoint; m_fArmorPoint = info->ArmorPoint; m_fHP = m_fHPMax = info->HP; m_fMP = m_fMPMax = info->MP; m_iLevel = info->Level; m_iExp = info->Exp; m_iGold = info->Gold; } } void AMonster::UnPossessed() { } float AMonster::TakeDamage(float DamageAmount, struct FDamageEvent const& DamageEvent, class AController* EventInstigator, AActor* DamageCauser) { float fDamage = Super::TakeDamage(DamageAmount, DamageEvent, EventInstigator, DamageCauser); if (fDamage > 0.f) { fDamage -= m_fArmorPoint; fDamage = fDamage <= 0.f ? 1.f : fDamage; m_fHP -= fDamage; if (0 < m_arrFont.Num()) { Cast<UDamageFontWidget>(m_arrFont[m_iFontIndex]->GetUserWidgetObject())->Set_DamageText(FString::FromInt((int)fDamage)); m_iFontIndex = (++m_iFontIndex) % 20; } float fSetHP = m_fHP <= 0.f ? 0.f : m_fHP / m_fHPMax; ////if(IsValid(m_pMonsterInfoHUDWidget)) //// Cast<UCharacterInfoHUDWidget>(m_pMonsterInfoHUDWidget->GetUserWidgetObject())->Set_HPBar(fSetHP); if (m_fHP > 0.f) { if (ECharacterState::Running == m_pAnim->Get_State()) m_pAnim->Set_AnimType(TEXT("Hit")); } else { m_pAnim->Set_AnimType(TEXT("Death")); m_pAnim->Set_State(ECharacterState::Running); GetCapsuleComponent()->SetCollisionEnabled(ECollisionEnabled::NoCollision); m_pMesh->bPauseAnims = false; } } return fDamage; } void AMonster::SpawnSetting() { LOGW("Call SpawnSetting"); m_fHP = m_fHPMax; Cast<UCharacterInfoHUDWidget>(m_pMonsterInfoHUDWidget->GetUserWidgetObject())->Set_HPBar(1.f); m_pAnim->Set_AnimType(TEXT("Idle")); m_pMesh->SetVisibility(true); Cast<UCharacterInfoHUDWidget>(m_pMonsterInfoHUDWidget->GetUserWidgetObject())->SetVisibility(ESlateVisibility::Visible); GetCapsuleComponent()->SetCollisionEnabled(ECollisionEnabled::QueryAndPhysics); m_pMesh->bPauseAnims = false; } void AMonster::DeathEnd() { m_pMesh->SetVisibility(false); Cast<UCharacterInfoHUDWidget>(m_pMonsterInfoHUDWidget->GetUserWidgetObject())->SetVisibility(ESlateVisibility::Hidden); if (IsValid(m_pSpawnPoint)) m_pSpawnPoint->CallSpawnTimer(); m_pMesh->bPauseAnims = true; } void AMonster::AttackDelay() { GetWorldTimerManager().ClearTimer(m_AttackDelayTimerHandle); m_isAttackEnable = true; } void AMonster::AttackEnd() { m_OnAttackEnd.Broadcast(); for (FDelegateHandle handle : m_AttackEndHandleArray) { m_OnAttackEnd.Remove(handle); } GetWorldTimerManager().SetTimer(m_AttackDelayTimerHandle, this, &AMonster::AttackDelay, m_fAttackDelay, false); } bool AMonster::CollisionCheck(FHitResult& resultOut) { FCollisionQueryParams tParam(NAME_None, false, this); FVector vLoc = GetActorLocation(); FVector vForward = GetActorForwardVector(); bool bCollision = GetWorld()->SweepSingleByChannel(resultOut, vLoc, vLoc + vForward * m_fAttackRange, FQuat::Identity, (ECollisionChannel)CollisionMonsterAttack, FCollisionShape::MakeSphere(50.f), tParam); //#if ENABLE_DRAW_DEBUG // // FVector vCenter = vLoc + vForward * (m_fAttackRange / 2.f); // // FColor DrawColor = bCollision ? FColor::Red : FColor::Green; // // DrawDebugCapsule(GetWorld(), vCenter, m_fAttackRange / 2.f, 50.f, FRotationMatrix::MakeFromZ(vForward).ToQuat() // , DrawColor, false, 0.5f); // //#endif if (bCollision) { FDamageEvent damageEvent; //Damage parameter resultOut.GetActor()->TakeDamage(20.f, damageEvent, m_pController, this); // Add Effect FActorSpawnParameters tSpawnParams; tSpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn; auto HitEffect = GetWorld()->SpawnActor<ASkillEffect>(resultOut.ImpactPoint, resultOut.ImpactNormal.Rotation(), tSpawnParams); HitEffect->Load_Particle(TEXT("ParticleSystem'/Game/AdvancedMagicFX13/Particles/P_ky_impact.P_ky_impact'")); // Sound AEffectSound* pSound = GetWorld()->SpawnActor<AEffectSound>(resultOut.ImpactPoint, resultOut.ImpactNormal.Rotation(), tSpawnParams); pSound->LoadAudio(TEXT("SoundWave'/Game/Sound/MinionAttack.MinionAttack'")); pSound->Play(); } return true; }
[ "maxfightstar@naver.com" ]
maxfightstar@naver.com
1e5c421130136650f21904cc597324c7b0f27396
8a8a9a02ff426e36ba772955facbf4a72891ea6c
/DEVUGRAP.cpp
08a9560c057e12a31f22936e852edcff1eeb3d4a
[]
no_license
krishnaanaril/SPOJ
d9549ee313f6b6e7429bc950aa8d3b0860211f7e
74eb572318edc18470af1c2b3e6060e295ceb52b
refs/heads/master
2020-06-08T22:23:35.325838
2018-02-10T17:13:11
2018-02-10T17:13:11
12,751,622
0
0
null
null
null
null
UTF-8
C++
false
false
485
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define MAX 100005 int main() { ll t, n, k, val, ans; scanf("%lld", &t); while(t--) { ans=0; scanf("%lld%lld", &n, &k); for(int i=0;i<n;i++) { scanf("%lld", &val); ll tmp=val%k; ans+=(tmp>k/2)?k-tmp:tmp; //printf("1. %lld %lld %lld\n", tmp, k-tmp, ans); } printf("%lld\n", ans); } }
[ "krishnamohan.a.m@gmail.com" ]
krishnamohan.a.m@gmail.com
01d44260d6be5ee6de78cccd5191a75376ddaff4
0701c924d8f71df62105744edb0088cfd13b0a56
/Drawer.h
37705d22f706a5242e25717904616fb8ade0c1c1
[ "MIT" ]
permissive
catmousedog/fractal_drawer
b8e8e2055d9089d690eefe9802fe5dea644390da
6052da8697697c78b96a16b19d87a4f5e3613a1a
refs/heads/main
2023-07-04T03:43:11.554988
2021-08-05T14:24:57
2021-08-05T14:24:57
320,962,649
0
0
MIT
2021-06-20T16:11:49
2020-12-13T01:48:18
C++
UTF-8
C++
false
false
710
h
#pragma once #include "Fractal.h" #include "CImg.h" using namespace cimg_library; class Drawer { private: const int graphwidth = 800, graphheight = 600; static constexpr unsigned char black[3] = { 0, 0, 0 }; static constexpr unsigned char gray[3] = { 50, 50, 50 }; static constexpr unsigned char white[3] = { 255, 255, 255 }; static constexpr unsigned char red[3] = { 255, 0, 0 }; static constexpr unsigned char blue[3] = { 0, 0, 255 }; Fractal& fractal; CImgDisplay dsp; public: bool DrawPoints = true; Drawer(Fractal& f) : fractal(f), dsp(Fractal::p, Fractal::p, 0) { } void Draw(); bool IsClosed() { return dsp.is_closed(); } CImgDisplay& GetDisplay() { return dsp; } };
[ "lauwersarno@hotmail.com" ]
lauwersarno@hotmail.com
1ceb86ee64fd70c595aab32fadddeed042d835d9
8edde9d2e5cea812b4b3db859d2202d0a65cb800
/Documentation/Code/Engine/Graphics/GrColor.cpp
988bfe07561c89a7f06e7e220df4f412b6974425
[ "MIT" ]
permissive
shawwn/bootstrap
751cb00175933f91a2e5695d99373fca46a0778e
39742d2a4b7d1ab0444d9129152252dfcfb4d41b
refs/heads/master
2023-04-09T20:41:05.034596
2023-03-28T17:43:50
2023-03-28T17:43:50
130,915,922
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,395
cpp
//---------------------------------------------------------- //! File: GrColor.cpp //! Author: Kevin Bray //! Created: 10-28-04 //! Copyright © 2004 Bootstrap Studios. All rights reserved. //---------------------------------------------------------- #include "graphics_afx.h" //! class header. #include "GrColor.h" #include "UReader.h" #include "UWriter.h" //! unpacks a floating point value. static inline unsigned char PackFloatColor( float v ) { return ( unsigned char )( 255.0f * Clamp( v, 0.0f, 1.0f ) + 0.5f ); } //********************************************************** //! class GrColor //********************************************************** //========================================================== //! public methods //========================================================== //---------------------------------------------------------- bool GrColor::IsGray( float epsilon ) const { return ( Abs( _r - _g ) < epsilon && Abs( _r - _b ) < epsilon && Abs( _r - _g ) < epsilon && Abs( _r - _a ) < epsilon ); } //---------------------------------------------------------- bool GrColor::ApproxEqual( const GrColor& color, float epsilon ) const { return ( Abs( _r - color.GetR() ) <= epsilon && Abs( _g - color.GetG() ) <= epsilon && Abs( _b - color.GetB() ) <= epsilon && Abs( _a - color.GetA() ) <= epsilon ); } //---------------------------------------------------------- GrColor GrColor::Min( const GrColor& color ) const { return GrColor( ::Min( _r, color.GetR() ), ::Min( _g, color.GetG() ), ::Min( _b, color.GetB() ), ::Min( _a, color.GetA() ) ); } //---------------------------------------------------------- GrColor GrColor::Max( const GrColor& color ) const { return GrColor( ::Max( _r, color.GetR() ), ::Max( _g, color.GetG() ), ::Max( _b, color.GetB() ), ::Max( _a, color.GetA() ) ); } //---------------------------------------------------------- bool GrColor::IsBetween( const GrColor& color1, const GrColor& color2 ) const { GrColor min = color1.Min( color2 ); GrColor max = color1.Max( color2 ); return ( ( _r >= min.GetR() && _g >= min.GetG() && _b >= min.GetB() ) && ( _r <= max.GetR() && _g <= max.GetG() && _b <= max.GetB() ) ); } //---------------------------------------------------------- void GrColor::PackToBGR( unsigned char* bgra ) const { bgra[ 0 ] = PackFloatColor( _b ); bgra[ 1 ] = PackFloatColor( _g ); bgra[ 2 ] = PackFloatColor( _r ); } //---------------------------------------------------------- void GrColor::PackToBGRA( unsigned char* bgra ) const { bgra[ 0 ] = PackFloatColor( _b ); bgra[ 1 ] = PackFloatColor( _g ); bgra[ 2 ] = PackFloatColor( _r ); bgra[ 3 ] = PackFloatColor( _a ); } //---------------------------------------------------------- void GrColor::PackToRGBA( unsigned char* rgba ) const { rgba[ 0 ] = PackFloatColor( _r ); rgba[ 1 ] = PackFloatColor( _g ); rgba[ 2 ] = PackFloatColor( _b ); rgba[ 3 ] = PackFloatColor( _a ); } //---------------------------------------------------------- void GrColor::Save( UWriter& writer ) const { writer.WriteFloat( _r ); writer.WriteFloat( _g ); writer.WriteFloat( _b ); writer.WriteFloat( _a ); } //---------------------------------------------------------- void GrColor::Load( UReader& reader ) { _r = reader.ReadFloat(); _g = reader.ReadFloat(); _b = reader.ReadFloat(); _a = reader.ReadFloat(); }
[ "shawnpresser@gmail.com" ]
shawnpresser@gmail.com
96eefa461959e1e34dea323eeff8cd009d92e9ba
b3c8f62e9b479f24a6c65bccccf1c38edf568bf8
/libs/hana/benchmark/at_key/index_of_lookup/hana_map.erb.cpp
8228b689294837640b73bb81b2bc253640148443
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
snichols/boost_1_61_0
3cba4d7bd5243176cbfdd2ac7c4049c33570472d
10142fe2415a0c4ddb72207b5f235cce20f72649
refs/heads/master
2020-04-18T18:01:18.093840
2016-09-04T18:19:34
2016-09-04T18:19:34
67,361,167
1
0
null
null
null
null
UTF-8
C++
false
false
589
cpp
// Copyright Louis Dionne 2013-2016 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #include <boost/hana/at_key.hpp> #include <boost/hana/integral_constant.hpp> #include <boost/hana/map.hpp> #include "../pair.hpp" namespace hana = boost::hana; struct undefined { }; int main() { auto map = hana::make_map(<%= env[:range].map { |n| "light_pair<hana::int_<#{n}>, undefined>{}" }.join(', ') %>); hana::at_key(map, hana::int_c<<%= input_size %>>); }
[ "snichols@therealm.io" ]
snichols@therealm.io
419cad155a00bb053a091452b4581b82872f72f1
72129375aee74492443177742243e2f0b65d96d6
/Aurdino Codes/air_quality/air_quality.ino
3df08008463e388439b57dc2b7b5ffcfbfdd56b6
[]
no_license
shauryamanhar/standforwild
e4c2633ac38a5ae951918da3bf8d79a726bd7b9f
50716b78d6420b365d61f941d7033aa864850f0c
refs/heads/master
2020-05-03T13:37:46.585958
2019-04-20T12:26:32
2019-04-20T12:26:32
178,657,813
1
0
null
null
null
null
UTF-8
C++
false
false
239
ino
int airquality = 0; void setup() { Serial.begin(9600); } void loop() { int sensorValue = analogRead(A0); Serial.print("Air Quality = "); Serial.print(sensorValue); Serial.print("*PPM"); Serial.println(); delay(1000); }
[ "smanhar747@gmail.com" ]
smanhar747@gmail.com
70a4d1afaa5710c1f63687ea291dcd7cafd03307
c896ca2e53872690a6cb4a9be4418d802ac3c6ef
/CPP03/ex00/main.cpp
0605b9adb247b11775071a591ff69ed78b9814fa
[]
no_license
paspd/CPP_ALL
a1f66648798765085cfaf2b8558d2a76cfeb20c2
c4120a7b61b2a7243a3338dee335a151db0b6c52
refs/heads/master
2023-09-04T08:21:10.802507
2021-11-09T10:02:01
2021-11-09T10:02:01
405,879,580
0
1
null
null
null
null
UTF-8
C++
false
false
390
cpp
#include "ClapTrap.hpp" int main(void) { ClapTrap Bob("Bob"); ClapTrap Jhon("Jhon"); ClapTrap Bob_copy(Bob); std::cout << std::endl; Bob.attack("Tree"); Bob_copy.attack("Tree"); Jhon.attack("Bee"); std::cout << std::endl; Jhon = Bob_copy; Jhon.attack("Table"); std::cout << std::endl; Bob.beRepaired(20); Bob_copy.beRepaired(42); std::cout << std::endl; return(0); }
[ "leoir1807@gmail.com" ]
leoir1807@gmail.com
7ef6ef5fa7d68e91c096f7c3d9710f0531787e29
e5915783daab49e7218fa27e565647278fc46804
/src/utils/dns_utils.cpp
6ddcfa0205c58657e1f34a06b1a3d9f07945fc46
[ "MIT" ]
permissive
chratos-system/chratos-core
c2d985272c1113c52b79f47bc87de98df586d224
26488032eff82a99b99c48bde31d3fbb1863f2f9
refs/heads/master
2020-03-19T21:01:08.133304
2018-08-11T21:58:39
2018-08-11T21:58:39
136,926,009
0
0
null
null
null
null
UTF-8
C++
false
false
14,011
cpp
// Copyright (c) 2014-2017, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifdef HAVE_UNBOUND #include "utils/dns_utils.h" #include "util.h" #include <boost/filesystem/fstream.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/lock_guard.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread.hpp> #include <deque> #include <stdlib.h> #include <random> #include <sstream> #include <unbound.h> namespace bf = boost::filesystem; static boost::mutex instance_lock; namespace { /* * The following function was taken from unbound-anchor.c, from * the unbound library. */ /** return the built in root DS trust anchor */ static const char* get_builtin_ds(void) { return ". IN DS 19036 8 2 49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDDE32F24E8FB5\n"; } /************************************************************ ************************************************************ ***********************************************************/ } // anonymous namespace namespace utils { // fuck it, I'm tired of dealing with getnameinfo()/inet_ntop/etc std::string ipv4_to_string(const char* src, size_t len) { assert(len >= 4); std::stringstream ss; unsigned int bytes[4]; for (int i = 0; i < 4; i++) { unsigned char a = src[i]; bytes[i] = a; } ss << bytes[0] << "." << bytes[1] << "." << bytes[2] << "." << bytes[3]; return ss.str(); } // this obviously will need to change, but is here to reflect the above // stop-gap measure and to make the tests pass at least... std::string ipv6_to_string(const char* src, size_t len) { assert(len >= 8); std::stringstream ss; unsigned int bytes[8]; for (int i = 0; i < 8; i++) { unsigned char a = src[i]; bytes[i] = a; } ss << bytes[0] << ":" << bytes[1] << ":" << bytes[2] << ":" << bytes[3] << ":" << bytes[4] << ":" << bytes[5] << ":" << bytes[6] << ":" << bytes[7]; return ss.str(); } std::string txt_to_string(const char* src, size_t len) { return std::string(src+1, len-1); } // custom smart pointer. // TODO: see if std::auto_ptr and the like support custom destructors template<typename type, void (*freefunc)(type*)> class scoped_ptr { public: scoped_ptr(): ptr(nullptr) { } scoped_ptr(type *p): ptr(p) { } ~scoped_ptr() { freefunc(ptr); } operator type *() { return ptr; } type **operator &() { return &ptr; } type *operator->() { return ptr; } operator const type*() const { return &ptr; } private: type* ptr; }; typedef class scoped_ptr<ub_result,ub_resolve_free> ub_result_ptr; struct DNSResolverData { ub_ctx* m_ub_context; }; // work around for bug https://www.nlnetlabs.nl/bugs-script/show_bug.cgi?id=515 needed for it to compile on e.g. Debian 7 class string_copy { public: string_copy(const char *s): str(strdup(s)) {} ~string_copy() { free(str); } operator char*() { return str; } public: char *str; }; DNSResolver::DNSResolver() : m_data(new DNSResolverData()) { int use_dns_public = 0; std::string dns_public_addr = GetArg("-dnsserver","8.8.4.4"); if (auto res = getenv("DNS_PUBLIC")) { dns_public_addr = utils::dns_utils::parse_dns_public(res); if (!dns_public_addr.empty()) { LogPrintf("DNSResolver: Using public DNS server: %s (TCP)",dns_public_addr); use_dns_public = 1; } else { LogPrintf("DNSResolver: Failed to parse DNS_PUBLIC"); } } // init libunbound context m_data->m_ub_context = ub_ctx_create(); if (use_dns_public) { ub_ctx_set_fwd(m_data->m_ub_context, dns_public_addr.c_str()); ub_ctx_set_option(m_data->m_ub_context, string_copy("do-udp:"), string_copy("no")); ub_ctx_set_option(m_data->m_ub_context, string_copy("do-tcp:"), string_copy("yes")); } else { // look for "/etc/resolv.conf" and "/etc/hosts" or platform equivalent ub_ctx_resolvconf(m_data->m_ub_context, NULL); ub_ctx_hosts(m_data->m_ub_context, NULL); } ub_ctx_add_ta(m_data->m_ub_context, string_copy(::get_builtin_ds())); } DNSResolver::~DNSResolver() { if (m_data) { if (m_data->m_ub_context != NULL) { ub_ctx_delete(m_data->m_ub_context); } delete m_data; } } std::vector<std::string> DNSResolver::get_record(const std::string& url, int record_type, std::string (*reader)(const char *,size_t), bool& dnssec_available, bool& dnssec_valid) { std::vector<std::string> addresses; dnssec_available = false; dnssec_valid = false; if (!check_address_syntax(url.c_str())) { return addresses; } // destructor takes care of cleanup ub_result_ptr result; // call DNS resolver, blocking. if return value not zero, something went wrong if (!ub_resolve(m_data->m_ub_context, string_copy(url.c_str()), record_type, DNS_CLASS_IN, &result)) { dnssec_available = (result->secure || (!result->secure && result->bogus)); dnssec_valid = result->secure && !result->bogus; if (result->havedata) { for (size_t i=0; result->data[i] != NULL; i++) { addresses.push_back((*reader)(result->data[i], result->len[i])); } } } return addresses; } std::vector<std::string> DNSResolver::get_ipv4(const std::string& url, bool& dnssec_available, bool& dnssec_valid) { return get_record(url, DNS_TYPE_A, ipv4_to_string, dnssec_available, dnssec_valid); } std::vector<std::string> DNSResolver::get_ipv6(const std::string& url, bool& dnssec_available, bool& dnssec_valid) { return get_record(url, DNS_TYPE_AAAA, ipv6_to_string, dnssec_available, dnssec_valid); } std::vector<std::string> DNSResolver::get_txt_record(const std::string& url, bool& dnssec_available, bool& dnssec_valid) { return get_record(url, DNS_TYPE_TXT, txt_to_string, dnssec_available, dnssec_valid); } std::string DNSResolver::get_dns_format_from_oa_address(const std::string& oa_addr) { std::string addr(oa_addr); auto first_at = addr.find("@"); if (first_at == std::string::npos) return addr; // convert name@domain.tld to name.domain.tld addr.replace(first_at, 1, "."); return addr; } DNSResolver& DNSResolver::instance() { boost::lock_guard<boost::mutex> lock(instance_lock); static DNSResolver staticInstance; return staticInstance; } DNSResolver DNSResolver::create() { return DNSResolver(); } bool DNSResolver::check_address_syntax(const char *addr) const { // if string doesn't contain a dot, we won't consider it a url for now. if (strchr(addr,'.') == NULL) { return false; } return true; } namespace dns_utils { //----------------------------------------------------------------------- // TODO: parse the string in a less stupid way, probably with regex std::string address_from_txt_record(const std::string& s) { // make sure the txt record has "oa1:nav" and find it auto pos = s.find("oa1:nav"); if (pos == std::string::npos) return {}; // search from there to find "recipient_address=" pos = s.find("recipient_address=", pos); if (pos == std::string::npos) return {}; pos += 18; // move past "recipient_address=" return s.substr(pos, 34); } /** * @brief gets a chratos address from the TXT record of a DNS entry * * gets the chratos address from the TXT record of the DNS entry associated * with <url>. If this lookup fails, or the TXT record does not contain a * CHR address in the correct format, returns an empty string. <dnssec_valid> * will be set true or false according to whether or not the DNS query passes * DNSSEC validation. * * @param url the url to look up * @param dnssec_valid return-by-reference for DNSSEC status of query * * @return a chratos address (as a string) or an empty string */ std::vector<std::string> addresses_from_url(const std::string& url, bool& dnssec_valid) { std::vector<std::string> addresses; // get txt records bool dnssec_available, dnssec_isvalid; std::string oa_addr = DNSResolver::instance().get_dns_format_from_oa_address(url); auto records = DNSResolver::instance().get_txt_record(oa_addr, dnssec_available, dnssec_isvalid); // TODO: update this to allow for conveying that dnssec was not available if (dnssec_available && dnssec_isvalid) { dnssec_valid = true; } else dnssec_valid = false; // for each txt record, try to find a chratos address in it. for (auto& rec : records) { std::string addr = address_from_txt_record(rec); if (addr.size()) { addresses.push_back(addr); } } return addresses; } std::string get_account_address_as_str_from_url(const std::string& url, bool& dnssec_valid, std::function<std::string(const std::string&, const std::vector<std::string>&, bool)> dns_confirm) { // attempt to get address from dns query auto addresses = addresses_from_url(url, dnssec_valid); if (addresses.empty()) { LogPrintf("OpenAlias: wrong address: %s"); return {}; } return dns_confirm(url, addresses, dnssec_valid); } namespace { bool dns_records_match(const std::vector<std::string>& a, const std::vector<std::string>& b) { if (a.size() != b.size()) return false; for (const auto& record_in_a : a) { bool ok = false; for (const auto& record_in_b : b) { if (record_in_a == record_in_b) { ok = true; break; } } if (!ok) return false; } return true; } } bool load_txt_records_from_dns(std::vector<std::string> &good_records, const std::vector<std::string> &dns_urls) { // Prevent infinite recursion when distributing if (dns_urls.empty()) return false; std::vector<std::vector<std::string> > records; records.resize(dns_urls.size()); std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<int> dis(0, dns_urls.size() - 1); size_t first_index = dis(gen); // send all requests in parallel std::vector<boost::thread> threads(dns_urls.size()); std::deque<bool> avail(dns_urls.size(), false), valid(dns_urls.size(), false); for (size_t n = 0; n < dns_urls.size(); ++n) { threads[n] = boost::thread([n, dns_urls, &records, &avail, &valid](){ records[n] = utils::DNSResolver::instance().get_txt_record(dns_urls[n], avail[n], valid[n]); }); } for (size_t n = 0; n < dns_urls.size(); ++n) threads[n].join(); size_t cur_index = first_index; do { const std::string &url = dns_urls[cur_index]; if (!avail[cur_index]) { records[cur_index].clear(); LogPrintf("DNSSEC not available for checkpoint update at URL: %s, skipping.", url); } if (!valid[cur_index]) { records[cur_index].clear(); LogPrintf("DNSSEC validation failed for checkpoint update at URL: %s, skipping.", url); } cur_index++; if (cur_index == dns_urls.size()) { cur_index = 0; } } while (cur_index != first_index); size_t num_valid_records = 0; for( const auto& record_set : records) { if (record_set.size() != 0) { num_valid_records++; } } if (num_valid_records < 2) { LogPrintf("OpenAlias: WARNING: no two valid Pulse DNS checkpoint records were received"); return false; } int good_records_index = -1; for (size_t i = 0; i < records.size() - 1; ++i) { if (records[i].size() == 0) continue; for (size_t j = i + 1; j < records.size(); ++j) { if (dns_records_match(records[i], records[j])) { good_records_index = i; break; } } if (good_records_index >= 0) break; } if (good_records_index < 0) { LogPrintf("OpenAlias: WARNING: no two Pulse DNS checkpoint records matched"); return false; } good_records = records[good_records_index]; return true; } std::string parse_dns_public(const char *s) { unsigned ip0, ip1, ip2, ip3; char c; std::string dns_public_addr; if (!strcmp(s, "tcp")) { dns_public_addr = GetArg("-dnsserver","8.8.4.4"); LogPrintf("Parse-DNS-Public: Using default public DNS server: %s (TCP)",dns_public_addr); } else if (sscanf(s, "tcp://%u.%u.%u.%u%c", &ip0, &ip1, &ip2, &ip3, &c) == 4) { if (ip0 > 255 || ip1 > 255 || ip2 > 255 || ip3 > 255) { LogPrintf("Parse-DNS-Public: Invalid IP: %s, using default",s); } else { dns_public_addr = std::string(s + strlen("tcp://")); } } else { LogPrintf("Parse-DNS-Public: Invalid DNS_PUBLIC contents, ignored"); } return dns_public_addr; } } // namespace utils::dns_utils } // namespace utils #endif
[ "vidaru@protonmail.com" ]
vidaru@protonmail.com
acfeb24a18bf88e88a72c903cac3778a1f0c9849
03f037d0f6371856ede958f0c9d02771d5402baf
/graphics/VTK-7.0.0/Imaging/General/vtkImageEuclideanDistance.h
6d89db9446fb66835fef21263e47f5ccc5731b54
[ "BSD-3-Clause" ]
permissive
hlzz/dotfiles
b22dc2dc5a9086353ed6dfeee884f7f0a9ddb1eb
0591f71230c919c827ba569099eb3b75897e163e
refs/heads/master
2021-01-10T10:06:31.018179
2016-09-27T08:13:18
2016-09-27T08:13:18
55,040,954
4
0
null
null
null
null
UTF-8
C++
false
false
5,209
h
/*========================================================================= Program: Visualization Toolkit Module: vtkImageEuclideanDistance.h 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. =========================================================================*/ // .NAME vtkImageEuclideanDistance - computes 3D Euclidean DT // .SECTION Description // vtkImageEuclideanDistance implements the Euclidean DT using // Saito's algorithm. The distance map produced contains the square of the // Euclidean distance values. // // The algorithm has a o(n^(D+1)) complexity over nxnx...xn images in D // dimensions. It is very efficient on relatively small images. Cuisenaire's // algorithms should be used instead if n >> 500. These are not implemented // yet. // // For the special case of images where the slice-size is a multiple of // 2^N with a large N (typically for 256x256 slices), Saito's algorithm // encounters a lot of cache conflicts during the 3rd iteration which can // slow it very significantly. In that case, one should use // ::SetAlgorithmToSaitoCached() instead for better performance. // // References: // // T. Saito and J.I. Toriwaki. New algorithms for Euclidean distance // transformations of an n-dimensional digitised picture with applications. // Pattern Recognition, 27(11). pp. 1551--1565, 1994. // // O. Cuisenaire. Distance Transformation: fast algorithms and applications // to medical image processing. PhD Thesis, Universite catholique de Louvain, // October 1999. http://ltswww.epfl.ch/~cuisenai/papers/oc_thesis.pdf #ifndef vtkImageEuclideanDistance_h #define vtkImageEuclideanDistance_h #include "vtkImagingGeneralModule.h" // For export macro #include "vtkImageDecomposeFilter.h" #define VTK_EDT_SAITO_CACHED 0 #define VTK_EDT_SAITO 1 class VTKIMAGINGGENERAL_EXPORT vtkImageEuclideanDistance : public vtkImageDecomposeFilter { public: static vtkImageEuclideanDistance *New(); vtkTypeMacro(vtkImageEuclideanDistance,vtkImageDecomposeFilter); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Used internally for streaming and threads. // Splits output update extent into num pieces. // This method needs to be called num times. Results must not overlap for // consistent starting extent. Subclass can override this method. // This method returns the number of peices resulting from a // successful split. This can be from 1 to "total". // If 1 is returned, the extent cannot be split. int SplitExtent(int splitExt[6], int startExt[6], int num, int total); // Description: // Used to set all non-zero voxels to MaximumDistance before starting // the distance transformation. Setting Initialize off keeps the current // value in the input image as starting point. This allows to superimpose // several distance maps. vtkSetMacro(Initialize, int); vtkGetMacro(Initialize, int); vtkBooleanMacro(Initialize, int); // Description: // Used to define whether Spacing should be used in the computation of the // distances vtkSetMacro(ConsiderAnisotropy, int); vtkGetMacro(ConsiderAnisotropy, int); vtkBooleanMacro(ConsiderAnisotropy, int); // Description: // Any distance bigger than this->MaximumDistance will not ne computed but // set to this->MaximumDistance instead. vtkSetMacro(MaximumDistance, double); vtkGetMacro(MaximumDistance, double); // Description: // Selects a Euclidean DT algorithm. // 1. Saito // 2. Saito-cached // More algorithms will be added later on. vtkSetMacro(Algorithm, int); vtkGetMacro(Algorithm, int); void SetAlgorithmToSaito () { this->SetAlgorithm(VTK_EDT_SAITO); } void SetAlgorithmToSaitoCached () { this->SetAlgorithm(VTK_EDT_SAITO_CACHED); } virtual int IterativeRequestData(vtkInformation*, vtkInformationVector**, vtkInformationVector*); protected: vtkImageEuclideanDistance(); ~vtkImageEuclideanDistance() {} double MaximumDistance; int Initialize; int ConsiderAnisotropy; int Algorithm; // Replaces "EnlargeOutputUpdateExtent" virtual void AllocateOutputScalars(vtkImageData *outData, int outExt[6], vtkInformation* outInfo); virtual int IterativeRequestInformation(vtkInformation* in, vtkInformation* out); virtual int IterativeRequestUpdateExtent(vtkInformation* in, vtkInformation* out); private: vtkImageEuclideanDistance(const vtkImageEuclideanDistance&); // Not implemented. void operator=(const vtkImageEuclideanDistance&); // Not implemented. }; #endif
[ "shentianweipku@gmail.com" ]
shentianweipku@gmail.com
ffd9b5702920145b8437ca89d06619ca6a333dd3
5ebd5cee801215bc3302fca26dbe534e6992c086
/blaze/math/CustomMatrix.h
401b70f4296e9a7503d0b5c4a6f02f6ed2f552d8
[ "BSD-3-Clause" ]
permissive
mhochsteger/blaze
c66d8cf179deeab4f5bd692001cc917fe23e1811
fd397e60717c4870d942055496d5b484beac9f1a
refs/heads/master
2020-09-17T01:56:48.483627
2019-11-20T05:40:29
2019-11-20T05:41:35
223,951,030
0
0
null
null
null
null
UTF-8
C++
false
false
13,210
h
//================================================================================================= /*! // \file blaze/math/CustomMatrix.h // \brief Header file for the complete CustomMatrix implementation // // Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= #ifndef _BLAZE_MATH_CUSTOMMATRIX_H_ #define _BLAZE_MATH_CUSTOMMATRIX_H_ //************************************************************************************************* // Includes //************************************************************************************************* #include <blaze/math/dense/CustomMatrix.h> #include <blaze/math/dense/DynamicMatrix.h> #include <blaze/math/DenseMatrix.h> #include <blaze/math/DynamicVector.h> #include <blaze/math/Exception.h> #include <blaze/math/IdentityMatrix.h> #include <blaze/math/shims/Conjugate.h> #include <blaze/math/shims/Real.h> #include <blaze/math/typetraits/UnderlyingBuiltin.h> #include <blaze/math/ZeroMatrix.h> #include <blaze/util/Assert.h> #include <blaze/util/constraints/Numeric.h> #include <blaze/util/Random.h> namespace blaze { //================================================================================================= // // RAND SPECIALIZATION // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Specialization of the Rand class template for CustomMatrix. // \ingroup random // // This specialization of the Rand class creates random instances of CustomMatrix. */ template< typename Type // Data type of the matrix , bool AF // Alignment flag , bool PF // Padding flag , bool SO // Storage order , typename RT > // Result type class Rand< CustomMatrix<Type,AF,PF,SO,RT> > { public: //**Randomize functions************************************************************************* /*!\name Randomize functions */ //@{ inline void randomize( CustomMatrix<Type,AF,PF,SO,RT>& matrix ) const; template< typename Arg > inline void randomize( CustomMatrix<Type,AF,PF,SO,RT>& matrix, const Arg& min, const Arg& max ) const; //@} //********************************************************************************************** }; /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Randomization of a CustomMatrix. // // \param matrix The matrix to be randomized. // \return void */ template< typename Type // Data type of the matrix , bool AF // Alignment flag , bool PF // Padding flag , bool SO // Storage order , typename RT > // Result type inline void Rand< CustomMatrix<Type,AF,PF,SO,RT> >::randomize( CustomMatrix<Type,AF,PF,SO,RT>& matrix ) const { using blaze::randomize; const size_t m( matrix.rows() ); const size_t n( matrix.columns() ); for( size_t i=0UL; i<m; ++i ) { for( size_t j=0UL; j<n; ++j ) { randomize( matrix(i,j) ); } } } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Randomization of a CustomMatrix. // // \param matrix The matrix to be randomized. // \param min The smallest possible value for a matrix element. // \param max The largest possible value for a matrix element. // \return void */ template< typename Type // Data type of the matrix , bool AF // Alignment flag , bool PF // Padding flag , bool SO // Storage order , typename RT > // Result type template< typename Arg > // Min/max argument type inline void Rand< CustomMatrix<Type,AF,PF,SO,RT> >::randomize( CustomMatrix<Type,AF,PF,SO,RT>& matrix, const Arg& min, const Arg& max ) const { using blaze::randomize; const size_t m( matrix.rows() ); const size_t n( matrix.columns() ); for( size_t i=0UL; i<m; ++i ) { for( size_t j=0UL; j<n; ++j ) { randomize( matrix(i,j), min, max ); } } } /*! \endcond */ //************************************************************************************************* //================================================================================================= // // MAKE FUNCTIONS // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Setup of a random symmetric CustomMatrix. // // \param matrix The matrix to be randomized. // \return void // \exception std::invalid_argument Invalid non-square matrix provided. */ template< typename Type // Data type of the matrix , bool AF // Alignment flag , bool PF // Padding flag , bool SO // Storage order , typename RT > // Result type void makeSymmetric( CustomMatrix<Type,AF,PF,SO,RT>& matrix ) { using blaze::randomize; if( !isSquare( ~matrix ) ) { BLAZE_THROW_INVALID_ARGUMENT( "Invalid non-square matrix provided" ); } const size_t n( matrix.rows() ); for( size_t i=0UL; i<n; ++i ) { for( size_t j=0UL; j<i; ++j ) { randomize( matrix(i,j) ); matrix(j,i) = matrix(i,j); } randomize( matrix(i,i) ); } BLAZE_INTERNAL_ASSERT( isSymmetric( matrix ), "Non-symmetric matrix detected" ); } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Setup of a random symmetric CustomMatrix. // // \param matrix The matrix to be randomized. // \param min The smallest possible value for a matrix element. // \param max The largest possible value for a matrix element. // \return void // \exception std::invalid_argument Invalid non-square matrix provided. */ template< typename Type // Data type of the matrix , bool AF // Alignment flag , bool PF // Padding flag , bool SO // Storage order , typename RT // Result type , typename Arg > // Min/max argument type void makeSymmetric( CustomMatrix<Type,AF,PF,SO,RT>& matrix, const Arg& min, const Arg& max ) { using blaze::randomize; if( !isSquare( ~matrix ) ) { BLAZE_THROW_INVALID_ARGUMENT( "Invalid non-square matrix provided" ); } const size_t n( matrix.rows() ); for( size_t i=0UL; i<n; ++i ) { for( size_t j=0UL; j<i; ++j ) { randomize( matrix(i,j), min, max ); matrix(j,i) = matrix(i,j); } randomize( matrix(i,i), min, max ); } BLAZE_INTERNAL_ASSERT( isSymmetric( matrix ), "Non-symmetric matrix detected" ); } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Setup of a random Hermitian CustomMatrix. // // \param matrix The matrix to be randomized. // \return void // \exception std::invalid_argument Invalid non-square matrix provided. */ template< typename Type // Data type of the matrix , bool AF // Alignment flag , bool PF // Padding flag , bool SO // Storage order , typename RT > // Result type void makeHermitian( CustomMatrix<Type,AF,PF,SO,RT>& matrix ) { using blaze::randomize; BLAZE_CONSTRAINT_MUST_BE_NUMERIC_TYPE( Type ); using BT = UnderlyingBuiltin_t<Type>; if( !isSquare( ~matrix ) ) { BLAZE_THROW_INVALID_ARGUMENT( "Invalid non-square matrix provided" ); } const size_t n( matrix.rows() ); for( size_t i=0UL; i<n; ++i ) { for( size_t j=0UL; j<i; ++j ) { randomize( matrix(i,j) ); matrix(j,i) = conj( matrix(i,j) ); } matrix(i,i) = rand<BT>(); } BLAZE_INTERNAL_ASSERT( isHermitian( matrix ), "Non-Hermitian matrix detected" ); } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Setup of a random Hermitian CustomMatrix. // // \param matrix The matrix to be randomized. // \param min The smallest possible value for a matrix element. // \param max The largest possible value for a matrix element. // \return void // \exception std::invalid_argument Invalid non-square matrix provided. */ template< typename Type // Data type of the matrix , bool AF // Alignment flag , bool PF // Padding flag , bool SO // Storage order , typename RT // Result type , typename Arg > // Min/max argument type void makeHermitian( CustomMatrix<Type,AF,PF,SO,RT>& matrix, const Arg& min, const Arg& max ) { using blaze::randomize; BLAZE_CONSTRAINT_MUST_BE_NUMERIC_TYPE( Type ); using BT = UnderlyingBuiltin_t<Type>; if( !isSquare( ~matrix ) ) { BLAZE_THROW_INVALID_ARGUMENT( "Invalid non-square matrix provided" ); } const size_t n( matrix.rows() ); for( size_t i=0UL; i<n; ++i ) { for( size_t j=0UL; j<i; ++j ) { randomize( matrix(i,j), min, max ); matrix(j,i) = conj( matrix(i,j) ); } matrix(i,i) = rand<BT>( real( min ), real( max ) ); } BLAZE_INTERNAL_ASSERT( isHermitian( matrix ), "Non-Hermitian matrix detected" ); } /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ /*!\brief Setup of a random (Hermitian) positive definite CustomMatrix. // // \param matrix The matrix to be randomized. // \return void // \exception std::invalid_argument Invalid non-square matrix provided. */ template< typename Type // Data type of the matrix , bool AF // Alignment flag , bool PF // Padding flag , bool SO // Storage order , typename RT > // Result type void makePositiveDefinite( CustomMatrix<Type,AF,PF,SO,RT>& matrix ) { using blaze::randomize; BLAZE_CONSTRAINT_MUST_BE_NUMERIC_TYPE( Type ); if( !isSquare( ~matrix ) ) { BLAZE_THROW_INVALID_ARGUMENT( "Invalid non-square matrix provided" ); } const size_t n( matrix.rows() ); randomize( matrix ); matrix *= ctrans( matrix ); for( size_t i=0UL; i<n; ++i ) { matrix(i,i) += Type(n); } BLAZE_INTERNAL_ASSERT( isHermitian( matrix ), "Non-symmetric matrix detected" ); } /*! \endcond */ //************************************************************************************************* } // namespace blaze #endif
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
b3f1ee895518ab52e2ec471ba140103bb48e1aa9
a62342d6359a88b0aee911e549a4973fa38de9ea
/0.6.0.3/Internal/SDK/SpinningWheel_AnimBp_functions.cpp
d440614d14acb2bbd8c79240267fcf2ada51c119
[]
no_license
zanzo420/Medieval-Dynasty-SDK
d020ad634328ee8ee612ba4bd7e36b36dab740ce
d720e49ae1505e087790b2743506921afb28fc18
refs/heads/main
2023-06-20T03:00:17.986041
2021-07-15T04:51:34
2021-07-15T04:51:34
386,165,085
0
0
null
null
null
null
UTF-8
C++
false
false
1,781
cpp
// Name: Medieval Dynasty, Version: 0.6.0.3 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function SpinningWheel_AnimBp.SpinningWheel_AnimBp_C.AnimGraph // (HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // struct FPoseLink AnimGraph (Parm, OutParm, NoDestructor) void USpinningWheel_AnimBp_C::AnimGraph(struct FPoseLink* AnimGraph) { static auto fn = UObject::FindObject<UFunction>("Function SpinningWheel_AnimBp.SpinningWheel_AnimBp_C.AnimGraph"); USpinningWheel_AnimBp_C_AnimGraph_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (AnimGraph != nullptr) *AnimGraph = params.AnimGraph; } // Function SpinningWheel_AnimBp.SpinningWheel_AnimBp_C.ExecuteUbergraph_SpinningWheel_AnimBp // (Final) // Parameters: // int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void USpinningWheel_AnimBp_C::ExecuteUbergraph_SpinningWheel_AnimBp(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function SpinningWheel_AnimBp.SpinningWheel_AnimBp_C.ExecuteUbergraph_SpinningWheel_AnimBp"); USpinningWheel_AnimBp_C_ExecuteUbergraph_SpinningWheel_AnimBp_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
84c20cb4edb45bce8cb06b0c01051b56e861473a
1119fdac2610d934dd690b44c48a967ac782a1e2
/kp_nix/ui_framemvvstatus.h
8cc24905a0219d9e45c93b3927d81830f8280a00
[]
no_license
eugene-pa/armdncqt
6e744f6b35e0fd87ed8f06af35e4d7df6e28d4bd
3dcb31a33a0e9cca7b623006bfda360e068a8e17
refs/heads/master
2021-01-24T17:14:32.900853
2017-10-19T13:53:27
2017-10-19T13:53:27
63,157,609
0
0
null
null
null
null
UTF-8
C++
false
false
6,952
h
/******************************************************************************** ** Form generated from reading UI file 'framemvvstatus.ui' ** ** Created by: Qt User Interface Compiler version 5.9.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_FRAMEMVVSTATUS_H #define UI_FRAMEMVVSTATUS_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QGridLayout> #include <QtWidgets/QGroupBox> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QWidget> #include "qled.h" QT_BEGIN_NAMESPACE class Ui_FrameMvvStatus { public: QWidget *widget; QGridLayout *gridLayout; QLabel *label_12; QLabel *label; QLabel *label_2; QLed *label_TU1; QLabel *label_4; QLabel *label_5; QLed *label_OUT1; QLed *label_ATU1; QLed *label_TU2; QLed *label_OUT2; QLed *label_ATU2; QLabel *label_13; void setupUi(QGroupBox *FrameMvvStatus) { if (FrameMvvStatus->objectName().isEmpty()) FrameMvvStatus->setObjectName(QStringLiteral("FrameMvvStatus")); FrameMvvStatus->resize(109, 75); widget = new QWidget(FrameMvvStatus); widget->setObjectName(QStringLiteral("widget")); widget->setGeometry(QRect(10, 10, 93, 65)); gridLayout = new QGridLayout(widget); gridLayout->setObjectName(QStringLiteral("gridLayout")); gridLayout->setHorizontalSpacing(8); gridLayout->setVerticalSpacing(2); gridLayout->setContentsMargins(0, 6, 0, 0); label_12 = new QLabel(widget); label_12->setObjectName(QStringLiteral("label_12")); gridLayout->addWidget(label_12, 0, 0, 1, 1, Qt::AlignRight); label = new QLabel(widget); label->setObjectName(QStringLiteral("label")); gridLayout->addWidget(label, 0, 1, 1, 1); label_2 = new QLabel(widget); label_2->setObjectName(QStringLiteral("label_2")); gridLayout->addWidget(label_2, 0, 2, 1, 1); label_TU1 = new QLed(widget); label_TU1->setObjectName(QStringLiteral("label_TU1")); QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(label_TU1->sizePolicy().hasHeightForWidth()); label_TU1->setSizePolicy(sizePolicy); label_TU1->setMinimumSize(QSize(11, 11)); label_TU1->setPixmap(QPixmap(QString::fromUtf8(":/images/images/box_grn.png"))); gridLayout->addWidget(label_TU1, 1, 1, 1, 1); label_4 = new QLabel(widget); label_4->setObjectName(QStringLiteral("label_4")); gridLayout->addWidget(label_4, 2, 0, 1, 1, Qt::AlignRight); label_5 = new QLabel(widget); label_5->setObjectName(QStringLiteral("label_5")); gridLayout->addWidget(label_5, 3, 0, 1, 1, Qt::AlignRight); label_OUT1 = new QLed(widget); label_OUT1->setObjectName(QStringLiteral("label_OUT1")); sizePolicy.setHeightForWidth(label_OUT1->sizePolicy().hasHeightForWidth()); label_OUT1->setSizePolicy(sizePolicy); label_OUT1->setMinimumSize(QSize(11, 11)); label_OUT1->setPixmap(QPixmap(QString::fromUtf8(":/images/images/box_grn.png"))); gridLayout->addWidget(label_OUT1, 2, 1, 1, 1); label_ATU1 = new QLed(widget); label_ATU1->setObjectName(QStringLiteral("label_ATU1")); sizePolicy.setHeightForWidth(label_ATU1->sizePolicy().hasHeightForWidth()); label_ATU1->setSizePolicy(sizePolicy); label_ATU1->setMinimumSize(QSize(11, 11)); label_ATU1->setPixmap(QPixmap(QString::fromUtf8(":/images/images/box_grn.png"))); gridLayout->addWidget(label_ATU1, 3, 1, 1, 1); label_TU2 = new QLed(widget); label_TU2->setObjectName(QStringLiteral("label_TU2")); sizePolicy.setHeightForWidth(label_TU2->sizePolicy().hasHeightForWidth()); label_TU2->setSizePolicy(sizePolicy); label_TU2->setMinimumSize(QSize(11, 11)); label_TU2->setPixmap(QPixmap(QString::fromUtf8(":/images/images/box_grn.png"))); gridLayout->addWidget(label_TU2, 1, 2, 1, 1); label_OUT2 = new QLed(widget); label_OUT2->setObjectName(QStringLiteral("label_OUT2")); sizePolicy.setHeightForWidth(label_OUT2->sizePolicy().hasHeightForWidth()); label_OUT2->setSizePolicy(sizePolicy); label_OUT2->setMinimumSize(QSize(11, 11)); label_OUT2->setPixmap(QPixmap(QString::fromUtf8(":/images/images/box_grn.png"))); gridLayout->addWidget(label_OUT2, 2, 2, 1, 1); label_ATU2 = new QLed(widget); label_ATU2->setObjectName(QStringLiteral("label_ATU2")); sizePolicy.setHeightForWidth(label_ATU2->sizePolicy().hasHeightForWidth()); label_ATU2->setSizePolicy(sizePolicy); label_ATU2->setMinimumSize(QSize(11, 11)); label_ATU2->setPixmap(QPixmap(QString::fromUtf8(":/images/images/box_grn.png"))); gridLayout->addWidget(label_ATU2, 3, 2, 1, 1); label_13 = new QLabel(widget); label_13->setObjectName(QStringLiteral("label_13")); gridLayout->addWidget(label_13, 1, 0, 1, 1, Qt::AlignRight); retranslateUi(FrameMvvStatus); QMetaObject::connectSlotsByName(FrameMvvStatus); } // setupUi void retranslateUi(QGroupBox *FrameMvvStatus) { FrameMvvStatus->setWindowTitle(QApplication::translate("FrameMvvStatus", "GroupBox", Q_NULLPTR)); FrameMvvStatus->setTitle(QApplication::translate("FrameMvvStatus", "\320\241\320\276\321\201\321\202\320\276\321\217\320\275\320\270\320\265 \320\234\320\222\320\222", Q_NULLPTR)); label_12->setText(QApplication::translate("FrameMvvStatus", "\320\234\320\222\320\222:", Q_NULLPTR)); label->setText(QApplication::translate("FrameMvvStatus", "1", Q_NULLPTR)); label_2->setText(QApplication::translate("FrameMvvStatus", "2", Q_NULLPTR)); label_TU1->setText(QString()); label_4->setText(QApplication::translate("FrameMvvStatus", "\320\222\321\213\321\205\320\276\320\264 \320\242\320\243:", Q_NULLPTR)); label_5->setText(QApplication::translate("FrameMvvStatus", "\320\220\320\242\320\243:", Q_NULLPTR)); label_OUT1->setText(QString()); label_ATU1->setText(QString()); label_TU2->setText(QString()); label_OUT2->setText(QString()); label_ATU2->setText(QString()); label_13->setText(QApplication::translate("FrameMvvStatus", "\320\232\320\273\321\216\321\207 \320\242\320\243:", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class FrameMvvStatus: public Ui_FrameMvvStatus {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_FRAMEMVVSTATUS_H
[ "eugene.shmelev@gmail.com" ]
eugene.shmelev@gmail.com
7b75cc8ba96ae1ee38736ab960d1edb3a0b0da0b
a95d50763bf31c1ab5b2b50326f9f10eb219aef8
/src/appleseedmaya/exporters/alphamapexporter.cpp
32de6ddf32e1c402b8c646559334866feee345c3
[ "MIT" ]
permissive
shdwdln/appleseed-maya
1fccf585d28509922a83267f79b9d7506770da24
57b707dfbb2a66d00675c9dc0e30f04aea3ad748
refs/heads/master
2021-01-25T07:49:29.818453
2017-06-04T11:06:58
2017-06-04T11:06:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,774
cpp
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2017 Esteban Tovagliari, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "appleseedmaya/exporters/alphamapexporter.h" // Maya headers. #include <maya/MFnDependencyNode.h> // appleseed.renderer headers. #include "renderer/api/project.h" #include "renderer/api/scene.h" // appleseed.maya headers. #include "appleseedmaya/attributeutils.h" namespace asf = foundation; namespace asr = renderer; AlphaMapExporter* AlphaMapExporter::create( const MObject& object, asr::Project& project, AppleseedSession::SessionMode sessionMode) { MString map; AttributeUtils::get(object, "map", map); // Ignore alpha maps without image files. if (map.length() == 0) return 0; return new AlphaMapExporter(object, project, sessionMode); } AlphaMapExporter::AlphaMapExporter( const MObject& object, asr::Project& project, AppleseedSession::SessionMode sessionMode) : m_object(object) , m_sessionMode(sessionMode) , m_project(project) , m_mainAssembly(*project.get_scene()->assemblies().get_by_name("assembly")) { } AlphaMapExporter::~AlphaMapExporter() { if (m_sessionMode == AppleseedSession::ProgressiveRenderSession) { m_mainAssembly.texture_instances().remove(m_textureInstance.get()); m_mainAssembly.textures().remove(m_texture.get()); } } void AlphaMapExporter::createEntities() { MFnDependencyNode depNodeFn(m_object); MString map; AttributeUtils::get(depNodeFn, "map", map); MString textureName = depNodeFn.name() + "_texture"; m_texture = asr::DiskTexture2dFactory().create( textureName.asChar(), asr::ParamArray() .insert("filename", map.asChar()) .insert("color_space", "linear_rgb"), m_project.search_paths()); MString textureInstanceName = textureName + "_instance"; m_textureInstance = asr::TextureInstanceFactory().create( textureInstanceName.asChar(), asr::ParamArray() .insert("alpha_mode", "detect") .insert("addressing_mode", "clamp") .insert("filtering_mode", "bilinear"), textureName.asChar()); } void AlphaMapExporter::flushEntities() { m_mainAssembly.textures().insert(m_texture.release()); m_mainAssembly.texture_instances().insert(m_textureInstance.release()); } const char*AlphaMapExporter::textureInstanceName() const { return m_textureInstance->get_name(); }
[ "ramenhdr@gmail.com" ]
ramenhdr@gmail.com
6e492a63e927cec8354f4f67a8cf261bc37133cc
b09ca48770d05b90ee623486de6a02b999e5c5d9
/util/extvtkio.cpp
d3178c57d5ec0abc728c86a0a2050f9599f82e42
[]
no_license
capitalaslash/fsi
9bc7d8e8741fecd161eafeeadc6d88e3ec209336
34b7403efc9891f0ae06ea9c1747f1d8ad5d2ed4
refs/heads/master
2020-06-01T18:38:46.381122
2014-07-24T12:59:30
2014-07-24T12:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,794
cpp
#include "extvtkio.hpp" #include <iomanip> #include <libmesh/equation_systems.h> using namespace libMesh; ExtVTKIO::ExtVTKIO (MeshBase const & mesh, Parameters const & par): VTKIO (mesh), _dirname (par.get<std::string>("output_dir")), _basename (par.get<std::string>("basename")), _print_step(par.get<uint>("print_step")) { system (("mkdir -p " + _dirname).c_str()); if( _dirname.substr( _dirname.size()-1,1) != "/" ) { _dirname.append("/"); } #ifdef FSI_HAS_LIBXML2 write_pvd( par.get<Real>("t_in"), par.get<Real>("t_out"), par.get<Real>("dt") ); #endif } void ExtVTKIO::write_solution(const EquationSystems & es, const std::set<std::string> *system_names) { std::stringstream file_name; file_name << _dirname << _basename << '_'; file_name << std::setw(6) << std::setfill('0') << es.parameters.get<uint>("timestep"); file_name << ".pvtu"; VTKIO::write_equation_systems(file_name.str(), es, system_names); } #ifdef FSI_HAS_LIBXML2 void ExtVTKIO::write_pvd( Real const t_in, Real const t_out, Real const dt ) { xmlTextWriterPtr writer = xmlNewTextWriterFilename((_dirname + _basename + ".pvd").c_str(), 0); if (writer == NULL) { std::cerr << "testXmlwriterFilename: Error creating the xml writer" << std::endl; exit(1); } int rc = xmlTextWriterSetIndent(writer, 2); rc = xmlTextWriterStartDocument(writer, NULL, "UTF-8", NULL); if (rc < 0) { std::cerr << "testXmlwriterFilename: Error at xmlTextWriterStartDocument" << std::endl; exit(rc); } rc = xmlTextWriterStartElement(writer, BAD_CAST "VTKFile"); xmlTextWriterWriteAttribute(writer, BAD_CAST "type", BAD_CAST "Collection"); xmlTextWriterWriteAttribute(writer, BAD_CAST "version", BAD_CAST "0.1"); xmlTextWriterWriteAttribute(writer, BAD_CAST "byte_order", BAD_CAST "LittleEndian"); rc = xmlTextWriterStartElement(writer, BAD_CAST "Collection"); Real time = t_in; uint timestep = 0; while( time <= t_out ) { if ((timestep)%_print_step == 0) { std::stringstream ss; ss << time; xmlTextWriterStartElement(writer, BAD_CAST "DataSet"); xmlTextWriterWriteAttribute(writer, BAD_CAST "timestep", BAD_CAST ss.str().c_str()); std::stringstream file_name; file_name << _basename << '_'; file_name << std::setw(6) << std::setfill('0') << timestep; file_name << ".pvtu"; xmlTextWriterWriteAttribute(writer, BAD_CAST "file", BAD_CAST file_name.str().c_str()); xmlTextWriterEndElement(writer); } time += dt; timestep++; } rc = xmlTextWriterEndDocument(writer); xmlFreeTextWriter(writer); } #endif
[ "ant.cervone@gmail.com" ]
ant.cervone@gmail.com
2dd258a2af4ddef4668bbbb36c262c763ba91191
5d97cf075990e3260e8f2fba464c60b7211fbc76
/help/OpenGL.h
a0b537599b067b15e6f8a4aa249f1b6472f439e1
[]
no_license
kvitajin/zpg
ecfedd0626d02e825cf49f6f139658a0bb1c297e
24780af8d4017ff2da1549b66b0b08fabaf5c744
refs/heads/master
2020-08-08T06:49:11.827312
2020-02-25T20:19:14
2020-02-25T20:19:14
213,762,996
3
0
null
null
null
null
UTF-8
C++
false
false
642
h
#pragma once //Include GLEW #include <GL/glew.h> //Include GLFW #include <GLFW/glfw3.h> //Include GLM #include <glm/vec3.hpp> // glm::vec3 #include <glm/vec4.hpp> // glm::vec4 #include <glm/mat4x4.hpp> // glm::mat4 #include <glm/gtc/matrix_transform.hpp> // glm::translate, glm::rotate, glm::scale, glm::perspective #include <glm/gtc/type_ptr.hpp> // glm::value_ptr //Include the standard C++ headers #include <stdlib.h> #include <stdio.h> class OpenGL { private: int major, minor, revision, width, height; float ratio; public: GLFWwindow* window; OpenGL(); ~OpenGL(); void GetVersion(); };
[ "jindrich.kvita@gnj.cz" ]
jindrich.kvita@gnj.cz
4254e8bc610ed215962a75ba2a1a70ffee233af9
aff4c6d67714c1df504c7c2e9bf3143cb32826a9
/examples/sdl/nick.double/sprite.cpp
2909a507eb1f980c2d45472cfa88e73a183093e0
[]
no_license
VishnuPrabhuT/2D-Game-Engine
8dc31a8f8c56f8a37f67580ac0713ce505354c66
2b20170c67851ce8148956a4997829c78e91129e
refs/heads/master
2021-01-22T01:42:43.077187
2017-12-13T01:06:25
2017-12-13T01:06:25
102,225,197
0
0
null
null
null
null
UTF-8
C++
false
false
2,389
cpp
#include <cmath> #include <random> #include <functional> #include "sprite.h" #include "gamedata.h" #include "renderContext.h" Vector2f Sprite::makeVelocity(int vx, int vy) const { float newvx = Gamedata::getInstance().getRandFloat(vx-50,vx+50);; float newvy = Gamedata::getInstance().getRandFloat(vy-50,vy+50);; newvx *= [](){ if(rand()%2) return -1; else return 1; }(); newvy *= [](){ if(rand()%2) return -1; else return 1; }(); return Vector2f(newvx, newvy); } Sprite::Sprite(const string& n, const Vector2f& pos, const Vector2f& vel, const Image* img): Drawable(n, pos, vel), image( img ), worldWidth(Gamedata::getInstance().getXmlInt("world/width")), worldHeight(Gamedata::getInstance().getXmlInt("world/height")) { } Sprite::Sprite(const std::string& name) : Drawable(name, Vector2f(Gamedata::getInstance().getXmlInt(name+"/startLoc/x"), Gamedata::getInstance().getXmlInt(name+"/startLoc/y")), Vector2f( Gamedata::getInstance().getXmlInt(name+"/speedX"), Gamedata::getInstance().getXmlInt(name+"/speedY")) ), image( RenderContext::getInstance()->getImage(name) ), worldWidth(Gamedata::getInstance().getXmlInt("world/width")), worldHeight(Gamedata::getInstance().getXmlInt("world/height")) { } Sprite::Sprite(const Sprite& s) : Drawable(s), image(s.image), worldWidth(Gamedata::getInstance().getXmlInt("world/width")), worldHeight(Gamedata::getInstance().getXmlInt("world/height")) { } Sprite& Sprite::operator=(const Sprite& rhs) { Drawable::operator=( rhs ); image = rhs.image; worldWidth = rhs.worldWidth; worldHeight = rhs.worldHeight; return *this; } inline namespace{ constexpr float SCALE_EPSILON = 2e-7; } void Sprite::draw() const { if(getScale() < SCALE_EPSILON) return; image->draw(getX(), getY(), getScale()); } void Sprite::update(Uint32 ticks) { Vector2f incr = getVelocity() * static_cast<float>(ticks) * 0.001; setPosition(getPosition() + incr); if ( getY() < 0) { setVelocityY( std::abs( getVelocityY() ) ); } if ( getY() > worldHeight-getScaledHeight()) { setVelocityY( -std::abs( getVelocityY() ) ); } if ( getX() < 0) { setVelocityX( std::abs( getVelocityX() ) ); } if ( getX() > worldWidth-getScaledWidth()) { setVelocityX( -std::abs( getVelocityX() ) ); } }
[ "malloy@clemson.edu" ]
malloy@clemson.edu
f08f7105cfebb440f382ef78e005d46511c8ed1b
69fda66dcff0572908b5743888a7824158385123
/CSC Files from 2013 VS/inClassWork4/inClassWork4/Source.cpp
4316568f3f300f5c6f216dd4209143613360f620
[]
no_license
Erkin-George/Cplusprograming-schoolwork
add9e73d81e3964b98bae840b9dead49c79cdb13
e584186eecafb9e7c9113c4713d9c40411e42076
refs/heads/master
2022-11-06T09:06:20.091315
2017-09-08T06:01:34
2017-09-08T06:01:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,099
cpp
//Erkin George //CSC 1230 //In class work #include<iostream> #include<string> using namespace std; void greetUser(string& userName); void favoriteStuff(string& userName, string& favMovie, string& favBook); void criticizeUser(string& userName, string& favMovie, string& favBook); int main() { string userName; string favMovie; string favBook; greetUser(userName); favoriteStuff(userName,favMovie,favBook); criticizeUser(userName, favMovie, favBook); return 0; } void greetUser(string& userName) { cout << "Hello user! Please enter your name:" << endl; getline(cin, userName); return; } void favoriteStuff(string& userName,string& favMovie,string& favBook) { cout << "Hello, " << userName << endl; cout << "What is your favorite book?" << endl; getline(cin,favBook); cout << "What is your favorite movie?" << endl; getline(cin, favMovie); return; } void criticizeUser(string& userName, string& favMovie, string& favBook) { string temp; temp = userName + " loves the movie " + favMovie + " and also loves the book " + favBook; cout << "The user, " << temp << endl; return; }
[ "erkin.george@gmail.com" ]
erkin.george@gmail.com
b3e4d04fe92961c050e3844b88c2d69843c0bd13
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Extras/ThirdPartyNotUE/emsdk/emscripten/1.37.19/system/include/libcxx/support/win32/locale_win32.h
ebf5bda740a531f6cc421ce3faf81843903b929e
[ "NCSA", "MIT", "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-mit-nagy", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
4,036
h
// -*- C++ -*- //===--------------------- support/win32/locale_win32.h -------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef _LIBCPP_SUPPORT_WIN32_LOCALE_WIN32_H #define _LIBCPP_SUPPORT_WIN32_LOCALE_WIN32_H #include <crtversion.h> #if _VC_CRT_MAJOR_VERSION < 14 // ctype mask table defined in msvcrt.dll extern "C" unsigned short __declspec(dllimport) _ctype[]; #endif #include "support/win32/support.h" #include "support/win32/locale_mgmt_win32.h" #include <stdio.h> lconv *localeconv_l( locale_t loc ); size_t mbrlen_l( const char *__restrict s, size_t n, mbstate_t *__restrict ps, locale_t loc); size_t mbsrtowcs_l( wchar_t *__restrict dst, const char **__restrict src, size_t len, mbstate_t *__restrict ps, locale_t loc ); size_t wcrtomb_l( char *__restrict s, wchar_t wc, mbstate_t *__restrict ps, locale_t loc); size_t mbrtowc_l( wchar_t *__restrict pwc, const char *__restrict s, size_t n, mbstate_t *__restrict ps, locale_t loc); size_t mbsnrtowcs_l( wchar_t *__restrict dst, const char **__restrict src, size_t nms, size_t len, mbstate_t *__restrict ps, locale_t loc); size_t wcsnrtombs_l( char *__restrict dst, const wchar_t **__restrict src, size_t nwc, size_t len, mbstate_t *__restrict ps, locale_t loc); wint_t btowc_l( int c, locale_t loc ); int wctob_l( wint_t c, locale_t loc ); inline _LIBCPP_ALWAYS_INLINE decltype(MB_CUR_MAX) MB_CUR_MAX_L( locale_t __l ) { return ___mb_cur_max_l_func(__l); } // the *_l functions are prefixed on Windows, only available for msvcr80+, VS2005+ #define mbtowc_l _mbtowc_l #define strtoll_l _strtoi64_l #define strtoull_l _strtoui64_l #define strtof_l _strtof_l #define strtod_l _strtod_l #define strtold_l _strtold_l inline _LIBCPP_INLINE_VISIBILITY int islower_l(int c, _locale_t loc) { return _islower_l((int)c, loc); } inline _LIBCPP_INLINE_VISIBILITY int isupper_l(int c, _locale_t loc) { return _isupper_l((int)c, loc); } #define isdigit_l _isdigit_l #define isxdigit_l _isxdigit_l #define strcoll_l _strcoll_l #define strxfrm_l _strxfrm_l #define wcscoll_l _wcscoll_l #define wcsxfrm_l _wcsxfrm_l #define toupper_l _toupper_l #define tolower_l _tolower_l #define iswspace_l _iswspace_l #define iswprint_l _iswprint_l #define iswcntrl_l _iswcntrl_l #define iswupper_l _iswupper_l #define iswlower_l _iswlower_l #define iswalpha_l _iswalpha_l #define iswdigit_l _iswdigit_l #define iswpunct_l _iswpunct_l #define iswxdigit_l _iswxdigit_l #define towupper_l _towupper_l #define towlower_l _towlower_l #define strftime_l _strftime_l #define sscanf_l( __s, __l, __f, ...) _sscanf_l( __s, __f, __l, __VA_ARGS__ ) #define vsscanf_l( __s, __l, __f, ...) _sscanf_l( __s, __f, __l, __VA_ARGS__ ) #define sprintf_l( __s, __l, __f, ... ) _sprintf_l( __s, __f, __l, __VA_ARGS__ ) #define vsprintf_l( __s, __l, __f, ... ) _vsprintf_l( __s, __f, __l, __VA_ARGS__ ) #define vsnprintf_l( __s, __n, __l, __f, ... ) _vsnprintf_l( __s, __n, __f, __l, __VA_ARGS__ ) int snprintf_l(char *ret, size_t n, locale_t loc, const char *format, ...); int asprintf_l( char **ret, locale_t loc, const char *format, ... ); int vasprintf_l( char **ret, locale_t loc, const char *format, va_list ap ); // not-so-pressing FIXME: use locale to determine blank characters inline int isblank_l( int c, locale_t /*loc*/ ) { return ( c == ' ' || c == '\t' ); } inline int iswblank_l( wint_t c, locale_t /*loc*/ ) { return ( c == L' ' || c == L'\t' ); } #if defined(_LIBCPP_MSVCRT) inline int isblank( int c, locale_t /*loc*/ ) { return ( c == ' ' || c == '\t' ); } inline int iswblank( wint_t c, locale_t /*loc*/ ) { return ( c == L' ' || c == L'\t' ); } #endif // _LIBCPP_MSVCRT #endif // _LIBCPP_SUPPORT_WIN32_LOCALE_WIN32_H
[ "tungnt.rec@gmail.com" ]
tungnt.rec@gmail.com
9b863d4f623257160152dc051e171261d13f8e22
fe5938ec35ed8e344a3c3d2bf3d3d456f53a5d16
/src/net.cpp
a8b751d5ca19db81086aeec31c75ce97e07a2b55
[ "MIT" ]
permissive
bitluckdev/bitluckcoin
1c6f971f9d7205cbe33df05b86319a8c54cf096d
6a1d14d021b59fd31f9493428b941ec0d6af7621
refs/heads/master
2020-04-17T11:07:57.951826
2018-11-19T02:30:36
2018-11-19T02:30:36
67,142,664
1
0
MIT
2018-11-19T02:30:37
2016-09-01T15:18:18
C++
UTF-8
C++
false
false
64,202
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "irc.h" #include "db.h" #include "net.h" #include "init.h" #include "strlcpy.h" #include "addrman.h" #include "ui_interface.h" #ifdef WIN32 #include <string.h> #endif #ifdef USE_UPNP #include <miniupnpc/miniwget.h> #include <miniupnpc/miniupnpc.h> #include <miniupnpc/upnpcommands.h> #include <miniupnpc/upnperrors.h> #endif using namespace std; using namespace boost; static const int MAX_OUTBOUND_CONNECTIONS = 16; void ThreadMessageHandler2(void* parg); void ThreadSocketHandler2(void* parg); void ThreadOpenConnections2(void* parg); void ThreadOpenAddedConnections2(void* parg); #ifdef USE_UPNP void ThreadMapPort2(void* parg); #endif void ThreadDNSAddressSeed2(void* parg); bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false); struct LocalServiceInfo { int nScore; int nPort; }; // // Global state variables // bool fDiscover = true; bool fUseUPnP = false; uint64_t nLocalServices = NODE_NETWORK; static CCriticalSection cs_mapLocalHost; static map<CNetAddr, LocalServiceInfo> mapLocalHost; static bool vfReachable[NET_MAX] = {}; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; CAddress addrSeenByPeer(CService("0.0.0.0", 0), nLocalServices); uint64_t nLocalHostNonce = 0; boost::array<int, THREAD_MAX> vnThreadsRunning; static std::vector<SOCKET> vhListenSocket; CAddrMan addrman; vector<CNode*> vNodes; CCriticalSection cs_vNodes; map<CInv, CDataStream> mapRelay; deque<pair<int64_t, CInv> > vRelayExpiration; CCriticalSection cs_mapRelay; map<CInv, int64_t> mapAlreadyAskedFor; static deque<string> vOneShots; CCriticalSection cs_vOneShots; set<CNetAddr> setservAddNodeAddresses; CCriticalSection cs_setservAddNodeAddresses; static CSemaphore *semOutbound = NULL; void AddOneShot(string strDest) { LOCK(cs_vOneShots); vOneShots.push_back(strDest); } unsigned short GetListenPort() { return (unsigned short)(GetArg("-port", GetDefaultPort())); } void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd) { // Filter out duplicate requests if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd) return; pindexLastGetBlocksBegin = pindexBegin; hashLastGetBlocksEnd = hashEnd; PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd); } // find 'best' local address for a particular peer bool GetLocal(CService& addr, const CNetAddr *paddrPeer) { if (fNoListen) return false; int nBestScore = -1; int nBestReachability = -1; { LOCK(cs_mapLocalHost); for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) { int nScore = (*it).second.nScore; int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr = CService((*it).first, (*it).second.nPort); nBestReachability = nReachability; nBestScore = nScore; } } } return nBestScore >= 0; } // get best local address for a particular peer as a CAddress CAddress GetLocalAddress(const CNetAddr *paddrPeer) { CAddress ret(CService("0.0.0.0",0),0); CService addr; if (GetLocal(addr, paddrPeer)) { ret = CAddress(addr); ret.nServices = nLocalServices; ret.nTime = GetAdjustedTime(); } return ret; } bool RecvLine(SOCKET hSocket, string& strLine) { strLine = ""; while (true) { char c; int nBytes = recv(hSocket, &c, 1, 0); if (nBytes > 0) { if (c == '\n') continue; if (c == '\r') return true; strLine += c; if (strLine.size() >= 9000) return true; } else if (nBytes <= 0) { if (fShutdown) return false; if (nBytes < 0) { int nErr = WSAGetLastError(); if (nErr == WSAEMSGSIZE) continue; if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) { MilliSleep(10); continue; } } if (!strLine.empty()) return true; if (nBytes == 0) { // socket closed printf("socket closed\n"); return false; } else { // socket error int nErr = WSAGetLastError(); printf("recv failed: %d\n", nErr); return false; } } } } // used when scores of local addresses may have changed // pushes better local address to peers void static AdvertizeLocal() { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->fSuccessfullyConnected) { CAddress addrLocal = GetLocalAddress(&pnode->addr); if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal) { pnode->PushAddress(addrLocal); pnode->addrLocal = addrLocal; } } } } void SetReachable(enum Network net, bool fFlag) { LOCK(cs_mapLocalHost); vfReachable[net] = fFlag; if (net == NET_IPV6 && fFlag) vfReachable[NET_IPV4] = true; } // learn a new local address bool AddLocal(const CService& addr, int nScore) { if (!addr.IsRoutable()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) return false; if (IsLimited(addr)) return false; printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore); { LOCK(cs_mapLocalHost); bool fAlready = mapLocalHost.count(addr) > 0; LocalServiceInfo &info = mapLocalHost[addr]; if (!fAlready || nScore >= info.nScore) { info.nScore = nScore + (fAlready ? 1 : 0); info.nPort = addr.GetPort(); } SetReachable(addr.GetNetwork()); } AdvertizeLocal(); return true; } bool AddLocal(const CNetAddr &addr, int nScore) { return AddLocal(CService(addr, GetListenPort()), nScore); } /** Make a particular network entirely off-limits (no automatic connects to it) */ void SetLimited(enum Network net, bool fLimited) { if (net == NET_UNROUTABLE) return; LOCK(cs_mapLocalHost); vfLimited[net] = fLimited; } bool IsLimited(enum Network net) { LOCK(cs_mapLocalHost); return vfLimited[net]; } bool IsLimited(const CNetAddr &addr) { return IsLimited(addr.GetNetwork()); } /** vote for a local address */ bool SeenLocal(const CService& addr) { { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == 0) return false; mapLocalHost[addr].nScore++; } AdvertizeLocal(); return true; } /** check whether a given address is potentially local */ bool IsLocal(const CService& addr) { LOCK(cs_mapLocalHost); return mapLocalHost.count(addr) > 0; } /** check whether a given address is in a network we can probably connect to */ bool IsReachable(const CNetAddr& addr) { LOCK(cs_mapLocalHost); enum Network net = addr.GetNetwork(); return vfReachable[net] && !vfLimited[net]; } bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet) { SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str()); send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL); string strLine; while (RecvLine(hSocket, strLine)) { if (strLine.empty()) // HTTP response is separated from headers by blank line { while (true) { if (!RecvLine(hSocket, strLine)) { closesocket(hSocket); return false; } if (pszKeyword == NULL) break; if (strLine.find(pszKeyword) != string::npos) { strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword)); break; } } closesocket(hSocket); if (strLine.find("<") != string::npos) strLine = strLine.substr(0, strLine.find("<")); strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r")); while (strLine.size() > 0 && isspace(strLine[strLine.size()-1])) strLine.resize(strLine.size()-1); CService addr(strLine,0,true); printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str()); if (!addr.IsValid() || !addr.IsRoutable()) return false; ipRet.SetIP(addr); return true; } } closesocket(hSocket); return error("GetMyExternalIP() : connection closed"); } // We now get our external IP from the IRC server first and only use this as a backup bool GetMyExternalIP(CNetAddr& ipRet) { CService addrConnect; const char* pszGet; const char* pszKeyword; for (int nLookup = 0; nLookup <= 1; nLookup++) for (int nHost = 1; nHost <= 2; nHost++) { // We should be phasing out our use of sites like these. If we need // replacements, we should ask for volunteers to put this simple // php file on their web server that prints the client IP: // <?php echo $_SERVER["REMOTE_ADDR"]; ?> if (nHost == 1) { addrConnect = CService("91.198.22.70",80); // checkip.dyndns.org if (nLookup == 1) { CService addrIP("checkip.dyndns.org", 80, true); if (addrIP.IsValid()) addrConnect = addrIP; } pszGet = "GET / HTTP/1.1\r\n" "Host: checkip.dyndns.org\r\n" "User-Agent: BitLuckCoin\r\n" "Connection: close\r\n" "\r\n"; pszKeyword = "Address:"; } else if (nHost == 2) { addrConnect = CService("74.208.43.192", 80); // www.showmyip.com if (nLookup == 1) { CService addrIP("www.showmyip.com", 80, true); if (addrIP.IsValid()) addrConnect = addrIP; } pszGet = "GET /simple/ HTTP/1.1\r\n" "Host: www.showmyip.com\r\n" "User-Agent: BitLuckCoin\r\n" "Connection: close\r\n" "\r\n"; pszKeyword = NULL; // Returns just IP address } if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet)) return true; } return false; } void ThreadGetMyExternalIP(void* parg) { // Make this thread recognisable as the external IP detection thread RenameThread("bitluckcoin-ext-ip"); CNetAddr addrLocalHost; if (GetMyExternalIP(addrLocalHost)) { printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str()); AddLocal(addrLocalHost, LOCAL_HTTP); } } void AddressCurrentlyConnected(const CService& addr) { addrman.Connected(addr); } uint64_t CNode::nTotalBytesRecv = 0; uint64_t CNode::nTotalBytesSent = 0; CCriticalSection CNode::cs_totalBytesRecv; CCriticalSection CNode::cs_totalBytesSent; CNode* FindNode(const CNetAddr& ip) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CNetAddr)pnode->addr == ip) return (pnode); } return NULL; } CNode* FindNode(std::string addrName) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->addrName == addrName) return (pnode); return NULL; } CNode* FindNode(const CService& addr) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CService)pnode->addr == addr) return (pnode); } return NULL; } CNode* ConnectNode(CAddress addrConnect, const char *pszDest) { if (pszDest == NULL) { if (IsLocal(addrConnect)) return NULL; // Look for an existing connection CNode* pnode = FindNode((CService)addrConnect); if (pnode) { pnode->AddRef(); return pnode; } } /// debug print printf("trying connection %s lastseen=%.1fhrs\n", pszDest ? pszDest : addrConnect.ToString().c_str(), pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0); // Connect SOCKET hSocket; if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket)) { addrman.Attempt(addrConnect); /// debug print printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str()); // Set to non-blocking #ifdef WIN32 u_long nOne = 1; if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError()); #else if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno); #endif // Add node CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } pnode->nTimeConnected = GetTime(); return pnode; } else { return NULL; } } void CNode::CloseSocketDisconnect() { fDisconnect = true; if (hSocket != INVALID_SOCKET) { printf("disconnecting node %s\n", addrName.c_str()); closesocket(hSocket); hSocket = INVALID_SOCKET; // in case this fails, we'll empty the recv buffer when the CNode is deleted TRY_LOCK(cs_vRecvMsg, lockRecv); if (lockRecv) vRecvMsg.clear(); } } void CNode::Cleanup() { } void CNode::PushVersion() { /// when NTP implemented, change to just nTime = GetAdjustedTime() int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime()); CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0))); CAddress addrMe = GetLocalAddress(&addr); RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str()); PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight); } std::map<CNetAddr, int64_t> CNode::setBanned; CCriticalSection CNode::cs_setBanned; void CNode::ClearBanned() { setBanned.clear(); } bool CNode::IsBanned(CNetAddr ip) { bool fResult = false; { LOCK(cs_setBanned); std::map<CNetAddr, int64_t>::iterator i = setBanned.find(ip); if (i != setBanned.end()) { int64_t t = (*i).second; if (GetTime() < t) fResult = true; } } return fResult; } bool CNode::Misbehaving(int howmuch) { if (addr.IsLocal()) { printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch); return false; } nMisbehavior += howmuch; if (nMisbehavior >= GetArg("-banscore", 100)) { int64_t banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior); { LOCK(cs_setBanned); if (setBanned[addr] < banTime) setBanned[addr] = banTime; } CloseSocketDisconnect(); return true; } else printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior); return false; } #undef X #define X(name) stats.name = name void CNode::copyStats(CNodeStats &stats) { X(nServices); X(nLastSend); X(nLastRecv); X(nSendBytes); X(nRecvBytes); X(nTimeConnected); X(addrName); X(nVersion); X(strSubVer); X(fInbound); X(nStartingHeight); X(nMisbehavior); // It is common for nodes with good ping times to suddenly become lagged, // due to a new block arriving or other large transfer. // Merely reporting pingtime might fool the caller into thinking the node was still responsive, // since pingtime does not update until the ping is complete, which might take a while. // So, if a ping is taking an unusually long time in flight, // the caller can immediately detect that this is happening. int64_t nPingUsecWait = 0; if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) { nPingUsecWait = GetTimeMicros() - nPingUsecStart; } // Raw ping time is in microseconds, but show it to user as whole seconds (Bitcoin users should be well used to small numbers with many decimal places by now :) stats.dPingTime = (((double)nPingUsecTime) / 1e6); stats.dPingWait = (((double)nPingUsecWait) / 1e6); } #undef X void CNode::RecordBytesRecv(uint64_t bytes) { LOCK(cs_totalBytesRecv); nTotalBytesRecv += bytes; } void CNode::RecordBytesSent(uint64_t bytes) { LOCK(cs_totalBytesSent); nTotalBytesSent += bytes; } uint64_t CNode::GetTotalBytesRecv() { LOCK(cs_totalBytesRecv); return nTotalBytesRecv; } uint64_t CNode::GetTotalBytesSent() { LOCK(cs_totalBytesSent); return nTotalBytesSent; } // requires LOCK(cs_vRecvMsg) bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes) { while (nBytes > 0) { // get current incomplete message, or create a new one if (vRecvMsg.empty() || vRecvMsg.back().complete()) vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion)); CNetMessage& msg = vRecvMsg.back(); // absorb network data int handled; if (!msg.in_data) handled = msg.readHeader(pch, nBytes); else handled = msg.readData(pch, nBytes); if (handled < 0) return false; pch += handled; nBytes -= handled; if (msg.complete()) msg.nTime = GetTimeMicros(); } return true; } int CNetMessage::readHeader(const char *pch, unsigned int nBytes) { // copy data to temporary parsing buffer unsigned int nRemaining = 24 - nHdrPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&hdrbuf[nHdrPos], pch, nCopy); nHdrPos += nCopy; // if header incomplete, exit if (nHdrPos < 24) return nCopy; // deserialize to CMessageHeader try { hdrbuf >> hdr; } catch (std::exception &e) { return -1; } // reject messages larger than MAX_SIZE if (hdr.nMessageSize > MAX_SIZE) return -1; // switch state to reading message data in_data = true; vRecv.resize(hdr.nMessageSize); return nCopy; } int CNetMessage::readData(const char *pch, unsigned int nBytes) { unsigned int nRemaining = hdr.nMessageSize - nDataPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&vRecv[nDataPos], pch, nCopy); nDataPos += nCopy; return nCopy; } // requires LOCK(cs_vSend) void SocketSendData(CNode *pnode) { std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin(); while (it != pnode->vSendMsg.end()) { const CSerializeData &data = *it; assert(data.size() > pnode->nSendOffset); int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT); if (nBytes > 0) { pnode->nLastSend = GetTime(); pnode->nSendOffset += nBytes; pnode->nSendBytes += nBytes; pnode->RecordBytesSent(nBytes); if (pnode->nSendOffset == data.size()) { pnode->nSendOffset = 0; pnode->nSendSize -= data.size(); it++; } else { // could not send full message; stop sending more break; } } else { if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { printf("socket send error %d\n", nErr); pnode->CloseSocketDisconnect(); } } // couldn't send anything at all break; } } if (it == pnode->vSendMsg.end()) { assert(pnode->nSendOffset == 0); assert(pnode->nSendSize == 0); } pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it); } void ThreadSocketHandler(void* parg) { // Make this thread recognisable as the networking thread RenameThread("bitluckcoin-net"); try { vnThreadsRunning[THREAD_SOCKETHANDLER]++; ThreadSocketHandler2(parg); vnThreadsRunning[THREAD_SOCKETHANDLER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_SOCKETHANDLER]--; PrintException(&e, "ThreadSocketHandler()"); } catch (...) { vnThreadsRunning[THREAD_SOCKETHANDLER]--; throw; // support pthread_cancel() } printf("ThreadSocketHandler exited\n"); } void ThreadSocketHandler2(void* parg) { printf("ThreadSocketHandler started\n"); list<CNode*> vNodesDisconnected; unsigned int nPrevNodeCount = 0; while (true) { // // Disconnect nodes // { LOCK(cs_vNodes); // Disconnect unused nodes vector<CNode*> vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) { // remove from vNodes vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); // release outbound grant (if any) pnode->grantOutbound.Release(); // close socket and cleanup pnode->CloseSocketDisconnect(); pnode->Cleanup(); // hold in disconnected pool until all refs are released if (pnode->fNetworkNode || pnode->fInbound) pnode->Release(); vNodesDisconnected.push_back(pnode); } } // Delete disconnected nodes list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { TRY_LOCK(pnode->cs_mapRequests, lockReq); if (lockReq) { TRY_LOCK(pnode->cs_inventory, lockInv); if (lockInv) fDelete = true; } } } } if (fDelete) { vNodesDisconnected.remove(pnode); delete pnode; } } } } if (vNodes.size() != nPrevNodeCount) { nPrevNodeCount = vNodes.size(); uiInterface.NotifyNumConnectionsChanged(vNodes.size()); } // // Find which sockets have data to receive // struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; // frequency to poll pnode->vSend fd_set fdsetRecv; fd_set fdsetSend; fd_set fdsetError; FD_ZERO(&fdsetRecv); FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); SOCKET hSocketMax = 0; bool have_fds = false; BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) { FD_SET(hListenSocket, &fdsetRecv); hSocketMax = max(hSocketMax, hListenSocket); have_fds = true; } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->hSocket == INVALID_SOCKET) continue; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { // do not read, if draining write queue if (!pnode->vSendMsg.empty()) FD_SET(pnode->hSocket, &fdsetSend); else FD_SET(pnode->hSocket, &fdsetRecv); FD_SET(pnode->hSocket, &fdsetError); hSocketMax = max(hSocketMax, pnode->hSocket); have_fds = true; } } } } vnThreadsRunning[THREAD_SOCKETHANDLER]--; int nSelect = select(have_fds ? hSocketMax + 1 : 0, &fdsetRecv, &fdsetSend, &fdsetError, &timeout); vnThreadsRunning[THREAD_SOCKETHANDLER]++; if (fShutdown) return; if (nSelect == SOCKET_ERROR) { if (have_fds) { int nErr = WSAGetLastError(); printf("socket select error %d\n", nErr); for (unsigned int i = 0; i <= hSocketMax; i++) FD_SET(i, &fdsetRecv); } FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); MilliSleep(timeout.tv_usec/1000); } // // Accept new connections // BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv)) { struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len); CAddress addr; int nInbound = 0; if (hSocket != INVALID_SOCKET) if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) printf("Warning: Unknown socket family\n"); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->fInbound) nInbound++; } if (hSocket == INVALID_SOCKET) { int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK) printf("socket error accept failed: %d\n", nErr); } else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS) { closesocket(hSocket); } else if (CNode::IsBanned(addr)) { printf("connection from %s dropped (banned)\n", addr.ToString().c_str()); closesocket(hSocket); } else { printf("accepted connection %s\n", addr.ToString().c_str()); CNode* pnode = new CNode(hSocket, addr, "", true); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } } } // // Service each socket // vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->AddRef(); } BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (fShutdown) return; // // Receive // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { if (pnode->GetTotalRecvSize() > ReceiveFloodSize()) { if (!pnode->fDisconnect) printf("socket recv flood control disconnect (%u bytes)\n", pnode->GetTotalRecvSize()); pnode->CloseSocketDisconnect(); } else { // typical socket buffer is 8K-64K char pchBuf[0x10000]; int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); if (nBytes > 0) { if (!pnode->ReceiveMsgBytes(pchBuf, nBytes)) pnode->CloseSocketDisconnect(); pnode->nLastRecv = GetTime(); pnode->nRecvBytes += nBytes; pnode->RecordBytesRecv(nBytes); } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) printf("socket closed\n"); pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) printf("socket recv error %d\n", nErr); pnode->CloseSocketDisconnect(); } } } } } // // Send // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetSend)) { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SocketSendData(pnode); } // // Inactivity checking // int64_t nTime = GetTime(); if (nTime - pnode->nTimeConnected > 60) { if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) { printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0); pnode->fDisconnect = true; } else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) { printf("socket sending timeout: %"PRId64"s\n", nTime - pnode->nLastSend); pnode->fDisconnect = true; } else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60)) { printf("socket receive timeout: %"PRId64"s\n", nTime - pnode->nLastRecv); pnode->fDisconnect = true; } else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) { printf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart)); pnode->fDisconnect = true; } } } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } MilliSleep(10); } } #ifdef USE_UPNP void ThreadMapPort(void* parg) { // Make this thread recognisable as the UPnP thread RenameThread("bitluckcoin-UPnP"); try { vnThreadsRunning[THREAD_UPNP]++; ThreadMapPort2(parg); vnThreadsRunning[THREAD_UPNP]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_UPNP]--; PrintException(&e, "ThreadMapPort()"); } catch (...) { vnThreadsRunning[THREAD_UPNP]--; PrintException(NULL, "ThreadMapPort()"); } printf("ThreadMapPort exited\n"); } void ThreadMapPort2(void* parg) { printf("ThreadMapPort started\n"); std::string port = strprintf("%u", GetListenPort()); const char * multicastif = 0; const char * minissdpdpath = 0; struct UPNPDev * devlist = 0; char lanaddr[64]; #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0); #else /* miniupnpc 1.6 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error); #endif struct UPNPUrls urls; struct IGDdatas data; int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { if (fDiscover) { char externalIPAddress[40]; r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); if(r != UPNPCOMMAND_SUCCESS) printf("UPnP: GetExternalIPAddress() returned %d\n", r); else { if(externalIPAddress[0]) { printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); } else printf("UPnP: GetExternalIPAddress failed.\n"); } } string strDesc = "BitLuckCoin " + FormatFullVersion(); #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0); #else /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0"); #endif if(r!=UPNPCOMMAND_SUCCESS) printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port.c_str(), port.c_str(), lanaddr, r, strupnperror(r)); else printf("UPnP Port Mapping successful.\n"); int i = 1; while (true) { if (fShutdown || !fUseUPnP) { r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0); printf("UPNP_DeletePortMapping() returned : %d\n", r); freeUPNPDevlist(devlist); devlist = 0; FreeUPNPUrls(&urls); return; } if (i % 600 == 0) // Refresh every 20 minutes { #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0); #else /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0"); #endif if(r!=UPNPCOMMAND_SUCCESS) printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port.c_str(), port.c_str(), lanaddr, r, strupnperror(r)); else printf("UPnP Port Mapping successful.\n");; } MilliSleep(2000); i++; } } else { printf("No valid UPnP IGDs found\n"); freeUPNPDevlist(devlist); devlist = 0; if (r != 0) FreeUPNPUrls(&urls); while (true) { if (fShutdown || !fUseUPnP) return; MilliSleep(2000); } } } void MapPort() { if (fUseUPnP && vnThreadsRunning[THREAD_UPNP] < 1) { if (!NewThread(ThreadMapPort, NULL)) printf("Error: ThreadMapPort(ThreadMapPort) failed\n"); } } #else void MapPort() { // Intentionally left blank. } #endif // DNS seeds // Each pair gives a source name and a seed name. // The first name is used as information source for addrman. // The second name should resolve to a list of seed addresses. static const char *strDNSSeed[][2] = { {"BitLuckCoin 1st Seed Server","167.179.79.10"}, {"BitLuckCoin 2nd Seed Server","45.76.196.129"}, }; void ThreadDNSAddressSeed(void* parg) { // Make this thread recognisable as the DNS seeding thread RenameThread("bitluckcoin-dnsseed"); try { vnThreadsRunning[THREAD_DNSSEED]++; ThreadDNSAddressSeed2(parg); vnThreadsRunning[THREAD_DNSSEED]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_DNSSEED]--; PrintException(&e, "ThreadDNSAddressSeed()"); } catch (...) { vnThreadsRunning[THREAD_DNSSEED]--; throw; // support pthread_cancel() } printf("ThreadDNSAddressSeed exited\n"); } void ThreadDNSAddressSeed2(void* parg) { printf("ThreadDNSAddressSeed started\n"); int found = 0; if (!fTestNet) { printf("Loading addresses from DNS seeds (could take a while)\n"); for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) { if (HaveNameProxy()) { AddOneShot(strDNSSeed[seed_idx][1]); } else { vector<CNetAddr> vaddr; vector<CAddress> vAdd; if (LookupHost(strDNSSeed[seed_idx][1], vaddr)) { BOOST_FOREACH(CNetAddr& ip, vaddr) { int nOneDay = 24*3600; CAddress addr = CAddress(CService(ip, GetDefaultPort())); addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; } } addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true)); } } } printf("%d addresses found from DNS seeds\n", found); } unsigned int pnSeed[] = { 0x266e8368, 0x0bd724d3, 0x9e418368, 0x62418368 }; void DumpAddresses() { int64_t nStart = GetTimeMillis(); CAddrDB adb; adb.Write(addrman); printf("Flushed %d addresses to peers.dat %"PRId64"ms\n", addrman.size(), GetTimeMillis() - nStart); } void ThreadDumpAddress2(void* parg) { vnThreadsRunning[THREAD_DUMPADDRESS]++; while (!fShutdown) { DumpAddresses(); vnThreadsRunning[THREAD_DUMPADDRESS]--; MilliSleep(600000); vnThreadsRunning[THREAD_DUMPADDRESS]++; } vnThreadsRunning[THREAD_DUMPADDRESS]--; } void ThreadDumpAddress(void* parg) { // Make this thread recognisable as the address dumping thread RenameThread("bitluckcoin-adrdump"); try { ThreadDumpAddress2(parg); } catch (std::exception& e) { PrintException(&e, "ThreadDumpAddress()"); } printf("ThreadDumpAddress exited\n"); } void ThreadOpenConnections(void* parg) { // Make this thread recognisable as the connection opening thread RenameThread("bitluckcoin-opencon"); try { vnThreadsRunning[THREAD_OPENCONNECTIONS]++; ThreadOpenConnections2(parg); vnThreadsRunning[THREAD_OPENCONNECTIONS]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_OPENCONNECTIONS]--; PrintException(&e, "ThreadOpenConnections()"); } catch (...) { vnThreadsRunning[THREAD_OPENCONNECTIONS]--; PrintException(NULL, "ThreadOpenConnections()"); } printf("ThreadOpenConnections exited\n"); } void static ProcessOneShot() { string strDest; { LOCK(cs_vOneShots); if (vOneShots.empty()) return; strDest = vOneShots.front(); vOneShots.pop_front(); } CAddress addr; CSemaphoreGrant grant(*semOutbound, true); if (grant) { if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true)) AddOneShot(strDest); } } void static ThreadStakeMiner(void* parg) { printf("ThreadStakeMiner started\n"); CWallet* pwallet = (CWallet*)parg; try { vnThreadsRunning[THREAD_STAKE_MINER]++; StakeMiner(pwallet); vnThreadsRunning[THREAD_STAKE_MINER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_STAKE_MINER]--; PrintException(&e, "ThreadStakeMiner()"); } catch (...) { vnThreadsRunning[THREAD_STAKE_MINER]--; PrintException(NULL, "ThreadStakeMiner()"); } printf("ThreadStakeMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_STAKE_MINER]); } void ThreadOpenConnections2(void* parg) { printf("ThreadOpenConnections started\n"); // Connect to specific addresses if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { for (int64_t nLoop = 0;; nLoop++) { ProcessOneShot(); BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"]) { CAddress addr; OpenNetworkConnection(addr, NULL, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { MilliSleep(500); if (fShutdown) return; } } MilliSleep(500); } } // Initiate network connections int64_t nStart = GetTime(); while (true) { ProcessOneShot(); vnThreadsRunning[THREAD_OPENCONNECTIONS]--; MilliSleep(500); vnThreadsRunning[THREAD_OPENCONNECTIONS]++; if (fShutdown) return; vnThreadsRunning[THREAD_OPENCONNECTIONS]--; CSemaphoreGrant grant(*semOutbound); vnThreadsRunning[THREAD_OPENCONNECTIONS]++; if (fShutdown) return; // Add seed nodes if IRC isn't working if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet) { std::vector<CAddress> vAdd; for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; struct in_addr ip; memcpy(&ip, &pnSeed[i], sizeof(ip)); CAddress addr(CService(ip, GetDefaultPort())); addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek; vAdd.push_back(addr); } addrman.Add(vAdd, CNetAddr("127.0.0.1")); } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; // Only connect out to one peer per network group (/16 for IPv4). // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. int nOutbound = 0; set<vector<unsigned char> > setConnected; { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (!pnode->fInbound) { setConnected.insert(pnode->addr.GetGroup()); nOutbound++; } } } int64_t nANow = GetAdjustedTime(); int nTries = 0; while (true) { // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections) CAddress addr = addrman.Select(10 + min(nOutbound,8)*10); // if we selected an invalid address, restart if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) break; // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman, // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates // already-connected network ranges, ...) before trying new addrman addresses. nTries++; if (nTries > 100) break; if (IsLimited(addr)) continue; // only consider very recently tried nodes after 30 failed attempts if (nANow - addr.nLastTry < 600 && nTries < 30) continue; // do not allow non-default ports, unless after 50 invalid addresses selected already if (addr.GetPort() != GetDefaultPort() && nTries < 50) continue; addrConnect = addr; break; } if (addrConnect.IsValid()) OpenNetworkConnection(addrConnect, &grant); } } void ThreadOpenAddedConnections(void* parg) { // Make this thread recognisable as the connection opening thread RenameThread("bitluckcoin-opencon"); try { vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++; ThreadOpenAddedConnections2(parg); vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--; PrintException(&e, "ThreadOpenAddedConnections()"); } catch (...) { vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--; PrintException(NULL, "ThreadOpenAddedConnections()"); } printf("ThreadOpenAddedConnections exited\n"); } void ThreadOpenAddedConnections2(void* parg) { printf("ThreadOpenAddedConnections started\n"); if (mapArgs.count("-addnode") == 0) return; if (HaveNameProxy()) { while(!fShutdown) { BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) { CAddress addr; CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(addr, &grant, strAddNode.c_str()); MilliSleep(500); } vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--; MilliSleep(120000); // Retry every 2 minutes vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++; } return; } vector<vector<CService> > vservAddressesToAdd(0); BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) { vector<CService> vservNode(0); if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0)) { vservAddressesToAdd.push_back(vservNode); { LOCK(cs_setservAddNodeAddresses); BOOST_FOREACH(CService& serv, vservNode) setservAddNodeAddresses.insert(serv); } } } while (true) { vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd; // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry // (keeping in mind that addnode entries can have many IPs if fNameLookup) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++) BOOST_FOREACH(CService& addrNode, *(it)) if (pnode->addr == addrNode) { it = vservConnectAddresses.erase(it); it--; break; } } BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses) { CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(CAddress(*(vserv.begin())), &grant); MilliSleep(500); if (fShutdown) return; } if (fShutdown) return; vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--; MilliSleep(120000); // Retry every 2 minutes vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++; if (fShutdown) return; } } // if successful, this moves the passed grant to the constructed node bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot) { // // Initiate outbound network connection // if (fShutdown) return false; if (!strDest) if (IsLocal(addrConnect) || FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort().c_str())) return false; if (strDest && FindNode(strDest)) return false; vnThreadsRunning[THREAD_OPENCONNECTIONS]--; CNode* pnode = ConnectNode(addrConnect, strDest); vnThreadsRunning[THREAD_OPENCONNECTIONS]++; if (fShutdown) return false; if (!pnode) return false; if (grantOutbound) grantOutbound->MoveTo(pnode->grantOutbound); pnode->fNetworkNode = true; if (fOneShot) pnode->fOneShot = true; return true; } void ThreadMessageHandler(void* parg) { // Make this thread recognisable as the message handling thread RenameThread("bitluckcoin-msghand"); try { vnThreadsRunning[THREAD_MESSAGEHANDLER]++; ThreadMessageHandler2(parg); vnThreadsRunning[THREAD_MESSAGEHANDLER]--; } catch (std::exception& e) { vnThreadsRunning[THREAD_MESSAGEHANDLER]--; PrintException(&e, "ThreadMessageHandler()"); } catch (...) { vnThreadsRunning[THREAD_MESSAGEHANDLER]--; PrintException(NULL, "ThreadMessageHandler()"); } printf("ThreadMessageHandler exited\n"); } void ThreadMessageHandler2(void* parg) { printf("ThreadMessageHandler started\n"); SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); while (!fShutdown) { vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->AddRef(); } // Poll the connected nodes for messages CNode* pnodeTrickle = NULL; if (!vNodesCopy.empty()) pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())]; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect) continue; // Receive messages { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) if (!ProcessMessages(pnode)) pnode->CloseSocketDisconnect(); } if (fShutdown) return; // Send messages { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SendMessages(pnode, pnode == pnodeTrickle); } if (fShutdown) return; } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } // Wait and allow messages to bunch up. // Reduce vnThreadsRunning so StopNode has permission to exit while // we're sleeping, but we must always check fShutdown after doing this. vnThreadsRunning[THREAD_MESSAGEHANDLER]--; MilliSleep(100); if (fRequestShutdown) StartShutdown(); vnThreadsRunning[THREAD_MESSAGEHANDLER]++; if (fShutdown) return; } } bool BindListenPort(const CService &addrBind, string& strError) { strError = ""; int nOne = 1; #ifdef WIN32 // Initialize Windows Sockets WSADATA wsadata; int ret = WSAStartup(MAKEWORD(2,2), &wsadata); if (ret != NO_ERROR) { strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret); printf("%s\n", strError.c_str()); return false; } #endif // Create socket for listening for incoming connections struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str()); printf("%s\n", strError.c_str()); return false; } SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hListenSocket == INVALID_SOCKET) { strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } #ifdef SO_NOSIGPIPE // Different way of disabling SIGPIPE on BSD setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int)); #endif #ifndef WIN32 // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. Not an issue on windows. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); #endif #ifdef WIN32 // Set to non-blocking, incoming connections will also inherit this if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR) #else if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) #endif { strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option // and enable it by default or not. Try to enable it, if possible. if (addrBind.IsIPv6()) { #ifdef IPV6_V6ONLY #ifdef WIN32 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int)); #else setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int)); #endif #endif #ifdef WIN32 int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */; int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */; // this call is allowed to fail setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int)); #endif } if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_("Unable to bind to %s on this computer. BitLuckCoin is probably already running."), addrBind.ToString().c_str()); else strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr)); printf("%s\n", strError.c_str()); return false; } printf("Bound to %s\n", addrBind.ToString().c_str()); // Listen for incoming connections if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) { strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError()); printf("%s\n", strError.c_str()); return false; } vhListenSocket.push_back(hListenSocket); if (addrBind.IsRoutable() && fDiscover) AddLocal(addrBind, LOCAL_BIND); return true; } void static Discover() { if (!fDiscover) return; #ifdef WIN32 // Get local host IP char pszHostName[1000] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { vector<CNetAddr> vaddr; if (LookupHost(pszHostName, vaddr)) { BOOST_FOREACH (const CNetAddr &addr, vaddr) { AddLocal(addr, LOCAL_IF); } } } #else // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); CNetAddr addr(s4->sin_addr); if (AddLocal(addr, LOCAL_IF)) printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str()); } else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); CNetAddr addr(s6->sin6_addr); if (AddLocal(addr, LOCAL_IF)) printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str()); } } freeifaddrs(myaddrs); } #endif // Don't use external IPv4 discovery, when -onlynet="IPv6" if (!IsLimited(NET_IPV4)) NewThread(ThreadGetMyExternalIP, NULL); } void StartNode(void* parg) { // Make this thread recognisable as the startup thread RenameThread("bitluckcoin-start"); if (semOutbound == NULL) { // initialize semaphore int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125)); semOutbound = new CSemaphore(nMaxOutbound); } if (pnodeLocalHost == NULL) pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices)); Discover(); // // Start threads // if (!GetBoolArg("-dnsseed", true)) printf("DNS seeding disabled\n"); else if (!NewThread(ThreadDNSAddressSeed, NULL)) printf("Error: NewThread(ThreadDNSAddressSeed) failed\n"); // Map ports with UPnP if (fUseUPnP) MapPort(); // Get addresses from IRC and advertise ours if (!NewThread(ThreadIRCSeed, NULL)) printf("Error: NewThread(ThreadIRCSeed) failed\n"); // Send and receive from sockets, accept connections if (!NewThread(ThreadSocketHandler, NULL)) printf("Error: NewThread(ThreadSocketHandler) failed\n"); // Initiate outbound connections from -addnode if (!NewThread(ThreadOpenAddedConnections, NULL)) printf("Error: NewThread(ThreadOpenAddedConnections) failed\n"); // Initiate outbound connections if (!NewThread(ThreadOpenConnections, NULL)) printf("Error: NewThread(ThreadOpenConnections) failed\n"); // Process messages if (!NewThread(ThreadMessageHandler, NULL)) printf("Error: NewThread(ThreadMessageHandler) failed\n"); // Dump network addresses if (!NewThread(ThreadDumpAddress, NULL)) printf("Error; NewThread(ThreadDumpAddress) failed\n"); // Mine proof-of-stake blocks in the background if (!GetBoolArg("-staking", true)) printf("Staking disabled\n"); else if (!NewThread(ThreadStakeMiner, pwalletMain)) printf("Error: NewThread(ThreadStakeMiner) failed\n"); } bool StopNode() { printf("StopNode()\n"); fShutdown = true; nTransactionsUpdated++; int64_t nStart = GetTime(); if (semOutbound) for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++) semOutbound->post(); do { int nThreadsRunning = 0; for (int n = 0; n < THREAD_MAX; n++) nThreadsRunning += vnThreadsRunning[n]; if (nThreadsRunning == 0) break; if (GetTime() - nStart > 20) break; MilliSleep(20); } while(true); if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n"); if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n"); if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n"); if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n"); if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n"); #ifdef USE_UPNP if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n"); #endif if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n"); if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n"); if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n"); if (vnThreadsRunning[THREAD_STAKE_MINER] > 0) printf("ThreadStakeMiner still running\n"); while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0) MilliSleep(20); MilliSleep(50); DumpAddresses(); return true; } class CNetCleanup { public: CNetCleanup() { } ~CNetCleanup() { // Close sockets BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->hSocket != INVALID_SOCKET) closesocket(pnode->hSocket); BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) if (hListenSocket != INVALID_SOCKET) if (closesocket(hListenSocket) == SOCKET_ERROR) printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError()); #ifdef WIN32 // Shutdown Windows Sockets WSACleanup(); #endif } } instance_of_cnetcleanup; void RelayTransaction(const CTransaction& tx, const uint256& hash) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(10000); ss << tx; RelayTransaction(tx, hash, ss); } void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss) { CInv inv(MSG_TX, hash); { LOCK(cs_mapRelay); // Expire old relay messages while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) { mapRelay.erase(vRelayExpiration.front().second); vRelayExpiration.pop_front(); } // Save original serialized message so newer versions are preserved mapRelay.insert(std::make_pair(inv, ss)); vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv)); } RelayInventory(inv); }
[ "bitluckdev@gmail.com" ]
bitluckdev@gmail.com
6eda9a997bd30334329321571b7073495544137d
16caad6ae23609e5f9bdf9cc7a568db6bfd4c57d
/src/coreclr/vm/nativeimage.cpp
777ab182ee8f66481c65867347562eda8980ea13
[ "MIT" ]
permissive
Emmy96/runtime
eae07c6d6e23a54802f5df2e0d278136e1d043da
6527f540e4b50bc84eb72705f80d3f2bdd57473b
refs/heads/main
2023-09-05T00:31:29.490643
2021-11-03T04:27:34
2021-11-03T04:27:34
424,103,302
1
0
NOASSERTION
2021-11-03T05:33:36
2021-11-03T05:33:35
null
UTF-8
C++
false
false
12,403
cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // -------------------------------------------------------------------------------- // NativeImage.cpp // // -------------------------------------------------------------------------------- #include "common.h" #include "nativeimage.h" // -------------------------------------------------------------------------------- // Headers // -------------------------------------------------------------------------------- #include <shlwapi.h> BOOL AssemblyNameIndexHashTraits::Equals(LPCUTF8 a, LPCUTF8 b) { WRAPPER_NO_CONTRACT; return SString(SString::Utf8Literal, a).CompareCaseInsensitive(SString(SString::Utf8Literal, b)) == 0; } AssemblyNameIndexHashTraits::count_t AssemblyNameIndexHashTraits::Hash(LPCUTF8 s) { WRAPPER_NO_CONTRACT; return SString(SString::Utf8Literal, s).HashCaseInsensitive(); } BOOL NativeImageIndexTraits::Equals(LPCUTF8 a, LPCUTF8 b) { WRAPPER_NO_CONTRACT; return SString(SString::Utf8Literal, a).CompareCaseInsensitive(SString(SString::Utf8Literal, b)) == 0; } NativeImageIndexTraits::count_t NativeImageIndexTraits::Hash(LPCUTF8 a) { WRAPPER_NO_CONTRACT; return SString(SString::Utf8Literal, a).HashCaseInsensitive(); } NativeImage::NativeImage(AssemblyBinder *pAssemblyBinder, PEImageLayout *pImageLayout, LPCUTF8 imageFileName) : m_eagerFixupsLock(CrstNativeImageEagerFixups) { CONTRACTL { THROWS; CONSTRUCTOR_CHECK; STANDARD_VM_CHECK; INJECT_FAULT(COMPlusThrowOM();); } CONTRACTL_END; m_pAssemblyBinder = pAssemblyBinder; m_pImageLayout = pImageLayout; m_fileName = imageFileName; m_eagerFixupsHaveRun = false; } void NativeImage::Initialize(READYTORUN_HEADER *pHeader, LoaderAllocator *pLoaderAllocator, AllocMemTracker *pamTracker) { LoaderHeap *pHeap = pLoaderAllocator->GetHighFrequencyHeap(); m_pReadyToRunInfo = new ReadyToRunInfo(/*pModule*/ NULL, pLoaderAllocator, m_pImageLayout, pHeader, /*compositeImage*/ NULL, pamTracker); m_pComponentAssemblies = m_pReadyToRunInfo->FindSection(ReadyToRunSectionType::ComponentAssemblies); m_pComponentAssemblyMvids = m_pReadyToRunInfo->FindSection(ReadyToRunSectionType::ManifestAssemblyMvids); m_componentAssemblyCount = m_pComponentAssemblies->Size / sizeof(READYTORUN_COMPONENT_ASSEMBLIES_ENTRY); // Check if the current module's image has native manifest metadata, otherwise the current->GetNativeAssemblyImport() asserts. m_pManifestMetadata = LoadManifestMetadata(); HENUMInternal assemblyEnum; HRESULT hr = m_pManifestMetadata->EnumAllInit(mdtAssemblyRef, &assemblyEnum); mdAssemblyRef assemblyRef; m_manifestAssemblyCount = 0; while (m_pManifestMetadata->EnumNext(&assemblyEnum, &assemblyRef)) { LPCSTR assemblyName; hr = m_pManifestMetadata->GetAssemblyRefProps(assemblyRef, NULL, NULL, &assemblyName, NULL, NULL, NULL, NULL); m_assemblySimpleNameToIndexMap.Add(AssemblyNameIndex(assemblyName, m_manifestAssemblyCount)); m_manifestAssemblyCount++; } // When a composite image contributes to a larger version bubble, its manifest assembly // count may exceed its component assembly count as it may contain references to // assemblies outside of the composite image that are part of its version bubble. _ASSERTE(m_manifestAssemblyCount >= m_componentAssemblyCount); S_SIZE_T dwAllocSize = S_SIZE_T(sizeof(PTR_Assembly)) * S_SIZE_T(m_manifestAssemblyCount); // Note: Memory allocated on loader heap is zero filled m_pNativeMetadataAssemblyRefMap = (PTR_Assembly*)pamTracker->Track(pLoaderAllocator->GetLowFrequencyHeap()->AllocMem(dwAllocSize)); } NativeImage::~NativeImage() { STANDARD_VM_CONTRACT; delete m_pReadyToRunInfo; delete m_pImageLayout; if (m_pManifestMetadata != NULL) { m_pManifestMetadata->Release(); } } #ifndef DACCESS_COMPILE NativeImage *NativeImage::Open( Module *componentModule, LPCUTF8 nativeImageFileName, AssemblyBinder *pAssemblyBinder, LoaderAllocator *pLoaderAllocator, /* out */ bool *isNewNativeImage) { STANDARD_VM_CONTRACT; NativeImage *pExistingImage = AppDomain::GetCurrentDomain()->GetNativeImage(nativeImageFileName); if (pExistingImage != nullptr) { *isNewNativeImage = false; return pExistingImage->GetAssemblyBinder() == pAssemblyBinder ? pExistingImage : nullptr; } SString path = componentModule->GetPath(); SString::Iterator lastPathSeparatorIter = path.End(); size_t pathDirLength = 0; if (PEAssembly::FindLastPathSeparator(path, lastPathSeparatorIter)) { pathDirLength = (lastPathSeparatorIter - path.Begin()) + 1; } SString compositeImageFileName(SString::Utf8, nativeImageFileName); SString fullPath; fullPath.Set(path, path.Begin(), (COUNT_T)pathDirLength); fullPath += compositeImageFileName; LPWSTR searchPathsConfig; IfFailThrow(CLRConfig::GetConfigValue(CLRConfig::INTERNAL_NativeImageSearchPaths, &searchPathsConfig)); PEImageLayoutHolder peLoadedImage; BundleFileLocation bundleFileLocation = Bundle::ProbeAppBundle(fullPath, /*pathIsBundleRelative */ true); if (bundleFileLocation.IsValid()) { // No need to use cache for this PE image. // Composite r2r PE image is not a part of anyone's identity. // We only need it to obtain the native image, which will be cached at AppDomain level. PEImageHolder pImage = PEImage::OpenImage(fullPath, MDInternalImport_NoCache, bundleFileLocation); PEImageLayout* mapped = pImage->GetOrCreateLayout(PEImageLayout::LAYOUT_MAPPED); // We will let pImage instance be freed after exiting this scope, but we will keep the layout, // thus the layout needs an AddRef, or it will be gone together with pImage. mapped->AddRef(); peLoadedImage = mapped; } if (peLoadedImage.IsNull()) { EX_TRY { peLoadedImage = PEImageLayout::LoadNative(fullPath); } EX_CATCH { SString searchPaths(searchPathsConfig); SString::CIterator start = searchPaths.Begin(); while (start != searchPaths.End()) { SString::CIterator end = start; if (!searchPaths.Find(end, PATH_SEPARATOR_CHAR_W)) { end = searchPaths.End(); } fullPath.Set(searchPaths, start, (COUNT_T)(end - start)); if (end != searchPaths.End()) { // Skip path separator character ++end; } start = end; if (fullPath.GetCount() == 0) { continue; } fullPath.Append(DIRECTORY_SEPARATOR_CHAR_W); fullPath += compositeImageFileName; EX_TRY { peLoadedImage = PEImageLayout::LoadNative(fullPath); break; } EX_CATCH { } EX_END_CATCH(SwallowAllExceptions) } } EX_END_CATCH(SwallowAllExceptions) if (peLoadedImage.IsNull()) { // Failed to locate the native composite R2R image LOG((LF_LOADER, LL_ALWAYS, "LOADER: failed to load native image '%s' for component assembly '%S' using search paths: '%S'\n", nativeImageFileName, path.GetUnicode(), searchPathsConfig != nullptr ? searchPathsConfig : W("<use COMPlus_NativeImageSearchPaths to set>"))); RaiseFailFastException(nullptr, nullptr, 0); } } READYTORUN_HEADER *pHeader = (READYTORUN_HEADER *)peLoadedImage->GetExport("RTR_HEADER"); if (pHeader == NULL) { COMPlusThrowHR(COR_E_BADIMAGEFORMAT); } if (pHeader->Signature != READYTORUN_SIGNATURE) { COMPlusThrowHR(COR_E_BADIMAGEFORMAT); } if (pHeader->MajorVersion < MINIMUM_READYTORUN_MAJOR_VERSION || pHeader->MajorVersion > READYTORUN_MAJOR_VERSION) { COMPlusThrowHR(COR_E_BADIMAGEFORMAT); } NewHolder<NativeImage> image = new NativeImage(pAssemblyBinder, peLoadedImage.Extract(), nativeImageFileName); AllocMemTracker amTracker; image->Initialize(pHeader, pLoaderAllocator, &amTracker); pExistingImage = AppDomain::GetCurrentDomain()->SetNativeImage(nativeImageFileName, image); if (pExistingImage == nullptr) { // No pre-existing image, new image has been stored in the map *isNewNativeImage = true; amTracker.SuppressRelease(); return image.Extract(); } // Return pre-existing image if it was loaded into the same ALC, null otherwise *isNewNativeImage = false; return (pExistingImage->GetAssemblyBinder() == pAssemblyBinder ? pExistingImage : nullptr); } #endif #ifndef DACCESS_COMPILE Assembly *NativeImage::LoadManifestAssembly(uint32_t rowid, DomainAssembly *pParentAssembly) { STANDARD_VM_CONTRACT; AssemblySpec spec; spec.InitializeSpec(TokenFromRid(rowid, mdtAssemblyRef), m_pManifestMetadata, pParentAssembly); return spec.LoadAssembly(FILE_LOADED); } #endif #ifndef DACCESS_COMPILE PTR_READYTORUN_CORE_HEADER NativeImage::GetComponentAssemblyHeader(LPCUTF8 simpleName) { STANDARD_VM_CONTRACT; const AssemblyNameIndex *assemblyNameIndex = m_assemblySimpleNameToIndexMap.LookupPtr(simpleName); if (assemblyNameIndex != NULL) { const BYTE *pImageBase = (const BYTE *)m_pImageLayout->GetBase(); const READYTORUN_COMPONENT_ASSEMBLIES_ENTRY *componentAssembly = (const READYTORUN_COMPONENT_ASSEMBLIES_ENTRY *)&pImageBase[m_pComponentAssemblies->VirtualAddress] + assemblyNameIndex->Index; return (PTR_READYTORUN_CORE_HEADER)&pImageBase[componentAssembly->ReadyToRunCoreHeader.VirtualAddress]; } return NULL; } #endif #ifndef DACCESS_COMPILE void NativeImage::CheckAssemblyMvid(Assembly *assembly) const { STANDARD_VM_CONTRACT; if (m_pComponentAssemblyMvids == NULL) { return; } const AssemblyNameIndex *assemblyNameIndex = m_assemblySimpleNameToIndexMap.LookupPtr(assembly->GetSimpleName()); if (assemblyNameIndex == NULL) { return; } GUID assemblyMvid; assembly->GetManifestImport()->GetScopeProps(NULL, &assemblyMvid); const byte *pImageBase = (const BYTE *)m_pImageLayout->GetBase(); const GUID *componentMvid = (const GUID *)&pImageBase[m_pComponentAssemblyMvids->VirtualAddress] + assemblyNameIndex->Index; if (IsEqualGUID(*componentMvid, assemblyMvid)) { return; } static const size_t MVID_TEXT_LENGTH = 39; WCHAR assemblyMvidText[MVID_TEXT_LENGTH]; StringFromGUID2(assemblyMvid, assemblyMvidText, MVID_TEXT_LENGTH); WCHAR componentMvidText[MVID_TEXT_LENGTH]; StringFromGUID2(*componentMvid, componentMvidText, MVID_TEXT_LENGTH); SString message; message.Printf(W("MVID mismatch between loaded assembly '%s' (MVID = %s) and an assembly with the same simple name embedded in the native image '%s' (MVID = %s)"), SString(SString::Utf8, assembly->GetSimpleName()).GetUnicode(), assemblyMvidText, SString(SString::Utf8, GetFileName()).GetUnicode(), componentMvidText); EEPOLICY_HANDLE_FATAL_ERROR_WITH_MESSAGE(COR_E_FAILFAST, message.GetUnicode()); } #endif #ifndef DACCESS_COMPILE IMDInternalImport *NativeImage::LoadManifestMetadata() { STANDARD_VM_CONTRACT; IMAGE_DATA_DIRECTORY *pMeta = m_pReadyToRunInfo->FindSection(ReadyToRunSectionType::ManifestMetadata); if (pMeta == NULL) { return NULL; } IMDInternalImport *pNewImport = NULL; IfFailThrow(GetMetaDataInternalInterface((BYTE *)m_pImageLayout->GetBase() + VAL32(pMeta->VirtualAddress), VAL32(pMeta->Size), ofRead, IID_IMDInternalImport, (void **) &pNewImport)); return pNewImport; } #endif
[ "noreply@github.com" ]
noreply@github.com
2fdc588844b993d88516851a268e21f12d7766ad
31acc88f8baac2099cc18fa58752e3deb4f76bc5
/serialPort/serial.cpp
3850d38d145537fdb8f887954456893d4225aa9d
[]
no_license
HackerTheWorld/serialPort
859eb52da68f7ae43bee725fd0cd436e55afbdc0
31101d6ff35cafd307085a5a5ca1a9dd639d7ea7
refs/heads/master
2020-04-07T11:17:00.347249
2018-11-20T02:35:02
2018-11-20T02:35:02
158,319,786
0
0
null
null
null
null
UTF-8
C++
false
false
3,216
cpp
// // serial.cpp // serialPort // // Created by apple on 2018/11/19. // Copyright © 2018 apple. All rights reserved. // #include "serial.hpp" int SerialPorts::OpenDev(char* Dev){ int fd = open( Dev, O_RDWR | O_NOCTTY ); //| O_NOCTTY | O_NDELAY if (-1 == fd) { perror("Can't Open Serial Port"); return -1; } else return fd; }; void SerialPorts::set_speed(int fd, int speed){ int i; int status; struct termios Opt; tcgetattr(fd, &Opt); for ( i= 0; i < sizeof(speed_arr) / sizeof(int); i++) { if (speed == name_arr[i]) { tcflush(fd, TCIOFLUSH); cfsetispeed(&Opt, speed_arr[i]); cfsetospeed(&Opt, speed_arr[i]); status = tcsetattr(fd, TCSANOW, &Opt); if (status != 0) { perror("tcsetattr fd1"); return; } tcflush(fd,TCIOFLUSH); } } } int SerialPorts::set_Parity(int fd,int databits,int stopbits,int parity) { struct termios options; options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); /*Input*/ options.c_oflag &= ~OPOST; /*Output*/ if ( tcgetattr( fd,&options) != 0) { perror("SetupSerial 1"); return(FALSE); } options.c_cflag &= ~CSIZE; switch (databits) /*设置数据位数*/ { case 7: options.c_cflag |= CS7; break; case 8: options.c_cflag |= CS8; break; default: fprintf(stderr,"Unsupported data size/n"); return (FALSE); } switch (parity) { case 'n': case 'N': options.c_cflag &= ~PARENB; /* Clear parity enable */ options.c_iflag &= ~INPCK; /* Enable parity checking */ break; case 'o': case 'O': options.c_cflag |= (PARODD | PARENB); /* 设置为奇效验*/ options.c_iflag |= INPCK; /* Disnable parity checking */ break; case 'e': case 'E': options.c_cflag |= PARENB; /* Enable parity */ options.c_cflag &= ~PARODD; /* 转换为偶效验*/ options.c_iflag |= INPCK; /* Disnable parity checking */ break; case 'S': case 's': /*as no parity*/ options.c_cflag &= ~PARENB; options.c_cflag &= ~CSTOPB;break; default: fprintf(stderr,"Unsupported parity/n"); return (FALSE); } /* 设置停止位*/ switch (stopbits) { case 1: options.c_cflag &= ~CSTOPB; break; case 2: options.c_cflag |= CSTOPB; break; default: fprintf(stderr,"Unsupported stop bits/n"); return (FALSE); } /* Set input parity option */ if (parity != 'n') options.c_iflag |= INPCK; tcflush(fd,TCIFLUSH); options.c_cc[VTIME] = 150; /* 设置超时15 seconds*/ options.c_cc[VMIN] = 0; /* Update the options and do it NOW */ if (tcsetattr(fd,TCSANOW,&options) != 0) { perror("SetupSerial 3"); return (FALSE); } return (TRUE); }
[ "gc_xuankui@gagc.tv" ]
gc_xuankui@gagc.tv
8e9bb789b14b8a2f576fc237c06bd6f34f22dbcb
0a52dc6c4d730fd70f874beae4bd18d06346d1c7
/RingBufferTest/Main.cpp
e1ff9001d8572db59092f4e4ffa6668833825935
[]
no_license
stargate2718/guruguru
29f468edb1874052bc6dd2726152a5b0e0bd0f1e
38d59827348f26f2feae981e961ea700b8264f28
refs/heads/master
2021-01-19T21:12:40.370157
2017-06-03T12:21:27
2017-06-03T12:21:27
88,625,208
0
0
null
null
null
null
UTF-8
C++
false
false
476
cpp
#include <iostream> #include "RingBuffer.h" int main(int argc, char* argv[]) { RingBuffer<std::string, 5> rb; std::string str; rb.enqueue("taro"); rb.enqueue("jiro"); rb.enqueue("hanako"); rb.enqueue("saburo"); rb.dequeue(&str); rb.enqueue("hikaru"); rb.enqueue("tsubasa"); rb.dequeue(&str); rb.enqueue("makoto"); rb.enqueue("natsumi"); while (rb.dequeue(&str) == 0) { std::cout << str.c_str() << std::endl; } std::cin.sync(), std::cin.get(); return 0; }
[ "star.gate.2718@gmail.com" ]
star.gate.2718@gmail.com
8d78bf7bc22d2065705e45220f092b352b6c6cfd
72d5aa0ec4b9077f2dd22c6d53944edbda3ac076
/Project/Project.ino
0396089711291c4da2ceeb9a64227c0d88a5c66e
[]
no_license
KadarTibor/ArduinoNintendoController
731fefb8013bc6d66f83721cf20963ccecbd7240
b8cfea72b1361a9212b2001908a095d3963ec6bb
refs/heads/master
2021-09-04T00:53:46.134946
2018-01-13T16:44:42
2018-01-13T16:44:42
115,626,826
0
0
null
null
null
null
UTF-8
C++
false
false
1,464
ino
#include <SoftwareSerial.h>// import the serial library SoftwareSerial bluetoothSerial(10, 11); // RX, TX int ledPin=13; // led on D13 will show blink on / off int BluetoothData; // the data given from Computer int buttonPin[] = {2,3,4,5,6,7}; String buttonMessage[] = {"left","up","down","right","select","back"}; unsigned long lastSampleTime[] = {0,0,0,0,0,0}; int buttonPreviousState[] = {0,0,0,0,0,0}; int buttonState[] = {0,0,0,0,0,0}; unsigned long currentTime = 0; void setup() { bluetoothSerial.begin(9600); //bluetoothSerial.println("Bluetooth On please press 1 or 0 blink LED .."); pinMode(ledPin,OUTPUT); for(int i = 0; i < 6; i++){ pinMode(buttonPin[i], INPUT); } check_connection(); } void loop() { handle_button_press(); } void check_connection(){ while(!bluetoothSerial.available()); BluetoothData=bluetoothSerial.read(); if(BluetoothData=='1'){ // if number 1 pressed .... digitalWrite(ledPin,HIGH); bluetoothSerial.println("Connected"); } } void handle_button_press(){ for(int i = 0; i < 6; i++){ currentTime = millis(); if(currentTime - lastSampleTime[i] >= 50){ buttonState[i] = digitalRead(buttonPin[i]); if(buttonState[i] == 1 && buttonPreviousState[i] == 0){ bluetoothSerial.println(buttonMessage[i]); } buttonPreviousState[i] = buttonState[i]; lastSampleTime[i] = currentTime; } } }
[ "kadartibor24@gmail.com" ]
kadartibor24@gmail.com
6ba28cbecd9419cd2a8e00039086d385fd1d3229
a5299edfc0d5d82d936e59111e7765e9a2dcfac9
/InterviewQuestions.h
aa90496e6afabcaa0219823f22ceb1d038bad8e2
[]
no_license
brandon-irl/EulerAndOtherProblems
d787de243c5ebad32edc851ce5980b46cde5f035
abeb31cd3750d54dae7cbe60189897eec239f930
refs/heads/master
2021-05-30T20:34:49.556698
2015-11-25T15:50:09
2015-11-25T15:50:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
200
h
#ifndef __InterviewQuestions_H_INCLUDED__ #define __InterviewQuestions_H_INCLUDED__ #pragma once class InterviewQuestions { public: InterviewQuestions(); ~InterviewQuestions(); }; #endif
[ "haxard10@hotmail.com" ]
haxard10@hotmail.com
169506c98b2249a77e6c489d048e95397fed81a7
6f2ed6b34af4cf1442d6fcbc4d09952dca729a28
/stream_util.cpp
c8599e6add4ae186c214061adf396fe34ccc35d1
[]
no_license
xibeilang524/rtp
400eb018310c13f05826e45d507a2c42805ec57d
70b0220293a394dbb16d0cce73a321a6257fb741
refs/heads/master
2022-02-26T17:26:32.594225
2019-09-14T12:55:16
2019-09-14T12:55:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,334
cpp
// // Created by hijiang on 2019/8/4. // #include <assert.h> #include "stream_util.h" using namespace std; StreamUtil::StreamUtil() { p = bytes = NULL; nb_bytes = 0; // TODO: support both little and big endian. // assert(srs_is_little_endian()); } StreamUtil::~StreamUtil() { } int StreamUtil::initialize(char* b, int nb) { int ret = 0; if (!b) { ret = -1; return ret; } if (nb <= 0) { ret = -2; return ret; } nb_bytes = nb; p = bytes = b; return ret; } char* StreamUtil::data() { return bytes; } int StreamUtil::size() { return nb_bytes; } int StreamUtil::pos() { return (int)(p - bytes); } int StreamUtil::left() { return nb_bytes - (int)(p-bytes); } bool StreamUtil::empty() { return !bytes || (p >= bytes + nb_bytes); } bool StreamUtil::require(int required_size) { return required_size <= nb_bytes - (p - bytes); } void StreamUtil::skip(int size) { p += size; } int8_t StreamUtil::read_1bytes() { return (int8_t)*p++; } int16_t StreamUtil::read_2bytes() { int16_t value; char* pp = (char*)&value; pp[1] = *p++; pp[0] = *p++; return value; } int32_t StreamUtil::read_3bytes() { int32_t value = 0x00; char* pp = (char*)&value; pp[2] = *p++; pp[1] = *p++; pp[0] = *p++; return value; } int32_t StreamUtil::read_4bytes() { int32_t value; char* pp = (char*)&value; pp[3] = *p++; pp[2] = *p++; pp[1] = *p++; pp[0] = *p++; return value; } int64_t StreamUtil::read_8bytes() { int64_t value; char* pp = (char*)&value; pp[7] = *p++; pp[6] = *p++; pp[5] = *p++; pp[4] = *p++; pp[3] = *p++; pp[2] = *p++; pp[1] = *p++; pp[0] = *p++; return value; } string StreamUtil::read_string(int len) { std::string value; value.append(p, len); p += len; return value; } void StreamUtil::read_bytes(char* data, int size) { memcpy(data, p, size); p += size; } void StreamUtil::write_1bytes(int8_t value) { assert(require(1)); *p++ = value; } void StreamUtil::write_2bytes(int16_t value) { assert(require(2)); char* pp = (char*)&value; *p++ = pp[1]; *p++ = pp[0]; } void StreamUtil::write_4bytes(int32_t value) { assert(require(4)); char* pp = (char*)&value; *p++ = pp[3]; *p++ = pp[2]; *p++ = pp[1]; *p++ = pp[0]; } void StreamUtil::write_3bytes(int32_t value) { assert(require(3)); char* pp = (char*)&value; *p++ = pp[2]; *p++ = pp[1]; *p++ = pp[0]; } void StreamUtil::write_8bytes(int64_t value) { assert(require(8)); char* pp = (char*)&value; *p++ = pp[7]; *p++ = pp[6]; *p++ = pp[5]; *p++ = pp[4]; *p++ = pp[3]; *p++ = pp[2]; *p++ = pp[1]; *p++ = pp[0]; } void StreamUtil::write_string(string value) { assert(require((int)value.length())); memcpy(p, value.data(), value.length()); p += value.length(); } void StreamUtil::write_bytes(char* data, int size) { assert(require(size)); memcpy(p, data, size); p += size; }
[ "noreply@github.com" ]
noreply@github.com
37d607d52f8d1584223401d693ba4c198f79673d
c98f6ab0ae2b579432ca24c4bbbabceba1320a44
/C++ Assignment_2/RuelasCastillo_A2_P4/RuelasCastillo_A2P4/Source.cpp
7b8802d854693f55242bd26cf9a81bcd7b3bdb04
[]
no_license
isaacruelas68/isaacruelas68-Assignment-2-programs
60d8bae61ddfe28b3154f35539947cdd04caa473
4fdea38bdbb85b41dddda8b3bf223a28cf34893e
refs/heads/master
2021-04-05T22:43:09.531235
2020-03-19T23:15:25
2020-03-19T23:15:25
248,609,240
0
0
null
null
null
null
UTF-8
C++
false
false
1,133
cpp
//ISAAC RUELAS CASTILLO ASSIGNMENT 2 PROBLEM 4 #include<iostream> using namespace std; //prototypes void Decoder(char c[], int key); int main() { char code[] = { ",vtaNm a_\"dabp!!" }; int key = 1; Decoder(code, key); } void Decoder(char c[],int key) { char copy[16]; char temp[4]; char* letters; int* num; int size = 4; int index = 0; int start = 0; while (key < 501) { for (int length = 0; length < 16; length++)//this copies the c array to copy copy[length] = c[length]; for (int run = 0; run < 4; run++)//this runs four times and breaks the 16 char word into bit { for (int zero = 0; zero < size; zero++)//this saves copy to a temp array { temp[zero] = copy[index]; index++; } num = (int*)temp;//this code transfers the temp array to int and then back to a char *num = *num - key; letters = (char*)num; for(int p=0;p<sizeof(temp);p++,start++) copy[start] = letters[p]; } for (int p = 0; p < 16; p++)//this loop prints out the changed array. { cout << copy[p]; } cout << " key is: " << key << endl; key++; index = 0; start = 0; } }
[ "isaacruelas68@yahoo.com" ]
isaacruelas68@yahoo.com
2e0aef29611bb1ae3a69bb9de485db0c41d4fd4f
197ac8fea464120ff28fded1334c2f7aa2663629
/Clientes.cpp
8ff9be43ef5962d85bb9a38466bef8fac11ae47d
[]
no_license
moises1747/Programacion
6f4a33d8aff19fc23211b85f343eff7609ec15fa
c136c1767110df207c2b1521a7e9f27a47d2f3e4
refs/heads/master
2020-03-14T13:41:29.557795
2018-04-30T19:38:55
2018-04-30T19:38:55
131,637,998
0
0
null
null
null
null
UTF-8
C++
false
false
429
cpp
#include "Clientes.h" #include <iostream> #include <string.h> using namespace std; //SE DEBE CREAR SIEMPRE LOS METODOS QUE SE COLOQUEN EN EL .H Clientes::Clientes() { strcpy(nombre ,""); strcpy(apellido ,""); } Clientes::Clientes(char * _nombre, char * _apellido) { strcpy(nombre, _nombre); strcpy(apellido, _apellido); } void Clientes::mostrarDatos() { cout<<"Moises "<<nombre; cout<<endl<<"Leal "<<apellido<<endl; }
[ "moises.leals@labcomp.unet.edu.ve" ]
moises.leals@labcomp.unet.edu.ve
0e1518796812f34e625f8f79a93f3f78a9f25d0c
a52aedb1544d7d15a3ddd8da50e289be45f41e40
/cpp work/2_Shibaji_paul/25_remove_if_and_functor.cpp
f533b8f0c3db8a5a6195414b56dec213484d7a2c
[]
no_license
SI-Tanbir/my_code
e3e0acdfdf00b506924bce7d85d29bc8f20eed8d
fa85aa3c2bf3dd1eb5c26df9590b2b59dd5e4ad5
refs/heads/main
2023-07-11T18:53:39.897700
2021-08-27T06:57:29
2021-08-27T06:57:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
979
cpp
//date: 2021-04-08 #include <bits/stdc++.h> #include <algorithm> //for count_fuction using namespace std; #define ullint unsigned long long int class functor_odd { public: bool operator()(int val) { return val % 2 != 0; } }; class functor_even { public: bool operator()(int val) { return val % 2 == 0; } }; void displayVector(vector<int> &v) { cout << "content of the vector is :" << endl; for (auto it = v.begin(); it != v.end(); it++) { cout << *it << " , "; } cout << endl; } int main() { vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; // criteria_functor_even func_obj1(7, 13); // int count1 = count_if(v.begin(), v.end(), functor_odd()); // cout << "Total even integers in the vector " << count1 << endl; displayVector(v); auto it = remove_if(v.begin(), v.end(), functor_odd()); displayVector(v); v.erase(it, v.end()); displayVector(v); return 0; }
[ "sk470004@gmail.com" ]
sk470004@gmail.com
eb2e6bc0f5ab371b77dc211582d01754758168e8
e010cb49958efcb775ab87142a296e91db69cd9c
/my_hello/libprocess_learning/collect_tests.cpp
f03b8dbd9793207da893b83b8f9b380c87a596f9
[]
no_license
lilelr/libprocess-start
8949fd704edc80092fd53f68b0ea80def84300af
62324ebba88582415e25471665e961d06c60a601
refs/heads/master
2021-06-24T16:39:10.757462
2020-10-17T05:03:17
2020-10-17T05:03:17
146,831,757
0
0
null
null
null
null
UTF-8
C++
false
false
5,673
cpp
// 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 #include <gtest/gtest.h> #include <gmock/gmock.h> #include <process/collect.hpp> #include <process/gtest.hpp> #include <stout/gtest.hpp> using process::Future; using process::Promise; using std::list; TEST(CollectTest, Ready) { // First ensure an empty list functions correctly. list<Future<int>> empty; Future<list<int>> collect = process::collect(empty); AWAIT_READY(collect); EXPECT_TRUE(collect.get().empty()); Promise<int> promise1; Promise<int> promise2; Promise<int> promise3; Promise<int> promise4; list<Future<int>> futures; futures.push_back(promise1.future()); futures.push_back(promise2.future()); futures.push_back(promise3.future()); futures.push_back(promise4.future()); // Set them out-of-order. promise4.set(4); promise2.set(2); promise1.set(1); promise3.set(3); collect = process::collect(futures); AWAIT_ASSERT_READY(collect); list<int> values; values.push_back(1); values.push_back(2); values.push_back(3); values.push_back(4); // We expect them to be returned in the same order as the // future list that was passed in. EXPECT_EQ(values, collect.get()); } TEST(CollectTest, Failure) { Promise<int> promise1; Promise<bool> promise2; Future<std::tuple<int, bool>> collect = process::collect(promise1.future(), promise2.future()); ASSERT_TRUE(collect.isPending()); promise1.set(42); ASSERT_TRUE(collect.isPending()); promise2.set(true); AWAIT_READY(collect); std::tuple<int, bool> values = collect.get(); ASSERT_EQ(42, std::get<0>(values)); ASSERT_TRUE(std::get<1>(values)); // Collect should fail when a future fails. Promise<bool> promise3; collect = process::collect(promise1.future(), promise3.future()); ASSERT_TRUE(collect.isPending()); promise3.fail("failure"); AWAIT_FAILED(collect); // Collect should fail when a future is discarded. Promise<bool> promise4; collect = process::collect(promise1.future(), promise4.future()); ASSERT_TRUE(collect.isPending()); promise4.discard(); AWAIT_FAILED(collect); } TEST(CollectTest, DiscardPropagation) { Future<int> future1; Future<bool> future2; future1 .onDiscard([=](){ process::internal::discarded(future1); }); future2 .onDiscard([=](){ process::internal::discarded(future2); }); Future<std::tuple<int, bool>> collect = process::collect(future1, future2); collect.discard(); AWAIT_DISCARDED(future1); AWAIT_DISCARDED(future2); } TEST(AwaitTest, Success) { // First ensure an empty list functions correctly. list<Future<int>> empty; Future<list<Future<int>>> future = process::await(empty); AWAIT_ASSERT_READY(future); EXPECT_TRUE(future.get().empty()); Promise<int> promise1; Promise<int> promise2; Promise<int> promise3; Promise<int> promise4; list<Future<int>> futures; futures.push_back(promise1.future()); futures.push_back(promise2.future()); futures.push_back(promise3.future()); futures.push_back(promise4.future()); // Set them out-of-order. promise4.set(4); promise2.set(2); promise1.set(1); promise3.set(3); future = process::await(futures); AWAIT_ASSERT_READY(future); EXPECT_EQ(futures.size(), future.get().size()); // We expect them to be returned in the same order as the // future list that was passed in. int i = 1; foreach (const Future<int>& result, future.get()) { ASSERT_TRUE(result.isReady()); ASSERT_EQ(i, result.get()); ++i; } } TEST(AwaitTest, Failure) { Promise<int> promise1; Promise<bool> promise2; Future<std::tuple<Future<int>, Future<bool>>> await = process::await(promise1.future(), promise2.future()); ASSERT_TRUE(await.isPending()); promise1.set(42); ASSERT_TRUE(await.isPending()); promise2.fail("failure message"); AWAIT_READY(await); std::tuple<Future<int>, Future<bool>> futures = await.get(); ASSERT_TRUE(std::get<0>(futures).isReady()); ASSERT_EQ(42, std::get<0>(futures).get()); ASSERT_TRUE(std::get<1>(futures).isFailed()); } TEST(AwaitTest, Discarded) { Promise<int> promise1; Promise<bool> promise2; Future<std::tuple<Future<int>, Future<bool>>> await = process::await(promise1.future(), promise2.future()); ASSERT_TRUE(await.isPending()); promise1.set(42); ASSERT_TRUE(await.isPending()); promise2.discard(); AWAIT_READY(await); std::tuple<Future<int>, Future<bool>> futures = await.get(); ASSERT_TRUE(std::get<0>(futures).isReady()); ASSERT_EQ(42, std::get<0>(futures).get()); ASSERT_TRUE(std::get<1>(futures).isDiscarded()); } TEST(AwaitTest, DiscardPropagation) { Future<int> future1; Future<bool> future2; future1 .onDiscard([=](){ process::internal::discarded(future1); }); future2 .onDiscard([=](){ process::internal::discarded(future2); }); Future<std::tuple<Future<int>, Future<bool>>> await = process::await(future1, future2); await.discard(); AWAIT_DISCARDED(future1); AWAIT_DISCARDED(future2); } int main(int argc, char** argv) { // Initialize Google Mock/Test. testing::InitGoogleMock(&argc, argv); return RUN_ALL_TESTS(); }
[ "lilelr@163.com" ]
lilelr@163.com
179705814f39814bc48bc7d05f5c67f090a15305
318b737f3fe69171f706d2d990c818090ee6afce
/hybridse/src/passes/physical/long_window_optimized.cc
496d69c9aa43f28ae539bd067535a196bb1579df
[ "Apache-2.0" ]
permissive
4paradigm/OpenMLDB
e884c33f62177a70749749bd3b67e401c135f645
a013ba33e4ce131353edc71e27053b1801ffb8f7
refs/heads/main
2023-09-01T02:15:28.821235
2023-08-31T11:42:02
2023-08-31T11:42:02
346,976,717
3,323
699
Apache-2.0
2023-09-14T09:55:44
2021-03-12T07:18:31
C++
UTF-8
C++
false
false
15,271
cc
/* * Copyright 2021 4paradigm * * 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. */ #include "passes/physical/long_window_optimized.h" #include <string> #include <vector> #include "absl/algorithm/container.h" #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "vm/engine.h" #include "vm/physical_op.h" namespace hybridse { namespace passes { static const absl::flat_hash_set<absl::string_view> WHERE_FUNS = { "count_where", "sum_where", "avg_where", "min_where", "max_where", }; LongWindowOptimized::LongWindowOptimized(PhysicalPlanContext* plan_ctx) : TransformUpPysicalPass(plan_ctx) { std::vector<std::string> windows; const auto* options = plan_ctx_->GetOptions(); if (!options) { LOG(ERROR) << "plan_ctx option is empty"; return; } boost::split(windows, options->at(vm::LONG_WINDOWS), boost::is_any_of(",")); for (auto& w : windows) { std::vector<std::string> window_info; boost::split(window_info, w, boost::is_any_of(":")); boost::trim(window_info[0]); long_windows_.insert(window_info[0]); } } bool LongWindowOptimized::Transform(PhysicalOpNode* in, PhysicalOpNode** output) { *output = in; if (vm::kPhysicalOpProject != in->GetOpType()) { return false; } auto project_op = dynamic_cast<vm::PhysicalProjectNode*>(in); if (project_op->project_type_ != vm::kAggregation) { return false; } auto project_aggr_op = dynamic_cast<vm::PhysicalAggregationNode*>(project_op); // TODO(zhanghao): we only support transform PhysicalAggregationNode with one and only one window aggregation op // we may remove this constraint in a later optimization if (!VerifySingleAggregation(project_op)) { LOG(WARNING) << "we only support transform PhysicalAggregationNode with one and only one window aggregation op"; return false; } // this case shouldn't happen as we add the LongWindowOptimized pass only when `long_windows` option exists if (long_windows_.empty()) { LOG(ERROR) << "Long Windows is empty"; return false; } const auto& projects = project_aggr_op->project(); for (size_t i = 0; i < projects.size(); i++) { const auto* expr = projects.GetExpr(i); if (expr->GetExprType() == node::kExprCall) { const auto* call_expr = dynamic_cast<const node::CallExprNode*>(expr); const auto* window = call_expr->GetOver(); if (window == nullptr) continue; // skip ANONYMOUS_WINDOW if (!window->GetName().empty()) { if (long_windows_.count(window->GetName())) { return OptimizeWithPreAggr(project_aggr_op, i, output); } } } } return true; } bool LongWindowOptimized::OptimizeWithPreAggr(vm::PhysicalAggregationNode* in, int idx, PhysicalOpNode** output) { *output = in; if (in->producers()[0]->GetOpType() != vm::kPhysicalOpRequestUnion) { return false; } auto req_union_op = dynamic_cast<vm::PhysicalRequestUnionNode*>(in->producers()[0]); if (!req_union_op->window_unions_.Empty()) { LOG(WARNING) << "Not support optimization of RequestUnionOp with window unions"; return false; } const auto& projects = in->project(); auto orig_data_provider = dynamic_cast<vm::PhysicalDataProviderNode*>(req_union_op->GetProducer(1)); auto aggr_op = dynamic_cast<const node::CallExprNode*>(projects.GetExpr(idx)); auto window = aggr_op->GetOver(); auto s = CheckCallExpr(aggr_op); if (!s.ok()) { LOG(ERROR) << s.status(); return false; } const std::string& db_name = orig_data_provider->GetDb(); const std::string& table_name = orig_data_provider->GetName(); std::string func_name = aggr_op->GetFnDef()->GetName(); std::string aggr_col = ConcatExprList({aggr_op->children_.front()}); std::string filter_col = std::string(s->filter_col_name); std::string partition_col; if (window->GetPartitions()) { partition_col = ConcatExprList(window->GetPartitions()->children_); } else { partition_col = ConcatExprList(req_union_op->window().partition().keys()->children_); } std::string order_col; if (window->GetOrders()) { order_col = ConcatExprList(window->GetOrders()->children_); } else { auto orders = req_union_op->window().sort().orders()->order_expressions(); for (size_t i = 0; i < orders->GetChildNum(); i++) { auto order = dynamic_cast<node::OrderExpression*>(orders->GetChild(i)); if (order == nullptr || order->expr() == nullptr) { LOG(ERROR) << "OrderBy col is empty"; return false; } auto col_ref = dynamic_cast<const node::ColumnRefNode*>(order->expr()); if (!col_ref) { LOG(ERROR) << "OrderBy Col is not ColumnRefNode"; return false; } if (order_col.empty()) { order_col = col_ref->GetColumnName(); } else { order_col = absl::StrCat(order_col, ",", col_ref->GetColumnName()); } } } auto table_infos = catalog_->GetAggrTables(db_name, table_name, func_name, aggr_col, partition_col, order_col, filter_col); if (table_infos.empty()) { LOG(WARNING) << absl::StrCat("No Pre-aggregation tables exists for ", db_name, ".", table_name, ": ", func_name, "(", aggr_col, ")", " partition by ", partition_col, " order by ", order_col); return false; } // TODO(zhanghao): optimize the selection of the best pre-aggregation tables auto table = catalog_->GetTable(table_infos[0].aggr_db, table_infos[0].aggr_table); if (!table) { LOG(ERROR) << "Fail to get table handler for pre-aggregation table " << table_infos[0].aggr_db << "." << table_infos[0].aggr_table; return false; } vm::PhysicalTableProviderNode* aggr = nullptr; auto status = plan_ctx_->CreateOp<vm::PhysicalTableProviderNode>(&aggr, table); if (!status.isOK()) { LOG(ERROR) << "Fail to create PhysicalTableProviderNode for pre-aggregation table " << table_infos[0].aggr_db << "." << table_infos[0].aggr_table << ": " << status; return false; } if (table->GetIndex().size() != 1) { LOG(ERROR) << "PreAggregation table index size != 1"; return false; } auto index = table->GetIndex().cbegin()->second; auto nm = plan_ctx_->node_manager(); auto request = req_union_op->GetProducer(0); auto raw = req_union_op->GetProducer(1); // generate an aggregation window for the aggr table auto req_window = req_union_op->window(); auto partitions = nm->MakeExprList(); for (size_t i = 0; i < index.keys.size(); i++) { auto col_ref = nm->MakeColumnRefNode(index.keys[i].name, table->GetName(), table->GetDatabase()); partitions->AddChild(col_ref); } vm::RequestWindowOp aggr_window(partitions); auto order_col_ref = nm->MakeColumnRefNode((*table->GetSchema())[index.ts_pos].name(), table->GetName(), table->GetDatabase()); auto order_expr = nm->MakeOrderExpression(order_col_ref, true); auto orders = nm->MakeExprList(); orders->AddChild(order_expr); auto partition_by = nm->MakeExprList(); for (size_t i = 0; i < index.keys.size(); i++) { auto col_ref = nm->MakeColumnRefNode((*table->GetSchema())[index.keys[i].idx].name(), table->GetName(), table->GetDatabase()); partition_by->AddChild(col_ref); } aggr_window.sort_.orders_ = nm->MakeOrderByNode(orders); aggr_window.name_ = req_window.name(); aggr_window.range_ = req_window.range_; aggr_window.range_.range_key_ = order_col_ref; aggr_window.partition_.keys_ = partition_by; vm::PhysicalRequestAggUnionNode* request_aggr_union = nullptr; status = plan_ctx_->CreateOp<vm::PhysicalRequestAggUnionNode>( &request_aggr_union, request, raw, aggr, req_union_op->window(), aggr_window, req_union_op->instance_not_in_window(), req_union_op->exclude_current_time(), req_union_op->output_request_row(), aggr_op); if (req_union_op->exclude_current_row()) { request_aggr_union->set_out_request_row(false); } if (!status.isOK()) { LOG(ERROR) << "Fail to create PhysicalRequestAggUnionNode: " << status; return false; } vm::PhysicalReduceAggregationNode* reduce_aggr = nullptr; auto condition = in->having_condition_.condition(); if (condition) { condition = condition->DeepCopy(plan_ctx_->node_manager()); } status = plan_ctx_->CreateOp<vm::PhysicalReduceAggregationNode>(&reduce_aggr, request_aggr_union, in->project(), condition, in); auto ctx = reduce_aggr->schemas_ctx(); if (ctx->GetSchemaSourceSize() != 1 || ctx->GetSchema(0)->size() != 1) { LOG(ERROR) << "PhysicalReduceAggregationNode schema is unexpected"; return false; } request_aggr_union->UpdateParentSchema(ctx); if (!status.isOK()) { LOG(ERROR) << "Fail to create PhysicalReduceAggregationNode: " << status; return false; } DLOG(INFO) << "[LongWindowOptimized] Before transform sql:\n" << (*output)->GetTreeString(); *output = reduce_aggr; DLOG(INFO) << "[LongWindowOptimized] After transform sql:\n" << (*output)->GetTreeString(); return true; } bool LongWindowOptimized::VerifySingleAggregation(vm::PhysicalProjectNode* op) { return op->project().size() == 1; } std::string LongWindowOptimized::ConcatExprList(std::vector<node::ExprNode*> exprs, const std::string& delimiter) { std::string str = ""; for (const auto expr : exprs) { std::string expr_val; if (expr->GetExprType() == node::kExprAll) { expr_val = expr->GetExprString(); } else if (expr->GetExprType() == node::kExprColumnRef) { expr_val = dynamic_cast<node::ColumnRefNode*>(expr)->GetColumnName(); } else { LOG(ERROR) << "non support expr type in ConcatExprList"; return ""; } if (str.empty()) { str = absl::StrCat(str, expr_val); } else { str = absl::StrCat(str, delimiter, expr_val); } } return str; } // type check of count_where condition node // left -> column ref // right -> constant absl::StatusOr<absl::string_view> CheckCountWhereCond(const node::ExprNode* lhs, const node::ExprNode* rhs) { if (lhs->GetExprType() != node::ExprType::kExprColumnRef) { return absl::UnimplementedError(absl::StrCat("expect left as column reference but get ", lhs->GetExprString())); } if (rhs->GetExprType() != node::ExprType::kExprPrimary) { return absl::UnimplementedError(absl::StrCat("expect right as constant but get ", rhs->GetExprString())); } return dynamic_cast<const node::ColumnRefNode*>(lhs)->GetColumnName(); } // left -> * or column name // right -> BinaryExpr of // lhs column name and rhs constant, or versa // op -> (eq, ne, gt, lt, ge, le) absl::StatusOr<absl::string_view> CheckCountWhereArgs(const node::ExprNode* right) { if (right->GetExprType() != node::ExprType::kExprBinary) { return absl::UnimplementedError(absl::StrCat("[Long Window] ExprType ", node::ExprTypeName(right->GetExprType()), " not implemented as count_where condition")); } auto* bin_expr = dynamic_cast<const node::BinaryExpr*>(right); if (bin_expr == nullptr) { return absl::UnknownError("[Long Window] right can't cast to binary expr"); } auto s1 = CheckCountWhereCond(right->GetChild(0), right->GetChild(1)); auto s2 = CheckCountWhereCond(right->GetChild(1), right->GetChild(0)); if (!s1.ok() && !s2.ok()) { return absl::UnimplementedError( absl::StrCat("[Long Window] cond as ", right->GetExprString(), " not support: ", s1.status().message())); } switch (bin_expr->GetOp()) { case node::FnOperator::kFnOpLe: case node::FnOperator::kFnOpLt: case node::FnOperator::kFnOpGt: case node::FnOperator::kFnOpGe: case node::FnOperator::kFnOpNeq: case node::FnOperator::kFnOpEq: break; default: return absl::UnimplementedError( absl::StrCat("[Long Window] filter cond operator ", node::ExprOpTypeName(bin_expr->GetOp()))); } if (s1.ok()) { return s1.value(); } return s2.value(); } // Supported: // - count(col) or count(*) // - sum(col) // - min(col) // - max(col) // - avg(col) // - count_where(col, simple_expr) // - count_where(*, simple_expr) // // simple_expr can be // - BinaryExpr // - operand nodes of the expr can only be column ref and const node // - with operator: // - eq // - neq // - lt // - gt // - le // - ge absl::StatusOr<LongWindowOptimized::AggInfo> LongWindowOptimized::CheckCallExpr(const node::CallExprNode* call) { if (call->GetChildNum() != 1 && call->GetChildNum() != 2) { return absl::UnimplementedError( absl::StrCat("expect call function with argument number 1 or 2, but got ", call->GetExprString())); } // count/sum/min/max/avg auto expr_type = call->GetChild(0)->GetExprType(); absl::string_view key_col; absl::string_view filter_col; if (expr_type == node::kExprColumnRef) { auto* col_ref = dynamic_cast<const node::ColumnRefNode*>(call->GetChild(0)); key_col = col_ref->GetColumnName(); } else if (expr_type == node::kExprAll) { key_col = call->GetChild(0)->GetExprString(); } else { return absl::UnimplementedError( absl::StrCat("[Long Window] first arg to op is not column or * :", call->GetExprString())); } if (call->GetChildNum() == 2) { if (absl::c_none_of(WHERE_FUNS, [&call](absl::string_view e) { return call->GetFnDef()->GetName() == e; })) { return absl::UnimplementedError(absl::StrCat(call->GetFnDef()->GetName(), " not implemented")); } // count_where auto s = CheckCountWhereArgs(call->GetChild(1)); if (!s.ok()) { return s.status(); } filter_col = s.value(); } return AggInfo{key_col, filter_col}; } } // namespace passes } // namespace hybridse
[ "noreply@github.com" ]
noreply@github.com
89bf3d1e0dcfa8a159c04916430386eef301fbaf
5e4987b32f5199c8886b67dccb75e8956db58d8d
/src/tracer/test/sound_test.cpp
07fef36a90cca78330e077e9288badef4ba48d0b
[ "MIT" ]
permissive
Mesocopic/branchedflowsim
3d78aec220e48f1952f50e821a54356483058e56
63cef65a846d56ea7779ef53e6a20d46d8a42890
refs/heads/master
2022-03-03T21:15:59.851646
2022-02-16T13:36:45
2022-02-16T13:36:45
160,659,776
0
0
MIT
2018-12-07T13:34:28
2018-12-06T10:39:17
null
UTF-8
C++
false
false
3,232
cpp
#include "tracer.hpp" #include "initial_conditions/initial_conditions.hpp" #include "dynamics/sound.hpp" #include "observers/observer.hpp" #define BOOST_TEST_MODULE sound_test #include <boost/test/unit_test.hpp> using zero_vec = boost::numeric::ublas::zero_vector<double>; // make an observer that checks that analytic and numeric solutins coincide // x(t) = (1+y0 - sqrt(1+t^2)/2)t + sinh^-1(t)/2 // y(t) = 1 - sqrt(1+t^2) + y0 class CheckSoundObserver final: public ThreadLocalObserver { public: /// create an observer and specify the time interval for saving the particle's position CheckSoundObserver( ); /// d'tor ~CheckSoundObserver() = default; // standard observer functions // for documentation look at observer.hpp bool watch( const State& state, double t ) override; void startTrajectory(const InitialCondition& start, std::size_t trajectory) override; void save( std::ostream& ) override {} std::shared_ptr<ThreadLocalObserver> clone() const override; void combine(ThreadLocalObserver&) override {} double x0; double y0; }; CheckSoundObserver::CheckSoundObserver() : ThreadLocalObserver("tlo") { } void CheckSoundObserver::startTrajectory( const InitialCondition& start, std::size_t ) { x0 = start.getState().getPosition()[0]; y0 = start.getState().getPosition()[1]; } bool CheckSoundObserver::watch( const State& state, double t ) { double ax = (1 + y0 - std::sqrt(1+t*t)/2)*t + std::asinh(t)/2 + x0; double ay = 1 - std::sqrt( 1 + t*t ) + y0; double nx = state.getPosition()[0]; double ny = state.getPosition()[1]; BOOST_CHECK_CLOSE( ax, nx, 1e-9 ); BOOST_CHECK_CLOSE( ay, ny, 1e-9 ); return true; } std::shared_ptr<ThreadLocalObserver> CheckSoundObserver::clone() const { return std::make_shared<CheckSoundObserver>( ); } BOOST_AUTO_TEST_SUITE(sound_trace_tests) BOOST_AUTO_TEST_CASE(gradient) { Potential potential(2, 1, 256); default_grid g(2, 256); g.setAccessMode(TransformationType::PERIODIC); for(auto& data : g) data = 0; potential.setDerivative(std::vector<int>{0,0}, g.clone(), "velocity1"); potential.setDerivative(std::vector<int>{1,0}, g.clone(), "velocity1"); potential.setDerivative(std::vector<int>{0,1}, g.clone(), "velocity1"); potential.setDerivative(std::vector<int>{1,0}, g.clone(), "velocity0"); for(auto& data : g) data = 1; potential.setDerivative(std::vector<int>{0,1}, g.clone(), "velocity0"); for(auto ind = g.getIndex(); ind.valid(); ++ind) { g(ind) = ind[1] / 256.; } potential.setDerivative(std::vector<int>{0,0}, g.clone(), "velocity0"); std::unique_ptr<RayDynamics> dynamics(new Sound(potential, false, false)); auto tracer = std::make_shared<Tracer>( potential, std::move(dynamics)); tracer->setMaxThreads(1); tracer->addObserver( CheckSoundObserver().clone() ); auto generator = createInitialConditionGenerator( 2, std::vector<std::string>{"planar"} ); init_cond::InitialConditionConfiguration config; config.setParticleCount(1000).setEnergyNormalization(true).setSupport(potential.getSupport()) .setOffset(zero_vec(2)); tracer->trace( generator, config ); std::cout << "FINNISHED\n"; } BOOST_AUTO_TEST_SUITE_END()
[ "ngc92@users.noreply.github.com" ]
ngc92@users.noreply.github.com
33a4855b3a5295ccfa1ae2379ada7fbb1cb933a4
dcd70031041dabecc6abfa5f2847c299fc7fef70
/백준/12778_CTP공국으로이민가자.cpp
b66588812228b84961c5c8e07ab6a2a940d25bad
[]
no_license
JJJoonngg/Algorithm
cab395760ef604a1764391847473c838e3beac9f
32d574558c1747008e7ac3dfe4f9d4f07c58a58b
refs/heads/master
2021-06-21T01:01:36.302243
2021-03-24T14:01:06
2021-03-24T14:01:06
196,032,101
1
0
null
null
null
null
UHC
C++
false
false
2,427
cpp
/* https://www.acmicpc.net/problem/12778 문제 신생국가 CTP공국은 자신들만의 글자가 없다. CTP공국의 왕 준형이는 전 세계 표준 언어인 알파벳을 사용하기로 했다. 하지만 숫자에 미친 사람들이 모인 CTP공국 주민들은 알파벳을 사용할 때 평범한 알파벳이 아니라 쓰려고 하는 알파벳이 앞에서부터 몇 번째 알파벳인지를 의미하는 숫자로 나타낸다. 예를 들어 ‘A’는 ‘1’로, ‘Z’는 ‘26’로 나타낸다. CTP공국은 현재 부흥 중이라 새로 국민이 되고자 하는 사람이 많다. 하지만 아무나 CTP공국의 국민이 될 수는 없는 법. CTP공국의 이민국장 인덕이는 이민 신청자들이 CTP 공국의 글자체계를 잘 알고 있는지 확인하는 시험문제를 내기로 했다. 시험문제는 두 가지 종류로 구분된다. CTP공국의 글자가 주어졌을 때 알파벳을 쓰는 문제와 알파벳이 주어졌을 때 CTP공국의 글자를 쓰는 문제 두 가지이다. 너무 많은 이민 신청자들 때문에 시험문제 채점에 골치가 아픈 인덕이를 위해 주어진 시험문제의 정답을 알려주는 프로그램을 작성하라. 입력 입력의 첫 줄에는 시험문제의 개수 T(1 ≤ T ≤ 50)가 주어진다. 각 시험문제의 첫 번째 줄에는 알파벳 또는 숫자의 개수 M(1 ≤ M ≤ 500) 과 문제의 종류를 나타내는 문자가 주어진다. 알파벳을 숫자로 바꾸는 문제인 경우에는 C, 숫자를 문자로 바꾸는 문제인 경우에는 N이 주어진다. 각 시험문제의 두 번째 줄에는 문제의 종류에 따라 공백을 구분으로 알파벳(A~Z,대문자) 또는 숫자(1~26, 정수)가 M개 주어진다. 3 3 C C T P 4 N 9 14 8 1 5 C H E L L O 출력 각 시험문제의 정답을 출력한다. 출력이 알파벳인 경우 대문자로 출력한다. 3 20 16 I N H A 8 5 12 12 15 */ #include <iostream> using namespace std; int main() { cin.tie(NULL); cout.tie(NULL); std::ios::sync_with_stdio(false); int t; cin >> t; while (t--) { int m; char input; cin >> m >> input; if (input == 'C') { for (int i = 0; i < m; i++) { char tmp; cin >> tmp; cout << int(tmp - 'A' + 1) << " "; } } else if (input == 'N') { for (int i = 0; i < m; i++) { int tmp; cin >> tmp; cout << char(tmp + 'A' - 1) << " "; } } cout << "\n"; } }
[ "whdtls3878@gmail.com" ]
whdtls3878@gmail.com
d968e05927438e42ce4c97172b8cb39ebad2e0e5
d63dbf8814db0b5f7631cce53af5dcc14543fe62
/examples/testshapes_16x32/testshapes_16x32.ino
bc8813fb4afae80c76b8be50579b175d52d363b7
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
sugarcrystals01/Orbis
412c9641d63c9c0933d7eb4d6c16d4a627996a43
755098b80abe446a9ad1eaa1dfd162e79a457f3a
refs/heads/master
2020-03-11T21:45:17.422272
2018-05-18T03:28:49
2018-05-18T03:28:49
130,274,258
0
0
null
null
null
null
UTF-8
C++
false
false
20,615
ino
// testshapes demo for Adafruit RGBmatrixPanel library. // Demonstrates the drawing abilities of the RGBmatrixPanel library. // For 16x32 RGB LED matrix: // http://www.adafruit.com/products/420 // Written by Limor Fried/Ladyada & Phil Burgess/PaintYourDragon // for Adafruit Industries. // BSD license, all text above must be included in any redistribution. #include "Adafruit_GFX.h" // Core graphics library #include "RGBmatrixPanel.h" // Hardware-specific library #define CLK 8 // MUST be on PORTB! (Use pin 11 on Mega) #define LAT A3 #define OE 9 #define A A0 #define B A1 #define C A2 RGBmatrixPanel matrix(A, B, C, CLK, LAT, OE, false); void setup() { matrix.begin(); // draw a pixel in solid white matrix.drawPixel(0, 0, matrix.Color333(7, 7, 7)); delay(500); matrix.drawPixel(1,0, matrix.Color333(6, 0, 6)); delay(1000); matrix.drawLine(9,1,4, 1, matrix.Color333(7, 7, 7)); delay(1000); matrix.drawLine(8, 2, 1, 2, matrix.Color333(7,7,7)); //333 means 3-bit numbers(up to 512 colors,values go from 0 to 7), delay(1000); matrix.drawLine(9,3,2,3, matrix.Color333(7, 7, 7)); delay(1000); // draw some text! matrix.setCursor(1, 0); // start at top left, with one pixel of spacing matrix.setTextSize(1); // size 1 == 8 pixels high matrix.drawPixel(5,0, matrix.Color333(4,4,4)); delay(1000); matrix.fillScreen(matrix.Color333(0, 0, 0)); // print each letter with a rainbow color /*matrix.setTextColor(matrix.Color333(4,0,0)); matrix.print('1'); matrix.setTextColor(matrix.Color333(4,4,0)); matrix.print('6'); matrix.setTextColor(matrix.Color333(4,4,0)); matrix.print('x'); matrix.setTextColor(matrix.Color333(4,4,0)); matrix.print('3'); matrix.setTextColor(matrix.Color333(0,4,0)); matrix.print('2'); matrix.setCursor(1, 9); // next line matrix.setTextColor(matrix.Color333(0,4,4)); matrix.print('*'); matrix.setTextColor(matrix.Color333(0,4,4)); matrix.print('R'); matrix.setTextColor(matrix.Color333(0,0,4)); matrix.print('G'); matrix.setTextColor(matrix.Color333(4,0,4)); matrix.print("B"); matrix.setTextColor(matrix.Color333(4,0,4)); matrix.print("*"); */ // whew! } void northAmerica() { matrix.drawLine(9,1,4, 1, matrix.Color333(4, 4, 4)); //matrix.drawLine(end of x, end of y, start of x, start of y, matrix.Color333(r, g, b)); matrix.drawLine(8, 2, 1, 2, matrix.Color333(4,4,4)); //333 means 3-bit numbers(up to 512 colors,values go from 0 to 4), matrix.drawLine(9,3,2,3, matrix.Color333(4, 4, 4)); //there is also 444, which accepts 4 bit numbers matrix.drawLine(9,4,3,4, matrix.Color333(4, 4, 4)); matrix.drawLine(8,5,3,5, matrix.Color333(4, 4, 4)); matrix.drawLine(6,6,4,6, matrix.Color333(4, 4, 4)); matrix.drawLine(7,7,5,7, matrix.Color333(4, 4, 4)); matrix.drawPixel(0,5, matrix.Color333(4, 4, 4)); delay(250); //color: red matrix.drawLine(9,1,4, 1, matrix.Color333(4, 0, 0)); //matrix.drawLine(end of x, end of y, start of x, start of y, matrix.Color333(r, g, b)); matrix.drawLine(8, 2, 1, 2, matrix.Color333(4, 0, 0)); //333 means 3-bit numbers(up to 512 colors,values go from 0 to 4), matrix.drawLine(9,3,2,3, matrix.Color333(4, 0, 0)); //there is also 444, which accepts 4 bit numbers matrix.drawLine(9,4,3,4, matrix.Color333(4, 0, 0)); matrix.drawLine(8,5,3,5, matrix.Color333(4, 0, 0)); matrix.drawLine(6,6,4,6, matrix.Color333(4, 0, 0)); matrix.drawLine(7,7,5,7, matrix.Color333(4, 0, 0)); matrix.drawPixel(0,5, matrix.Color333(4, 0, 0)); delay(250); //color: green matrix.drawLine(9,1,4, 1, matrix.Color333(0, 4, 0)); //matrix.drawLine(end of x, end of y, start of x, start of y, matrix.Color333(r, g, b)); matrix.drawLine(8, 2, 1, 2, matrix.Color333(0, 4, 0)); //333 means 3-bit numbers(up to 512 colors,values go from 0 to 4), matrix.drawLine(9,3,2,3, matrix.Color333(0, 4, 0)); //there is also 444, which accepts 4 bit numbers matrix.drawLine(9,4,3,4, matrix.Color333(0, 4, 0)); matrix.drawLine(8,5,3,5, matrix.Color333(0, 4, 0)); matrix.drawLine(6,6,4,6, matrix.Color333(0, 4, 0)); matrix.drawLine(7,7,5,7, matrix.Color333(0, 4, 0)); matrix.drawPixel(0,5, matrix.Color333(0, 4, 0)); delay(250); //color: blue matrix.drawLine(9,1,4, 1, matrix.Color333(0, 0, 4)); //matrix.drawLine(end of x, end of y, start of x, start of y, matrix.Color333(r, g, b)); matrix.drawLine(8, 2, 1, 2, matrix.Color333(0, 0, 4)); //333 means 3-bit numbers(up to 512 colors,values go from 0 to 4), matrix.drawLine(9,3,2,3, matrix.Color333(0, 0, 4)); //there is also 444, which accepts 4 bit numbers matrix.drawLine(9,4,3,4, matrix.Color333(0, 0, 4)); matrix.drawLine(8,5,3,5, matrix.Color333(0, 0, 4)); matrix.drawLine(6,6,4,6, matrix.Color333(0, 0, 4)); matrix.drawLine(7,7,5,7, matrix.Color333(0, 0, 4)); matrix.drawPixel(0,5, matrix.Color333(0, 0, 4)); delay(250); //color: purple matrix.drawLine(9,1,4, 1, matrix.Color333(4, 0, 4)); //matrix.drawLine(end of x, end of y, start of x, start of y, matrix.Color333(r, g, b)); matrix.drawLine(8, 2, 1, 2, matrix.Color333(4, 0, 4)); //333 means 3-bit numbers(up to 512 colors,values go from 0 to 4), matrix.drawLine(9,3,2,3, matrix.Color333(4, 0, 4)); //there is also 444, which accepts 4 bit numbers matrix.drawLine(9,4,3,4, matrix.Color333(4, 0, 4)); matrix.drawLine(8,5,3,5, matrix.Color333(4, 0, 4)); matrix.drawLine(6,6,4,6, matrix.Color333(4, 0, 4)); matrix.drawLine(7,7,5,7, matrix.Color333(4, 0, 4)); matrix.drawPixel(0,5, matrix.Color333(4, 0, 4)); delay(250); } void southAmerica() { matrix.drawLine(9,8,7, 8, matrix.Color333(4, 4, 4)); //matrix.drawLine(end of x, end of y, start of x, start of y, matrix.Color333(r, g, b)); matrix.drawLine(10,9,6,9, matrix.Color333(4, 4,4)); //333 means 3-bit numbers(up to 512 colors,values go from 0 to 7), matrix.drawLine(11,10,6,10, matrix.Color333(4, 4, 4)); //there is also 444, which accepts 4 bit numbers matrix.drawLine(10,11,6,11, matrix.Color333(4, 4, 4)); matrix.drawLine(9,12,7,12, matrix.Color333(4, 4, 4)); matrix.drawLine(8,13,7,13, matrix.Color333(4, 4, 4)); matrix.drawPixel(7,14, matrix.Color333(4, 4, 4)); matrix.drawPixel(1,10, matrix.Color333(4, 4, 4)); delay(250); //color: red matrix.drawLine(9,8,7, 8, matrix.Color333(4, 0, 0)); matrix.drawLine(10,9,6,9, matrix.Color333(4, 0, 0)); matrix.drawLine(11,10,6,10, matrix.Color333(4, 0, 0)); matrix.drawLine(10,11,6,11, matrix.Color333(4, 0, 0)); matrix.drawLine(9,12,7,12, matrix.Color333(4, 0, 0)); matrix.drawLine(8,13,7,13, matrix.Color333(4, 0, 0)); matrix.drawPixel(7,14, matrix.Color333(4, 0, 0)); matrix.drawPixel(1,10, matrix.Color333(4, 0, 0)); delay(250); //color: purple matrix.drawLine(9,8,7, 8, matrix.Color333(4, 0, 4)); matrix.drawLine(10,9,6,9, matrix.Color333(4, 0, 4)); matrix.drawLine(11,10,6,10, matrix.Color333(4, 0, 4)); matrix.drawLine(10,11,6,11, matrix.Color333(4, 0, 4)); matrix.drawLine(9,12,7,12, matrix.Color333(4, 0, 4)); matrix.drawLine(8,13,7,13, matrix.Color333(4, 0, 4)); matrix.drawPixel(7,14, matrix.Color333(4, 0, 4)); matrix.drawPixel(1,10, matrix.Color333(4, 0, 4)); delay(250); //color: green matrix.drawLine(9,8,7, 8, matrix.Color333(0, 4, 0)); //matrix.drawLine(end of x, end of y, start of x, start of y, matrix.Color333(r, g, b)); matrix.drawLine(10,9,6,9, matrix.Color333(0, 4, 0)); //333 means 3-bit numbers(up to 512 colors,values go from 0 to 7), matrix.drawLine(11,10,6,10, matrix.Color333(0, 4, 0)); //there is also 444, which accepts 4 bit numbers matrix.drawLine(10,11,6,11, matrix.Color333(0, 4, 0)); matrix.drawLine(9,12,7,12, matrix.Color333(0, 4, 0)); matrix.drawLine(8,13,7,13, matrix.Color333(0, 4, 0)); matrix.drawPixel(7,14, matrix.Color333(0, 4, 0)); matrix.drawPixel(1,10, matrix.Color333(0, 4, 0)); delay(250); //color: blue matrix.drawLine(9,8,7, 8, matrix.Color333(0, 0, 4)); //matrix.drawLine(end of x, end of y, start of x, start of y, matrix.Color333(r, g, b)); matrix.drawLine(10,9,6,9, matrix.Color333(0, 0, 4)); //333 means 3-bit numbers(up to 512 colors,values go from 0 to 7), matrix.drawLine(11,10,6,10, matrix.Color333(0, 0, 4)); //there is also 444, which accepts 4 bit numbers matrix.drawLine(10,11,6,11, matrix.Color333(0, 0, 4)); matrix.drawLine(9,12,7,12, matrix.Color333(0, 0, 4)); matrix.drawLine(8,13,7,13, matrix.Color333(0, 0, 4)); matrix.drawPixel(7,14, matrix.Color333(0, 0, 4)); matrix.drawPixel(1,10, matrix.Color333(0, 0, 4)); delay(250); } void eurasia() { //top half of europe/russia/asia matrix.drawLine(12, 1, 11, 1, matrix.Color333(4, 4, 4)); matrix.drawLine(12, 2, 11, 2, matrix.Color333(4, 4, 4)); matrix.drawLine(19, 1, 17, 1, matrix.Color333(4, 4, 4)); matrix.drawLine(28,1, 21, 1, matrix.Color333(4,4,4)); matrix.drawLine(15, 2, 14, 2, matrix.Color333(4, 4, 4)); matrix.drawLine(29, 2, 18, 2, matrix.Color333(4, 4, 4)); matrix.drawLine(28, 3, 16, 3, matrix.Color333(4, 4, 4)); matrix.drawLine(19, 4, 14, 4, matrix.Color333(4, 4, 4)); matrix.drawLine(28, 4, 21, 4, matrix.Color333(4, 4, 4)); matrix.drawPixel(30, 4, matrix.Color333(4, 4, 4)); matrix.drawPixel(30,5, matrix.Color333(4, 4, 4)); //bottom half matrix.drawLine(15, 5, 14, 5, matrix.Color333(4, 4, 4)); matrix.drawLine(28, 5, 19, 5, matrix.Color333(4, 4, 4)); matrix.drawLine(25, 6, 19, 6, matrix.Color333(4, 4, 4)); matrix.drawLine(28, 6, 27, 6, matrix.Color333(4, 4, 4)); matrix.drawLine(22, 7, 21, 7, matrix.Color333(4, 4, 4)); matrix.drawLine(28, 7, 27, 7, matrix.Color333(4, 4, 4)); matrix.drawLine(29, 10, 28, 10, matrix.Color333(4, 4, 4)); matrix.drawPixel(28,8, matrix.Color333(4, 4, 4)); matrix.drawPixel(27,9, matrix.Color333(4, 4, 4)); matrix.drawPixel(31,8, matrix.Color333(4, 4, 4)); matrix.drawPixel(25,7, matrix.Color333(4, 4, 4)); delay(250); //color green //top half of europe/russia/asia matrix.drawLine(12, 1, 11, 1, matrix.Color333(0, 4, 0)); matrix.drawLine(12, 2, 11, 2, matrix.Color333(0, 4, 0)); matrix.drawLine(19, 1, 17, 1, matrix.Color333(0, 4, 0)); matrix.drawLine(28,1, 21, 1, matrix.Color333(0, 4, 0)); matrix.drawLine(15, 2, 14, 2, matrix.Color333(0, 4, 0)); matrix.drawLine(29, 2, 18, 2, matrix.Color333(0, 4, 0)); matrix.drawLine(28, 3, 16, 3, matrix.Color333(0, 4, 0)); matrix.drawLine(19, 4, 14, 4, matrix.Color333(0, 4, 0)); matrix.drawLine(28, 4, 21, 4, matrix.Color333(0, 4, 0)); matrix.drawPixel(30, 4, matrix.Color333(0, 4, 0)); matrix.drawPixel(30,5, matrix.Color333(0, 4, 0)); //bottom half matrix.drawLine(15, 5, 14, 5, matrix.Color333(0, 4, 0)); matrix.drawLine(28, 5, 19, 5, matrix.Color333(0, 4, 0)); matrix.drawLine(25, 6, 19, 6, matrix.Color333(0, 4, 0)); matrix.drawLine(28, 6, 27, 6, matrix.Color333(0, 4, 0)); matrix.drawLine(22, 7, 21, 7, matrix.Color333(0, 4, 0)); matrix.drawLine(28, 7, 27, 7, matrix.Color333(0, 4, 0)); matrix.drawLine(29, 10, 28, 10, matrix.Color333(0, 4, 0)); matrix.drawPixel(28,8, matrix.Color333(0, 4, 0)); matrix.drawPixel(27,9, matrix.Color333(0, 4, 0)); matrix.drawPixel(31,8, matrix.Color333(0, 4, 0)); matrix.drawPixel(25,7, matrix.Color333(0, 4, 0)); delay(250); //color blue //top half of europe/russia/asia matrix.drawLine(12, 1, 11, 1, matrix.Color333(0, 0, 4)); matrix.drawLine(12, 2, 11, 2, matrix.Color333(0, 0, 4)); matrix.drawLine(19, 1, 17, 1, matrix.Color333(0, 0, 4)); matrix.drawLine(28,1, 21, 1, matrix.Color333(0, 0, 4)); matrix.drawLine(15, 2, 14, 2, matrix.Color333(0, 0, 4)); matrix.drawLine(29, 2, 18, 2, matrix.Color333(0, 0, 4)); matrix.drawLine(28, 3, 16, 3, matrix.Color333(0, 0, 4)); matrix.drawLine(19, 4, 14, 4, matrix.Color333(0, 0, 4)); matrix.drawLine(28, 4, 21, 4, matrix.Color333(0, 0, 4)); matrix.drawPixel(30, 4, matrix.Color333(0, 0, 4)); matrix.drawPixel(30,5, matrix.Color333(0, 0, 4)); //bottom half matrix.drawLine(15, 5, 14, 5, matrix.Color333(0, 0, 4)); matrix.drawLine(28, 5, 19, 5, matrix.Color333(0, 0, 4)); matrix.drawLine(25, 6, 19, 6, matrix.Color333(0, 0, 4)); matrix.drawLine(28, 6, 27, 6, matrix.Color333(0, 0, 4)); matrix.drawLine(22, 7, 21, 7, matrix.Color333(0, 0, 4)); matrix.drawLine(28, 7, 27, 7, matrix.Color333(0, 0, 4)); matrix.drawLine(29, 10, 28, 10, matrix.Color333(0, 0, 4)); matrix.drawPixel(28,8, matrix.Color333(0, 0, 4)); matrix.drawPixel(27,9, matrix.Color333(0, 0, 4)); matrix.drawPixel(31,8, matrix.Color333(0, 0, 4)); matrix.drawPixel(25,7, matrix.Color333(0, 0, 4)); //color:red //top half of europe/russia/asia matrix.drawLine(12, 1, 11, 1, matrix.Color333(4, 0, 0)); matrix.drawLine(12, 2, 11, 2, matrix.Color333(4, 0, 0)); matrix.drawLine(19, 1, 17, 1, matrix.Color333(4, 0, 0)); matrix.drawLine(28,1, 21, 1, matrix.Color333(4, 0, 0)); matrix.drawLine(15, 2, 14, 2, matrix.Color333(4, 0, 0)); matrix.drawLine(29, 2, 18, 2, matrix.Color333(4, 0, 0)); matrix.drawLine(28, 3, 16, 3, matrix.Color333(4, 0, 0)); matrix.drawLine(19, 4, 14, 4, matrix.Color333(4, 0, 0)); matrix.drawLine(28, 4, 21, 4, matrix.Color333(4, 0, 0)); matrix.drawPixel(30, 4, matrix.Color333(4, 0, 0)); matrix.drawPixel(30,5, matrix.Color333(4, 0, 0)); //bottom half matrix.drawLine(15, 5, 14, 5, matrix.Color333(4, 0, 0)); matrix.drawLine(28, 5, 19, 5, matrix.Color333(4, 0, 0)); matrix.drawLine(25, 6, 19, 6, matrix.Color333(4, 0, 0)); matrix.drawLine(28, 6, 27, 6, matrix.Color333(4, 0, 0)); matrix.drawLine(22, 7, 21, 7, matrix.Color333(4, 0, 0)); matrix.drawLine(28, 7, 27, 7, matrix.Color333(4, 0, 0)); matrix.drawLine(29, 10, 28, 10, matrix.Color333(4, 0, 0)); matrix.drawPixel(28,8, matrix.Color333(4, 0, 0)); matrix.drawPixel(27,9, matrix.Color333(4, 0, 0)); matrix.drawPixel(31,8, matrix.Color333(4, 0, 0)); matrix.drawPixel(25,7, matrix.Color333(4, 0, 0)); delay(250); //color purple //top half of europe/russia/asia matrix.drawLine(12, 1, 11, 1, matrix.Color333(4, 0, 4)); matrix.drawLine(12, 2, 11, 2, matrix.Color333(4, 0, 4)); matrix.drawLine(19, 1, 17, 1, matrix.Color333(4, 0, 4)); matrix.drawLine(28,1, 21, 1, matrix.Color333(4, 0, 4)); matrix.drawLine(15, 2, 14, 2, matrix.Color333(4, 0, 4)); matrix.drawLine(29, 2, 18, 2, matrix.Color333(4, 0, 4)); matrix.drawLine(28, 3, 16, 3, matrix.Color333(4, 0, 4)); matrix.drawLine(19, 4, 14, 4, matrix.Color333(4, 0, 4)); matrix.drawLine(28, 4, 21, 4, matrix.Color333(4, 0, 4)); matrix.drawPixel(30, 4, matrix.Color333(4, 0, 4)); matrix.drawPixel(30,5, matrix.Color333(4, 0, 4)); //bottom half matrix.drawLine(15, 5, 14, 5, matrix.Color333(4, 0, 4)); matrix.drawLine(28, 5, 19, 5, matrix.Color333(4, 0, 4)); matrix.drawLine(25, 6, 19, 6, matrix.Color333(4, 0, 4)); matrix.drawLine(28, 6, 27, 6, matrix.Color333(4, 0, 4)); matrix.drawLine(22, 7, 21, 7, matrix.Color333(4, 0, 4)); matrix.drawLine(28, 7, 27, 7, matrix.Color333(4, 0, 4)); matrix.drawLine(29, 10, 28, 10, matrix.Color333(4, 0, 4)); matrix.drawPixel(28,8, matrix.Color333(4, 0, 4)); matrix.drawPixel(27,9, matrix.Color333(4, 0, 4)); matrix.drawPixel(31,8, matrix.Color333(4, 0, 4)); matrix.drawPixel(25,7, matrix.Color333(4, 0, 4)); delay(250); } void africa() { matrix.drawLine(18, 6, 15, 6, matrix.Color333(4,4,4)); matrix.drawLine(19, 7, 13, 7, matrix.Color333(4,4,4)); matrix.drawLine(20, 8, 13, 8, matrix.Color333(4,4,4)); matrix.drawLine(20, 9, 15, 9, matrix.Color333(4,4,4)); matrix.drawLine(19, 10, 15, 10, matrix.Color333(4,4,4)); matrix.drawLine(18, 11, 15, 11, matrix.Color333(4,4,4)); matrix.drawLine(18, 12, 15, 12, matrix.Color333(4,4,4)); matrix.drawLine(17, 13, 16, 13, matrix.Color333(4,4,4)); delay(250); //color: green matrix.drawLine(18, 6, 15, 6, matrix.Color333(0,4,0)); matrix.drawLine(19, 7, 13, 7, matrix.Color333(0,4,0)); matrix.drawLine(20, 8, 13, 8, matrix.Color333(0,4,0)); matrix.drawLine(20, 9, 15, 9, matrix.Color333(0,4,0)); matrix.drawLine(19, 10, 15, 10, matrix.Color333(0,4,0)); matrix.drawLine(18, 11, 15, 11, matrix.Color333(0,4,0)); matrix.drawLine(18, 12, 15, 12, matrix.Color333(0,4,0)); matrix.drawLine(17, 13, 16, 13, matrix.Color333(0,4,0)); delay(250); //color: red matrix.drawLine(18, 6, 15, 6, matrix.Color333(4,0,0)); matrix.drawLine(19, 7, 13, 7, matrix.Color333(4,0,0)); matrix.drawLine(20, 8, 13, 8, matrix.Color333(4,0,0)); matrix.drawLine(20, 9, 15, 9, matrix.Color333(4,0,0)); matrix.drawLine(19, 10, 15, 10, matrix.Color333(4,0,0)); matrix.drawLine(18, 11, 15, 11, matrix.Color333(4,0,0)); matrix.drawLine(18, 12, 15, 12, matrix.Color333(4,0,0)); matrix.drawLine(17, 13, 16, 13, matrix.Color333(4,0,0)); delay(250); //color: purple matrix.drawLine(18, 6, 15, 6, matrix.Color333(4,0,4)); matrix.drawLine(19, 7, 13, 7, matrix.Color333(4,0,4)); matrix.drawLine(20, 8, 13, 8, matrix.Color333(4,0,4)); matrix.drawLine(20, 9, 15, 9, matrix.Color333(4,0,4)); matrix.drawLine(19, 10, 15, 10, matrix.Color333(4,0,4)); matrix.drawLine(18, 11, 15, 11, matrix.Color333(4,0,4)); matrix.drawLine(18, 12, 15, 12, matrix.Color333(4,0,4)); matrix.drawLine(17, 13, 16, 13, matrix.Color333(4,0,4)); delay(250); //color: blue matrix.drawLine(18, 6, 15, 6, matrix.Color333(0,0,4)); matrix.drawLine(19, 7, 13, 7, matrix.Color333(0,0,4)); matrix.drawLine(20, 8, 13, 8, matrix.Color333(0,0,4)); matrix.drawLine(20, 9, 15, 9, matrix.Color333(0,0,4)); matrix.drawLine(19, 10, 15, 10, matrix.Color333(0,0,4)); matrix.drawLine(18, 11, 15, 11, matrix.Color333(0,0,4)); matrix.drawLine(18, 12, 15, 12, matrix.Color333(0,0,4)); matrix.drawLine(17, 13, 16, 13, matrix.Color333(0,0,4)); delay(250); } void australia() { matrix.drawLine(29, 10, 28, 10, matrix.Color333(4,4,4)); matrix.drawLine(28, 11, 26, 11, matrix.Color333(4,4,4)); matrix.drawLine(29, 12, 25, 12, matrix.Color333(4,4,4)); matrix.drawLine(26, 13, 25, 13, matrix.Color333(4,4,4)); matrix.drawLine(29, 13, 28, 13, matrix.Color333(4,4,4)); delay(250); //color: green matrix.drawLine(29, 10, 28, 10, matrix.Color333(0,4,0)); matrix.drawLine(28, 11, 26, 11, matrix.Color333(0,4,0)); matrix.drawLine(29, 12, 25, 12, matrix.Color333(0,4,0)); matrix.drawLine(26, 13, 25, 13, matrix.Color333(0,4,0)); matrix.drawLine(29, 13, 28, 13, matrix.Color333(0,4,0)); delay(250); //color: purple matrix.drawLine(29, 10, 28, 10, matrix.Color333(4,0,4)); matrix.drawLine(28, 11, 26, 11, matrix.Color333(4,0,4)); matrix.drawLine(29, 12, 25, 12, matrix.Color333(4,0,4)); matrix.drawLine(26, 13, 25, 13, matrix.Color333(4,0,4)); matrix.drawLine(29, 13, 28, 13, matrix.Color333(4,0,4)); delay(250); //color: red matrix.drawLine(29, 10, 28, 10, matrix.Color333(4,0,0)); matrix.drawLine(28, 11, 26, 11, matrix.Color333(4,0,0)); matrix.drawLine(29, 12, 25, 12, matrix.Color333(4,0,0)); matrix.drawLine(26, 13, 25, 13, matrix.Color333(4,0,0)); matrix.drawLine(29, 13, 28, 13, matrix.Color333(4,0,0)); delay(250); //color: blue matrix.drawLine(29, 10, 28, 10, matrix.Color333(0,0,4)); matrix.drawLine(28, 11, 26, 11, matrix.Color333(0,0,4)); matrix.drawLine(29, 12, 25, 12, matrix.Color333(0,0,4)); matrix.drawLine(26, 13, 25, 13, matrix.Color333(0,0,4)); matrix.drawLine(29, 13, 28, 13, matrix.Color333(0,0,4)); delay(250); } void loop() { // do nothing // fix the screen with green+ /* matrix.fillRect(0, 0, 32, 16, matrix.Color333(0, 7, 0)); delay(500); // draw a box in yellow matrix.drawRect(0, 0, 32, 16, matrix.Color333(7, 7, 0)); delay(500); // draw an 'X' in red matrix.drawLine(0, 0, 31, 15, matrix.Color333(7, 0, 0)); matrix.drawLine(31, 0, 0, 15, matrix.Color333(7, 0, 0)); delay(500); // draw a blue circle matrix.drawCircle(7, 7, 7, matrix.Color333(0, 0, 7)); delay(500); // fill a violet circle matrix.fillCircle(23, 7, 7, matrix.Color333(7, 0, 7)); delay(500); // fill the screen with 'black' matrix.fillScreen(matrix.Color333(0, 0, 0)); delay(500); */ northAmerica(); southAmerica(); eurasia(); africa(); australia(); /* matrix.setCursor (1, 0); matrix.setTextColor(matrix.Color333(0,5,7)); matrix.print('O'); delay(500); matrix.setTextColor(matrix.Color333(0,7,0)); matrix.print('R'); delay(500); matrix.setTextColor(matrix.Color333(6,6,0)); matrix.print('B'); delay(500); matrix.setTextColor(matrix.Color333(4,0,7)); matrix.print("I"); delay(500); matrix.setTextColor(matrix.Color333(5,5,5)); matrix.print("S"); delay(500); */ }
[ "sugarcrystals01@gmail.com" ]
sugarcrystals01@gmail.com
1f597d424be26274b8473b537a2d66ce77a43a5d
ef1e1901b88c30e0a5fabb09ee93a4b711e2cc6b
/ardMoteur/Asservissement.ino
7bde4cfe561247ca6b72b1207680dc07c7f9a4ab
[]
no_license
RobotechLille/Cerveau_CDF
acc371587a8563f7f4557187b59e42c1622080b4
75119c7e6d4097a52947c61780f4893be27364f3
refs/heads/master
2021-01-23T03:16:42.654474
2017-05-26T09:48:15
2017-05-26T09:48:15
86,065,597
0
0
null
null
null
null
UTF-8
C++
false
false
7,585
ino
#include <TimedPID.h> #include <SimpleTimer.h> #include <math.h> #include <Servo.h> Servo myservo; // create servo object to control a servo // COMMANDES QUI PEUVENT ÊTRE REÇUES OU ENVOYÉES // Les 3 premières servent aussi pour l'état du PID #define AVANCER_RECULER 0 #define TOURNER 1 #define STOP 2 #define OBST_DEV 3 #define OBST_DER 4 #define FUNNY_ACT 5 #define TIRETTE 6 //variable globale de choix de commande int etat_pid = STOP; //Définition des pins des signaux A et B des codeuses #define pinA_G 2 // int0 #define pinA_D 3 // int1 #define pinB_G 4 #define pinB_D 8 #define pinTirette 51 //Définitions des pins de commande moteur #define pin_cmd_G 11 //9 uno //11 méga #define pin_rot_G 7 #define pin_cmd_D 12 // 10 uno // 12 méga #define pin_rot_D 5 // Define the PID controller proportional, integral and derivative gains float Kp = 0.8; float Ki = 0.001; float Kd = 0.01; //Variables PID int long tick_G = 0;// Compteur de tick de la codeuse gauche int long tick_D = 0;// Compteur de tick de la codeuse droite int long tick_G_prec = 0; int long tick_D_prec = 0; int long consigne_G = 6000 ; int long consigne_D = 0; int pwm_g =0, pwm_d = 0; // Create a TimedPID object instance TimedPID pid_G(Kp, Ki, Kd); TimedPID pid_D(Kp, Ki, Kd); float force; // the force applied to the mass by the control system // Define the maximum force the system can apply float fMax = 80; // Variables used for set point control and time step calculation unsigned long initialTime; unsigned long lastTime; //variables de timer #define frequence_echantillonnage 20 SimpleTimer timer; int timer_T; int trig = 53; int echo = 52; long lecture_echo; long cm; void setup() { myservo.attach(9); myservo.write(25); delay(15); //set sensor pinMode(trig, OUTPUT); digitalWrite(trig, LOW); pinMode(echo, INPUT); //Set PWM frequency to 31kHz for D11 & D12 !!!FOR Arduino Mega only TCCR1B = TCCR1B & B11111000 | B00000001; // Open Serial communication and wait for monitor to be opened Serial.begin(9600); while(!Serial); // Set the PID controller command range pid_G.setCmdRange(-fMax, fMax); // Définition des pins et des routines d'interruption attachInterrupt(0, compteur_gauche, RISING); // Appel de compteur_gauche sur front montant valeur signal A de la codeuse gauche (interruption 0 = pin2 arduino mega) // attachInterrupt(1, compteur_droit, RISING); // Appel de compteur_droit sur front montant valeur signal A de la codeuse droite (interruption 1 = pin3 arduino mega) pinMode(pinB_G, INPUT); // Pin de signal B du la codeuse gauche pinMode(pinB_D, INPUT); // Pin de signal B de la codeuse droite // Liaison avec les résistances de Pull-up pour les interuptions digitalWrite(pinA_G,HIGH); digitalWrite(pinA_D,HIGH); digitalWrite(pinB_G,HIGH); digitalWrite(pinB_D,HIGH); pinMode(pin_cmd_G,OUTPUT); pinMode(pin_rot_G,OUTPUT); pinMode(pin_cmd_D,OUTPUT); pinMode(pin_rot_D,OUTPUT); //tirette pinMode(pinTirette, OUTPUT); digitalWrite(pinTirette,HIGH) ; // Initialisation du timer qui lance le calcul PID (fonction asservissement) à la fréquence d'échantillonage timer_T = timer.setInterval(1000/frequence_echantillonnage,asservissement); delay(1); timer.enable(timer_T); delay(1); } void loop() { timer.run(); } void verifierCapDev() { digitalWrite(trig, HIGH); delayMicroseconds(10); digitalWrite(trig, LOW); lecture_echo = pulseIn(echo, HIGH); cm = lecture_echo / 58; if (cm < 12) { Serial.write(OBST_DEV); } } float conversion = (M_PI*8)/1024; //-------------------------------------------------------------------------------------------------------- /* Arrêt du PID et retour sur ce qui a été fait */ void retourConsigne() { if (etat_pid == AVANCER_RECULER) { } else if (etat_pid == TOURNER) { } else { } } //-------------------------------------------------------------------------------------------------------- /* Actualisation du PID (sur timer) */ void asservissement() { // Serial.print("Time - \t"); // Serial.println((millis()-depart)/1000); // Serial.print("Status - \t"); // Serial.println(status_prog); // Vérification du capteur devant verifierCapDev() // TODO A faire sur un autre Arduino parce que ça démonte la fréquence d'échantillonage // Paramètrage du PID action(); switch(etat_pid){ case AVANCER_RECULER : Kp = 0.08; Ki = 0.001; Kd = 0.01; pwm_g = pid_G.getCmdAutoStep(consigne_G, tick_G); if(pwm_g <0) { digitalWrite(pin_rot_G,HIGH); delay(1); digitalWrite(pin_rot_D,LOW); delay(1); } else { digitalWrite(pin_rot_G,LOW); delay(1); digitalWrite(pin_rot_D,HIGH); delay(1); } pwm_g = abs(pwm_g); break; case TOURNER : Kp = 0.2; Ki = 0.00025; Kd = 0.0025; pwm_g = pid_G.getCmdAutoStep(consigne_G, tick_G); pwm_d = pid_D.getCmdAutoStep(consigne_D, tick_D); break; case STOP : pwm_g = 0; pwm_d =0 ; break; } // Mise à jour du PID analogWrite(pin_cmd_G,pwm_g); delay(1); analogWrite(pin_cmd_D,pwm_g); delay(1); /// put your main code here, to run repeatedly: // Serial.print("tick_g - tick_d : \t"); // Serial.print(tick_G); // Serial.print("\t"); // Serial.print(tick_D); // Serial.print("\t"); // Serial.print(pwm_g); // Serial.print("\t"); // Serial.println(pwm_d); // Si on est arrivé à la consigne if (consigne_G - 10 <= tick_G) { etat_PID = STOP; retourConsigne(); } } //-------------------------------------------------------------------------------------------------------- /* Interruption sur tick des codeuses */ void compteur_gauche() { if (digitalRead(pinB_G)==LOW) { tick_G--; // On incrémente le nombre de tick de la codeuse } else { tick_G++; } } void compteur_droit() { if (digitalRead(pinB_D)==LOW) { tick_D++; // On incrémente le nombre de tick de la codeuse } else { tick_D--; } } //-------------------------------------------------------------------------------------------------------- /* Interruption sur evenement serial */ void serialEvent() { while(Serial.available()) // Tant qu'il y a des choses à lire (vu qu'une interruption désactive les autres) { int cmd = Serial.read(); delay(1); inFloat = Serialreadfloat(); switch (cmd) { case AVANCER_RECULER : etat_pid = AVANCER_RECULER; //On recoit alors des centimetres qu'on convertit en ticks consigne_G = Serialreadfloat() * conversion; consigne_D = consigne_G; break; case TOURNER : etat_pid = TOURNER; //On recoit alors des degres qu'on convertit en ticks // TODO Conversion fausse consigne_G = Serialreadfloat() * conversion; consigne_D = -consigne_G; break; case STOP : etat_pid = STOP; consigne_G = 0; consigne_D = 0; break; case FUNNY_ACT: etat_pid = STOP; // On est censé recevoir un STOP avant mais sais-t-on jamais myservo.write(250); delay(15); break; case TIRETTE: // Attend jusqu'à la tirette while(!digitalRead(pinTirette)){} Serial.write(TIRETTE); break; } // Serial.write(cmd); // delay(5); // Serialsendfloat(inFloat); } }
[ "francois.duport@hotmail.fr" ]
francois.duport@hotmail.fr
6cd89086c14c3b492da082d0f58efdc867dbc115
a5f29829fd8b54e8fc27373e8379d0dc22b1b992
/simpleMRsimulation/src/grids.cpp
dbeabd58b48fa6e6e51f933858dc91eb7ada2bfb
[]
no_license
YaoNiMing/AlgoTrading
17b5e2024cbefbf74c76b536e7300124f020efe3
2bd93823e7d7d46cab3cb5f9531a67fff93d566f
refs/heads/master
2021-01-13T11:35:11.316286
2017-02-08T18:53:03
2017-02-08T18:53:03
81,176,321
0
1
null
null
null
null
UTF-8
C++
false
false
936
cpp
#include "grids.h" Grids::Grids(double T, size_t n_dt, double sigma, double theta, double kappa){ size_t ii; this->T = T; this->n_dt = n_dt; dt = T/n_dt; t_grid = new double[n_dt+1]; for (ii=0;ii<=n_dt;++ii) { t_grid[ii] = dt*ii; } double nsigma,ep_max,ep_min; dep = sigma*sqrt(3*dt); nsigma = 5*sigma*(1-exp(-2*kappa*T))/sqrt(2*kappa); ep_max = theta + ceil(nsigma / dep) * dep; ep_min = theta - ceil(nsigma / dep) * dep; n_ep = size_t(rint((ep_max-ep_min)/dep)+1); ep_grid = new double[n_ep]; for (ii=0; ii<n_ep; ++ii) { ep_grid[ii] = ep_min + ii*dep; } } double Grids::get_T() {return T;} size_t Grids::get_n_dt() {return n_dt;} double Grids::get_dt() {return dt;} double *Grids::get_t_grid() {return t_grid;} double Grids::get_dep() {return dep;} size_t Grids::get_n_ep() {return n_ep;} double *Grids::get_ep_grid() {return ep_grid;} void Grids::del_grids() { delete[] t_grid; delete[] ep_grid; }
[ "gplrabbit@gmail.com" ]
gplrabbit@gmail.com
8df6418e7ec80edffa7b266ff9251c87e5c69734
1ff37aa5192edc5940876d73eeb05fa4ecc5f28e
/lib/src/vulkan/glslang/hlsl/hlslTokens.h
5a5266ae32781c652656843921fdaa069b1c0852
[ "Apache-2.0" ]
permissive
gitter-badger/Viry3D
6cf453ea3a0df9aeb7d18b7a090f91e038c0eb3d
da59fdd49e181110e58adf80c2f76c9bd1e7e18f
refs/heads/master
2020-03-31T21:26:59.201087
2018-10-10T18:41:02
2018-10-10T18:41:02
152,580,957
0
0
Apache-2.0
2018-10-11T11:30:16
2018-10-11T11:30:16
null
UTF-8
C++
false
false
6,033
h
// //Copyright (C) 2016 Google, Inc. //Copyright (C) 2016 LunarG, Inc. // //All rights reserved. // //Redistribution and use in source and binary forms, with or without //modification, are permitted provided that the following conditions //are met: // // Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // Neither the name of Google, Inc., nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS //"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT //LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS //FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE //COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, //INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, //BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; //LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER //CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT //LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN //ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE //POSSIBILITY OF SUCH DAMAGE. // #ifndef EHLSLTOKENS_H_ #define EHLSLTOKENS_H_ namespace glslang { enum EHlslTokenClass { EHTokNone = 0, // qualifiers EHTokStatic, EHTokConst, EHTokSNorm, EHTokUnorm, EHTokExtern, EHTokUniform, EHTokVolatile, EHTokPrecise, EHTokShared, EHTokGroupShared, EHTokLinear, EHTokCentroid, EHTokNointerpolation, EHTokNoperspective, EHTokSample, EHTokRowMajor, EHTokColumnMajor, EHTokPackOffset, EHTokIn, EHTokOut, EHTokInOut, // template types EHTokBuffer, EHTokVector, EHTokMatrix, // scalar types EHTokVoid, EHTokBool, EHTokInt, EHTokUint, EHTokDword, EHTokHalf, EHTokFloat, EHTokDouble, EHTokMin16float, EHTokMin10float, EHTokMin16int, EHTokMin12int, EHTokMin16uint, // vector types EHTokBool1, EHTokBool2, EHTokBool3, EHTokBool4, EHTokFloat1, EHTokFloat2, EHTokFloat3, EHTokFloat4, EHTokInt1, EHTokInt2, EHTokInt3, EHTokInt4, EHTokDouble1, EHTokDouble2, EHTokDouble3, EHTokDouble4, EHTokUint1, EHTokUint2, EHTokUint3, EHTokUint4, // matrix types EHTokInt1x1, EHTokInt1x2, EHTokInt1x3, EHTokInt1x4, EHTokInt2x1, EHTokInt2x2, EHTokInt2x3, EHTokInt2x4, EHTokInt3x1, EHTokInt3x2, EHTokInt3x3, EHTokInt3x4, EHTokInt4x1, EHTokInt4x2, EHTokInt4x3, EHTokInt4x4, EHTokUint1x1, EHTokUint1x2, EHTokUint1x3, EHTokUint1x4, EHTokUint2x1, EHTokUint2x2, EHTokUint2x3, EHTokUint2x4, EHTokUint3x1, EHTokUint3x2, EHTokUint3x3, EHTokUint3x4, EHTokUint4x1, EHTokUint4x2, EHTokUint4x3, EHTokUint4x4, EHTokBool1x1, EHTokBool1x2, EHTokBool1x3, EHTokBool1x4, EHTokBool2x1, EHTokBool2x2, EHTokBool2x3, EHTokBool2x4, EHTokBool3x1, EHTokBool3x2, EHTokBool3x3, EHTokBool3x4, EHTokBool4x1, EHTokBool4x2, EHTokBool4x3, EHTokBool4x4, EHTokFloat1x1, EHTokFloat1x2, EHTokFloat1x3, EHTokFloat1x4, EHTokFloat2x1, EHTokFloat2x2, EHTokFloat2x3, EHTokFloat2x4, EHTokFloat3x1, EHTokFloat3x2, EHTokFloat3x3, EHTokFloat3x4, EHTokFloat4x1, EHTokFloat4x2, EHTokFloat4x3, EHTokFloat4x4, EHTokDouble1x1, EHTokDouble1x2, EHTokDouble1x3, EHTokDouble1x4, EHTokDouble2x1, EHTokDouble2x2, EHTokDouble2x3, EHTokDouble2x4, EHTokDouble3x1, EHTokDouble3x2, EHTokDouble3x3, EHTokDouble3x4, EHTokDouble4x1, EHTokDouble4x2, EHTokDouble4x3, EHTokDouble4x4, // texturing types EHTokSampler, EHTokSampler1d, EHTokSampler2d, EHTokSampler3d, EHTokSamplerCube, EHTokSamplerState, EHTokSamplerComparisonState, EHTokTexture, EHTokTexture1d, EHTokTexture1darray, EHTokTexture2d, EHTokTexture2darray, EHTokTexture3d, EHTokTextureCube, EHTokTextureCubearray, EHTokTexture2DMS, EHTokTexture2DMSarray, // variable, user type, ... EHTokIdentifier, EHTokTypeName, EHTokStruct, EHTokTypedef, // constant EHTokFloatConstant, EHTokDoubleConstant, EHTokIntConstant, EHTokUintConstant, EHTokBoolConstant, // control flow EHTokFor, EHTokDo, EHTokWhile, EHTokBreak, EHTokContinue, EHTokIf, EHTokElse, EHTokDiscard, EHTokReturn, EHTokSwitch, EHTokCase, EHTokDefault, // expressions EHTokLeftOp, EHTokRightOp, EHTokIncOp, EHTokDecOp, EHTokLeOp, EHTokGeOp, EHTokEqOp, EHTokNeOp, EHTokAndOp, EHTokOrOp, EHTokXorOp, EHTokAssign, EHTokMulAssign, EHTokDivAssign, EHTokAddAssign, EHTokModAssign, EHTokLeftAssign, EHTokRightAssign, EHTokAndAssign, EHTokXorAssign, EHTokOrAssign, EHTokSubAssign, EHTokLeftParen, EHTokRightParen, EHTokLeftBracket, EHTokRightBracket, EHTokLeftBrace, EHTokRightBrace, EHTokDot, EHTokComma, EHTokColon, EHTokSemicolon, EHTokBang, EHTokDash, EHTokTilde, EHTokPlus, EHTokStar, EHTokSlash, EHTokPercent, EHTokLeftAngle, EHTokRightAngle, EHTokVerticalBar, EHTokCaret, EHTokAmpersand, EHTokQuestion, }; } // end namespace glslang #endif // EHLSLTOKENS_H_
[ "stackos@qq.com" ]
stackos@qq.com
8a037a8485021cb93ff250fd11fb3b90445f6513
43d5b851932ca564bd26a4e96212797ae0e2cd21
/Include/Goblin/User/Interface/NPCDialog.hpp
4ea55d0e0a953bb35bbbd0ab89502a6126f5d5ca
[]
no_license
HexColors60/GoblinCamp
8c427bd04beba022b0c6df980eccfe93ac5770af
80b2ee98dc20ea10a9f5731338f548f0cb2197a5
refs/heads/main
2023-03-21T05:31:29.831316
2021-03-20T02:41:03
2021-03-20T02:41:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,130
hpp
/* Copyright 2010-2011 Ilkka Halila This file is part of Goblin Camp. Goblin Camp is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Goblin Camp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Goblin Camp. If not, see <http://www.gnu.org/licenses/>.*/ #pragma once #include <memory> #include <utility> #include <libtcod.hpp> #include "Goblin/Entity/NPC.hpp" #include "Goblin/User/Interface/Dialog.hpp" #include <Goblin/User/Interface/UIContainer.hpp> class NPCDialog : public UIContainer { public: NPCDialog(); static void DrawNPC(std::pair<int, std::shared_ptr<NPC> >, int, int, int, int, bool, TCODConsole*); static Dialog* npcListDialog; static Dialog* NPCListDialog(); };
[ "andres6936@live.com" ]
andres6936@live.com
2c3b836243337d5ee91a1244404a55ee1f22cf10
6586ec50430a7c0e9da66f9c8f13dddaddedd47f
/scope/global_scope.cpp
cd8f9feb57515b19e5e2267bfe9676cd59a43c4a
[]
no_license
ali01/galadriel
f1d3239834b2e4b70ecd962bab7d41d0c4aafb88
24fc228e9afe4ee72d81c346d9f2fab65f9458b3
refs/heads/master
2016-09-11T00:36:05.897111
2014-04-16T22:21:37
2014-04-16T22:21:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
528
cpp
#include "global_scope.h" /* code_generator includes */ #include <code_generator/location_includes.h> GlobalScope::GlobalScope() : Scope(NULL) { node_functor_ = NodeFunctor::NodeFunctorNew(this); } void GlobalScope::NodeFunctor::operator()(VarDecl *_d) { Location::Offset off = scope_->varDeclCount(); Location::Segment seg = Location::kData; VarLocation::Ptr loc; loc = VarLocation::VarLocationNew(seg, off, _d); _d->locationIs(loc); /* calling base class version */ Scope::NodeFunctor::operator()(_d); }
[ "alive@ali01.com" ]
alive@ali01.com
1ef26df79ea3b696272947534c3956aad6c53b86
67fc10f71b4dd3e9956eb2e4b871d2abc659acb6
/iteration 1/prototypes/image/obj.h
20fe707b3aed37fe61cb04f932541fe9653783fe
[]
no_license
Batyan/Eliminator
84418a9520aed260e78fcdf66406864f353778c1
1b7f7ff9457cf013da0f575fc4a88913aebfee31
refs/heads/master
2021-01-19T06:06:18.674091
2013-12-04T22:11:29
2013-12-04T22:11:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
386
h
#ifndef OBJ_H #define OBJ_H #include <QGraphicsItem> class obj : public QGraphicsItem { public: obj(); QRectF boundingRect() const; QPainterPath shape() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); protected: void advance(int step); private: qreal angle; qreal speed; }; #endif // OBJ_H
[ "bouyaka_619@hotmail.fr" ]
bouyaka_619@hotmail.fr
fdeb631de00b1fc1d05b60fd201bf986f82c7993
0e8cf7868f8dbc4617b0bbd9a6da2923af90d9b6
/src/qross/core/metatype.h
50d43580bed4797da7a2b088c60a82c293569e07
[]
no_license
0xd34df00d/Qross
ec7542a753222f66935a6c51bc7d4b06a24ac4ff
32b5f16c421b4a60b327c2d05e8e9a2908fb9a22
refs/heads/master
2020-12-23T00:48:55.710182
2020-05-17T15:46:09
2020-05-17T15:46:09
575,775
2
3
null
2022-04-27T21:19:12
2010-03-23T14:56:27
C#
UTF-8
C++
false
false
5,941
h
/*************************************************************************** * metatype.h * This file is part of the KDE project * copyright (C)2004-2006 by Sebastian Sauer (mail@dipe.org) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * You should have received a copy of the GNU Library General Public License * along with this program; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. ***************************************************************************/ #ifndef QROSS_METATYPE_H #define QROSS_METATYPE_H #include "qrossconfig.h" //#include "object.h" #include <QtCore/QStringList> #include <QtCore/QVariant> #include <QtCore/QMetaType> #include <typeinfo> //#include <QDate> //#include <QTime> //#include <QDateTime> namespace Qross { /** * Base class for metatype-implementations. */ class MetaType { public: virtual ~MetaType() {} virtual int typeId() = 0; //virtual QObject* toObject() = 0; //virtual QVariant toVariant() = 0; virtual void* toVoidStar() = 0; }; /** * Metatypes which are registered in the QMetaType system. */ template<typename METATYPE> class MetaTypeImpl : public MetaType { public: MetaTypeImpl(const METATYPE& v) : m_variant(v) { #ifdef QROSS_METATYPE_DEBUG qrossdebug( QString("MetaTypeImpl<METATYPE> Ctor typeid=%1 typename=%2").arg(qMetaTypeId<METATYPE>()).arg(typeid(METATYPE).name()) ); #endif } virtual ~MetaTypeImpl() { #ifdef QROSS_METATYPE_DEBUG qrossdebug( QString("MetaTypeImpl<METATYPE> Dtor typeid=%1 typename=%2").arg(qMetaTypeId<METATYPE>()).arg(typeid(METATYPE).name()) ); #endif } virtual int typeId() { return qMetaTypeId<METATYPE>(); } //virtual QVariant toVariant() { return QVariant(typeId(), m_variant); } virtual void* toVoidStar() { return (void*) &m_variant; } private: METATYPE m_variant; }; /** * Metatypes which are listened in QVariant::Type. */ template<typename VARIANTTYPE> class MetaTypeVariant : public MetaType { public: MetaTypeVariant(const VARIANTTYPE& v) : m_value(v) { #ifdef QROSS_METATYPE_DEBUG qrossdebug( QString("MetaTypeVariant<VARIANTTYPE> Ctor value=%1 typename=%2").arg(qVariantFromValue(m_value).toString()).arg(qVariantFromValue(m_value).typeName()) ); #endif } virtual ~MetaTypeVariant() { #ifdef QROSS_METATYPE_DEBUG qrossdebug( QString("MetaTypeVariant<VARIANTTYPE> Dtor value=%1 typename=%2").arg(qVariantFromValue(m_value).toString()).arg(qVariantFromValue(m_value).typeName()) ); #endif } virtual int typeId() { return qVariantFromValue(m_value).type(); } //virtual QVariant toVariant() { return qVariantFromValue(m_value); } virtual void* toVoidStar() { return (void*) &m_value; } private: VARIANTTYPE m_value; }; /** * Metatype for generic VoidStar pointers. */ class MetaTypeVoidStar : public MetaType { public: MetaTypeVoidStar(int typeId, void* ptr, bool owner) : m_typeId(typeId), m_ptr(ptr), m_owner(owner) { #ifdef QROSS_METATYPE_DEBUG qrossdebug( QString("MetaTypeVoidStar Ctor typeid=%1 typename=%2 owner=%3").arg(m_typeId).arg(typeid(m_ptr).name()).arg(m_owner) ); #endif } virtual ~MetaTypeVoidStar() { #ifdef QROSS_METATYPE_DEBUG qrossdebug( QString("MetaTypeVoidStar Ctor typeid=%1 typename=%2 owner=%3").arg(m_typeId).arg(typeid(m_ptr).name()).arg(m_owner) ); #endif if( m_owner ) QMetaType::destroy(m_typeId, m_ptr); } virtual int typeId() { return m_typeId; } virtual void* toVoidStar() { return (void*) &m_ptr; /*return m_ptr;*/ } protected: int m_typeId; void* m_ptr; bool m_owner; }; /** * Base class for metatype-handlers as used returned by * the Qross::Manager::metaTypeHandler() method. * * \since 4.2 */ class QROSSCORE_EXPORT MetaTypeHandler { public: typedef QVariant (FunctionPtr) (void*); typedef QVariant (FunctionPtr2) (MetaTypeHandler* handler, void*); explicit MetaTypeHandler() : m_func1(0), m_func2(0) {} explicit MetaTypeHandler(FunctionPtr *func) : m_func1(func), m_func2(0) {} explicit MetaTypeHandler(FunctionPtr2 *func) : m_func1(0), m_func2(func) {} virtual ~MetaTypeHandler() {} /** * This got called by the scripting-backend if the type-handler * is called to translate a void-star pointer to a QVariant. */ virtual QVariant callHandler(void* ptr) { return m_func1 ? m_func1(ptr) : m_func2 ? m_func2(this, ptr) : QVariant(); } private: FunctionPtr *m_func1; FunctionPtr2 *m_func2; }; } #endif
[ "0xd34df00d@gmail.com" ]
0xd34df00d@gmail.com
56c14172d67132c74f268fdc68a070fb6c3523e9
f0ba9db32f36c5aba864e5978872b2e8ad10aa40
/examples/example_class_empty.hpp
df7c888772fab8341b6ca56de92e0a44b206cdb5
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
Bareflank/bsl
fb325084b19cd48e03197f4265049f9c8d008c9f
6509cfff948fa34b98585512d7be33a36e2f9522
refs/heads/master
2021-12-25T11:19:43.743888
2021-10-21T14:47:58
2021-10-21T14:47:58
216,364,945
77
5
NOASSERTION
2021-10-21T02:24:26
2019-10-20T13:18:28
C++
UTF-8
C++
false
false
1,488
hpp
/// @copyright /// Copyright (C) 2020 Assured Information Security, Inc. /// /// @copyright /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// @copyright /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// @copyright /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE /// SOFTWARE. #ifndef BSL_EXAMPLE_CLASS_EMPTY_HPP #define BSL_EXAMPLE_CLASS_EMPTY_HPP namespace bsl { /// @class bsl::example_class_empty /// /// <!-- description --> /// @brief An example of an empty class. /// struct example_class_empty final {}; } #endif
[ "rianquinn@gmail.com" ]
rianquinn@gmail.com
fd080df53f9615d5dad7ac98ace3f69a8fb7a4a8
42c0ea78faf8e22d4036cf2937b46ee0cb97e9af
/3d_vector.cpp
9038692316f2d63581a903fcf21bdb45b88249b4
[]
no_license
forsaken1/glut
39a71ce784a124bbae150190f6ef89374e683f0f
6458bd582e27bdc50265c2001aa03664160106ba
refs/heads/master
2021-01-20T22:41:27.450923
2014-06-25T18:44:55
2014-06-25T18:44:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
191
cpp
struct Vector3f { float x; float y; float z; Vector3f() { } Vector3f(float _x, float _y, float _z) { x = _x; y = _y; z = _z; } };
[ "alexey2142@mail.ru" ]
alexey2142@mail.ru
b9eb3e13e2f104fdc764919552e4eafdcafbb1ab
f6b6f9ded57dc7f2fd43dbe0dd84484311b6dc4f
/ext/timers.cpp
355a1555a8f55a9f4ae731726480bc181641d298
[]
no_license
linoma/ideas
6bfce79e7fcefbc8755cab4e45b71ec76f8edfc9
d68329115e7de093987aa07c45e3ab9fb7dfcd4b
refs/heads/master
2020-04-12T05:22:46.073859
2018-12-19T07:54:39
2018-12-19T07:54:39
162,324,906
2
0
null
null
null
null
UTF-8
C++
false
false
5,811
cpp
#include "ideastypes.h" #include "lds.h" TIMER timers[8]; static u16 value[2][4] = {{0,6,8,10},{1,64,256,1024}}; //----------------------------------------------------------------------- BOOL TIMER_Save(LStream *pFile) { pFile->Write(timers,sizeof(timers)); return TRUE; } //----------------------------------------------------------------------- BOOL TIMER_Load(LStream *pFile,int ver) { pFile->Read(timers,sizeof(timers)); return TRUE; } //----------------------------------------------------------------------- void ResetTimer() { u8 i; PTIMER p; p = timers; ZeroMemory(timers,sizeof(timers)); for(i=0;i<8;i++,p++){ p->Index = (u8)(i&3); p->Freq = value[1][0]; p->logFreq = value[0][0]; } } /*extern void ExecDMA(u8 i); for(i=0;i<4;i++){ if(dma9_cycles_irq[i] == 0) continue; if(dma9_cycles_irq[i] > cyc) dma9_cycles_irq[i] -= cyc; else{ dma9_cycles_irq[i] = 0; ExecDMA((i + 4)|0xF0); } }*/ //----------------------------------------------------------------------- void RenderTimer(u16 cyc) { u8 i,ovr,i1; u16 res,div; PTIMER p; p = timers; for(i1=0;i1<2;i1++){ ovr = 0; for(i=0;i<4;i++,p++){ if(!p->Enable) continue; if(p->Cascade){ if(!ovr) continue; res = p->Count; p->Count += ovr; ovr = 0; if(p->Count < res){ p->Count += p->ResetValue; if(p->Irq) ds.set_IRQ((u32)(1 << (p->Index + 3)),FALSE,(i1 ^ 1) +1); ovr = 1; } } else{ p->Value += cyc; ovr = 0; if(p->Value < p->Freq) continue; res = p->Count; p->Count += (div = (u16)(p->Value >> p->logFreq)); p->Value -= (div << p->logFreq); if(p->Count < res){ p->Remainder += p->Count; p->Count += p->ResetValue; ovr = 1; if(p->Remainder >= p->Diff && p->Diff >= 2){ p->Remainder -= (u16)((div = (u16)(p->Remainder / p->Diff)) * p->Diff); p->Inc += (u8)div; ovr += (u8)div; } if(p->Irq) ds.set_IRQ((u32)(1 << (p->Index + 3)),FALSE,(i1 ^ 1) +1); } } } } } //----------------------------------------------------------------------- static u32 oTIMER_L7(u32 adr,u8 am) { LPTIMER p; p = &timers[((adr - 0x100) >> 2)]; if(am == AMM_HWORD) return (u32)p->Count; else if(am == AMM_WORD) return (u32)MAKELONG(p->Count,*((u16 *)(io_mem7 + adr + 2))); return 0; } //----------------------------------------------------------------------- static void iTIMER_H7(u32 adr,u32 data,u8 am) { u16 Control; LPTIMER p; u8 Enable; p = &timers[((adr - 0x100) >> 2)]; p->Control = (u16)data; Enable = p->Enable; p->Enable = (u8)((Control = p->Control) >> 7); if(p->Enable != Enable) p->Count = p->ResetValue; p->Irq = (u8)((Control & 0x40) >> 6); p->Cascade = (u8)(p->Index == 0 ? 0 : ((Control & 0x4) >> 2)); p->Freq = value[1][(Control & 0x3)]; p->logFreq = value[0][(Control & 0x3)]; } //----------------------------------------------------------------------- static void iTIMER_L7(u32 adr,u32 data,u8 am) { LPTIMER p; p = &timers[((adr - 0x100) >> 2)]; p->ResetValue = (u16)data; p->Diff = (u16)(65536 - p->ResetValue); //802fefA p->Inc = 0; p->Remainder = 0; p->Value = 0; if(am == AMM_WORD) iTIMER_H7(adr,(u32)(data >> 16),AMM_WORD); } //----------------------------------------------------------------------- static u32 oTIMER_L9(u32 adr,u8 am) { LPTIMER p; p = &timers[4+((adr - 0x100) >> 2)]; if(am == AMM_HWORD) return (u32)p->Count; else if(am == AMM_WORD) return (u32)MAKELONG(p->Count,*((u16 *)(io_mem + adr + 2))); return 0; } //----------------------------------------------------------------------- static void iTIMER_H9(u32 adr,u32 data,u8 am) { u16 Control; LPTIMER p; u8 Enable; p = &timers[4+((adr - 0x100) >> 2)]; p->Control = (u16)data; Enable = p->Enable; p->Enable = (u8)((Control = p->Control) >> 7); // if(p->Enable != Enable) // p->Count = p->ResetValue; p->Irq = (u8)((Control & 0x40) >> 6); p->Cascade = (u8)(p->Index == 0 ? 0 : ((Control & 0x4) >> 2)); p->Freq = value[1][(Control & 0x3)]; p->logFreq = value[0][(Control & 0x3)]; } //----------------------------------------------------------------------- static void iTIMER_L9(u32 adr,u32 data,u8 am) { LPTIMER p; p = &timers[4+((adr - 0x100) >> 2)]; p->ResetValue = (u16)data; p->Count = p->ResetValue; p->Diff = (u16)(65536 - p->ResetValue); //802fefA p->Inc = 0; p->Remainder = 0; p->Value = 0; if(am == AMM_WORD) iTIMER_H9(adr,(u32)(data >> 16),AMM_WORD); } //----------------------------------------------------------------------- void InitTimersTable(LPIFUNC *p,LPIFUNC *p1,LPOFUNC *p2,LPOFUNC *p3) { int i,i1; for(i=0x100;i<0x10F;){ for(i1=0;i1<2;i1++,i++){ p1[i] = iTIMER_L7; p[i] = iTIMER_L9; p2[i] = oTIMER_L9; p3[i] = oTIMER_L7; } for(i1=0;i1<2;i1++,i++){ p1[i] = iTIMER_H7; p[i] = iTIMER_H9; } } }
[ "linoma@gmail.com" ]
linoma@gmail.com
b97d502b9937e9e831f667405824a0b842356d9a
4b4f9fed54eb783bdfc488c9e0b13ee2d7220667
/BitManipulations/FindUniqueNumber.cpp
9e7d224b52bc93af9de322c4c0f1743b121c01dc
[]
no_license
codingducksorg/DataStructuresAndAlgorithms
45d33d7ff8e65e94661b6410d736da89a5f0ea18
d9029cb1eda72da853a4760a9c61dcea95075fbc
refs/heads/master
2021-01-25T04:14:40.559724
2017-06-15T07:28:44
2017-06-15T07:28:44
93,413,371
8
6
null
2020-10-09T16:56:32
2017-06-05T14:36:24
Python
UTF-8
C++
false
false
158
cpp
#include <iostream> using namespace std; int main() { int a[7] = {1,2,1,3,1,2,1}, i, res=0; for(i=0;i<7;i++) res^=a[i]; cout<<res<<endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
3bcb4153d89026d7d8aad67228a5c239746e50eb
6e57bdc0a6cd18f9f546559875256c4570256c45
/frameworks/native/services/surfaceflinger/Layer.h
d5d89e4c44d6a03df6dcf50e9f6cf1dd3d25f333
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
dongdong331/test
969d6e945f7f21a5819cd1d5f536d12c552e825c
2ba7bcea4f9d9715cbb1c4e69271f7b185a0786e
refs/heads/master
2023-03-07T06:56:55.210503
2020-12-07T04:15:33
2020-12-07T04:15:33
134,398,935
2
1
null
2022-11-21T07:53:41
2018-05-22T10:26:42
null
UTF-8
C++
false
false
28,707
h
/* * Copyright (C) 2007 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. */ #ifndef ANDROID_LAYER_H #define ANDROID_LAYER_H #include <sys/types.h> #include <utils/RefBase.h> #include <utils/String8.h> #include <utils/Timers.h> #include <ui/FloatRect.h> #include <ui/FrameStats.h> #include <ui/GraphicBuffer.h> #include <ui/PixelFormat.h> #include <ui/Region.h> #include <gui/ISurfaceComposerClient.h> #include <gui/LayerState.h> #include <gui/BufferQueue.h> #include <list> #include <cstdint> #include "Client.h" #include "FrameTracker.h" #include "LayerVector.h" #include "MonitoredProducer.h" #include "SurfaceFlinger.h" #include "TimeStats/TimeStats.h" #include "Transform.h" #include <layerproto/LayerProtoHeader.h> #include "DisplayHardware/HWComposer.h" #include "DisplayHardware/HWComposerBufferCache.h" #include "RenderArea.h" #include "RenderEngine/Mesh.h" #include "RenderEngine/Texture.h" #include <math/vec4.h> #include <vector> using namespace android::surfaceflinger; namespace android { // --------------------------------------------------------------------------- class Client; class Colorizer; class DisplayDevice; class GraphicBuffer; class SurfaceFlinger; class LayerDebugInfo; class LayerBE; namespace impl { class SurfaceInterceptor; } // --------------------------------------------------------------------------- struct CompositionInfo { HWC2::Composition compositionType; sp<GraphicBuffer> mBuffer = nullptr; int mBufferSlot = BufferQueue::INVALID_BUFFER_SLOT; struct { HWComposer* hwc; sp<Fence> fence; HWC2::BlendMode blendMode; Rect displayFrame; float alpha; FloatRect sourceCrop; HWC2::Transform transform; int z; int type; int appId; Region visibleRegion; Region surfaceDamage; sp<NativeHandle> sidebandStream; android_dataspace dataspace; hwc_color_t color; } hwc; struct { RE::RenderEngine* renderEngine; Mesh* mesh; } renderEngine; }; class LayerBE { public: LayerBE(); // The mesh used to draw the layer in GLES composition mode Mesh mMesh; // HWC items, accessed from the main thread struct HWCInfo { HWCInfo() : hwc(nullptr), layer(nullptr), forceClientComposition(false), compositionType(HWC2::Composition::Invalid), clearClientTarget(false), transform(HWC2::Transform::None) {} HWComposer* hwc; HWC2::Layer* layer; bool forceClientComposition; HWC2::Composition compositionType; bool clearClientTarget; Rect displayFrame; FloatRect sourceCrop; HWComposerBufferCache bufferCache; HWC2::Transform transform; }; // A layer can be attached to multiple displays when operating in mirror mode // (a.k.a: when several displays are attached with equal layerStack). In this // case we need to keep track. In non-mirror mode, a layer will have only one // HWCInfo. This map key is a display layerStack. std::unordered_map<int32_t, HWCInfo> mHwcLayers; CompositionInfo compositionInfo; }; class Layer : public virtual RefBase { static int32_t sSequence; public: LayerBE& getBE() { return mBE; } LayerBE& getBE() const { return mBE; } mutable bool contentDirty; // regions below are in window-manager space Region visibleRegion; Region coveredRegion; Region visibleNonTransparentRegion; Region surfaceDamageRegion; // Layer serial number. This gives layers an explicit ordering, so we // have a stable sort order when their layer stack and Z-order are // the same. int32_t sequence; enum { // flags for doTransaction() eDontUpdateGeometryState = 0x00000001, eVisibleRegion = 0x00000002, }; struct Geometry { uint32_t w; uint32_t h; Transform transform; inline bool operator==(const Geometry& rhs) const { return (w == rhs.w && h == rhs.h) && (transform.tx() == rhs.transform.tx()) && (transform.ty() == rhs.transform.ty()); } inline bool operator!=(const Geometry& rhs) const { return !operator==(rhs); } }; struct State { Geometry active; Geometry requested; int32_t z; // The identifier of the layer stack this layer belongs to. A layer can // only be associated to a single layer stack. A layer stack is a // z-ordered group of layers which can be associated to one or more // displays. Using the same layer stack on different displays is a way // to achieve mirroring. uint32_t layerStack; uint8_t flags; uint8_t reserved[2]; int32_t sequence; // changes when visible regions can change bool modified; // Crop is expressed in layer space coordinate. Rect crop; Rect requestedCrop; // finalCrop is expressed in display space coordinate. Rect finalCrop; Rect requestedFinalCrop; // If set, defers this state update until the identified Layer // receives a frame with the given frameNumber wp<Layer> barrierLayer; uint64_t frameNumber; // the transparentRegion hint is a bit special, it's latched only // when we receive a buffer -- this is because it's "content" // dependent. Region activeTransparentRegion; Region requestedTransparentRegion; int32_t appId; int32_t type; // If non-null, a Surface this Surface's Z-order is interpreted relative to. wp<Layer> zOrderRelativeOf; // A list of surfaces whose Z-order is interpreted relative to ours. SortedVector<wp<Layer>> zOrderRelatives; half4 color; }; Layer(SurfaceFlinger* flinger, const sp<Client>& client, const String8& name, uint32_t w, uint32_t h, uint32_t flags); virtual ~Layer(); void setPrimaryDisplayOnly() { mPrimaryDisplayOnly = true; } // ------------------------------------------------------------------------ // Geometry setting functions. // // The following group of functions are used to specify the layers // bounds, and the mapping of the texture on to those bounds. According // to various settings changes to them may apply immediately, or be delayed until // a pending resize is completed by the producer submitting a buffer. For example // if we were to change the buffer size, and update the matrix ahead of the // new buffer arriving, then we would be stretching the buffer to a different // aspect before and after the buffer arriving, which probably isn't what we wanted. // // The first set of geometry functions are controlled by the scaling mode, described // in window.h. The scaling mode may be set by the client, as it submits buffers. // This value may be overriden through SurfaceControl, with setOverrideScalingMode. // // Put simply, if our scaling mode is SCALING_MODE_FREEZE, then // matrix updates will not be applied while a resize is pending // and the size and transform will remain in their previous state // until a new buffer is submitted. If the scaling mode is another value // then the old-buffer will immediately be scaled to the pending size // and the new matrix will be immediately applied following this scaling // transformation. // Set the default buffer size for the assosciated Producer, in pixels. This is // also the rendered size of the layer prior to any transformations. Parent // or local matrix transformations will not affect the size of the buffer, // but may affect it's on-screen size or clipping. bool setSize(uint32_t w, uint32_t h); // Set a 2x2 transformation matrix on the layer. This transform // will be applied after parent transforms, but before any final // producer specified transform. bool setMatrix(const layer_state_t::matrix22_t& matrix); // This second set of geometry attributes are controlled by // setGeometryAppliesWithResize, and their default mode is to be // immediate. If setGeometryAppliesWithResize is specified // while a resize is pending, then update of these attributes will // be delayed until the resize completes. // setPosition operates in parent buffer space (pre parent-transform) or display // space for top-level layers. bool setPosition(float x, float y, bool immediate); // Buffer space bool setCrop(const Rect& crop, bool immediate); // Parent buffer space/display space bool setFinalCrop(const Rect& crop, bool immediate); // TODO(b/38182121): Could we eliminate the various latching modes by // using the layer hierarchy? // ----------------------------------------------------------------------- bool setLayer(int32_t z); bool setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ); bool setAlpha(float alpha); bool setColor(const half3& color); bool setTransparentRegionHint(const Region& transparent); bool setFlags(uint8_t flags, uint8_t mask); bool setLayerStack(uint32_t layerStack); uint32_t getLayerStack() const; void deferTransactionUntil(const sp<IBinder>& barrierHandle, uint64_t frameNumber); void deferTransactionUntil(const sp<Layer>& barrierLayer, uint64_t frameNumber); bool setOverrideScalingMode(int32_t overrideScalingMode); void setInfo(int32_t type, int32_t appId); bool reparentChildren(const sp<IBinder>& layer); void setChildrenDrawingParent(const sp<Layer>& layer); bool reparent(const sp<IBinder>& newParentHandle); bool detachChildren(); ui::Dataspace getDataSpace() const { return mCurrentDataSpace; } // Before color management is introduced, contents on Android have to be // desaturated in order to match what they appears like visually. // With color management, these contents will appear desaturated, thus // needed to be saturated so that they match what they are designed for // visually. bool isLegacyDataSpace() const; // If we have received a new buffer this frame, we will pass its surface // damage down to hardware composer. Otherwise, we must send a region with // one empty rect. virtual void useSurfaceDamage() {} virtual void useEmptyDamage() {} uint32_t getTransactionFlags(uint32_t flags); uint32_t setTransactionFlags(uint32_t flags); bool belongsToDisplay(uint32_t layerStack, bool isPrimaryDisplay) const { return getLayerStack() == layerStack && (!mPrimaryDisplayOnly || isPrimaryDisplay); } void computeGeometry(const RenderArea& renderArea, Mesh& mesh, bool useIdentityTransform) const; FloatRect computeBounds(const Region& activeTransparentRegion) const; FloatRect computeBounds() const; int32_t getSequence() const { return sequence; } // ----------------------------------------------------------------------- // Virtuals virtual const char* getTypeId() const = 0; /* * isOpaque - true if this surface is opaque * * This takes into account the buffer format (i.e. whether or not the * pixel format includes an alpha channel) and the "opaque" flag set * on the layer. It does not examine the current plane alpha value. */ virtual bool isOpaque(const Layer::State&) const { return false; } /* * isSecure - true if this surface is secure, that is if it prevents * screenshots or VNC servers. */ bool isSecure() const; /* * isVisible - true if this layer is visible, false otherwise */ virtual bool isVisible() const = 0; /* * isHiddenByPolicy - true if this layer has been forced invisible. * just because this is false, doesn't mean isVisible() is true. * For example if this layer has no active buffer, it may not be hidden by * policy, but it still can not be visible. */ bool isHiddenByPolicy() const; /* * isFixedSize - true if content has a fixed size */ virtual bool isFixedSize() const { return true; } bool isPendingRemoval() const { return mPendingRemoval; } void writeToProto(LayerProto* layerInfo, LayerVector::StateSet stateSet = LayerVector::StateSet::Drawing); void writeToProto(LayerProto* layerInfo, int32_t hwcId); protected: /* * onDraw - draws the surface. */ virtual void onDraw(const RenderArea& renderArea, const Region& clip, bool useIdentityTransform) const = 0; public: virtual void setDefaultBufferSize(uint32_t /*w*/, uint32_t /*h*/) {} virtual bool isHdrY410() const { return false; } void setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z); void forceClientComposition(int32_t hwcId); bool getForceClientComposition(int32_t hwcId); virtual void setPerFrameData(const sp<const DisplayDevice>& displayDevice) = 0; // callIntoHwc exists so we can update our local state and call // acceptDisplayChanges without unnecessarily updating the device's state void setCompositionType(int32_t hwcId, HWC2::Composition type, bool callIntoHwc = true); HWC2::Composition getCompositionType(int32_t hwcId) const; void setClearClientTarget(int32_t hwcId, bool clear); bool getClearClientTarget(int32_t hwcId) const; void updateCursorPosition(const sp<const DisplayDevice>& hw); /* * called after page-flip */ virtual void onLayerDisplayed(const sp<Fence>& releaseFence); virtual void abandon() {} virtual bool shouldPresentNow(const DispSync& /*dispSync*/) const { return false; } virtual void setTransformHint(uint32_t /*orientation*/) const { } /* * called before composition. * returns true if the layer has pending updates. */ virtual bool onPreComposition(nsecs_t /*refreshStartTime*/) { return true; } /* * called after composition. * returns true if the layer latched a new buffer this frame. */ virtual bool onPostComposition(const std::shared_ptr<FenceTime>& /*glDoneFence*/, const std::shared_ptr<FenceTime>& /*presentFence*/, const CompositorTiming& /*compositorTiming*/) { return false; } // If a buffer was replaced this frame, release the former buffer virtual void releasePendingBuffer(nsecs_t /*dequeueReadyTime*/) { } /* * draw - performs some global clipping optimizations * and calls onDraw(). */ void draw(const RenderArea& renderArea, const Region& clip) const; void draw(const RenderArea& renderArea, bool useIdentityTransform) const; void draw(const RenderArea& renderArea) const; /* * doTransaction - process the transaction. This is a good place to figure * out which attributes of the surface have changed. */ uint32_t doTransaction(uint32_t transactionFlags); /* * setVisibleRegion - called to set the new visible region. This gives * a chance to update the new visible region or record the fact it changed. */ void setVisibleRegion(const Region& visibleRegion); /* * setCoveredRegion - called when the covered region changes. The covered * region corresponds to any area of the surface that is covered * (transparently or not) by another surface. */ void setCoveredRegion(const Region& coveredRegion); /* * setVisibleNonTransparentRegion - called when the visible and * non-transparent region changes. */ void setVisibleNonTransparentRegion(const Region& visibleNonTransparentRegion); /* * Clear the visible, covered, and non-transparent regions. */ void clearVisibilityRegions(); /* * latchBuffer - called each time the screen is redrawn and returns whether * the visible regions need to be recomputed (this is a fairly heavy * operation, so this should be set only if needed). Typically this is used * to figure out if the content or size of a surface has changed. */ virtual Region latchBuffer(bool& /*recomputeVisibleRegions*/, nsecs_t /*latchTime*/) { return {}; } virtual bool isBufferLatched() const { return false; } bool isPotentialCursor() const { return mPotentialCursor; } /* * called with the state lock from a binder thread when the layer is * removed from the current list to the pending removal list */ void onRemovedFromCurrentState(); /* * called with the state lock from the main thread when the layer is * removed from the pending removal list */ void onRemoved(); // Updates the transform hint in our SurfaceFlingerConsumer to match // the current orientation of the display device. void updateTransformHint(const sp<const DisplayDevice>& hw) const; /* * returns the rectangle that crops the content of the layer and scales it * to the layer's size. */ Rect getContentCrop() const; /* * Returns if a frame is queued. */ bool hasQueuedFrame() const { return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh; } int32_t getQueuedFrameCount() const { return mQueuedFrames; } // ----------------------------------------------------------------------- bool createHwcLayer(HWComposer* hwc, int32_t hwcId); bool destroyHwcLayer(int32_t hwcId); void destroyAllHwcLayers(); bool hasHwcLayer(int32_t hwcId) { return getBE().mHwcLayers.count(hwcId) > 0; } HWC2::Layer* getHwcLayer(int32_t hwcId) { if (getBE().mHwcLayers.count(hwcId) == 0) { return nullptr; } return getBE().mHwcLayers[hwcId].layer; } // ----------------------------------------------------------------------- void clearWithOpenGL(const RenderArea& renderArea) const; void setFiltering(bool filtering); bool getFiltering() const; inline const State& getDrawingState() const { return mDrawingState; } inline const State& getCurrentState() const { return mCurrentState; } inline State& getCurrentState() { return mCurrentState; } LayerDebugInfo getLayerDebugInfo() const; /* always call base class first */ static void miniDumpHeader(String8& result); void miniDump(String8& result, int32_t hwcId) const; void dumpFrameStats(String8& result) const; void dumpFrameEvents(String8& result); void clearFrameStats(); void logFrameStats(); void getFrameStats(FrameStats* outStats) const; virtual std::vector<OccupancyTracker::Segment> getOccupancyHistory(bool /*forceFlush*/) { return {}; } void onDisconnect(); void addAndGetFrameTimestamps(const NewFrameEventsEntry* newEntry, FrameEventHistoryDelta* outDelta); virtual bool getTransformToDisplayInverse() const { return false; } Transform getTransform() const; // Returns the Alpha of the Surface, accounting for the Alpha // of parent Surfaces in the hierarchy (alpha's will be multiplied // down the hierarchy). half getAlpha() const; half4 getColor() const; void traverseInReverseZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor); void traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor); /** * Traverse only children in z order, ignoring relative layers that are not children of the * parent. */ void traverseChildrenInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor); size_t getChildrenCount() const; void addChild(const sp<Layer>& layer); // Returns index if removed, or negative value otherwise // for symmetry with Vector::remove ssize_t removeChild(const sp<Layer>& layer); sp<Layer> getParent() const { return mCurrentParent.promote(); } bool hasParent() const { return getParent() != nullptr; } Rect computeScreenBounds(bool reduceTransparentRegion = true) const; bool setChildLayer(const sp<Layer>& childLayer, int32_t z); bool setChildRelativeLayer(const sp<Layer>& childLayer, const sp<IBinder>& relativeToHandle, int32_t relativeZ); // Copy the current list of children to the drawing state. Called by // SurfaceFlinger to complete a transaction. void commitChildList(); int32_t getZ() const; void pushPendingState(); protected: // constant sp<SurfaceFlinger> mFlinger; /* * Trivial class, used to ensure that mFlinger->onLayerDestroyed(mLayer) * is called. */ class LayerCleaner { sp<SurfaceFlinger> mFlinger; wp<Layer> mLayer; protected: ~LayerCleaner() { // destroy client resources mFlinger->onLayerDestroyed(mLayer); } public: LayerCleaner(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer) : mFlinger(flinger), mLayer(layer) {} }; friend class impl::SurfaceInterceptor; void commitTransaction(const State& stateToCommit); uint32_t getEffectiveUsage(uint32_t usage) const; FloatRect computeCrop(const sp<const DisplayDevice>& hw) const; // Compute the initial crop as specified by parent layers and the // SurfaceControl for this layer. Does not include buffer crop from the // IGraphicBufferProducer client, as that should not affect child clipping. // Returns in screen space. Rect computeInitialCrop(const sp<const DisplayDevice>& hw) const; // drawing void clearWithOpenGL(const RenderArea& renderArea, float r, float g, float b, float alpha) const; void setParent(const sp<Layer>& layer); LayerVector makeTraversalList(LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers); void addZOrderRelative(const wp<Layer>& relative); void removeZOrderRelative(const wp<Layer>& relative); class SyncPoint { public: explicit SyncPoint(uint64_t frameNumber) : mFrameNumber(frameNumber), mFrameIsAvailable(false), mTransactionIsApplied(false) {} uint64_t getFrameNumber() const { return mFrameNumber; } bool frameIsAvailable() const { return mFrameIsAvailable; } void setFrameAvailable() { mFrameIsAvailable = true; } bool transactionIsApplied() const { return mTransactionIsApplied; } void setTransactionApplied() { mTransactionIsApplied = true; } private: const uint64_t mFrameNumber; std::atomic<bool> mFrameIsAvailable; std::atomic<bool> mTransactionIsApplied; }; // SyncPoints which will be signaled when the correct frame is at the head // of the queue and dropped after the frame has been latched. Protected by // mLocalSyncPointMutex. Mutex mLocalSyncPointMutex; std::list<std::shared_ptr<SyncPoint>> mLocalSyncPoints; // SyncPoints which will be signaled and then dropped when the transaction // is applied std::list<std::shared_ptr<SyncPoint>> mRemoteSyncPoints; // Returns false if the relevant frame has already been latched bool addSyncPoint(const std::shared_ptr<SyncPoint>& point); void popPendingState(State* stateToCommit); bool applyPendingStates(State* stateToCommit); void clearSyncPoints(); // Returns mCurrentScaling mode (originating from the // Client) or mOverrideScalingMode mode (originating from // the Surface Controller) if set. virtual uint32_t getEffectiveScalingMode() const { return 0; } public: /* * The layer handle is just a BBinder object passed to the client * (remote process) -- we don't keep any reference on our side such that * the dtor is called when the remote side let go of its reference. * * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for * this layer when the handle is destroyed. */ class Handle : public BBinder, public LayerCleaner { public: Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer) : LayerCleaner(flinger, layer), owner(layer) {} wp<Layer> owner; }; sp<IBinder> getHandle(); const String8& getName() const; virtual void notifyAvailableFrames() {} virtual PixelFormat getPixelFormat() const { return PIXEL_FORMAT_NONE; } bool getPremultipledAlpha() const; protected: // ----------------------------------------------------------------------- bool usingRelativeZ(LayerVector::StateSet stateSet); bool mPremultipliedAlpha; String8 mName; String8 mTransactionName; // A cached version of "TX - " + mName for systraces bool mPrimaryDisplayOnly = false; // these are protected by an external lock State mCurrentState; State mDrawingState; volatile int32_t mTransactionFlags; // Accessed from main thread and binder threads Mutex mPendingStateMutex; Vector<State> mPendingStates; // thread-safe volatile int32_t mQueuedFrames; volatile int32_t mSidebandStreamChanged; // used like an atomic boolean // Timestamp history for UIAutomation. Thread safe. FrameTracker mFrameTracker; // Timestamp history for the consumer to query. // Accessed by both consumer and producer on main and binder threads. Mutex mFrameEventHistoryMutex; ConsumerFrameEventHistory mFrameEventHistory; FenceTimeline mAcquireTimeline; FenceTimeline mReleaseTimeline; TimeStats& mTimeStats = TimeStats::getInstance(); // main thread int mActiveBufferSlot; sp<GraphicBuffer> mActiveBuffer; sp<NativeHandle> mSidebandStream; ui::Dataspace mCurrentDataSpace = ui::Dataspace::UNKNOWN; Rect mCurrentCrop; uint32_t mCurrentTransform; // We encode unset as -1. int32_t mOverrideScalingMode; bool mCurrentOpacity; std::atomic<uint64_t> mCurrentFrameNumber; bool mFrameLatencyNeeded; // Whether filtering is forced on or not bool mFiltering; // Whether filtering is needed b/c of the drawingstate bool mNeedsFiltering; bool mPendingRemoval = false; // page-flip thread (currently main thread) bool mProtectedByApp; // application requires protected path to external sink // protected by mLock mutable Mutex mLock; const wp<Client> mClientRef; // This layer can be a cursor on some displays. bool mPotentialCursor; // Local copy of the queued contents of the incoming BufferQueue mutable Mutex mQueueItemLock; Condition mQueueItemCondition; Vector<BufferItem> mQueueItems; std::atomic<uint64_t> mLastFrameNumberReceived; bool mAutoRefresh; bool mFreezeGeometryUpdates; // Child list about to be committed/used for editing. LayerVector mCurrentChildren; // Child list used for rendering. LayerVector mDrawingChildren; wp<Layer> mCurrentParent; wp<Layer> mDrawingParent; mutable LayerBE mBE; private: /** * Returns an unsorted vector of all layers that are part of this tree. * That includes the current layer and all its descendants. */ std::vector<Layer*> getLayersInTree(LayerVector::StateSet stateSet); /** * Traverses layers that are part of this tree in the correct z order. * layersInTree must be sorted before calling this method. */ void traverseChildrenInZOrderInner(const std::vector<Layer*>& layersInTree, LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor); LayerVector makeChildrenTraversalList(LayerVector::StateSet stateSet, const std::vector<Layer*>& layersInTree); }; // --------------------------------------------------------------------------- }; // namespace android #endif // ANDROID_LAYER_H
[ "dongdong331@163.com" ]
dongdong331@163.com
d01a8d8d836473383c3af13d88fcaf62ea601662
8aa6ac20dc293ec33b2617907ac4ab0f06b22ad5
/source/player/player_tag_provider.h
dba56c4ba9c56f73c8525117b463cdc1bd711b55
[]
no_license
swipswaps/musciteer
481304b7bae660f8046c336255e6dec708eea691
690a00e77a56f4d1ad89506fa80d18fb8029dc83
refs/heads/master
2021-09-15T05:48:12.432280
2018-05-27T08:37:25
2018-05-27T08:37:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,806
h
// ---------------------------------------------------------------------------- // // Author : Benny Bach <benny.bach@gmail.com> // Copyright (C) 2016 // // ---------------------------------------------------------------------------- #ifndef __player__tag_provider_h__ #define __player__tag_provider_h__ // ---------------------------------------------------------------------------- #include "player_list_provider_base.h" // ---------------------------------------------------------------------------- #include "../dm/tracks.h" // ---------------------------------------------------------------------------- namespace musciteer { class tag_provider : public list_provider_base { public: tag_provider(const std::string& tag) : tag_(tag), index_(0) { auto tracks = musciteer::dm::tracks(); tracks.each([&](musciteer::dm::track& track) { const auto& tags = track.tags(); if ( tags.find(tag) != tags.end() ) { tracks_.push_back(track); } return true; }); shuffle(); } public: bool done() override { return tracks_.size() == 0 || index_ >= tracks_.size(); } public: dm::track next() override { auto t = dm::track(); if ( index_ < tracks_.size() ) { t = tracks_[index_]; index_++; } return t; } public: std::string info() override { return tag_; } private: void shuffle() { std::random_device rd; std::mt19937 g(rd()); std::shuffle(tracks_.begin(), tracks_.end(), g); } private: std::string tag_; std::vector<dm::track> tracks_; size_t index_; }; } // ---------------------------------------------------------------------------- #endif
[ "benny.bach@gmail.com" ]
benny.bach@gmail.com
262f44c7f72229fdaad427ab6a95cfcee62f2277
97fc7177de35aca6d65c92fa3d274806dba9eb2f
/index.h
e2d9f21378b01ab7834b10b75b8f6e954f00e699
[]
no_license
wdzeng/nctucs-database-hw2
185d36a80c22e2d54ed0292e30719e759c674fe6
98d7b8b0698461694f352d5d1a415ea153b3218a
refs/heads/master
2022-07-17T00:57:05.468276
2020-05-20T03:32:53
2020-05-20T03:32:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,146
h
#pragma GCC optimize("O3") #include <utility> #include <vector> using namespace std; typedef pair<int, int> entry; /* template <typename E> class Array { private: E store[M]; int size = 0; public: Array(); Array(const E& e) { add(e); } inline void add(const E& e) { // assert(size < M); store[size++] = e; } inline E& operator[](int index) { return store[index]; } inline const E& operator[](int index) const { return [index]; } inline int length() const { return size; } inline Array addSplit(const E& e) { // assert(size == M); Array<E> ret; const int requireSplitSize = M / 2; int i = 0; for (int j = 0; j < requireSplitSize; j++) { if (e < store[i]) ret.add(e); else ret.add(store[i++]); } int k = 0; while (i < M) { if (e < store[i]) store[k++] = e; else store[k++] = store[i++]; } size = M - requireSplitSize; return ret; } }; */ class Internal { public: Internal(); vector<void*> children; vector<int> keys; inline void insert(int key, void* child); inline Internal* insertAndSplit(int key, void* newChild, int& kick); inline void* findChildByKey(int key) const; }; class Leaf { public: vector<entry> entries; Leaf* prev; Leaf* next; int x; Leaf(); inline void insert(int key, int value); inline Leaf* insertAndSplit(int key, int value, int& kick); inline int query(int key) const; }; class BPlusTree { private: void* root = NULL; int level = 0; public: BPlusTree(); ~BPlusTree(); void insert(int k, int v); int query(const int k) const; int query(const int from, const int to) const; void test(int s) const; }; class Index { private: BPlusTree b; public: Index(int num_rows, const vector<int>& keys, const vector<int>& values); void key_query(vector<int>& keys); void range_query(const vector<pair<int, int>>& keys); void clear_index(); };
[ "hyperbola.cs07@gmail.com" ]
hyperbola.cs07@gmail.com
1c9e8df819c133ff43e344a8b1f8da5a2d168637
ebacc5b1b457b08eac119e43c030281c98343aeb
/ABCBank/BankClient/UI/CloseAccountForm.h
d84cc1e484178c20496d07d3ebab5483f4ad6caa
[]
no_license
deardeng/learning
e9993eece3ed22891f2e54df7c8cf19bf1ce89f4
338d6431cb2d64b25b3d28bbdd3e47984f422ba2
refs/heads/master
2020-05-17T13:12:43.808391
2016-02-11T16:24:09
2016-02-11T16:24:09
19,692,141
1
1
null
null
null
null
UTF-8
C++
false
false
835
h
#ifndef _CLOSE_ACCOUNT_FORM_H_ #define _CLOSE_ACCOUNT_FORM_H_ #include "../JFC/JForm.h" #include "../JFC/JLable.h" #include "../JFC/JEdit.h" #include "../JFC/JButton.h" #include <string> using namespace JFC; namespace UI { class CloseAccountForm : public JForm { public: CloseAccountForm(); ~CloseAccountForm(); CloseAccountForm(SHORT x, SHORT y, SHORT w, SHORT h, const std::string& title); virtual void Draw(); virtual void OnKeyEvent(JEvent* e); private: void DrawBorder(); void Reset(); void Submit(); std::string title_; JLable* lblAccountId_; JEdit* editAccountId_; JLable* lblAccountIdTip_; JLable* lblPass_; JEdit* editPass_; JLable* lblPassTip_; JButton* btnSubmit_; JButton* btnReset_; JButton* btnCancel_; }; } #endif // _CLOSE_ACCOUNT_FORM_H_
[ "565620795@qq.com" ]
565620795@qq.com
b82821c676bbb8b8595ea818b54fac80a1040701
26f7c777a81061a8bcc80fae91fdc6663ec2a7bf
/Testing/igstkCoordinateSystemEventTest.cxx
fefd8e1647a8bd0e07773c6b9c50ce17c6c959d7
[ "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
JQiu/IGSTK-5.2
0af66324623d33d171ee775098894048e12e9023
605a87e177c6e68acc773efe1fe5206cfb15dfbd
HEAD
2016-09-05T13:55:54.626920
2014-11-23T15:57:09
2014-11-23T15:57:09
27,037,331
1
3
null
null
null
null
UTF-8
C++
false
false
3,093
cxx
/*========================================================================= Program: Image Guided Surgery Software Toolkit Module: igstkCoordinateSystemEventTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) ISC Insight Software Consortium. All rights reserved. See IGSTKCopyright.txt or http://www.igstk.org/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 notices for more information. =========================================================================*/ #if defined(_MSC_VER) // Warning about: identifier was truncated to '255' characters // in the debug information (MVC6.0 Debug) #pragma warning( disable : 4786 ) #endif #include <iostream> #include "igstkCoordinateSystem.h" #include "igstkCoordinateSystemTransformToResult.h" #include "igstkCoordinateSystemTransformToErrorResult.h" #include "igstkCoordinateSystemSetTransformResult.h" int igstkCoordinateSystemEventTest( int, char * [] ) { /** This test is mainly for code coverage on the event results. */ typedef igstk::CoordinateSystem CoordinateSystemType; typedef igstk::CoordinateSystemTransformToResult TransformToResult; typedef igstk::CoordinateSystemTransformToErrorResult ErrorResult; typedef igstk::CoordinateSystemSetTransformResult SetTransformResult; typedef igstk::Transform TransformType; CoordinateSystemType::Pointer cs1 = CoordinateSystemType::New(); CoordinateSystemType::Pointer cs2 = CoordinateSystemType::New(); TransformType transform; TransformToResult transformToResult; // Test Initialize transformToResult.Initialize( transform, cs1, cs2 ); // Copy ctor TransformToResult transformToResult2 = transformToResult; // Assignment operator transformToResult = transformToResult2; // GetTransform transformToResult.GetTransform(); // GetSource transformToResult.GetSource(); // GetDestination transformToResult.GetDestination(); // Clear transformToResult.Clear(); // Error result ErrorResult errorResult; // Test Initialize errorResult.Initialize( cs1, cs2 ); // Copy ctor ErrorResult errorResult2 = errorResult; // Assignment operator errorResult = errorResult2; // GetSource errorResult.GetSource(); // GetDestination errorResult.GetDestination(); // Clear errorResult.Clear(); // Set transform result SetTransformResult stResult; bool attaching = true; // Test Initialize stResult.Initialize( transform, cs1, cs2, attaching ); // Copy ctor SetTransformResult stResult2 = stResult; // Assignment operator stResult = stResult2; // GetTransform stResult.GetTransform(); // GetSource stResult.GetSource(); // GetDestination stResult.GetDestination(); // Is attaching? if (! stResult.IsAttach()) { return EXIT_FAILURE; } // Clear stResult.Clear(); return EXIT_SUCCESS; }
[ "jqvroom@gmail.com" ]
jqvroom@gmail.com
28232614af753daf39598a03deaa354f78df0dbd
785df77400157c058a934069298568e47950e40b
/Common/Foam/include/base/PatchToolsGatherAndMergeI.hxx
02e51315e07f4d0fc0db4bbde2bfef99c709b25c
[]
no_license
amir5200fx/Tonb
cb108de09bf59c5c7e139435e0be008a888d99d5
ed679923dc4b2e69b12ffe621fc5a6c8e3652465
refs/heads/master
2023-08-31T08:59:00.366903
2023-08-31T07:42:24
2023-08-31T07:42:24
230,028,961
9
3
null
2023-07-20T16:53:31
2019-12-25T02:29:32
C++
UTF-8
C++
false
false
5,044
hxx
#pragma once #include <polyMesh.hxx> #include <globalMeshData.hxx> #include <mergePoints.hxx> #include <IPstream.hxx> // added by amir #include <OPstream.hxx> // added by amir // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class FaceList, class PointField> void tnbLib::PatchTools::gatherAndMerge ( const scalar mergeDist, const PrimitivePatch<FaceList, PointField>& p, Field<typename PrimitivePatch<FaceList, PointField>::PointType>& mergedPoints, List<typename PrimitivePatch<FaceList, PointField>::FaceType>& mergedFaces, labelList& pointMergeMap ) { typedef typename PrimitivePatch<FaceList, PointField>::FaceType FaceType; typedef typename PrimitivePatch<FaceList, PointField>::PointType PointType; // Collect points from all processors labelList pointSizes; { List<Field<PointType>> gatheredPoints(Pstream::nProcs()); gatheredPoints[Pstream::myProcNo()] = p.points(); Pstream::gatherList(gatheredPoints); if (Pstream::master()) { pointSizes = ListListOps::subSizes ( gatheredPoints, accessOp<Field<PointType>>() ); mergedPoints = ListListOps::combine<Field<PointType>> ( gatheredPoints, accessOp<Field<PointType>>() ); } } // Collect faces from all processors and renumber using sizes of // gathered points { List<List<FaceType>> gatheredFaces(Pstream::nProcs()); gatheredFaces[Pstream::myProcNo()] = p; Pstream::gatherList(gatheredFaces); if (Pstream::master()) { mergedFaces = static_cast<const List<FaceType>&> ( ListListOps::combineOffset<List<FaceType>> ( gatheredFaces, pointSizes, accessOp<List<FaceType>>(), offsetOp<FaceType>() ) ); } } if (Pstream::master()) { Field<PointType> newPoints; labelList oldToNew; bool hasMerged = mergePoints ( mergedPoints, mergeDist, false, // verbosity oldToNew, newPoints ); if (hasMerged) { // Store point mapping pointMergeMap.transfer(oldToNew); // Copy points mergedPoints.transfer(newPoints); // Relabel faces List<FaceType>& faces = mergedFaces; forAll(faces, facei) { inplaceRenumber(pointMergeMap, faces[facei]); } } } } template<class FaceList> void tnbLib::PatchTools::gatherAndMerge ( const polyMesh& mesh, const FaceList& localFaces, const labelList& meshPoints, const Map<label>& meshPointMap, labelList& pointToGlobal, labelList& uniqueMeshPointLabels, autoPtr<globalIndex>& globalPointsPtr, autoPtr<globalIndex>& globalFacesPtr, List<typename FaceList::value_type>& mergedFaces, pointField& mergedPoints ) { typedef typename FaceList::value_type FaceType; if (Pstream::parRun()) { // Renumber the setPatch points/faces into unique points globalPointsPtr = mesh.globalData().mergePoints ( meshPoints, meshPointMap, pointToGlobal, uniqueMeshPointLabels ); globalFacesPtr.reset(new globalIndex(localFaces.size())); if (Pstream::master()) { // Get renumbered local data pointField myPoints(mesh.points(), uniqueMeshPointLabels); List<FaceType> myFaces(localFaces); forAll(myFaces, i) { inplaceRenumber(pointToGlobal, myFaces[i]); } mergedFaces.setSize(globalFacesPtr().size()); mergedPoints.setSize(globalPointsPtr().size()); // Insert master data first label pOffset = globalPointsPtr().offset(Pstream::masterNo()); SubList<point>(mergedPoints, myPoints.size(), pOffset) = myPoints; label fOffset = globalFacesPtr().offset(Pstream::masterNo()); SubList<FaceType>(mergedFaces, myFaces.size(), fOffset) = myFaces; // Receive slave ones for (int slave = 1; slave < Pstream::nProcs(); slave++) { IPstream fromSlave(Pstream::commsTypes::scheduled, slave); pointField slavePoints(fromSlave); List<FaceType> slaveFaces(fromSlave); label pOffset = globalPointsPtr().offset(slave); SubList<point>(mergedPoints, slavePoints.size(), pOffset) = slavePoints; label fOffset = globalFacesPtr().offset(slave); SubList<FaceType>(mergedFaces, slaveFaces.size(), fOffset) = slaveFaces; } } else { // Get renumbered local data pointField myPoints(mesh.points(), uniqueMeshPointLabels); List<FaceType> myFaces(localFaces); forAll(myFaces, i) { inplaceRenumber(pointToGlobal, myFaces[i]); } // Construct processor stream with estimate of size. Could // be improved. OPstream toMaster ( Pstream::commsTypes::scheduled, Pstream::masterNo(), myPoints.byteSize() + 4 * sizeof(label)*myFaces.size() ); toMaster << myPoints << myFaces; } } else { pointToGlobal = identity(meshPoints.size()); uniqueMeshPointLabels = pointToGlobal; globalPointsPtr.reset(new globalIndex(meshPoints.size())); globalFacesPtr.reset(new globalIndex(localFaces.size())); mergedFaces = localFaces; mergedPoints = pointField(mesh.points(), meshPoints); } } // ************************************************************************* //
[ "aasoleimani86@gmail.com" ]
aasoleimani86@gmail.com